diff --git a/binaries/aarch64/nfqws b/binaries/aarch64/nfqws index 130b2d0..375f518 100755 Binary files a/binaries/aarch64/nfqws and b/binaries/aarch64/nfqws differ diff --git a/binaries/arm/nfqws b/binaries/arm/nfqws index 9a0ee68..25b0d0f 100755 Binary files a/binaries/arm/nfqws and b/binaries/arm/nfqws differ diff --git a/binaries/freebsd-x64/dvtws b/binaries/freebsd-x64/dvtws index a6422e9..83aae99 100755 Binary files a/binaries/freebsd-x64/dvtws and b/binaries/freebsd-x64/dvtws differ diff --git a/binaries/mips32r1-lsb/nfqws b/binaries/mips32r1-lsb/nfqws index 479e78e..a2f069f 100755 Binary files a/binaries/mips32r1-lsb/nfqws and b/binaries/mips32r1-lsb/nfqws differ diff --git a/binaries/mips32r1-msb/nfqws b/binaries/mips32r1-msb/nfqws index b6e8fdb..592a659 100755 Binary files a/binaries/mips32r1-msb/nfqws and b/binaries/mips32r1-msb/nfqws differ diff --git a/binaries/mips64r2-msb/nfqws b/binaries/mips64r2-msb/nfqws index b8aa7df..6c8d796 100755 Binary files a/binaries/mips64r2-msb/nfqws and b/binaries/mips64r2-msb/nfqws differ diff --git a/binaries/ppc/nfqws b/binaries/ppc/nfqws index 15f614a..1df5254 100755 Binary files a/binaries/ppc/nfqws and b/binaries/ppc/nfqws differ diff --git a/binaries/x86/nfqws b/binaries/x86/nfqws index f37dc59..d27cbcb 100755 Binary files a/binaries/x86/nfqws and b/binaries/x86/nfqws differ diff --git a/binaries/x86_64/nfqws b/binaries/x86_64/nfqws index 1a1756b..b788326 100755 Binary files a/binaries/x86_64/nfqws and b/binaries/x86_64/nfqws differ diff --git a/docs/changes.txt b/docs/changes.txt index 03209d6..0787f20 100644 --- a/docs/changes.txt +++ b/docs/changes.txt @@ -274,3 +274,12 @@ v56 tpws: mss fooling tpws: multi thread resolver. eliminates blocks related to hostname resolve. + +v57 + +tpws: --nosplice option +nfqws: postnat fixes +nfqws: --dpi-desync-start option +nfqws: packet delay for kyber TLS and QUIC +nfqws: --dpi-desync-retrans obsolete +nfqws: --qnum is mandatory, no more default queue 0 diff --git a/docs/readme.eng.md b/docs/readme.eng.md index d2736ad..ff7f17c 100644 --- a/docs/readme.eng.md +++ b/docs/readme.eng.md @@ -173,7 +173,6 @@ nfqws takes the following parameters: --dpi-desync-autottl=[[:[-]]] ; auto ttl mode for both ipv4 and ipv6. default: 1:3-20 --dpi-desync-autottl6=[[:[-]]] ; overrides --dpi-desync-autottl for ipv6 only --dpi-desync-fooling=[,] ; can use multiple comma separated values. modes : none md5sig ts badseq badsum datanoack hopbyhop hopbyhop2 - --dpi-desync-retrans=0|1 ; 0(default)=reinject original data packet after fake 1=drop original data packet to force its retransmission --dpi-desync-repeats= ; send every desync packet N times --dpi-desync-skip-nosni=0|1 ; 1(default)=do not act on ClientHello without SNI (ESNI ?) --dpi-desync-split-pos=<1..9216> ; data payload split position @@ -263,10 +262,7 @@ add tcp option **MD5 signature**. All of them have their own disadvantages : `--dpi-desync-fooling` takes multiple comma separated values. -For fake,rst,rstack modes original packet can be sent after the fake one or just dropped. -If its dropped OS will perform first retransmission after 0.2 sec, then the delay increases exponentially. -Delay can help to make sure fake and original packets are properly ordered and processed on DPI. -When `dpi-desync-retrans=1` its mandatory to use connbytes in iptables rule. Otherwise loop happens. +For fake,rst,rstack modes original packet is sent after the fake. Disorder mode splits original packet and sends packets in the following order : 1. 2nd segment @@ -461,6 +457,16 @@ If the connection falls out of the conntrack and --dpi-desync-cutoff is set, dpi Set conntrack timeouts appropriately. +### Reassemble + +nfqws supports reassemble of TLS and QUIC ClientHello. +They can consist of multiple packets if kyber crypto is used (default from chromium 124). +Chromium randomizes TLS fingerprint. SNI can be in any packet. +Stateful DPIs usually reassemble all packets in the request then apply block decision. +If nfqws receives a partial ClientHello it begins reassemble session. Packets are delayed until it's finished. +Then the first packet goes through desync using fully reassembled message. Other packets are sent +without desync. On any error reassemble is cancelled and all delayed packets are sent immediately without desync. + ### UDP support UDP attacks are limited. Its not possible to fragment UDP on transport level, only on network (ip) level. diff --git a/docs/readme.txt b/docs/readme.txt index 7cc47e1..0ff95a5 100644 --- a/docs/readme.txt +++ b/docs/readme.txt @@ -1,4 +1,4 @@ -zapret v.56 +zapret v.57 English ------- @@ -246,7 +246,6 @@ nfqws --dpi-desync-autottl=[[:[-]]] ; режим auto ttl для ipv4 и ipv6. по умолчанию: 1:3-20. delta=0 отключает функцию. --dpi-desync-autottl6=[[:[-]]] ; переопределение предыдущего параметра для ipv6 --dpi-desync-fooling= ; дополнительные методики как сделать, чтобы фейковый пакет не дошел до сервера. none md5sig badseq badsum datanoack hopbyhop hopbyhop2 - --dpi-desync-retrans=0|1 ; (только для fake,rst,rstack) 0(default)=отправлять оригинал следом за фейком 1=дропать оригинал, заставляя ОС выполнять ретрансмиссию через 0.2 сек --dpi-desync-repeats= ; посылать каждый генерируемый в nfqws пакет N раз (не влияет на остальные пакеты) --dpi-desync-skip-nosni=0| 1 ; 1(default)=не применять dpi desync для запросов без hostname в SNI, в частности для ESNI --dpi-desync-split-pos=<1..1500> ; (только для split*, disorder*) разбивать пакет на указанной позиции @@ -352,11 +351,7 @@ fakeknown отличается от fake тем, что применяется Режимы дурения могут сочетаться в любых комбинациях. --dpi-desync-fooling берет множество значений через запятую. -Для режимов fake, rst, rstack после фейка отправляем оригинальный пакет. Можно его отправить сразу следом за фейком, а можно его просто дропнуть. -Если его дропнуть, ОС выполнит ретрансмиссию. Первая ретрансмиссия случается через 0.2 сек, потом задержка увеличивается экспоненциально. -Задержка может дать надежную гарантию, что пакеты пойдут именно в нужном порядке и будут именно в нем обработаны на DPI. -По умолчанию используется первый вариант, т.к. он быстрее. -При использовании dpi-desync-retrans=1 обязательно вставлять ограничитель connbytes в iptables, иначе получим зацикливание. +Для режимов fake, rst, rstack после фейка отправляем оригинальный пакет. Режим disorder делит оригинальный пакет на 2 части и отправляет следующую комбинацию в указанном порядке : 1. 2-я часть пакета @@ -529,16 +524,17 @@ window size итоговый размер окна стал максимальн На склонных к бездействию соединениях следует изменить таймауты conntrack. Если соединение выпало из conntrack и задана опция --dpi-desync-cutoff, dpi desync применяться не будет. -РЕАССЕМБЛИНГ TCP -nfqws поддерживает реассемблинг некоторых видов tcp запросов. -На текущий момент это TLS ClientHello. Он бывает длинным, если в chrome включить пост-квантовую -криптографию tls-kyber, и занимает как правило 2 пакета. +РЕАССЕМБЛИНГ +nfqws поддерживает реассемблинг некоторых видов запросов. +На текущий момент это TLS и QUIC ClientHello. Они бывает длинными, если в chrome включить пост-квантовую +криптографию tls-kyber, и занимают как правило 2 или 3 пакета. kyber включен по умолчанию, начиная с chromium 124. chrome рандомизирует фингерпринт TLS. SNI может оказаться как в начале, так и в конце, то есть -попасть в 1 или 2 пакет. stateful DPI обычно реассемблирует запрос целиком, и только потом +попасть любой пакет. stateful DPI обычно реассемблирует запрос целиком, и только потом принимает решение о блокировке. -nfqws реагирует десинхронизацией на каждый пакет из TLSClientHello, если задана опция ---dpi-desync-skip-nosni=0. В противном случае десинхронизация идет на сам пакет, -включающий SNI, и все последующие. +В случае получения TLS или QUIC пакета с частичным ClientHello начинается процесс сборки, а пакеты +задерживаются и не отсылаются до ее окончания. По окончании сборки первый пакет проходит через десинхронизацию +на основании полностью собранного ClientHello. Остальные пакеты отсылаются без десинхронизации. +При любой ошибке в процессе сборки задержанные пакеты немедленно отсылаются в сеть, а десинхронизация отменяется. ПОДДЕРЖКА UDP Атаки на udp более ограничены в возможностях. udp нельзя фрагментировать иначе, чем на уровне ip. diff --git a/nfq/conntrack.c b/nfq/conntrack.c index 01368d0..938c2f9 100644 --- a/nfq/conntrack.c +++ b/nfq/conntrack.c @@ -37,6 +37,7 @@ static void ConntrackClearTrack(t_ctrack *track) { ConntrackClearHostname(track); ReasmClear(&track->reasm_orig); + rawpacket_queue_destroy(&track->delayed); } static void ConntrackFreeElem(t_conntrack_pool *elem) @@ -99,19 +100,24 @@ static void ConntrackInitTrack(t_ctrack *t) memset(t,0,sizeof(*t)); t->scale_orig = t->scale_reply = SCALE_NONE; time(&t->t_start); + rawpacket_queue_init(&t->delayed); +} +static void ConntrackReInitTrack(t_ctrack *t) +{ + ConntrackClearTrack(t); + ConntrackInitTrack(t); } - static t_conntrack_pool *ConntrackNew(t_conntrack_pool **pp, const t_conn *c) { - t_conntrack_pool *new; - if (!(new = malloc(sizeof(*new)))) return NULL; - new->conn = *c; + t_conntrack_pool *ctnew; + if (!(ctnew = malloc(sizeof(*ctnew)))) return NULL; + ctnew->conn = *c; oom = false; - HASH_ADD(hh, *pp, conn, sizeof(*c), new); - if (oom) { free(new); return NULL; } - ConntrackInitTrack(&new->track); - return new; + HASH_ADD(hh, *pp, conn, sizeof(*c), ctnew); + if (oom) { free(ctnew); return NULL; } + ConntrackInitTrack(&ctnew->track); + return ctnew; } // non-tcp packets are passed with tcphdr=NULL but len_payload filled @@ -135,13 +141,13 @@ static void ConntrackFeedPacket(t_ctrack *t, bool bReverse, const struct tcphdr { if (tcp_syn_segment(tcphdr)) { - if (t->state!=SYN) ConntrackInitTrack(t); // erase current entry + if (t->state!=SYN) ConntrackReInitTrack(t); // erase current entry t->seq0 = htonl(tcphdr->th_seq); } else if (tcp_synack_segment(tcphdr)) { - if (t->state!=SYN) ConntrackInitTrack(t); // erase current entry - if (!t->seq0) t->seq0 = htonl(tcphdr->th_ack)-1; + if (t->state!=SYN) ConntrackReInitTrack(t); // erase current entry + if (!t->seq0) t->seq0 = htonl(tcphdr->th_ack)-1; t->ack0 = htonl(tcphdr->th_seq); } else if (tcphdr->th_flags & (TH_FIN|TH_RST)) @@ -192,6 +198,35 @@ static void ConntrackFeedPacket(t_ctrack *t, bool bReverse, const struct tcphdr time(&t->t_last); } +static bool ConntrackPoolDoubleSearchPool(t_conntrack_pool **pp, const struct ip *ip, const struct ip6_hdr *ip6, const struct tcphdr *tcphdr, const struct udphdr *udphdr, t_ctrack **ctrack, bool *bReverse) +{ + bool b_rev; + t_conn conn,connswp; + t_conntrack_pool *ctr; + + ConntrackExtractConn(&conn,false,ip,ip6,tcphdr,udphdr); + if ((ctr=ConntrackPoolSearch(*pp,&conn))) + { + if (bReverse) *bReverse = false; + if (ctrack) *ctrack = &ctr->track; + return true; + } + else + { + connswap(&conn,&connswp); + if ((ctr=ConntrackPoolSearch(*pp,&connswp))) + { + if (bReverse) *bReverse = true; + if (ctrack) *ctrack = &ctr->track; + return true; + } + } + return false; +} +bool ConntrackPoolDoubleSearch(t_conntrack *p, const struct ip *ip, const struct ip6_hdr *ip6, const struct tcphdr *tcphdr, const struct udphdr *udphdr, t_ctrack **ctrack, bool *bReverse) +{ + return ConntrackPoolDoubleSearchPool(&p->pool, ip, ip6, tcphdr, udphdr, ctrack, bReverse); +} static bool ConntrackPoolFeedPool(t_conntrack_pool **pp, const struct ip *ip, const struct ip6_hdr *ip6, const struct tcphdr *tcphdr, const struct udphdr *udphdr, size_t len_payload, t_ctrack **ctrack, bool *bReverse) { @@ -343,9 +378,18 @@ bool ReasmInit(t_reassemble *reasm, size_t size_requested, uint32_t seq_start) reasm->seq = seq_start; return true; } +bool ReasmResize(t_reassemble *reasm, size_t new_size) +{ + uint8_t *p = realloc(reasm->packet, new_size); + if (!p) return false; + reasm->packet = p; + reasm->size = new_size; + if (reasm->size_present > new_size) reasm->size_present = new_size; + return true; +} bool ReasmFeed(t_reassemble *reasm, uint32_t seq, const void *payload, size_t len) { - if (reasm->seq!=seq) return false; // fail session if out of sequence + if (seq!=-1 && reasm->seq!=seq) return false; // fail session if out of sequence size_t szcopy; szcopy = reasm->size - reasm->size_present; diff --git a/nfq/conntrack.h b/nfq/conntrack.h index 7e3ed62..7114c99 100644 --- a/nfq/conntrack.h +++ b/nfq/conntrack.h @@ -14,6 +14,8 @@ #include #include +#include "packet_queue.h" + //#define HASH_BLOOM 20 #define HASH_NONFATAL_OOM 1 #undef HASH_FUNCTION @@ -63,7 +65,7 @@ typedef struct uint8_t scale_orig, scale_reply; // last seen window scale factor. SCALE_NONE if none uint8_t req_retrans_counter; // number of request retransmissions - bool req_seq_start_present, req_seq_present; + bool req_seq_present,req_seq_finalized; uint32_t req_seq_start,req_seq_end; // sequence interval of the request (to track retransmissions) uint8_t autottl; @@ -71,10 +73,11 @@ typedef struct bool b_cutoff; // mark for deletion bool b_wssize_cutoff, b_desync_cutoff; - t_reassemble reasm_orig; - t_l7proto l7proto; char *hostname; + + t_reassemble reasm_orig; + struct rawpacket_tailhead delayed; } t_ctrack; typedef struct @@ -94,6 +97,8 @@ typedef struct void ConntrackPoolInit(t_conntrack *p, time_t purge_interval, uint32_t timeout_syn, uint32_t timeout_established, uint32_t timeout_fin, uint32_t timeout_udp); void ConntrackPoolDestroy(t_conntrack *p); bool ConntrackPoolFeed(t_conntrack *p, const struct ip *ip, const struct ip6_hdr *ip6, const struct tcphdr *tcphdr, const struct udphdr *udphdr, size_t len_payload, t_ctrack **ctrack, bool *bReverse); +// do not create, do not update. only find existing +bool ConntrackPoolDoubleSearch(t_conntrack *p, const struct ip *ip, const struct ip6_hdr *ip6, const struct tcphdr *tcphdr, const struct udphdr *udphdr, t_ctrack **ctrack, bool *bReverse); bool ConntrackPoolDrop(t_conntrack *p, const struct ip *ip, const struct ip6_hdr *ip6, const struct tcphdr *tcphdr, const struct udphdr *udphdr); void CaonntrackExtractConn(t_conn *c, bool bReverse, const struct ip *ip, const struct ip6_hdr *ip6, const struct tcphdr *tcphdr, const struct udphdr *udphdr); void ConntrackPoolDump(const t_conntrack *p); @@ -101,6 +106,7 @@ void ConntrackPoolPurge(t_conntrack *p); void ConntrackClearHostname(t_ctrack *track); bool ReasmInit(t_reassemble *reasm, size_t size_requested, uint32_t seq_start); +bool ReasmResize(t_reassemble *reasm, size_t new_size); void ReasmClear(t_reassemble *reasm); // false means reassemble session has failed and we should ReasmClear() it bool ReasmFeed(t_reassemble *reasm, uint32_t seq, const void *payload, size_t len); diff --git a/nfq/darkmagic.c b/nfq/darkmagic.c index f98b2dc..b4d14f0 100644 --- a/nfq/darkmagic.c +++ b/nfq/darkmagic.c @@ -10,7 +10,7 @@ #include #include "helpers.h" - +#include "params.h" uint32_t net32_add(uint32_t netorder_value, uint32_t cpuorder_increment) { @@ -840,6 +840,64 @@ void proto_skip_ipv6(uint8_t **data, size_t *len, uint8_t *proto_type, uint8_t * // we have garbage } +void proto_dissect_l3l4( + uint8_t *data, size_t len, + struct ip **ip, struct ip6_hdr **ip6, + uint8_t *proto, + struct tcphdr **tcp, + struct udphdr **udp, + size_t *transport_len, + uint8_t **data_payload, size_t *len_payload) +{ + *ip = NULL; + *ip6 = NULL; + *proto = 0; + *tcp = NULL; + *transport_len = 0; + *udp = NULL; + *data_payload = NULL; + *len_payload = 0; + + if (proto_check_ipv4(data, len)) + { + *ip = (struct ip *) data; + *proto = (*ip)->ip_p; + proto_skip_ipv4(&data, &len); + } + else if (proto_check_ipv6(data, len)) + { + *ip6 = (struct ip6_hdr *) data; + proto_skip_ipv6(&data, &len, proto, NULL); + } + else + { + return; + } + + if (*proto==IPPROTO_TCP && proto_check_tcp(data, len)) + { + *tcp = (struct tcphdr *) data; + *transport_len = len; + + proto_skip_tcp(&data, &len); + + *data_payload = data; + *len_payload = len; + + } + else if (*proto==IPPROTO_UDP && proto_check_udp(data, len)) + { + *udp = (struct udphdr *) data; + *transport_len = len; + + proto_skip_udp(&data, &len); + + *data_payload = data; + *len_payload = len; + } +} + + bool tcp_synack_segment(const struct tcphdr *tcphdr) { /* check for set bits in TCP hdr */ @@ -1204,6 +1262,20 @@ nofix: return true; } +bool rawsend_rp(const struct rawpacket *rp) +{ + return rawsend((struct sockaddr*)&rp->dst,rp->fwmark,rp->ifout,rp->packet,rp->len); +} +bool rawsend_queue(struct rawpacket_tailhead *q) +{ + struct rawpacket *rp; + bool b; + for (b=true; (rp=rawpacket_dequeue(q)) ; rawpacket_free(rp)) + b &= rawsend_rp(rp); + return b; +} + + // return guessed fake ttl value. 0 means unsuccessfull, should not perform autottl fooling // ttl = TTL of incoming packet uint8_t autottl_guess(uint8_t ttl, const autottl *attl) @@ -1233,3 +1305,27 @@ uint8_t autottl_guess(uint8_t ttl, const autottl *attl) return fake; } + + +void verdict_tcp_csum_fix(uint8_t verdict, struct tcphdr *tcphdr, size_t transport_len, struct ip *ip, struct ip6_hdr *ip6hdr) +{ + #ifdef __FreeBSD__ + // FreeBSD tend to pass ipv6 frames with wrong checksum + if ((verdict & VERDICT_MASK)==VERDICT_MODIFY || ip6hdr) + #else + // if original packet was tampered earlier it needs checksum fixed + if ((verdict & VERDICT_MASK)==VERDICT_MODIFY) + #endif + tcp_fix_checksum(tcphdr,transport_len,ip,ip6hdr); +} +void verdict_udp_csum_fix(uint8_t verdict, struct udphdr *udphdr, size_t transport_len, struct ip *ip, struct ip6_hdr *ip6hdr) +{ + #ifdef __FreeBSD__ + // FreeBSD tend to pass ipv6 frames with wrong checksum + if ((verdict & VERDICT_MASK)==VERDICT_MODIFY || ip6hdr) + #else + // if original packet was tampered earlier it needs checksum fixed + if ((verdict & VERDICT_MASK)==VERDICT_MODIFY) + #endif + udp_fix_checksum(udphdr,transport_len,ip,ip6hdr); +} diff --git a/nfq/darkmagic.h b/nfq/darkmagic.h index c0be6f8..308fb06 100644 --- a/nfq/darkmagic.h +++ b/nfq/darkmagic.h @@ -11,6 +11,8 @@ #include #include +#include "packet_queue.h" + #ifndef IPPROTO_DIVERT #define IPPROTO_DIVERT 258 #endif @@ -39,6 +41,12 @@ uint32_t net16_add(uint16_t netorder_value, uint16_t cpuorder_increment); #define SCALE_NONE ((uint8_t)-1) +#define VERDICT_PASS 0 +#define VERDICT_MODIFY 1 +#define VERDICT_DROP 2 +#define VERDICT_MASK 3 +#define VERDICT_NOCSUM 4 + // seq and wsize have network byte order bool prepare_tcp_segment4( const struct sockaddr_in *src, const struct sockaddr_in *dst, @@ -136,6 +144,9 @@ bool tcp_has_fastopen(const struct tcphdr *tcp); // auto creates internal socket and uses it for subsequent calls bool rawsend(const struct sockaddr* dst,uint32_t fwmark,const char *ifout,const void *data,size_t len); +bool rawsend_rp(const struct rawpacket *rp); +// return trues if all packets were send successfully +bool rawsend_queue(struct rawpacket_tailhead *q); // should pre-do it if dropping privileges. otherwise its not necessary bool rawsend_preinit(bool bind_fix4, bool bind_fix6); // cleans up socket autocreated by rawsend @@ -158,6 +169,14 @@ bool proto_check_tcp(const uint8_t *data, size_t len); void proto_skip_tcp(uint8_t **data, size_t *len); bool proto_check_udp(const uint8_t *data, size_t len); void proto_skip_udp(uint8_t **data, size_t *len); +void proto_dissect_l3l4( + uint8_t *data, size_t len, + struct ip **ip, struct ip6_hdr **ip6, + uint8_t *proto, + struct tcphdr **tcp, + struct udphdr **udp, + size_t *transport_len, + uint8_t **data_payload, size_t *len_payload); bool tcp_synack_segment(const struct tcphdr *tcphdr); bool tcp_syn_segment(const struct tcphdr *tcphdr); @@ -177,3 +196,6 @@ typedef struct #define AUTOTTL_SET_DEFAULT(a) {(a).delta=AUTOTTL_DEFAULT_DELTA; (a).min=AUTOTTL_DEFAULT_MIN; (a).max=AUTOTTL_DEFAULT_MAX;} uint8_t autottl_guess(uint8_t ttl, const autottl *attl); + +void verdict_tcp_csum_fix(uint8_t verdict, struct tcphdr *tcphdr, size_t transport_len, struct ip *ip, struct ip6_hdr *ip6hdr); +void verdict_udp_csum_fix(uint8_t verdict, struct udphdr *udphdr, size_t transport_len, struct ip *ip, struct ip6_hdr *ip6hdr); diff --git a/nfq/desync.c b/nfq/desync.c index e32d38e..b667bfd 100644 --- a/nfq/desync.c +++ b/nfq/desync.c @@ -181,13 +181,12 @@ static bool auto_hostlist_retrans(t_ctrack *ctrack, uint8_t l4proto, int thresho { if (l4proto==IPPROTO_TCP) { - if (!ctrack->req_seq_present) + if (!ctrack->req_seq_finalized) return false; if (!seq_within(ctrack->seq_last, ctrack->req_seq_start, ctrack->req_seq_end)) { DLOG("req retrans : tcp seq %u not within the req range %u-%u. stop tracking.\n", ctrack->seq_last, ctrack->req_seq_start, ctrack->req_seq_end); ctrack_stop_retrans_counter(ctrack); - ctrack->req_seq_present = false; return false; } } @@ -259,6 +258,17 @@ static void process_retrans_fail(t_ctrack *ctrack, uint8_t proto) } } +static bool send_delayed(t_ctrack *ctrack) +{ + if (!rawpacket_queue_empty(&ctrack->delayed)) + { + DLOG("SENDING %u delayed packets\n", rawpacket_queue_count(&ctrack->delayed)) + return rawsend_queue(&ctrack->delayed); + } + return true; +} + + static bool reasm_start(t_ctrack *ctrack, t_reassemble *reasm, size_t sz, size_t szMax, const uint8_t *data_payload, size_t len_payload) { ReasmClear(reasm); @@ -267,7 +277,7 @@ static bool reasm_start(t_ctrack *ctrack, t_reassemble *reasm, size_t sz, size_t if (ReasmInit(reasm,sz,ctrack->seq_last)) { ReasmFeed(reasm,ctrack->seq_last,data_payload,len_payload); - DLOG("starting reassemble. now we have %zu/%zu\n",reasm->size_present,reasm->size); + DLOG(reasm->size_present==reasm->size ? "starting reassemble. now we have %zu\n" : "starting reassemble. now we have %zu/%zu\n",reasm->size_present,reasm->size); return true; } else @@ -281,26 +291,27 @@ static bool reasm_orig_start(t_ctrack *ctrack, size_t sz, size_t szMax, const ui { return reasm_start(ctrack,&ctrack->reasm_orig,sz,szMax,data_payload,len_payload); } -static bool reasm_feed(t_ctrack *ctrack, t_reassemble *reasm, const uint8_t *data_payload, size_t len_payload) +static bool reasm_feed(t_ctrack *ctrack, t_reassemble *reasm, uint8_t proto, const uint8_t *data_payload, size_t len_payload) { if (ctrack && !ReasmIsEmpty(reasm)) { - if (ReasmFeed(reasm,ctrack->seq_last,data_payload,len_payload)) + if (ReasmFeed(reasm,proto==IPPROTO_TCP ? ctrack->seq_last : -1,data_payload,len_payload)) { - DLOG("reassemble : feeding data payload size=%zu. now we have %zu/%zu\n",len_payload,reasm->size_present,reasm->size) + DLOG(reasm->size_present==reasm->size ? "reassemble : feeding data payload size=%zu. now we have %zu\n" : "reassemble : feeding data payload size=%zu. now we have %zu/%zu\n", len_payload,reasm->size_present,reasm->size) return true; } else { ReasmClear(reasm); DLOG("reassemble session failed\n") + send_delayed(ctrack); } } return false; } -static bool reasm_orig_feed(t_ctrack *ctrack, const uint8_t *data_payload, size_t len_payload) +static bool reasm_orig_feed(t_ctrack *ctrack, uint8_t proto, const uint8_t *data_payload, size_t len_payload) { - return reasm_feed(ctrack, &ctrack->reasm_orig, data_payload, len_payload); + return reasm_feed(ctrack, &ctrack->reasm_orig, proto, data_payload, len_payload); } static void reasm_orig_fin(t_ctrack *ctrack) { @@ -308,6 +319,19 @@ static void reasm_orig_fin(t_ctrack *ctrack) { DLOG("reassemble session finished\n"); ReasmClear(&ctrack->reasm_orig); + send_delayed(ctrack); + } +} +static void reasm_orig_cancel(t_ctrack *ctrack) +{ + if (ctrack) + { + if (!ReasmIsEmpty(&ctrack->reasm_orig)) + { + DLOG("reassemble session cancelled\n"); + ReasmClear(&ctrack->reasm_orig); + } + send_delayed(ctrack); } } @@ -399,119 +423,149 @@ static bool check_desync_interval(const t_ctrack *ctrack) } return true; } - - -// result : true - drop original packet, false = dont drop -uint8_t dpi_desync_tcp_packet(uint32_t fwmark, const char *ifout, uint8_t *data_pkt, size_t *len_pkt, struct ip *ip, struct ip6_hdr *ip6hdr, struct tcphdr *tcphdr, size_t len_tcp, uint8_t *data_payload, size_t len_payload) +static bool process_desync_interval(t_ctrack *ctrack) { - uint8_t res=VERDICT_PASS; + if (check_desync_interval(ctrack)) + return true; + else + { + reasm_orig_cancel(ctrack); + return false; + } +} + +static bool replay_queue(struct rawpacket_tailhead *q); + +static uint8_t dpi_desync_tcp_packet_play(bool replay, uint32_t fwmark, const char *ifout, uint8_t *data_pkt, size_t *len_pkt, struct ip *ip, struct ip6_hdr *ip6hdr, struct tcphdr *tcphdr, size_t transport_len, uint8_t *data_payload, size_t len_payload) +{ + uint8_t verdict=VERDICT_PASS; + t_ctrack *ctrack=NULL; + const t_reassemble *reasm_replay=NULL; bool bReverse=false; struct sockaddr_storage src, dst; uint8_t pkt1[DPI_DESYNC_MAX_FAKE_LEN+100], pkt2[DPI_DESYNC_MAX_FAKE_LEN+100]; size_t pkt1_len, pkt2_len; - uint8_t ttl_orig,ttl_fake,flags_orig,scale_factor; + uint8_t ttl_orig,ttl_fake,ttl_auto=0,flags_orig,scale_factor; uint32_t *timestamps; - if (!!ip == !!ip6hdr) return res; // one and only one must be present ttl_orig = ip ? ip->ip_ttl : ip6hdr->ip6_ctlun.ip6_un1.ip6_un1_hlim; + uint32_t desync_fwmark = fwmark | params.desync_fwmark; - ConntrackPoolPurge(¶ms.conntrack); - if (ConntrackPoolFeed(¶ms.conntrack, ip, ip6hdr, tcphdr, NULL, len_payload, &ctrack, &bReverse)) - maybe_cutoff(ctrack, IPPROTO_TCP); - HostFailPoolPurgeRateLimited(¶ms.hostlist_auto_fail_counters); - - //ConntrackPoolDump(¶ms.conntrack); - - if (params.wsize && tcp_synack_segment(tcphdr)) + if (replay) { - tcp_rewrite_winsize(tcphdr, params.wsize, params.wscale); - res=VERDICT_MODIFY; - } - - if (bReverse) - { - if (ctrack && !ctrack->autottl && ctrack->pcounter_reply==1) + t_ctrack *ctrack; + bool bReverse; + //ConntrackPoolDump(¶ms.conntrack); + if (ConntrackPoolDoubleSearch(¶ms.conntrack, ip, ip6hdr, tcphdr, NULL, &ctrack, &bReverse) && !bReverse) { - autottl *attl = ip ? ¶ms.desync_autottl : ¶ms.desync_autottl6; - if (AUTOTTL_ENABLED(*attl)) - { - ctrack->autottl = autottl_guess(ttl_orig, attl); - if (ctrack->autottl) - DLOG("autottl: guessed %u\n",ctrack->autottl) - else - DLOG("autottl: could not guess\n") - } + reasm_replay = &ctrack->reasm_orig; + ttl_auto = ctrack->autottl; } - - // process reply packets for auto hostlist mode - // by looking at RSTs or HTTP replies we decide whether original request looks like DPI blocked - // we only process first-sequence replies. do not react to subsequent redirects or RSTs - if (*params.hostlist_auto_filename && ctrack && ctrack->hostname && (ctrack->ack_last-ctrack->ack0)==1) + else + return verdict; + } + else + { + ConntrackPoolPurge(¶ms.conntrack); + if (ConntrackPoolFeed(¶ms.conntrack, ip, ip6hdr, tcphdr, NULL, len_payload, &ctrack, &bReverse)) { - bool bFail=false; - if (tcphdr->th_flags & TH_RST) + maybe_cutoff(ctrack, IPPROTO_TCP); + ttl_auto = ctrack->autottl; + } + HostFailPoolPurgeRateLimited(¶ms.hostlist_auto_fail_counters); + + //ConntrackPoolDump(¶ms.conntrack); + + if (params.wsize && tcp_synack_segment(tcphdr)) + { + tcp_rewrite_winsize(tcphdr, params.wsize, params.wscale); + verdict=VERDICT_MODIFY; + } + + if (bReverse) + { + if (ctrack && !ctrack->autottl && ctrack->pcounter_reply==1) { - DLOG("incoming RST detected for hostname %s\n", ctrack->hostname); - HOSTLIST_DEBUGLOG_APPEND("%s : incoming RST", ctrack->hostname); - bFail = true; - } - else if (len_payload && ctrack->l7proto==HTTP) - { - if (IsHttpReply(data_payload,len_payload)) + autottl *attl = ip ? ¶ms.desync_autottl : ¶ms.desync_autottl6; + if (AUTOTTL_ENABLED(*attl)) { - DLOG("incoming HTTP reply detected for hostname %s\n", ctrack->hostname); - bFail = HttpReplyLooksLikeDPIRedirect(data_payload, len_payload, ctrack->hostname); - if (bFail) + ctrack->autottl = autottl_guess(ttl_orig, attl); + if (ctrack->autottl) + DLOG("autottl: guessed %u\n",ctrack->autottl) + else + DLOG("autottl: could not guess\n") + } + } + + // process reply packets for auto hostlist mode + // by looking at RSTs or HTTP replies we decide whether original request looks like DPI blocked + // we only process first-sequence replies. do not react to subsequent redirects or RSTs + if (*params.hostlist_auto_filename && ctrack && ctrack->hostname && (ctrack->ack_last-ctrack->ack0)==1) + { + bool bFail=false; + if (tcphdr->th_flags & TH_RST) + { + DLOG("incoming RST detected for hostname %s\n", ctrack->hostname); + HOSTLIST_DEBUGLOG_APPEND("%s : incoming RST", ctrack->hostname); + bFail = true; + } + else if (len_payload && ctrack->l7proto==HTTP) + { + if (IsHttpReply(data_payload,len_payload)) { - DLOG("redirect to another domain detected. possibly DPI redirect.\n") - HOSTLIST_DEBUGLOG_APPEND("%s : redirect to another domain", ctrack->hostname); + DLOG("incoming HTTP reply detected for hostname %s\n", ctrack->hostname); + bFail = HttpReplyLooksLikeDPIRedirect(data_payload, len_payload, ctrack->hostname); + if (bFail) + { + DLOG("redirect to another domain detected. possibly DPI redirect.\n") + HOSTLIST_DEBUGLOG_APPEND("%s : redirect to another domain", ctrack->hostname); + } + else + DLOG("local or in-domain redirect detected. it's not a DPI redirect.\n") } else - DLOG("local or in-domain redirect detected. it's not a DPI redirect.\n") + { + // received not http reply. do not monitor this connection anymore + DLOG("incoming unknown HTTP data detected for hostname %s\n", ctrack->hostname); + } + } + if (bFail) + auto_hostlist_failed(ctrack->hostname); + if (tcphdr->th_flags & TH_RST) + ConntrackClearHostname(ctrack); // do not react to further dup RSTs + } + + return verdict; // nothing to do. do not waste cpu + } + + + if (params.wssize) + { + if (ctrack) + { + if (ctrack->b_wssize_cutoff) + { + DLOG("not changing wssize. wssize-cutoff reached\n"); } else { - // received not http reply. do not monitor this connection anymore - DLOG("incoming unknown HTTP data detected for hostname %s\n", ctrack->hostname); + if (params.wssize_cutoff) DLOG("wssize-cutoff not reached (mode %c): %llu/%u\n", params.wssize_cutoff_mode, (unsigned long long)cutoff_get_limit(ctrack,params.wssize_cutoff_mode), params.wssize_cutoff); + tcp_rewrite_winsize(tcphdr, params.wssize, params.wsscale); + verdict=VERDICT_MODIFY; } } - if (bFail) - auto_hostlist_failed(ctrack->hostname); - if (tcphdr->th_flags & TH_RST) - ConntrackClearHostname(ctrack); // do not react to further dup RSTs - } - - return res; // nothing to do. do not waste cpu - } - - uint32_t desync_fwmark = fwmark | params.desync_fwmark; - - if (params.wssize) - { - if (ctrack) - { - if (ctrack->b_wssize_cutoff) - { - DLOG("not changing wssize. wssize-cutoff reached\n"); - } else { - if (params.wssize_cutoff) DLOG("wssize-cutoff not reached (mode %c): %llu/%u\n", params.wssize_cutoff_mode, (unsigned long long)cutoff_get_limit(ctrack,params.wssize_cutoff_mode), params.wssize_cutoff); - tcp_rewrite_winsize(tcphdr, params.wssize, params.wsscale); - res=VERDICT_MODIFY; + DLOG("not changing wssize. wssize is set but conntrack entry is missing\n"); } } - else - { - DLOG("not changing wssize. wssize is set but conntrack entry is missing\n"); - } - } + } // !replay if (params.desync_mode0!=DESYNC_NONE || params.desync_mode!=DESYNC_NONE) // save some cpu { - ttl_fake = (ctrack && ctrack->autottl) ? ctrack->autottl : (ip6hdr ? (params.desync_ttl6 ? params.desync_ttl6 : ttl_orig) : (params.desync_ttl ? params.desync_ttl : ttl_orig)); + ttl_fake = ttl_auto ? ttl_auto : (ip6hdr ? (params.desync_ttl6 ? params.desync_ttl6 : ttl_orig) : (params.desync_ttl ? params.desync_ttl : ttl_orig)); flags_orig = *((uint8_t*)tcphdr+13); scale_factor = tcp_find_scale_factor(tcphdr); timestamps = tcp_find_timestamps(tcphdr); @@ -519,57 +573,59 @@ uint8_t dpi_desync_tcp_packet(uint32_t fwmark, const char *ifout, uint8_t *data_ extract_endpoints(ip, ip6hdr, tcphdr, NULL, &src, &dst); } - if (tcp_syn_segment(tcphdr)) + if (!replay) { - switch (params.desync_mode0) + if (tcp_syn_segment(tcphdr)) { - case DESYNC_SYNACK: - pkt1_len = sizeof(pkt1); - if (!prepare_tcp_segment((struct sockaddr *)&src, (struct sockaddr *)&dst, TH_SYN|TH_ACK, tcphdr->th_seq, tcphdr->th_ack, tcphdr->th_win, scale_factor, timestamps, - ttl_fake,params.desync_fooling_mode,params.desync_badseq_increment,params.desync_badseq_ack_increment, - NULL, 0, pkt1, &pkt1_len)) - { - return res; - } - DLOG("sending fake SYNACK\n"); - if (!rawsend_rep((struct sockaddr *)&dst, desync_fwmark, ifout , pkt1, pkt1_len)) - return res; - break; - case DESYNC_SYNDATA: - // make sure we are not breaking TCP fast open - if (tcp_has_fastopen(tcphdr)) - { - DLOG("received SYN with TCP fast open option. syndata desync is not applied.\n"); + switch (params.desync_mode0) + { + case DESYNC_SYNACK: + pkt1_len = sizeof(pkt1); + if (!prepare_tcp_segment((struct sockaddr *)&src, (struct sockaddr *)&dst, TH_SYN|TH_ACK, tcphdr->th_seq, tcphdr->th_ack, tcphdr->th_win, scale_factor, timestamps, + ttl_fake,params.desync_fooling_mode,params.desync_badseq_increment,params.desync_badseq_ack_increment, + NULL, 0, pkt1, &pkt1_len)) + { + return verdict; + } + DLOG("sending fake SYNACK\n"); + if (!rawsend_rep((struct sockaddr *)&dst, desync_fwmark, ifout , pkt1, pkt1_len)) + return verdict; break; - } - if (len_payload) - { - DLOG("received SYN with data payload. syndata desync is not applied.\n"); + case DESYNC_SYNDATA: + // make sure we are not breaking TCP fast open + if (tcp_has_fastopen(tcphdr)) + { + DLOG("received SYN with TCP fast open option. syndata desync is not applied.\n"); + break; + } + if (len_payload) + { + DLOG("received SYN with data payload. syndata desync is not applied.\n"); + break; + } + pkt1_len = sizeof(pkt1); + if (!prepare_tcp_segment((struct sockaddr *)&src, (struct sockaddr *)&dst, flags_orig, tcphdr->th_seq, tcphdr->th_ack, tcphdr->th_win, scale_factor, timestamps, + ttl_orig,0,0,0, params.fake_syndata,params.fake_syndata_size, pkt1,&pkt1_len)) + { + return verdict; + } + DLOG("sending SYN with fake data : "); + hexdump_limited_dlog(params.fake_syndata,params.fake_syndata_size,PKTDATA_MAXDUMP); DLOG("\n") + if (!rawsend_rep((struct sockaddr *)&dst, desync_fwmark, ifout , pkt1, pkt1_len)) + return verdict; + verdict = ct_new_postnat_fix_tcp(ctrack, ip, ip6hdr, tcphdr); break; - } - pkt1_len = sizeof(pkt1); - if (!prepare_tcp_segment((struct sockaddr *)&src, (struct sockaddr *)&dst, flags_orig, tcphdr->th_seq, tcphdr->th_ack, tcphdr->th_win, scale_factor, timestamps, - ttl_orig,0,0,0, params.fake_syndata,params.fake_syndata_size, pkt1,&pkt1_len)) - { - return res; - } - DLOG("sending SYN with fake data : "); - hexdump_limited_dlog(params.fake_syndata,params.fake_syndata_size,PKTDATA_MAXDUMP); DLOG("\n") - if (!rawsend_rep((struct sockaddr *)&dst, desync_fwmark, ifout , pkt1, pkt1_len)) - return res; - - res = ct_new_postnat_fix_tcp(ctrack, ip, ip6hdr, tcphdr); - break; + } + // can do nothing else with SYN packet + return verdict; } - // can do nothing else with SYN packet - return res; - } - - if (!params.wssize && params.desync_mode==DESYNC_NONE && !params.hostcase && !params.hostnospace && !params.domcase && !*params.hostlist_auto_filename) return res; // nothing to do. do not waste cpu - - // start and cutoff limiters - if (!check_desync_interval(ctrack)) return res; + // start and cutoff limiters + if (!process_desync_interval(ctrack)) return verdict; + } // !replay + + if (!params.wssize && params.desync_mode==DESYNC_NONE && !params.hostcase && !params.hostnospace && !params.domcase && !*params.hostlist_auto_filename) return verdict; // nothing to do. do not waste cpu + if (!(tcphdr->th_flags & TH_SYN) && len_payload) { const uint8_t *fake; @@ -582,12 +638,19 @@ uint8_t dpi_desync_tcp_packet(uint32_t fwmark, const char *ifout, uint8_t *data_ const uint8_t *rdata_payload = data_payload; size_t rlen_payload = len_payload; - if (reasm_orig_feed(ctrack,data_payload,len_payload)) + if (reasm_replay) + { + rdata_payload = reasm_replay->packet; + rlen_payload = reasm_replay->size_present; + } + else if (reasm_orig_feed(ctrack,IPPROTO_TCP,data_payload,len_payload)) { rdata_payload = ctrack->reasm_orig.packet; rlen_payload = ctrack->reasm_orig.size_present; } + process_retrans_fail(ctrack, IPPROTO_TCP); + if ((bIsHttp = IsHttp(rdata_payload,rlen_payload))) { DLOG("packet contains HTTP request\n") @@ -601,9 +664,8 @@ uint8_t dpi_desync_tcp_packet(uint32_t fwmark, const char *ifout, uint8_t *data_ if (!bHaveHost) { DLOG("not applying tampering to HTTP without Host:\n") - process_retrans_fail(ctrack, IPPROTO_TCP); reasm_orig_fin(ctrack); - return res; + return verdict; } } if (ctrack) @@ -613,7 +675,7 @@ uint8_t dpi_desync_tcp_packet(uint32_t fwmark, const char *ifout, uint8_t *data_ { ctrack->req_seq_start=ctrack->seq_last; ctrack->req_seq_end=ctrack->pos_orig-1; - ctrack->req_seq_start_present=ctrack->req_seq_present=true; + ctrack->req_seq_present=ctrack->req_seq_finalized=true; DLOG("req retrans : tcp seq interval %u-%u\n",ctrack->req_seq_start,ctrack->req_seq_end); } } @@ -623,38 +685,73 @@ uint8_t dpi_desync_tcp_packet(uint32_t fwmark, const char *ifout, uint8_t *data_ { bool bReqFull = IsTLSRecordFull(rdata_payload,rlen_payload); DLOG(bReqFull ? "packet contains full TLS ClientHello\n" : "packet contains partial TLS ClientHello\n") - fake = params.fake_tls; - fake_size = params.fake_tls_size; + bHaveHost=TLSHelloExtractHost(rdata_payload,rlen_payload,host,sizeof(host),TLS_PARTIALS_ENABLE); + if (ctrack) { if (!ctrack->l7proto) ctrack->l7proto = TLS; - if (!bReqFull && ReasmIsEmpty(&ctrack->reasm_orig)) + // do not reasm retransmissions + if (!bReqFull && ReasmIsEmpty(&ctrack->reasm_orig) && + !(ctrack->req_seq_finalized && seq_within(ctrack->seq_last, ctrack->req_seq_start, ctrack->req_seq_end))) + { // do not reconstruct unexpected large payload (they are feeding garbage ?) - reasm_orig_start(ctrack,TLSRecordLen(data_payload),4096,data_payload,len_payload); - if (!ctrack->req_seq_start_present) - { - // lower bound of request seq interval - ctrack->req_seq_start=ctrack->seq_last; - ctrack->req_seq_start_present=true; + if (!reasm_orig_start(ctrack,TLSRecordLen(data_payload),16384,data_payload,len_payload)) + { + fprintf(stderr, "reasm start failed ! out of memory.\n"); + reasm_orig_cancel(ctrack); + return verdict; + } + } - if (!ctrack->req_seq_present && bReqFull) + if (!ctrack->req_seq_finalized) { + if (!ctrack->req_seq_present) + { + // lower bound of request seq interval + ctrack->req_seq_start=ctrack->seq_last; + ctrack->req_seq_present=true; + } // upper bound of request seq interval + // it can grow on every packet until request is complete. then interval is finalized and never touched again. ctrack->req_seq_end=ctrack->pos_orig-1; - ctrack->req_seq_present=ctrack->req_seq_start_present; DLOG("req retrans : seq interval %u-%u\n",ctrack->req_seq_start,ctrack->req_seq_end); + ctrack->req_seq_finalized |= bReqFull; + } + if (bReqFull || ReasmIsEmpty(&ctrack->reasm_orig)) forced_wssize_cutoff(ctrack); + + if (!ReasmIsEmpty(&ctrack->reasm_orig)) + { + verdict_tcp_csum_fix(verdict, tcphdr, transport_len, ip, ip6hdr); + if (rawpacket_queue(&ctrack->delayed, &dst, desync_fwmark, ifout, data_pkt, *len_pkt)) + { + DLOG("DELAY desync until reasm is complete (%u)\n", rawpacket_queue_count(&ctrack->delayed)); + } + else + { + fprintf(stderr, "rawpacket_queue failed !'\n"); + reasm_orig_cancel(ctrack); + return verdict; + } + if (ReasmIsFull(&ctrack->reasm_orig)) + { + replay_queue(&ctrack->delayed); + reasm_orig_fin(ctrack); + } + if (!ctrack->hostname && bHaveHost) ctrack->hostname=strdup(host); + return VERDICT_DROP; } } - if (bReqFull || !ctrack || ReasmIsEmpty(&ctrack->reasm_orig)) forced_wssize_cutoff(ctrack); if (params.desync_skip_nosni && !bHaveHost) { DLOG("not applying tampering to TLS ClientHello without hostname in the SNI\n") - process_retrans_fail(ctrack, IPPROTO_TCP); reasm_orig_fin(ctrack); - return res; + return verdict; } + + fake = params.fake_tls; + fake_size = params.fake_tls_size; bKnownProtocol = true; } @@ -673,20 +770,18 @@ uint8_t dpi_desync_tcp_packet(uint32_t fwmark, const char *ifout, uint8_t *data_ if (!bExcluded && *params.hostlist_auto_filename) { if (!ctrack->hostname) ctrack->hostname=strdup(host); - process_retrans_fail(ctrack, IPPROTO_TCP); } else ctrack_stop_retrans_counter(ctrack); } - return res; + return verdict; } ctrack_stop_retrans_counter(ctrack); } - process_retrans_fail(ctrack, IPPROTO_TCP); if (!bKnownProtocol) { - if (!params.desync_any_proto) return res; + if (!params.desync_any_proto) return verdict; DLOG("applying tampering to unknown protocol\n") fake = params.fake_unknown; fake_size = params.fake_unknown_size; @@ -698,14 +793,14 @@ uint8_t dpi_desync_tcp_packet(uint32_t fwmark, const char *ifout, uint8_t *data_ { DLOG("modifying Host: => %c%c%c%c:\n", params.hostspell[0], params.hostspell[1], params.hostspell[2], params.hostspell[3]) memcpy(phost + 2, params.hostspell, 4); - res=VERDICT_MODIFY; + verdict=VERDICT_MODIFY; } if (params.domcase) { DLOG("mixing domain case\n"); for (p = phost+7; p < (data_payload + len_payload) && *p != '\r' && *p != '\n'; p++) *p = (((size_t)p) & 1) ? tolower(*p) : toupper(*p); - res=VERDICT_MODIFY; + verdict=VERDICT_MODIFY; } uint8_t *pua; if (params.hostnospace && @@ -723,11 +818,11 @@ uint8_t dpi_desync_tcp_packet(uint32_t fwmark, const char *ifout, uint8_t *data_ memmove(pua + 1, pua, phost - pua + 7); *pua = ' '; } - res=VERDICT_MODIFY; + verdict=VERDICT_MODIFY; } } - if (params.desync_mode==DESYNC_NONE) return res; + if (params.desync_mode==DESYNC_NONE) return verdict; if (params.debug) { @@ -758,7 +853,7 @@ uint8_t dpi_desync_tcp_packet(uint32_t fwmark, const char *ifout, uint8_t *data_ ttl_fake,params.desync_fooling_mode,params.desync_badseq_increment,params.desync_badseq_ack_increment, fake, fake_size, pkt1, &pkt1_len)) { - return res; + return verdict; } DLOG("sending fake request : "); hexdump_limited_dlog(fake,fake_size,PKTDATA_MAXDUMP); DLOG("\n") @@ -770,7 +865,7 @@ uint8_t dpi_desync_tcp_packet(uint32_t fwmark, const char *ifout, uint8_t *data_ ttl_fake,params.desync_fooling_mode,params.desync_badseq_increment,params.desync_badseq_ack_increment, NULL, 0, pkt1, &pkt1_len)) { - return res; + return verdict; } DLOG("sending fake RST/RSTACK\n"); b = true; @@ -785,11 +880,11 @@ uint8_t dpi_desync_tcp_packet(uint32_t fwmark, const char *ifout, uint8_t *data_ ttl_orig,fooling_orig,0,0, data_payload, len_payload, pkt1, &pkt1_len)) { - return res; + return verdict; } DLOG("resending original packet with extension header\n"); if (!rawsend((struct sockaddr *)&dst, desync_fwmark, ifout , pkt1, pkt1_len)) - return res; + return verdict; // this mode is final, no other options available return VERDICT_DROP; } @@ -799,28 +894,14 @@ uint8_t dpi_desync_tcp_packet(uint32_t fwmark, const char *ifout, uint8_t *data_ if (b) { if (!rawsend_rep((struct sockaddr *)&dst, desync_fwmark, ifout , pkt1, pkt1_len)) - return res; + return verdict; if (params.desync_mode2==DESYNC_NONE || !desync_valid_second_stage_tcp(params.desync_mode2)) { - if (params.desync_retrans) - { - DLOG("dropping original packet to force retransmission. len=%zu len_payload=%zu\n", *len_pkt, len_payload) - } - else - { - DLOG("reinjecting original packet. len=%zu len_payload=%zu\n", *len_pkt, len_payload) - #ifdef __FreeBSD__ - // FreeBSD tend to pass ipv6 frames with wrong checksum - if ((res & VERDICT_MASK)==VERDICT_MODIFY || ip6hdr) - #else - // if original packet was tampered earlier it needs checksum fixed - if ((res & VERDICT_MASK)==VERDICT_MODIFY) - #endif - tcp_fix_checksum(tcphdr,len_tcp,ip,ip6hdr); - if (!rawsend((struct sockaddr *)&dst, desync_fwmark, ifout , data_pkt, *len_pkt)) - return res; - } - return VERDICT_DROP; + DLOG("reinjecting original packet. len=%zu len_payload=%zu\n", *len_pkt, len_payload) + verdict_tcp_csum_fix(verdict, tcphdr, transport_len, ip, ip6hdr); + if (!rawsend((struct sockaddr *)&dst, desync_fwmark, ifout , data_pkt, *len_pkt)) + return verdict; + return VERDICT_DROP; } desync_mode = params.desync_mode2; } @@ -840,11 +921,11 @@ uint8_t dpi_desync_tcp_packet(uint32_t fwmark, const char *ifout, uint8_t *data_ if (!prepare_tcp_segment((struct sockaddr *)&src, (struct sockaddr *)&dst, flags_orig, net32_add(tcphdr->th_seq,split_pos), tcphdr->th_ack, tcphdr->th_win, scale_factor, timestamps, ttl_orig,fooling_orig,params.desync_badseq_increment,params.desync_badseq_ack_increment, data_payload+split_pos, len_payload-split_pos, pkt1, &pkt1_len)) - return res; + return verdict; DLOG("sending 2nd out-of-order tcp segment %zu-%zu len=%zu : ",split_pos,len_payload-1, len_payload-split_pos) hexdump_limited_dlog(data_payload+split_pos,len_payload-split_pos,PKTDATA_MAXDUMP); DLOG("\n") if (!rawsend((struct sockaddr *)&dst, desync_fwmark, ifout , pkt1, pkt1_len)) - return res; + return verdict; } @@ -854,11 +935,11 @@ uint8_t dpi_desync_tcp_packet(uint32_t fwmark, const char *ifout, uint8_t *data_ if (!prepare_tcp_segment((struct sockaddr *)&src, (struct sockaddr *)&dst, flags_orig, tcphdr->th_seq, tcphdr->th_ack, tcphdr->th_win, scale_factor, timestamps, ttl_fake,params.desync_fooling_mode,params.desync_badseq_increment,params.desync_badseq_ack_increment, zeropkt, split_pos, fakeseg, &fakeseg_len)) - return res; + return verdict; DLOG("sending fake(1) 1st out-of-order tcp segment 0-%zu len=%zu : ",split_pos-1, split_pos) hexdump_limited_dlog(zeropkt,split_pos,PKTDATA_MAXDUMP); DLOG("\n") if (!rawsend_rep((struct sockaddr *)&dst, desync_fwmark, ifout , fakeseg, fakeseg_len)) - return res; + return verdict; } @@ -866,18 +947,18 @@ uint8_t dpi_desync_tcp_packet(uint32_t fwmark, const char *ifout, uint8_t *data_ if (!prepare_tcp_segment((struct sockaddr *)&src, (struct sockaddr *)&dst, flags_orig, tcphdr->th_seq, tcphdr->th_ack, tcphdr->th_win, scale_factor, timestamps, ttl_orig,fooling_orig,params.desync_badseq_increment,params.desync_badseq_ack_increment, data_payload, split_pos, pkt1, &pkt1_len)) - return res; + return verdict; DLOG("sending 1st out-of-order tcp segment 0-%zu len=%zu : ",split_pos-1, split_pos) hexdump_limited_dlog(data_payload,split_pos,PKTDATA_MAXDUMP); DLOG("\n") if (!rawsend((struct sockaddr *)&dst, desync_fwmark, ifout , pkt1, pkt1_len)) - return res; + return verdict; if (desync_mode==DESYNC_DISORDER) { DLOG("sending fake(2) 1st out-of-order tcp segment 0-%zu len=%zu : ",split_pos-1, split_pos) hexdump_limited_dlog(zeropkt,split_pos,PKTDATA_MAXDUMP); DLOG("\n") if (!rawsend_rep((struct sockaddr *)&dst, desync_fwmark, ifout , fakeseg, fakeseg_len)) - return res; + return verdict; } return VERDICT_DROP; @@ -895,29 +976,29 @@ uint8_t dpi_desync_tcp_packet(uint32_t fwmark, const char *ifout, uint8_t *data_ if (!prepare_tcp_segment((struct sockaddr *)&src, (struct sockaddr *)&dst, flags_orig, tcphdr->th_seq, tcphdr->th_ack, tcphdr->th_win, scale_factor, timestamps, ttl_fake,params.desync_fooling_mode,params.desync_badseq_increment,params.desync_badseq_ack_increment, zeropkt, split_pos, fakeseg, &fakeseg_len)) - return res; + return verdict; DLOG("sending fake(1) 1st tcp segment 0-%zu len=%zu : ",split_pos-1, split_pos) hexdump_limited_dlog(zeropkt,split_pos,PKTDATA_MAXDUMP); DLOG("\n") if (!rawsend_rep((struct sockaddr *)&dst, desync_fwmark, ifout , fakeseg, fakeseg_len)) - return res; + return verdict; } pkt1_len = sizeof(pkt1); if (!prepare_tcp_segment((struct sockaddr *)&src, (struct sockaddr *)&dst, flags_orig, tcphdr->th_seq, tcphdr->th_ack, tcphdr->th_win, scale_factor, timestamps, ttl_orig,fooling_orig,params.desync_badseq_increment,params.desync_badseq_ack_increment, data_payload, split_pos, pkt1, &pkt1_len)) - return res; + return verdict; DLOG("sending 1st tcp segment 0-%zu len=%zu : ",split_pos-1, split_pos) hexdump_limited_dlog(data_payload,split_pos,PKTDATA_MAXDUMP); DLOG("\n") if (!rawsend((struct sockaddr *)&dst, desync_fwmark, ifout , pkt1, pkt1_len)) - return res; + return verdict; if (desync_mode==DESYNC_SPLIT) { DLOG("sending fake(2) 1st tcp segment 0-%zu len=%zu : ",split_pos-1, split_pos) hexdump_limited_dlog(zeropkt,split_pos,PKTDATA_MAXDUMP); DLOG("\n") if (!rawsend_rep((struct sockaddr *)&dst, desync_fwmark, ifout , fakeseg, fakeseg_len)) - return res; + return verdict; } if (split_posth_seq,split_pos), tcphdr->th_ack, tcphdr->th_win, scale_factor, timestamps, ttl_orig,fooling_orig,params.desync_badseq_increment,params.desync_badseq_ack_increment, data_payload+split_pos, len_payload-split_pos, pkt1, &pkt1_len)) - return res; + return verdict; DLOG("sending 2nd tcp segment %zu-%zu len=%zu : ",split_pos,len_payload-1, len_payload-split_pos) hexdump_limited_dlog(data_payload+split_pos,len_payload-split_pos,PKTDATA_MAXDUMP); DLOG("\n") if (!rawsend((struct sockaddr *)&dst, desync_fwmark, ifout , pkt1, pkt1_len)) - return res; + return verdict; } return VERDICT_DROP; @@ -938,19 +1019,12 @@ uint8_t dpi_desync_tcp_packet(uint32_t fwmark, const char *ifout, uint8_t *data_ break; case DESYNC_IPFRAG2: { - #ifdef __FreeBSD__ - // FreeBSD tend to pass ipv6 frames with wrong checksum - if ((res & VERDICT_MASK)==VERDICT_MODIFY || ip6hdr) - #else - // if original packet was tampered earlier it needs checksum fixed - if ((res & VERDICT_MASK)==VERDICT_MODIFY) - #endif - tcp_fix_checksum(tcphdr,len_tcp,ip,ip6hdr); + verdict_tcp_csum_fix(verdict, tcphdr, transport_len, ip, ip6hdr); uint8_t pkt3[DPI_DESYNC_MAX_FAKE_LEN+100], *pkt_orig; size_t pkt_orig_len; - size_t ipfrag_pos = (params.desync_ipfrag_pos_tcp && params.desync_ipfrag_pos_tcpip_id ? ip->ip_id : htons(1+random()%0xFFFF) : htonl(1+random()%0xFFFFFFFF); pkt1_len = sizeof(pkt1); @@ -960,7 +1034,7 @@ uint8_t dpi_desync_tcp_packet(uint32_t fwmark, const char *ifout, uint8_t *data_ { pkt_orig_len = sizeof(pkt3); if (!ip6_insert_simple_hdr(fooling_orig==FOOL_HOPBYHOP ? IPPROTO_HOPOPTS : IPPROTO_DSTOPTS, data_pkt, *len_pkt, pkt3, &pkt_orig_len)) - return res; + return verdict; pkt_orig = pkt3; } else @@ -970,17 +1044,17 @@ uint8_t dpi_desync_tcp_packet(uint32_t fwmark, const char *ifout, uint8_t *data_ } if (!ip_frag(pkt_orig, pkt_orig_len, ipfrag_pos, ident, pkt1, &pkt1_len, pkt2, &pkt2_len)) - return res; + return verdict; DLOG("sending 1st ip fragment 0-%zu len=%zu : ", ipfrag_pos-1, ipfrag_pos) hexdump_limited_dlog(pkt1,pkt1_len,IP_MAXDUMP); DLOG("\n") if (!rawsend((struct sockaddr *)&dst, desync_fwmark, ifout , pkt2, pkt2_len)) - return res; + return verdict; - DLOG("sending 2nd ip fragment %zu-%zu len=%zu : ", ipfrag_pos, len_tcp-1, len_tcp-ipfrag_pos) + DLOG("sending 2nd ip fragment %zu-%zu len=%zu : ", ipfrag_pos, transport_len-1, transport_len-ipfrag_pos) hexdump_limited_dlog(pkt2,pkt2_len,IP_MAXDUMP); DLOG("\n") if (!rawsend((struct sockaddr *)&dst, desync_fwmark, ifout , pkt1, pkt1_len)) - return res; + return verdict; return VERDICT_DROP; } @@ -988,14 +1062,14 @@ uint8_t dpi_desync_tcp_packet(uint32_t fwmark, const char *ifout, uint8_t *data_ } - return res; + return verdict; } - -uint8_t dpi_desync_udp_packet(uint32_t fwmark, const char *ifout, uint8_t *data_pkt, size_t *len_pkt, struct ip *ip, struct ip6_hdr *ip6hdr, struct udphdr *udphdr, uint8_t *data_payload, size_t len_payload) +static uint8_t dpi_desync_udp_packet_play(bool replay, uint32_t fwmark, const char *ifout, uint8_t *data_pkt, size_t *len_pkt, struct ip *ip, struct ip6_hdr *ip6hdr, struct udphdr *udphdr, size_t transport_len, uint8_t *data_payload, size_t len_payload) { - uint8_t res=VERDICT_PASS; + uint8_t verdict=VERDICT_PASS; + t_ctrack *ctrack=NULL; bool bReverse=false; @@ -1003,23 +1077,41 @@ uint8_t dpi_desync_udp_packet(uint32_t fwmark, const char *ifout, uint8_t *data_ uint8_t pkt1[DPI_DESYNC_MAX_FAKE_LEN+100], pkt2[DPI_DESYNC_MAX_FAKE_LEN+100]; size_t pkt1_len, pkt2_len; uint8_t ttl_orig,ttl_fake; + + t_reassemble *reasm_replay = NULL; - if (!!ip == !!ip6hdr) return res; // one and only one must be present + if (replay) + { + t_ctrack *ctrack; + bool bReverse; + //ConntrackPoolDump(¶ms.conntrack); + if (ConntrackPoolDoubleSearch(¶ms.conntrack, ip, ip6hdr, NULL, udphdr, &ctrack, &bReverse) && !bReverse) + reasm_replay = &ctrack->reasm_orig; + else + return verdict; + } + else + { + ConntrackPoolPurge(¶ms.conntrack); + if (ConntrackPoolFeed(¶ms.conntrack, ip, ip6hdr, NULL, udphdr, len_payload, &ctrack, &bReverse)) + maybe_cutoff(ctrack, IPPROTO_UDP); + HostFailPoolPurgeRateLimited(¶ms.hostlist_auto_fail_counters); + //ConntrackPoolDump(¶ms.conntrack); + } - ConntrackPoolPurge(¶ms.conntrack); - if (ConntrackPoolFeed(¶ms.conntrack, ip, ip6hdr, NULL, udphdr, len_payload, &ctrack, &bReverse)) - maybe_cutoff(ctrack, IPPROTO_UDP); - HostFailPoolPurgeRateLimited(¶ms.hostlist_auto_fail_counters); + if (bReverse) return verdict; // nothing to do. do not waste cpu - //ConntrackPoolDump(¶ms.conntrack); - - if (bReverse) return res; // nothing to do. do not waste cpu - - if (params.desync_mode==DESYNC_NONE && !*params.hostlist_auto_filename) return res; // do not waste cpu + if (params.desync_mode==DESYNC_NONE && !*params.hostlist_auto_filename) return verdict; // do not waste cpu // start and cutoff limiters - if (!check_desync_interval(ctrack)) return res; + if (!replay && !process_desync_interval(ctrack)) return verdict; + uint32_t desync_fwmark = fwmark | params.desync_fwmark; + ttl_orig = ip ? ip->ip_ttl : ip6hdr->ip6_ctlun.ip6_un1.ip6_un1_hlim; + if (ip6hdr) ttl_fake = params.desync_ttl6 ? params.desync_ttl6 : ttl_orig; + else ttl_fake = params.desync_ttl ? params.desync_ttl : ttl_orig; + extract_endpoints(ip, ip6hdr, NULL, udphdr, &src, &dst); + if (len_payload) { const uint8_t *fake; @@ -1034,51 +1126,146 @@ uint8_t dpi_desync_udp_packet(uint32_t fwmark, const char *ifout, uint8_t *data_ DLOG("packet contains QUIC initial\n") if (ctrack && !ctrack->l7proto) ctrack->l7proto = QUIC; - fake = params.fake_quic; - fake_size = params.fake_quic_size; - bool bIsCryptoHello, bDecryptOK; - bHaveHost=QUICExtractHostFromInitial(data_payload,len_payload,host,sizeof(host), &bDecryptOK,&bIsCryptoHello); - if (bIsCryptoHello) + uint8_t clean[9000], *pclean; + size_t clean_len; + bool bIsHello = false; + + if (reasm_replay) { - // decrypted and payload is ClientHello - if (params.desync_skip_nosni && !bHaveHost) - { - DLOG("not applying tampering to QUIC ClientHello without hostname in the SNI\n") - return res; - } - } - else if (!bDecryptOK) - { - // could not decrypt - if (params.desync_skip_nosni) - { - DLOG("not applying tampering to QUIC initial that could not be decrypted\n") - return res; - } - else - // consider this case the same way as absence of the SNI. DPI also might not be able to decrypt this and get SNI - DLOG("QUIC initial decryption failed. still applying tampering because desync_skip_nosni is not set\n") + clean_len = reasm_replay->size_present; + pclean = reasm_replay->packet; } else { - // decrypted and payload is not ClientHello - if (params.desync_any_proto) + clean_len = sizeof(clean); + pclean = QUICDecryptInitial(data_payload,len_payload,clean,&clean_len) ? clean : NULL; + } + if (pclean) + { + if (ctrack && !ReasmIsEmpty(&ctrack->reasm_orig)) { - DLOG("QUIC initial without CRYPTO frame. applying tampering because desync_any_proto is set\n") + size_t newlen = ctrack->reasm_orig.size_present + clean_len; + if (newlen>16384) + { + DLOG("QUIC reasm is too long. cancelling.\n"); + reasm_orig_cancel(ctrack); + return verdict; // cannot be first packet + } + if (ReasmResize(&ctrack->reasm_orig, newlen)) + { + reasm_orig_feed(ctrack,IPPROTO_UDP,clean,clean_len); + pclean = ctrack->reasm_orig.packet; + clean_len = ctrack->reasm_orig.size_present; + } + else + { + fprintf(stderr, "reasm update failed ! out of memory.\n"); + reasm_orig_cancel(ctrack); + return verdict; // cannot be first packet + } + } + + uint8_t defrag[sizeof(clean)]; + size_t hello_offset, hello_len, defrag_len = sizeof(defrag); + if (QUICDefragCrypto(pclean,clean_len,defrag,&defrag_len)) + { + bool bIsHello = IsQUICCryptoHello(defrag, defrag_len, &hello_offset, &hello_len); + bool bReqFull = bIsHello ? IsTLSHandshakeFull(defrag+hello_offset,hello_len) : false; + + DLOG(bIsHello ? bReqFull ? "packet contains full TLS ClientHello\n" : "packet contains partial TLS ClientHello\n" : "packet does not contain TLS ClientHello\n") + + if (ctrack) + { + if (bIsHello && !bReqFull && ReasmIsEmpty(&ctrack->reasm_orig)) + { + if (!reasm_orig_start(ctrack,clean_len,clean_len,clean,clean_len)) + { + fprintf(stderr, "reasm start failed ! out of memory.\n"); + reasm_orig_cancel(ctrack); + return verdict; + } + } + if (!ReasmIsEmpty(&ctrack->reasm_orig)) + { + verdict_udp_csum_fix(verdict, udphdr, transport_len, ip, ip6hdr); + if (rawpacket_queue(&ctrack->delayed, &dst, desync_fwmark, ifout, data_pkt, *len_pkt)) + { + DLOG("DELAY desync until reasm is complete (%u)\n", rawpacket_queue_count(&ctrack->delayed)); + } + else + { + fprintf(stderr, "rawpacket_queue failed !'\n"); + reasm_orig_cancel(ctrack); + return verdict; + } + if (bReqFull) + { + replay_queue(&ctrack->delayed); + reasm_orig_fin(ctrack); + } + return ct_new_postnat_fix_udp(ctrack, ip, ip6hdr, udphdr, len_pkt); + } + } + + if (bIsHello) + { + bHaveHost = TLSHelloExtractHostFromHandshake(defrag + hello_offset, hello_len, host, sizeof(host), TLS_PARTIALS_ENABLE); + if (!bHaveHost && params.desync_skip_nosni) + { + reasm_orig_cancel(ctrack); + DLOG("not applying tampering to QUIC ClientHello without hostname in the SNI\n") + return verdict; + } + } + else + { + reasm_orig_cancel(ctrack); + if (params.desync_any_proto) + DLOG("QUIC initial without ClientHello. applying tampering because desync_any_proto is set\n") + else + { + DLOG("not applying tampering to QUIC initial without ClientHello\n") + return verdict; + } + } } else { - DLOG("not applying tampering to QUIC initial without CRYPTO frame\n") - return res; + // defrag failed + reasm_orig_cancel(ctrack); + if (params.desync_any_proto) + DLOG("QUIC initial without CRYPTO frame. applying tampering because desync_any_proto is set\n") + else + { + DLOG("not applying tampering to QUIC initial without CRYPTO frame\n") + return verdict; + } } } + else + { + // decrypt failed + reasm_orig_cancel(ctrack); + if (params.desync_any_proto) + DLOG("QUIC initial decryption failed. applying tampering because desync_any_proto is set\n") + else + { + DLOG("not applying tampering to QUIC initial that could not be decrypted\n") + return verdict; + } + } + + fake = params.fake_quic; + fake_size = params.fake_quic_size; bKnownProtocol = true; } - else + else // not QUIC initial { // received payload without host. it means we are out of the request retransmission phase. stop counter ctrack_stop_retrans_counter(ctrack); + + reasm_orig_cancel(ctrack); if (IsWireguardHandshakeInitiation(data_payload,len_payload)) { @@ -1098,7 +1285,7 @@ uint8_t dpi_desync_udp_packet(uint32_t fwmark, const char *ifout, uint8_t *data_ } else { - if (!params.desync_any_proto) return res; + if (!params.desync_any_proto) return verdict; DLOG("applying tampering to unknown protocol\n") fake = params.fake_unknown_udp; fake_size = params.fake_unknown_udp_size; @@ -1117,18 +1304,13 @@ uint8_t dpi_desync_udp_packet(uint32_t fwmark, const char *ifout, uint8_t *data_ if (!ctrack->hostname) ctrack->hostname=strdup(host); process_retrans_fail(ctrack, IPPROTO_UDP); } - return res; + return verdict; } } enum dpi_desync_mode desync_mode = params.desync_mode; uint32_t fooling_orig = FOOL_NONE; - ttl_orig = ip ? ip->ip_ttl : ip6hdr->ip6_ctlun.ip6_un1.ip6_un1_hlim; - if (ip6hdr) ttl_fake = params.desync_ttl6 ? params.desync_ttl6 : ttl_orig; - else ttl_fake = params.desync_ttl ? params.desync_ttl : ttl_orig; - extract_endpoints(ip, ip6hdr, NULL, udphdr, &src, &dst); - if (params.debug) { printf("dpi desync src="); @@ -1138,8 +1320,6 @@ uint8_t dpi_desync_udp_packet(uint32_t fwmark, const char *ifout, uint8_t *data_ printf("\n"); } - uint32_t desync_fwmark = fwmark | params.desync_fwmark; - pkt1_len = sizeof(pkt1); b = false; switch(desync_mode) @@ -1153,11 +1333,11 @@ uint8_t dpi_desync_udp_packet(uint32_t fwmark, const char *ifout, uint8_t *data_ } case DESYNC_FAKE: if (!prepare_udp_segment((struct sockaddr *)&src, (struct sockaddr *)&dst, ttl_fake, params.desync_fooling_mode, NULL, 0, 0, fake, fake_size, pkt1, &pkt1_len)) - return res; + return verdict; DLOG("sending fake request : "); hexdump_limited_dlog(fake,fake_size,PKTDATA_MAXDUMP); DLOG("\n") if (!rawsend_rep((struct sockaddr *)&dst, desync_fwmark, ifout , pkt1, pkt1_len)) - return res; + return verdict; b = true; break; case DESYNC_HOPBYHOP: @@ -1170,11 +1350,11 @@ uint8_t dpi_desync_udp_packet(uint32_t fwmark, const char *ifout, uint8_t *data_ ttl_orig,fooling_orig,NULL,0,0, data_payload, len_payload, pkt1, &pkt1_len)) { - return res; + return verdict; } DLOG("resending original packet with extension header\n"); if (!rawsend((struct sockaddr *)&dst, desync_fwmark, ifout , pkt1, pkt1_len)) - return res; + return verdict; // this mode is final, no other options available return ct_new_postnat_fix_udp(ctrack, ip, ip6hdr, udphdr, len_pkt); } @@ -1187,16 +1367,9 @@ uint8_t dpi_desync_udp_packet(uint32_t fwmark, const char *ifout, uint8_t *data_ if (params.desync_mode2==DESYNC_NONE || !desync_valid_second_stage_udp(params.desync_mode2)) { DLOG("reinjecting original packet. len=%zu len_payload=%zu\n", *len_pkt, len_payload) - #ifdef __FreeBSD__ - // FreeBSD tend to pass ipv6 frames with wrong checksum - if ((res & VERDICT_MASK)==VERDICT_MODIFY || ip6hdr) - #else - // if original packet was tampered earlier it needs checksum fixed - if ((res & VERDICT_MASK)==VERDICT_MODIFY) - #endif - udp_fix_checksum(udphdr,sizeof(struct udphdr)+len_payload,ip,ip6hdr); + verdict_udp_csum_fix(verdict, udphdr, transport_len, ip, ip6hdr); if (!rawsend((struct sockaddr *)&dst, desync_fwmark, ifout , data_pkt, *len_pkt)) - return res; + return verdict; return ct_new_postnat_fix_udp(ctrack, ip, ip6hdr, udphdr, len_pkt); } desync_mode = params.desync_mode2; @@ -1209,11 +1382,11 @@ uint8_t dpi_desync_udp_packet(uint32_t fwmark, const char *ifout, uint8_t *data_ if (!prepare_udp_segment((struct sockaddr *)&src, (struct sockaddr *)&dst, ttl_orig,fooling_orig, params.udplen_pattern, sizeof(params.udplen_pattern), params.udplen_increment, data_payload, len_payload, pkt1, &pkt1_len)) { DLOG("could not construct packet with modified length. too large ?\n"); - return res; + return verdict; } DLOG("resending original packet with increased by %d length\n", params.udplen_increment); if (!rawsend((struct sockaddr *)&dst, desync_fwmark, ifout , pkt1, pkt1_len)) - return res; + return verdict; return ct_new_postnat_fix_udp(ctrack, ip, ip6hdr, udphdr, len_pkt); case DESYNC_TAMPER: if (IsDhtD1(data_payload,len_payload)) @@ -1226,7 +1399,7 @@ uint8_t dpi_desync_udp_packet(uint32_t fwmark, const char *ifout, uint8_t *data_ if (szcopy>szbuf) { DLOG("packet is too long to tamper"); - return res; + return verdict; } memcpy(pkt2+pkt2_len,data_payload+1,szcopy); pkt2_len+=szcopy; @@ -1234,35 +1407,26 @@ uint8_t dpi_desync_udp_packet(uint32_t fwmark, const char *ifout, uint8_t *data_ if (!prepare_udp_segment((struct sockaddr *)&src, (struct sockaddr *)&dst, ttl_orig,fooling_orig, NULL, 0 , 0, pkt2, pkt2_len, pkt1, &pkt1_len)) { DLOG("could not construct packet with modified length. too large ?\n"); - return res; + return verdict; } DLOG("resending tampered DHT\n"); if (!rawsend((struct sockaddr *)&dst, desync_fwmark, ifout , pkt1, pkt1_len)) - return res; + return verdict; return ct_new_postnat_fix_udp(ctrack, ip, ip6hdr, udphdr, len_pkt); } else { DLOG("payload is not tamperable\n"); - return res; + return verdict; } case DESYNC_IPFRAG2: { - - #ifdef __FreeBSD__ - // FreeBSD tend to pass ipv6 frames with wrong checksum - if ((res & VERDICT_MASK)==VERDICT_MODIFY || ip6hdr) - #else - // if original packet was tampered earlier it needs checksum fixed - if ((res & VERDICT_MASK)==VERDICT_MODIFY) - #endif - udp_fix_checksum(udphdr,sizeof(struct udphdr)+len_payload,ip,ip6hdr); - + verdict_udp_csum_fix(verdict, udphdr, transport_len, ip, ip6hdr); + uint8_t pkt3[DPI_DESYNC_MAX_FAKE_LEN+100], *pkt_orig; size_t pkt_orig_len; - - size_t len_transport = len_payload + sizeof(struct udphdr); - size_t ipfrag_pos = (params.desync_ipfrag_pos_udp && params.desync_ipfrag_pos_udpip_id ? ip->ip_id : htons(1+random()%0xFFFF) : htonl(1+random()%0xFFFFFFFF); @@ -1273,7 +1437,7 @@ uint8_t dpi_desync_udp_packet(uint32_t fwmark, const char *ifout, uint8_t *data_ { pkt_orig_len = sizeof(pkt3); if (!ip6_insert_simple_hdr(fooling_orig==FOOL_HOPBYHOP ? IPPROTO_HOPOPTS : IPPROTO_DSTOPTS, data_pkt, *len_pkt, pkt3, &pkt_orig_len)) - return res; + return verdict; pkt_orig = pkt3; } else @@ -1283,17 +1447,17 @@ uint8_t dpi_desync_udp_packet(uint32_t fwmark, const char *ifout, uint8_t *data_ } if (!ip_frag(pkt_orig, pkt_orig_len, ipfrag_pos, ident, pkt1, &pkt1_len, pkt2, &pkt2_len)) - return res; + return verdict; DLOG("sending 1st ip fragment 0-%zu len=%zu : ", ipfrag_pos-1, ipfrag_pos) hexdump_limited_dlog(pkt1,pkt1_len,IP_MAXDUMP); DLOG("\n") if (!rawsend((struct sockaddr *)&dst, desync_fwmark, ifout , pkt2, pkt2_len)) - return res; + return verdict; - DLOG("sending 2nd ip fragment %zu-%zu len=%zu : ", ipfrag_pos, len_transport-1, len_transport-ipfrag_pos) + DLOG("sending 2nd ip fragment %zu-%zu len=%zu : ", ipfrag_pos, transport_len-1, transport_len-ipfrag_pos) hexdump_limited_dlog(pkt2,pkt2_len,IP_MAXDUMP); DLOG("\n") if (!rawsend((struct sockaddr *)&dst, desync_fwmark, ifout , pkt1, pkt1_len)) - return res; + return verdict; return ct_new_postnat_fix_udp(ctrack, ip, ip6hdr, udphdr, len_pkt); } @@ -1301,5 +1465,113 @@ uint8_t dpi_desync_udp_packet(uint32_t fwmark, const char *ifout, uint8_t *data_ } - return res; + return verdict; +} + + +static void packet_debug(bool replay, uint8_t proto, const struct ip *ip, const struct ip6_hdr *ip6hdr, const struct tcphdr *tcphdr, const struct udphdr *udphdr, const uint8_t *data_payload, size_t len_payload) +{ + if (params.debug) + { + if (replay) printf("REPLAY "); + if (ip) + { + printf("IP4: "); + print_ip(ip); + } + else if (ip6hdr) + { + printf("IP6: "); + print_ip6hdr(ip6hdr, proto); + } + if (tcphdr) + { + printf(" "); + print_tcphdr(tcphdr); + printf("\n"); + if (len_payload) { printf("TCP: "); hexdump_limited_dlog(data_payload, len_payload, 32); printf("\n"); } + + } + else if (udphdr) + { + printf(" "); + print_udphdr(udphdr); + printf("\n"); + if (len_payload) { printf("UDP: "); hexdump_limited_dlog(data_payload, len_payload, 32); printf("\n"); } + } + else + printf("\n"); + } +} + +static uint8_t dpi_desync_packet_play(bool replay, uint32_t fwmark, const char *ifout, uint8_t *data_pkt, size_t *len_pkt) +{ + struct ip *ip; + struct ip6_hdr *ip6hdr; + struct tcphdr *tcphdr; + struct udphdr *udphdr; + size_t transport_len; + uint8_t *data_payload,proto; + size_t len_payload; + uint8_t verdict = VERDICT_PASS; + + proto_dissect_l3l4(data_pkt,*len_pkt,&ip,&ip6hdr,&proto,&tcphdr,&udphdr,&transport_len,&data_payload,&len_payload); + if (!!ip != !!ip6hdr) + { + packet_debug(replay, proto, ip, ip6hdr, tcphdr, udphdr, data_payload, len_payload); + switch(proto) + { + case IPPROTO_TCP: + if (tcphdr) + { + verdict = dpi_desync_tcp_packet_play(replay, fwmark, ifout, data_pkt, len_pkt, ip, ip6hdr, tcphdr, transport_len, data_payload, len_payload); + verdict_tcp_csum_fix(verdict, tcphdr, transport_len, ip, ip6hdr); + } + break; + case IPPROTO_UDP: + if (udphdr) + { + verdict = dpi_desync_udp_packet_play(replay, fwmark, ifout, data_pkt, len_pkt, ip, ip6hdr, udphdr, transport_len, data_payload, len_payload); + verdict_udp_csum_fix(verdict, udphdr, transport_len, ip, ip6hdr); + } + break; + } + } + return verdict; +} +uint8_t dpi_desync_packet(uint32_t fwmark, const char *ifout, uint8_t *data_pkt, size_t *len_pkt) +{ + return dpi_desync_packet_play(false, fwmark, ifout, data_pkt, len_pkt); +} + + + +static bool replay_queue(struct rawpacket_tailhead *q) +{ + struct rawpacket *rp = rawpacket_dequeue(q); + if (rp) + { + DLOG("REPLAYING first delayed packet\n") + bool b = true; + uint8_t verdict = dpi_desync_packet_play(true, rp->fwmark, rp->ifout, rp->packet, &rp->len); + switch(verdict & VERDICT_MASK) + { + case VERDICT_MODIFY: + DLOG("SENDING first delayed packet modified\n") + b &= rawsend_rp(rp); + break; + case VERDICT_PASS: + DLOG("SENDING first delayed packet unmodified\n") + b &= rawsend_rp(rp); + break; + case VERDICT_DROP: + DLOG("DROPPING first delayed packet\n") + break; + } + rawpacket_free(rp); + DLOG("SENDING %u remaining delayed packets\n", rawpacket_queue_count(q)) + b &= rawsend_queue(q); + return b; + } + return false; } diff --git a/nfq/desync.h b/nfq/desync.h index 82dd782..5eb8137 100644 --- a/nfq/desync.h +++ b/nfq/desync.h @@ -1,7 +1,6 @@ #pragma once #include "darkmagic.h" -#include "nfqws.h" #include #include @@ -51,5 +50,4 @@ bool desync_valid_second_stage_tcp(enum dpi_desync_mode mode); bool desync_valid_second_stage_udp(enum dpi_desync_mode mode); void desync_init(void); -uint8_t dpi_desync_tcp_packet(uint32_t fwmark, const char *ifout, uint8_t *data_pkt, size_t *len_pkt, struct ip *ip, struct ip6_hdr *ip6hdr, struct tcphdr *tcphdr, size_t len_tcp, uint8_t *data_payload, size_t len_payload); -uint8_t dpi_desync_udp_packet(uint32_t fwmark, const char *ifout, uint8_t *data_pkt, size_t *len_pkt, struct ip *ip, struct ip6_hdr *ip6hdr, struct udphdr *udphdr, uint8_t *data_payload, size_t len_payload); +uint8_t dpi_desync_packet(uint32_t fwmark, const char *ifout, uint8_t *data_pkt, size_t *len_pkt); diff --git a/nfq/helpers.c b/nfq/helpers.c index a2ca4b7..8045275 100644 --- a/nfq/helpers.c +++ b/nfq/helpers.c @@ -5,9 +5,11 @@ #include #include #include -#include #include + +#include "params.h" + void hexdump_limited_dlog(const uint8_t *data, size_t size, size_t limit) { size_t k; diff --git a/nfq/helpers.h b/nfq/helpers.h index e1f6b22..66551bf 100644 --- a/nfq/helpers.h +++ b/nfq/helpers.h @@ -5,9 +5,9 @@ #include #include #include +#include #include - -#include "params.h" +#include void hexdump_limited_dlog(const uint8_t *data, size_t size, size_t limit); char *strncasestr(const char *s,const char *find, size_t slen); diff --git a/nfq/nfqws.c b/nfq/nfqws.c index 078dcca..20de560 100644 --- a/nfq/nfqws.c +++ b/nfq/nfqws.c @@ -79,108 +79,16 @@ static void onusr2(int sig) } - static uint8_t processPacketData(uint32_t *mark, const char *ifout, uint8_t *data_pkt, size_t *len_pkt) { - struct ip *ip = NULL; - struct ip6_hdr *ip6hdr = NULL; - struct tcphdr *tcphdr = NULL; - struct udphdr *udphdr = NULL; - size_t len = *len_pkt, len_with_th; - uint8_t *data = data_pkt; - uint8_t res = VERDICT_PASS; - uint8_t proto; - #ifdef __linux__ if (*mark & params.desync_fwmark) { DLOG("ignoring generated packet\n") - return res; + return VERDICT_PASS; } #endif - - if (proto_check_ipv4(data, len)) - { - ip = (struct ip *) data; - proto = ip->ip_p; - proto_skip_ipv4(&data, &len); - if (params.debug) - { - printf("IP4: "); - print_ip(ip); - } - } - else if (proto_check_ipv6(data, len)) - { - ip6hdr = (struct ip6_hdr *) data; - proto_skip_ipv6(&data, &len, &proto, NULL); - if (params.debug) - { - printf("IP6: "); - print_ip6hdr(ip6hdr, proto); - } - } - else - { - // not ipv6 and not ipv4 - return res; - } - - if (proto==IPPROTO_TCP && proto_check_tcp(data, len)) - { - tcphdr = (struct tcphdr *) data; - len_with_th = len; - proto_skip_tcp(&data, &len); - - if (params.debug) - { - printf(" "); - print_tcphdr(tcphdr); - printf("\n"); - } - - if (len) { DLOG("TCP: ") hexdump_limited_dlog(data, len, 32); DLOG("\n") } - - res = dpi_desync_tcp_packet(*mark, ifout, data_pkt, len_pkt, ip, ip6hdr, tcphdr, len_with_th, data, len); - // in my FreeBSD divert tests only ipv4 packets were reinjected with correct checksum - // ipv6 packets were with incorrect checksum -#ifdef __FreeBSD__ - // FreeBSD tend to pass ipv6 frames with wrong checksum - if (!(res & VERDICT_NOCSUM) && ((res & VERDICT_MASK)==VERDICT_MODIFY || ip6hdr && (res & VERDICT_MASK)==VERDICT_PASS)) -#else - if (!(res & VERDICT_NOCSUM) && (res & VERDICT_MASK)==VERDICT_MODIFY) -#endif - tcp_fix_checksum(tcphdr,len_with_th,ip,ip6hdr); - } - else if (proto==IPPROTO_UDP && proto_check_udp(data, len)) - { - udphdr = (struct udphdr *) data; - len_with_th = len; - proto_skip_udp(&data, &len); - - if (params.debug) - { - printf(" "); - print_udphdr(udphdr); - printf("\n"); - } - if (len) { DLOG("UDP: ") hexdump_limited_dlog(data, len, 32); DLOG("\n") } - - res = dpi_desync_udp_packet(*mark, ifout, data_pkt, len_pkt, ip, ip6hdr, udphdr, data, len); -#ifdef __FreeBSD__ - // FreeBSD tend to pass ipv6 frames with wrong checksum - if (!(res & VERDICT_NOCSUM) && ((res & VERDICT_MASK)==VERDICT_MODIFY || ip6hdr && (res & VERDICT_MASK)==VERDICT_PASS)) -#else - if (!(res & VERDICT_NOCSUM) && (res & VERDICT_MASK)==VERDICT_MODIFY) -#endif - udp_fix_checksum(udphdr,len_with_th,ip,ip6hdr); - } - else - { - if (params.debug) printf("\n"); - } - - return res; + return dpi_desync_packet(*mark, ifout, data_pkt, len_pkt); } @@ -214,8 +122,8 @@ static int nfq_cb(struct nfq_q_handle *qh, struct nfgenmsg *nfmsg, struct nfq_da if (ilen >= 0) { len = ilen; - uint8_t res = processPacketData(&mark, ifout, data, &len); - switch(res & VERDICT_MASK) + uint8_t verdict = processPacketData(&mark, ifout, data, &len); + switch(verdict & VERDICT_MASK) { case VERDICT_MODIFY: DLOG("packet: id=%d pass modified. len=%zu\n", id, len); @@ -438,16 +346,16 @@ static int dvt_main(void) else if (rd>0) { uint32_t mark=0; - uint8_t res; + uint8_t verdict; size_t len = rd; DLOG("packet: id=%u len=%zu\n", id, len) - res = processPacketData(&mark, NULL, buf, &len); - switch (res & VERDICT_MASK) + verdict = processPacketData(&mark, NULL, buf, &len); + switch (verdict & VERDICT_MASK) { case VERDICT_PASS: case VERDICT_MODIFY: - if ((res & VERDICT_MASK)==VERDICT_PASS) + if ((verdict & VERDICT_MASK)==VERDICT_PASS) DLOG("packet: id=%u reinject unmodified\n", id) else DLOG("packet: id=%u reinject modified len=%zu\n", id, len) @@ -544,9 +452,6 @@ static void exithelp(void) " --dpi-desync-autottl=[[:[-]]]\t; auto ttl mode for both ipv4 and ipv6. default: %u:%u-%u\n" " --dpi-desync-autottl6=[[:[-]]] ; overrides --dpi-desync-autottl for ipv6 only\n" " --dpi-desync-fooling=[,]\t\t; can use multiple comma separated values. modes : none md5sig ts badseq badsum datanoack hopbyhop hopbyhop2\n" -#ifdef __linux__ - " --dpi-desync-retrans=0|1\t\t\t; 0(default)=reinject original data packet after fake 1=drop original data packet to force its retransmission\n" -#endif " --dpi-desync-repeats=\t\t\t; send every desync packet N times\n" " --dpi-desync-skip-nosni=0|1\t\t\t; 1(default)=do not act on ClientHello without SNI (ESNI ?)\n" " --dpi-desync-split-pos=<1..%u>\t\t; data payload split position\n" @@ -765,38 +670,37 @@ int main(int argc, char **argv) {"dpi-desync-autottl",optional_argument,0,0}, // optidx=18 {"dpi-desync-autottl6",optional_argument,0,0}, // optidx=19 {"dpi-desync-fooling",required_argument,0,0}, // optidx=20 - {"dpi-desync-retrans",optional_argument,0,0}, // optidx=21 - {"dpi-desync-repeats",required_argument,0,0}, // optidx=22 - {"dpi-desync-skip-nosni",optional_argument,0,0},// optidx=23 - {"dpi-desync-split-pos",required_argument,0,0},// optidx=24 - {"dpi-desync-ipfrag-pos-tcp",required_argument,0,0},// optidx=25 - {"dpi-desync-ipfrag-pos-udp",required_argument,0,0},// optidx=26 - {"dpi-desync-badseq-increment",required_argument,0,0},// optidx=27 - {"dpi-desync-badack-increment",required_argument,0,0},// optidx=28 - {"dpi-desync-any-protocol",optional_argument,0,0},// optidx=29 - {"dpi-desync-fake-http",required_argument,0,0},// optidx=30 - {"dpi-desync-fake-tls",required_argument,0,0},// optidx=31 - {"dpi-desync-fake-unknown",required_argument,0,0},// optidx=32 - {"dpi-desync-fake-syndata",required_argument,0,0},// optidx=33 - {"dpi-desync-fake-quic",required_argument,0,0},// optidx=34 - {"dpi-desync-fake-wireguard",required_argument,0,0},// optidx=35 - {"dpi-desync-fake-dht",required_argument,0,0},// optidx=36 - {"dpi-desync-fake-unknown-udp",required_argument,0,0},// optidx=37 - {"dpi-desync-udplen-increment",required_argument,0,0},// optidx=38 - {"dpi-desync-udplen-pattern",required_argument,0,0},// optidx=39 - {"dpi-desync-cutoff",required_argument,0,0},// optidx=40 - {"dpi-desync-start",required_argument,0,0},// optidx=41 - {"hostlist",required_argument,0,0}, // optidx=42 - {"hostlist-exclude",required_argument,0,0}, // optidx=43 - {"hostlist-auto",required_argument,0,0}, // optidx=44 - {"hostlist-auto-fail-threshold",required_argument,0,0}, // optidx=45 - {"hostlist-auto-fail-time",required_argument,0,0}, // optidx=46 - {"hostlist-auto-retrans-threshold",required_argument,0,0}, // optidx=47 - {"hostlist-auto-debug",required_argument,0,0}, // optidx=48 + {"dpi-desync-repeats",required_argument,0,0}, // optidx=21 + {"dpi-desync-skip-nosni",optional_argument,0,0},// optidx=22 + {"dpi-desync-split-pos",required_argument,0,0},// optidx=23 + {"dpi-desync-ipfrag-pos-tcp",required_argument,0,0},// optidx=24 + {"dpi-desync-ipfrag-pos-udp",required_argument,0,0},// optidx=25 + {"dpi-desync-badseq-increment",required_argument,0,0},// optidx=26 + {"dpi-desync-badack-increment",required_argument,0,0},// optidx=27 + {"dpi-desync-any-protocol",optional_argument,0,0},// optidx=28 + {"dpi-desync-fake-http",required_argument,0,0},// optidx=29 + {"dpi-desync-fake-tls",required_argument,0,0},// optidx=30 + {"dpi-desync-fake-unknown",required_argument,0,0},// optidx=31 + {"dpi-desync-fake-syndata",required_argument,0,0},// optidx=32 + {"dpi-desync-fake-quic",required_argument,0,0},// optidx=33 + {"dpi-desync-fake-wireguard",required_argument,0,0},// optidx=34 + {"dpi-desync-fake-dht",required_argument,0,0},// optidx=35 + {"dpi-desync-fake-unknown-udp",required_argument,0,0},// optidx=36 + {"dpi-desync-udplen-increment",required_argument,0,0},// optidx=37 + {"dpi-desync-udplen-pattern",required_argument,0,0},// optidx=38 + {"dpi-desync-cutoff",required_argument,0,0},// optidx=39 + {"dpi-desync-start",required_argument,0,0},// optidx=40 + {"hostlist",required_argument,0,0}, // optidx=41 + {"hostlist-exclude",required_argument,0,0}, // optidx=42 + {"hostlist-auto",required_argument,0,0}, // optidx=43 + {"hostlist-auto-fail-threshold",required_argument,0,0}, // optidx=44 + {"hostlist-auto-fail-time",required_argument,0,0}, // optidx=45 + {"hostlist-auto-retrans-threshold",required_argument,0,0}, // optidx=46 + {"hostlist-auto-debug",required_argument,0,0}, // optidx=47 #ifdef __linux__ - {"bind-fix4",no_argument,0,0}, // optidx=49 - {"bind-fix6",no_argument,0,0}, // optidx=50 + {"bind-fix4",no_argument,0,0}, // optidx=48 + {"bind-fix6",no_argument,0,0}, // optidx=49 #endif {NULL,0,NULL,0} }; @@ -1012,32 +916,24 @@ int main(int argc, char **argv) } } break; - case 21: /* dpi-desync-retrans */ -#ifdef __linux__ - params.desync_retrans = !optarg || atoi(optarg); -#else - fprintf(stderr, "dpi-desync-retrans is only supported in linux\n"); - exit_clean(1); -#endif - break; - case 22: /* dpi-desync-repeats */ + case 21: /* dpi-desync-repeats */ if (sscanf(optarg,"%u",¶ms.desync_repeats)<1 || !params.desync_repeats || params.desync_repeats>20) { fprintf(stderr, "dpi-desync-repeats must be within 1..20\n"); exit_clean(1); } break; - case 23: /* dpi-desync-skip-nosni */ + case 22: /* dpi-desync-skip-nosni */ params.desync_skip_nosni = !optarg || atoi(optarg); break; - case 24: /* dpi-desync-split-pos */ + case 23: /* dpi-desync-split-pos */ if (sscanf(optarg,"%u",¶ms.desync_split_pos)<1 || params.desync_split_pos<1 || params.desync_split_pos>DPI_DESYNC_MAX_FAKE_LEN) { fprintf(stderr, "dpi-desync-split-pos must be within 1..%u range\n",DPI_DESYNC_MAX_FAKE_LEN); exit_clean(1); } break; - case 25: /* dpi-desync-ipfrag-pos-tcp */ + case 24: /* dpi-desync-ipfrag-pos-tcp */ if (sscanf(optarg,"%u",¶ms.desync_ipfrag_pos_tcp)<1 || params.desync_ipfrag_pos_tcp<1 || params.desync_ipfrag_pos_tcp>DPI_DESYNC_MAX_FAKE_LEN) { fprintf(stderr, "dpi-desync-ipfrag-pos-tcp must be within 1..%u range\n",DPI_DESYNC_MAX_FAKE_LEN); @@ -1049,7 +945,7 @@ int main(int argc, char **argv) exit_clean(1); } break; - case 26: /* dpi-desync-ipfrag-pos-udp */ + case 25: /* dpi-desync-ipfrag-pos-udp */ if (sscanf(optarg,"%u",¶ms.desync_ipfrag_pos_udp)<1 || params.desync_ipfrag_pos_udp<1 || params.desync_ipfrag_pos_udp>DPI_DESYNC_MAX_FAKE_LEN) { fprintf(stderr, "dpi-desync-ipfrag-pos-udp must be within 1..%u range\n",DPI_DESYNC_MAX_FAKE_LEN); @@ -1061,63 +957,63 @@ int main(int argc, char **argv) exit_clean(1); } break; - case 27: /* dpi-desync-badseq-increments */ + case 26: /* dpi-desync-badseq-increments */ if (!parse_badseq_increment(optarg,¶ms.desync_badseq_increment)) { fprintf(stderr, "dpi-desync-badseq-increment should be signed decimal or signed 0xHEX\n"); exit_clean(1); } break; - case 28: /* dpi-desync-badack-increment */ + case 27: /* dpi-desync-badack-increment */ if (!parse_badseq_increment(optarg,¶ms.desync_badseq_ack_increment)) { fprintf(stderr, "dpi-desync-badack-increment should be signed decimal or signed 0xHEX\n"); exit_clean(1); } break; - case 29: /* dpi-desync-any-protocol */ + case 28: /* dpi-desync-any-protocol */ params.desync_any_proto = !optarg || atoi(optarg); break; - case 30: /* dpi-desync-fake-http */ + case 29: /* dpi-desync-fake-http */ params.fake_http_size = sizeof(params.fake_http); load_file_or_exit(optarg,params.fake_http,¶ms.fake_http_size); break; - case 31: /* dpi-desync-fake-tls */ + case 30: /* dpi-desync-fake-tls */ params.fake_tls_size = sizeof(params.fake_tls); load_file_or_exit(optarg,params.fake_tls,¶ms.fake_tls_size); break; - case 32: /* dpi-desync-fake-unknown */ + case 31: /* dpi-desync-fake-unknown */ params.fake_unknown_size = sizeof(params.fake_unknown); load_file_or_exit(optarg,params.fake_unknown,¶ms.fake_unknown_size); break; - case 33: /* dpi-desync-fake-syndata */ + case 32: /* dpi-desync-fake-syndata */ params.fake_syndata_size = sizeof(params.fake_syndata); load_file_or_exit(optarg,params.fake_syndata,¶ms.fake_syndata_size); break; - case 34: /* dpi-desync-fake-quic */ + case 33: /* dpi-desync-fake-quic */ params.fake_quic_size = sizeof(params.fake_quic); load_file_or_exit(optarg,params.fake_quic,¶ms.fake_quic_size); break; - case 35: /* dpi-desync-fake-wireguard */ + case 34: /* dpi-desync-fake-wireguard */ params.fake_wg_size = sizeof(params.fake_wg); load_file_or_exit(optarg,params.fake_wg,¶ms.fake_wg_size); break; - case 36: /* dpi-desync-fake-dht */ + case 35: /* dpi-desync-fake-dht */ params.fake_dht_size = sizeof(params.fake_dht); load_file_or_exit(optarg,params.fake_dht,¶ms.fake_dht_size); break; - case 37: /* dpi-desync-fake-unknown-udp */ + case 36: /* dpi-desync-fake-unknown-udp */ params.fake_unknown_udp_size = sizeof(params.fake_unknown_udp); load_file_or_exit(optarg,params.fake_unknown_udp,¶ms.fake_unknown_udp_size); break; - case 38: /* dpi-desync-udplen-increment */ + case 37: /* dpi-desync-udplen-increment */ if (sscanf(optarg,"%d",¶ms.udplen_increment)<1 || params.udplen_increment>0x7FFF || params.udplen_increment<-0x8000) { fprintf(stderr, "dpi-desync-udplen-increment must be integer within -32768..32767 range\n"); exit_clean(1); } break; - case 39: /* dpi-desync-udplen-pattern */ + case 38: /* dpi-desync-udplen-pattern */ { char buf[sizeof(params.udplen_pattern)]; size_t sz=sizeof(buf); @@ -1125,35 +1021,35 @@ int main(int argc, char **argv) fill_pattern(params.udplen_pattern,sizeof(params.udplen_pattern),buf,sz); } break; - case 40: /* desync-cutoff */ + case 39: /* desync-cutoff */ if (!parse_cutoff(optarg, ¶ms.desync_cutoff, ¶ms.desync_cutoff_mode)) { fprintf(stderr, "invalid desync-cutoff value\n"); exit_clean(1); } break; - case 41: /* desync-start */ + case 40: /* desync-start */ if (!parse_cutoff(optarg, ¶ms.desync_start, ¶ms.desync_start_mode)) { fprintf(stderr, "invalid desync-start value\n"); exit_clean(1); } break; - case 42: /* hostlist */ + case 41: /* hostlist */ if (!strlist_add(¶ms.hostlist_files, optarg)) { fprintf(stderr, "strlist_add failed\n"); exit_clean(1); } break; - case 43: /* hostlist-exclude */ + case 42: /* hostlist-exclude */ if (!strlist_add(¶ms.hostlist_exclude_files, optarg)) { fprintf(stderr, "strlist_add failed\n"); exit_clean(1); } break; - case 44: /* hostlist-auto */ + case 43: /* hostlist-auto */ if (*params.hostlist_auto_filename) { fprintf(stderr, "only one auto hostlist is supported\n"); @@ -1184,7 +1080,7 @@ int main(int argc, char **argv) strncpy(params.hostlist_auto_filename, optarg, sizeof(params.hostlist_auto_filename)); params.hostlist_auto_filename[sizeof(params.hostlist_auto_filename) - 1] = '\0'; break; - case 45: /* hostlist-auto-fail-threshold */ + case 44: /* hostlist-auto-fail-threshold */ params.hostlist_auto_fail_threshold = (uint8_t)atoi(optarg); if (params.hostlist_auto_fail_threshold<1 || params.hostlist_auto_fail_threshold>20) { @@ -1192,7 +1088,7 @@ int main(int argc, char **argv) exit_clean(1); } break; - case 46: /* hostlist-auto-fail-time */ + case 45: /* hostlist-auto-fail-time */ params.hostlist_auto_fail_time = (uint8_t)atoi(optarg); if (params.hostlist_auto_fail_time<1) { @@ -1200,7 +1096,7 @@ int main(int argc, char **argv) exit_clean(1); } break; - case 47: /* hostlist-auto-retrans-threshold */ + case 46: /* hostlist-auto-retrans-threshold */ params.hostlist_auto_retrans_threshold = (uint8_t)atoi(optarg); if (params.hostlist_auto_retrans_threshold<2 || params.hostlist_auto_retrans_threshold>10) { @@ -1208,7 +1104,7 @@ int main(int argc, char **argv) exit_clean(1); } break; - case 48: /* hostlist-auto-debug */ + case 47: /* hostlist-auto-debug */ { FILE *F = fopen(optarg,"a+t"); if (!F) @@ -1224,10 +1120,10 @@ int main(int argc, char **argv) } break; #ifdef __linux__ - case 49: /* bind-fix4 */ + case 48: /* bind-fix4 */ params.bind_fix4 = true; break; - case 50: /* bind-fix6 */ + case 49: /* bind-fix6 */ params.bind_fix6 = true; break; #endif diff --git a/nfq/nfqws.h b/nfq/nfqws.h index c1c7893..6f70f09 100644 --- a/nfq/nfqws.h +++ b/nfq/nfqws.h @@ -1,7 +1 @@ #pragma once - -#define VERDICT_PASS 0 -#define VERDICT_MODIFY 1 -#define VERDICT_DROP 2 -#define VERDICT_MASK 3 -#define VERDICT_NOCSUM 4 diff --git a/nfq/packet_queue.c b/nfq/packet_queue.c new file mode 100644 index 0000000..f4107fa --- /dev/null +++ b/nfq/packet_queue.c @@ -0,0 +1,67 @@ +#include +#include + +#include "packet_queue.h" + +void rawpacket_queue_init(struct rawpacket_tailhead *q) +{ + TAILQ_INIT(q); +} +void rawpacket_free(struct rawpacket *rp) +{ + if (rp) free(rp->packet); + free(rp); +} +struct rawpacket *rawpacket_dequeue(struct rawpacket_tailhead *q) +{ + struct rawpacket *rp; + rp = TAILQ_FIRST(q); + if (rp) TAILQ_REMOVE(q, rp, next); + return rp; +} +void rawpacket_queue_destroy(struct rawpacket_tailhead *q) +{ + struct rawpacket *rp; + while((rp = rawpacket_dequeue(q))) rawpacket_free(rp); +} + +struct rawpacket *rawpacket_queue(struct rawpacket_tailhead *q,const struct sockaddr_storage* dst,uint32_t fwmark,const char *ifout,const void *data,size_t len) +{ + struct rawpacket *rp = malloc(sizeof(struct rawpacket)); + if (!rp) return NULL; + + rp->packet = malloc(len); + if (!rp->packet) + { + free(rp); + return NULL; + } + + rp->dst = *dst; + rp->fwmark = fwmark; + if (ifout) + { + strncpy(rp->ifout,ifout,sizeof(rp->ifout)); + rp->ifout[sizeof(rp->ifout)-1]=0; + } + else + rp->ifout[0]=0; + memcpy(rp->packet,data,len); + rp->len=len; + + TAILQ_INSERT_TAIL(q, rp, next); + + return rp; +} + +unsigned int rawpacket_queue_count(const struct rawpacket_tailhead *q) +{ + const struct rawpacket *rp; + unsigned int ct=0; + TAILQ_FOREACH(rp, q, next) ct++; + return ct; +} +bool rawpacket_queue_empty(const struct rawpacket_tailhead *q) +{ + return !TAILQ_FIRST(q); +} diff --git a/nfq/packet_queue.h b/nfq/packet_queue.h new file mode 100644 index 0000000..1d77079 --- /dev/null +++ b/nfq/packet_queue.h @@ -0,0 +1,26 @@ +#pragma once + +#include +#include +#include +#include +#include + +struct rawpacket +{ + struct sockaddr_storage dst; + char ifout[IFNAMSIZ+1]; + uint32_t fwmark; + size_t len; + uint8_t *packet; + TAILQ_ENTRY(rawpacket) next; +}; +TAILQ_HEAD(rawpacket_tailhead, rawpacket); + +void rawpacket_queue_init(struct rawpacket_tailhead *q); +void rawpacket_queue_destroy(struct rawpacket_tailhead *q); +bool rawpacket_queue_empty(const struct rawpacket_tailhead *q); +unsigned int rawpacket_queue_count(const struct rawpacket_tailhead *q); +struct rawpacket *rawpacket_queue(struct rawpacket_tailhead *q,const struct sockaddr_storage* dst,uint32_t fwmark,const char *ifout,const void *data,size_t len); +struct rawpacket *rawpacket_dequeue(struct rawpacket_tailhead *q); +void rawpacket_free(struct rawpacket *rp); diff --git a/nfq/protocol.c b/nfq/protocol.c index 819815d..031bf70 100644 --- a/nfq/protocol.c +++ b/nfq/protocol.c @@ -125,6 +125,20 @@ bool IsTLSClientHello(const uint8_t *data, size_t len, bool bPartialIsOK) return len >= 6 && data[0] == 0x16 && data[1] == 0x03 && data[2] >= 0x01 && data[2] <= 0x03 && data[5] == 0x01 && (bPartialIsOK || TLSRecordLen(data) <= len); } +size_t TLSHandshakeLen(const uint8_t *data) +{ + return data[1] << 16 | data[2] << 8 | data[3]; // HandshakeProtocol length +} +bool IsTLSHandshakeClientHello(const uint8_t *data, size_t len) +{ + return len>=4 && data[0]==0x01; +} +bool IsTLSHandshakeFull(const uint8_t *data, size_t len) +{ + return (4+TLSHandshakeLen(data))<=len; +} + + // bPartialIsOK=true - accept partial packets not containing the whole TLS message bool TLSFindExtInHandshake(const uint8_t *data, size_t len, uint16_t type, const uint8_t **ext, size_t *len_ext, bool bPartialIsOK) { @@ -143,14 +157,11 @@ bool TLSFindExtInHandshake(const uint8_t *data, size_t len, uint16_t type, const size_t l, ll; + if (!bPartialIsOK && !IsTLSHandshakeFull(data,len)) return false; + l = 1 + 3 + 2 + 32; // SessionIDLength if (len < (l + 1)) return false; - if (!bPartialIsOK) - { - ll = data[1] << 16 | data[2] << 8 | data[3]; // HandshakeProtocol length - if (len < (ll + 4)) return false; - } l += data[l] + 1; // CipherSuitesLength if (len < (l + 2)) return false; @@ -276,7 +287,7 @@ bool IsQUICCryptoHello(const uint8_t *data, size_t len, size_t *hello_offset, si // offset must be 0 if it's a full segment, not just a chunk if (coff || (offset+tvb_get_size(data[offset])) >= len) return false; offset += tvb_get_varint(data + offset, &clen); - if (data[offset] != 0x01 || (offset + clen) > len) return false; + if ((offset + clen) > len || !IsTLSHandshakeClientHello(data+offset,clen)) return false; if (hello_offset) *hello_offset = offset; if (hello_len) *hello_len = (size_t)clen; return true; diff --git a/nfq/protocol.h b/nfq/protocol.h index d915eec..7bdea55 100644 --- a/nfq/protocol.h +++ b/nfq/protocol.h @@ -22,6 +22,9 @@ uint16_t TLSRecordDataLen(const uint8_t *data); size_t TLSRecordLen(const uint8_t *data); bool IsTLSRecordFull(const uint8_t *data, size_t len); bool IsTLSClientHello(const uint8_t *data, size_t len, bool bPartialIsOK); +size_t TLSHandshakeLen(const uint8_t *data); +bool IsTLSHandshakeClientHello(const uint8_t *data, size_t len); +bool IsTLSHandshakeFull(const uint8_t *data, size_t len); bool TLSFindExt(const uint8_t *data, size_t len, uint16_t type, const uint8_t **ext, size_t *len_ext, bool bPartialIsOK); bool TLSFindExtInHandshake(const uint8_t *data, size_t len, uint16_t type, const uint8_t **ext, size_t *len_ext, bool bPartialIsOK); bool TLSHelloExtractHost(const uint8_t *data, size_t len, char *host, size_t len_host, bool bPartialIsOK);