Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 1개 있습니다.)

.NET Remoting에서 서비스 호출 시 SYN_SENT로 남는 현상

TCP 상태 다이어그램에 보면,

[출처: https://www.cisco.com/c/en/us/about/press/internet-protocol-journal/back-issues/table-contents-34/syn-flooding-attacks.html]
tcp_connect_1.jpg

SYN_SENT는 연결을 시도한 측에서 SYN 패킷을 보낸 후 대상이 ACK로 반응하기까지의 상태입니다. 다른 말로 하면, ACK 받기 전까지는 connect 한 측의 소켓이 SYN_SENT로 계속 머무른다는 것입니다. 이것을 재현하는 간단한 방법은, 서버 측 소켓에 backlog 값을 작게 주어 Accept 후 지연 시간을 주면,

using (_serverSocket = CreateServerSocket())
{
    _serverSocket.Listen(1);

    while (_serverSocket != null)
    {
        WriteLog("accept...");
        using (Socket clntSocket = _serverSocket.Accept())
        {
            Thread.Sleep(1000 * 60 * 5);
            clntSocket.Close();
        }
    }
}

클라이언트에서 접속 시,

static void Main(string[] args)
{
    while (true)
    {
        Thread t2 = new Thread(clntSockFunc);
        t2.Start();

        Console.WriteLine("Press any key to continue...");
        Console.ReadLine();
    }
}

private static void clntSockFunc(object obj)
{
    try
    {
        using (var socket = CreateClientSocket())
        {
            IPEndPoint ipEp = new IPEndPoint(IPAddress.Loopback, 57102);
            socket.Connect(ipEp);

            socket.Close();
        }
    }
    catch (Exception e)
    {
        Console.WriteLine(e.ToString());
    }
}

처음 한 번의 접속은 Accept를 타게 되고, 이후 한 번은 Listen(1)로 인해 큐에 담기고 3번째 접속부터 다음과 같은 예외가 발생합니다.

System.Net.Sockets.SocketException (0x80004005): No connection could be made because the target machine actively refused it 127.0.0.1:57102
   at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress)
   at System.Net.Sockets.Socket.Connect(EndPoint remoteEP)
   at Program.clntSockFunc(Object obj) in c:\temp\ConsoleApp2\Program.cs:line 31

그리고 위와 같은 오류가 발생하기 전, ^^ 재빠르게 netstat 명령어로 확인하면 다음과 같이 SYN_SENT를 볼 수 있습니다.

C:\Windows\System32> netstat -ano | findstr 57102
  TCP    127.0.0.1:2981         127.0.0.1:57102        ESTABLISHED     32564
  TCP    127.0.0.1:2983         127.0.0.1:57102        ESTABLISHED     32564
  TCP    127.0.0.1:2984         127.0.0.1:57102        SYN_SENT        32564
  TCP    127.0.0.1:57102        0.0.0.0:0              LISTENING       38696
  TCP    127.0.0.1:57102        127.0.0.1:2981         ESTABLISHED     38696
  TCP    127.0.0.1:57102        127.0.0.1:2983         ESTABLISHED     38696

또는 서버 측 대응 소켓이 없는 상태에서 클라이언트가 아무 데나 연결을 시도하면 역시 동일한 0x80004005 예외가 발생하고 그때도 잠시 SYN_SENT를 볼 수 있습니다. TIME_WAIT 과는 달리 삭제까지 별도로 대기 시간이 필요 없기 때문에 아주 잠시 SYN_SENT가 발생하므로 현업에서는 잘 볼 수 없습니다.




재미있는 것은, 이런 현상이 Windows Server 2008 x86 운영체제에서 .NET Remoting을 열었을 때 접속하려는 클라이언트 측에서 발생했습니다. SYN_SENT가 쌓이는데 시간이 지나도 끊어지지 않는다는 특징이 있습니다. 그래서 Socket.Connect를 호출한 측의 스레드가 블로킹되어 서비스 장애까지 간 것입니다.

재현 코드는 간단하게 .NET Remoing 서버를 다음과 같이 만들고,

using System;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;

class Program
{
    static TcpChannel tcpChannel;

    static void Main(string[] args)
    {
        RunServer();

        Console.WriteLine("Prees any key to run client...");
        Console.ReadLine();
    }

    static void RunServer()
    {
        try
        {
            /*
            Server Channel Properties
            ; https://learn.microsoft.com/en-us/previous-versions/dotnet/netframework-4.0/bb397831(v=vs.100)
            */
            System.Collections.IDictionary tcpProperties = new System.Collections.Hashtable();
            tcpProperties["port"] = HWConfig.TcpChannelPort;

            BinaryServerFormatterSinkProvider tcpServerProv = new BinaryServerFormatterSinkProvider();
            tcpServerProv.TypeFilterLevel = System.Runtime.Serialization.Formatters.TypeFilterLevel.Low;

            tcpChannel = new TcpChannel(tcpProperties, null, tcpServerProv);
            System.Diagnostics.Trace.WriteLine("TcpChannelPort is acquired!");

            ChannelServices.RegisterChannel(tcpChannel, false);
            RemotingConfiguration.RegisterWellKnownServiceType(typeof(HWSingleton), "HWSingleton", WellKnownObjectMode.Singleton);
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
    }
}

클라이언트 측은 이렇습니다.

using System;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;

class Program
{
    static void Main(string[] args)
    {
        string tcpServer = string.Format("tcp://localhost:{0}/HWSingleton", HWConfig.TcpChannelPort);
        Console.WriteLine(tcpServer);
        RegisterClient();

        HWSingleton hwSingleton = (HWSingleton)Activator.GetObject(typeof(HWSingleton), tcpServer);
        Console.WriteLine(hwSingleton.Echo("Hello"));
    }

    private static void RegisterClient()
    {
        /*
        Client Channel Properties
        ; https://learn.microsoft.com/en-us/previous-versions/dotnet/netframework-4.0/bb397839(v=vs.100)
        */

        System.Collections.IDictionary tcpProperties = new System.Collections.Hashtable();
        BinaryServerFormatterSinkProvider tcpServerProv = new BinaryServerFormatterSinkProvider();
        tcpServerProv.TypeFilterLevel = System.Runtime.Serialization.Formatters.TypeFilterLevel.Low;
        TcpChannel tcpChannel = new TcpChannel(tcpProperties, null, tcpServerProv);

        ChannelServices.RegisterChannel(tcpChannel, false);
    }
}

이렇게 하고 실행했더니, 다른 컴퓨터에서는 괜찮은데 유독 Windows Server 2008 x86에서만 클라이언트 측의 접속이 SYN_SENT로 머무르면서 절대 소켓 연결 시도가 끊기질 않습니다.




결국 해결 방법은 못 찾았습니다. 재미있는 것은 해당 시스템의 Tcpip 관련 레지스트리(HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters) 설정이 좀 이상했다는 점입니다. 가령 다음과 같은 값들이 그랬습니다.

TcpTimedWaitDelay ffffffff
TcpFinWait2Delay ffffffff
KeepAliveInterval ffffffff
KeepAliveTime ffffffff
EnablePMTUDiscovery ff
TcpMaxDataRetransmissions ff

아무래도 Tcpip 관련 옵션들에서 어떤 문제가 발생한 듯싶은데 저런 값들을 다른 시스템에 맞춰 값을 조절하거나 삭제를 하기도 했지만 저 문제가 없어지지는 않았습니다.

그런데, 재미있는 점이 하나 있었다면 접속 측에서 "localhost"가 아닌 IP 주소로 접속(예: 127.0.0.1)하면 잘 되었습니다. 그래서 HOSTS 파일의 localhost 등록을 명시적으로 임시 설정하고,

127.0.0.1 localhost

소스 코드의 접속 관련 코드들에서 "localhost"를 "127.0.0.1"로 바꾼 후 HOSTS 파일을 다시 원복하는 것으로 문제를 우회 해결했습니다. (다행히 테스트 서버에서 발생한 문제였습니다. ^^)

(첨부 파일은 이 글의 예제 코드를 포함합니다.)




참고로, .NET Remoting은 이제 역사의 뒤안길로 사라지는 기술이 되었습니다. 마이크로소프트는 향후 .NET 5로의 통합에서 더 이상 .NET Remoting(뿐만 아니라 WCF까지도!)을 지원하지 않기로 했으며 그 대체재로 gRPC를 추가하기로 결정했습니다.




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]

[연관 글]






[최초 등록일: ]
[최종 수정일: 7/7/2023]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




... 46  47  48  49  50  51  52  53  54  55  56  57  58  [59]  60  ...
NoWriterDateCnt.TitleFile(s)
12161정성태2/26/20209778오류 유형: 597. manifest - The value "x64" of attribute "processorArchitecture" in element "assemblyIdentity" is invalid.
12160정성태2/26/202010480개발 환경 구성: 469. Reg-free COM 개체 사용을 위한 manifest 파일 생성 도구 - COMRegFreeManifest
12159정성태2/26/20208612오류 유형: 596. Visual Studio - The project needs to include ATL support
12158정성태2/25/202010447디버깅 기술: 165. C# - Marshal.GetIUnknownForObject/GetIDispatchForObject 사용 시 메모리 누수(Memory Leak) 발생파일 다운로드1
12157정성태2/25/202010376디버깅 기술: 164. C# - Marshal.GetNativeVariantForObject 사용 시 메모리 누수(Memory Leak) 발생 및 해결 방법파일 다운로드1
12156정성태2/25/20209715오류 유형: 595. LINK : warning LNK4098: defaultlib 'nafxcw.lib' conflicts with use of other libs; use /NODEFAULTLIB:library
12155정성태2/25/20208989오류 유형: 594. Warning NU1701 - This package may not be fully compatible with your project
12154정성태2/25/20208796오류 유형: 593. warning LNK4070: /OUT:... directive in .EXP differs from output filename
12153정성태2/23/202011533.NET Framework: 898. Trampoline을 이용한 후킹의 한계파일 다운로드1
12152정성태2/23/202011281.NET Framework: 897. 실행 시에 메서드 가로채기 - CLR Injection: Runtime Method Replacer 개선 - 세 번째 이야기(Trampoline 후킹)파일 다운로드1
12151정성태2/22/202011761.NET Framework: 896. C# - Win32 API를 Trampoline 기법을 이용해 C# 메서드로 가로채는 방법 - 두 번째 이야기 (원본 함수 호출)파일 다운로드1
12150정성태2/21/202011642.NET Framework: 895. C# - Win32 API를 Trampoline 기법을 이용해 C# 메서드로 가로채는 방법 [1]파일 다운로드1
12149정성태2/20/202011398.NET Framework: 894. eBEST C# XingAPI 래퍼 - 연속 조회 처리 방법 [1]
12148정성태2/19/202012641디버깅 기술: 163. x64 환경에서 구현하는 다양한 Trampoline 기법 [1]
12147정성태2/19/202011277디버깅 기술: 162. x86/x64의 기계어 코드 최대 길이
12146정성태2/18/202011497.NET Framework: 893. eBEST C# XingAPI 래퍼 - 로그인 처리파일 다운로드1
12145정성태2/18/202010721.NET Framework: 892. eBEST C# XingAPI 래퍼 - Sqlite 지원 추가파일 다운로드1
12144정성태2/13/202010747.NET Framework: 891. 실행 시에 메서드 가로채기 - CLR Injection: Runtime Method Replacer 개선 - 두 번째 이야기파일 다운로드1
12143정성태2/13/20208790.NET Framework: 890. 상황별 GetFunctionPointer 반환값 정리 - x64파일 다운로드1
12142정성태2/12/202010538.NET Framework: 889. C# 코드로 접근하는 MethodDesc, MethodTable파일 다운로드1
12141정성태2/10/202010117.NET Framework: 888. C# - ASP.NET Core 웹 응용 프로그램의 출력 가로채기 [2]파일 다운로드1
12140정성태2/10/20209987.NET Framework: 887. C# - ASP.NET 웹 응용 프로그램의 출력 가로채기파일 다운로드1
12139정성태2/9/202011355.NET Framework: 886. C# - Console 응용 프로그램에서 UI 스레드 구현 방법
12138정성태2/9/202014116.NET Framework: 885. C# - 닷넷 응용 프로그램에서 SQLite 사용 [6]파일 다운로드1
12137정성태2/9/20209305오류 유형: 592. [AhnLab] 경고 - 디버거 실행을 탐지했습니다.
12136정성태2/6/20209708Windows: 168. Windows + S(또는 Q)로 뜨는 작업 표시줄의 검색 바가 동작하지 않는 경우
... 46  47  48  49  50  51  52  53  54  55  56  57  58  [59]  60  ...