forked from robertdavidgraham/masscan
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtempl-tcp-hdr.c
1608 lines (1353 loc) · 51.4 KB
/
templ-tcp-hdr.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
This module edits an existing TCP packet, adding and removing
options, setting the values of certain fields.
From RFC793:
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Source Port | Destination Port |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Sequence Number |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Acknowledgment Number |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Data | |U|A|P|R|S|F| |
| Offset| Reserved |R|C|S|S|Y|I| Window |
| | |G|K|H|T|N|N| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Checksum | Urgent Pointer |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Options | Padding |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| data |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
TCP Window Scale Option (WSopt):
Kind: 3 Length: 3 bytes
+---------+---------+---------+
| Kind=3 |Length=3 |shift.cnt|
+---------+---------+---------+
TCP Timestamps Option (TSopt):
Kind: 8
Length: 10 bytes
+-------+-------+---------------------+---------------------+
|Kind=8 | 10 | TS Value (TSval) |TS Echo Reply (TSecr)|
+-------+-------+---------------------+---------------------+
1 1 4 4
TCP Sack-Permitted Option:
Kind: 4
+---------+---------+
| Kind=4 | Length=2|
+---------+---------+
TCP SACK Option:
Kind: 5
Length: Variable
+--------+--------+
| Kind=5 | Length |
+--------+--------+--------+--------+
| Left Edge of 1st Block |
+--------+--------+--------+--------+
| Right Edge of 1st Block |
+--------+--------+--------+--------+
| |
/ . . . /
| |
+--------+--------+--------+--------+
| Left Edge of nth Block |
+--------+--------+--------+--------+
| Right Edge of nth Block |
+--------+--------+--------+--------+
*/
#include "templ-tcp-hdr.h"
#include "templ-opts.h"
#include "logger.h"
#include "proto-preprocess.h"
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
struct tcp_opt_t {
const unsigned char *buf;
size_t length;
unsigned kind;
bool is_found;
};
struct tcp_hdr_t {
size_t begin;
size_t max;
size_t ip_offset;
unsigned char ip_version;
bool is_found;
};
/**
* Do a memmove() of a chunk of memory within a buffer with bounds checking.
*/
static void
safe_memmove(unsigned char *buf, size_t length, size_t to, size_t from, size_t chunklength) {
if (chunklength + to > length) {
fprintf(stderr, "+"); fflush(stderr);
chunklength = length - to;
}
if (chunklength + from > length) {
fprintf(stderr, "-"); fflush(stderr);
chunklength = length - from;
}
memmove(buf + to, buf + from, chunklength);
}
/**
* Do a memset() of a chunk of memory within a buffer with bounds checking
*/
static void
safe_memset(unsigned char *buf, size_t length, size_t offset, int c, size_t chunklength) {
if (chunklength + offset > length) {
chunklength = length - offset;
fprintf(stderr, "*"); fflush(stderr);
}
memset(buf + offset, c, chunklength);
}
/***************************************************************************
* A typical hexdump function, but dumps specifically the <options-list>
* section of a TCP header. An added feature is that it marks the byte
* at "offset". This makes debugging easier, so I can see the <options-list>
* as I'm stepping through code. You'll see this commented-out throughout
* the code.
***************************************************************************/
static void
_HEXDUMP(const void *v, struct tcp_hdr_t hdr, size_t offset, const char *name)
{
const unsigned char *p = ((const unsigned char *)v) + hdr.begin + 20;
size_t i;
size_t len = hdr.max - hdr.begin + 8 - 20;
printf("%s:\n", name);
offset -= hdr.begin + 20;
for (i=0; i<len; i += 16) {
size_t j;
for (j=i; j<i+16 && j<len; j++) {
char c = ' ';
if (j == offset)
c = '>';
if (j + 1 == offset)
c = '<';
printf("%02x%c", p[j], c);
}
for (;j<i+16; j++)
printf(" ");
printf(" ");
for (j=i; j<i+16 && j<len; j++) {
char c = p[j];
if (j == offset)
c = '#';
if (isprint(c&0xff) && !isspace(c&0xff))
printf("%c", c);
else
printf(".");
}
printf("\n");
}
}
/***************************************************************************
* A quick macro to calculate the TCP header length, given a buffer
* and an offset to the start of the TCP header.
***************************************************************************/
static unsigned inline
_tcp_header_length(const unsigned char *buf, size_t offset) {
return (buf[offset + 12] >> 4) * 4;
}
/***************************************************************************
* Does a consistency check of the whole packet, including IP header,
* TCP header, and the options in the <options-list> field. This is used
* in the self-test feature after test cases, to make sure the packet
* hasn't bee corrupted.
***************************************************************************/
static int
_consistancy_check(const unsigned char *buf, size_t length,
const void *payload, size_t payload_length) {
struct PreprocessedInfo parsed;
unsigned is_success;
/* Parse the packet */
is_success = preprocess_frame(buf,
(unsigned)length,
1 /*enet*/,
&parsed);
if (!is_success || parsed.found != FOUND_TCP) {
fprintf(stderr, "[-] check: TCP header not found\n");
goto fail;
}
/* Check the lengths */
switch (parsed.ip_version) {
case 4:
if (parsed.ip_length + 14 != length) {
fprintf(stderr, "[-] check: IP length bad\n");
goto fail;
}
break;
case 6:
break;
default:
fprintf(stderr, "[-] check: IPv?\n");
goto fail;
}
/* Validate TCP header options */
{
size_t offset = parsed.transport_offset;
size_t max = offset + _tcp_header_length(buf, offset);
/* Get the start of the <options> section of the header. This is defined
* as 20 bytes into the TCP header. */
offset += 20;
/* Enumerate any existing options one-by-one. */
while (offset < max) {
unsigned kind;
unsigned len;
/* Get the option type (aka. "kind") */
kind = buf[offset++];
if (kind == 0x00) {
/* EOL - end of options list
* According to the spec, processing should stop here, even if
* there are additional options after this point. */
break;
} else if (kind == 0x01) {
/* NOP - No-operation
* This is a single byte option, used to pad other options to
* even 4 byte boundaries. Padding is optional. */
continue;
}
/* If we've reached the end of */
if (offset > max)
goto fail;
if (offset == max)
break;
len = buf[offset++];
/* Check for corruption, the lenth field is inclusive, so should
* equal at least two. It's maximum length should be bfore the end
* of the packet */
if (len < 2 || len > (max-offset+2)) {
goto fail;
}
offset += len - 2;
}
}
/* Check the payload */
if (parsed.app_length != payload_length)
goto fail;
if (memcmp(buf + parsed.app_offset, payload, payload_length) != 0)
goto fail;
return 0;
fail:
return 1;
}
/***************************************************************************
* Find the TCP header in the packet. We can't be sure what's in the
* current template because it could've been provided by the user, so
* we instead parse it as if we've received it from the network wire.
***************************************************************************/
static struct tcp_hdr_t
_find_tcp_header(const unsigned char *buf, size_t length) {
struct tcp_hdr_t hdr = {0};
struct PreprocessedInfo parsed;
unsigned is_success;
/*
* Parse the packet, telling us where the TCP header is. This works
* for both IPv4 and IPv6, we care only about the TCP header portion.
*/
is_success = preprocess_frame(buf, /* the packet, including Ethernet hdr */
(unsigned)length,
1 /*enet*/,
&parsed);
if (!is_success || parsed.found != FOUND_TCP) {
/* We were unable to parse a well-formatted TCP packet. This
* might've been UDP or something. */
goto fail;
}
hdr.begin = parsed.transport_offset;
hdr.max = hdr.begin + _tcp_header_length(buf, hdr.begin);
hdr.ip_offset = parsed.ip_offset;
hdr.ip_version = (unsigned char)parsed.ip_version;
hdr.is_found = true;
return hdr;
fail:
hdr.is_found = false;
return hdr;
}
/***************************************************************************
* A quick macro at the start of for(;;) loops that enumerate all the
* options in the <option-list>
***************************************************************************/
static inline size_t
_opt_begin(struct tcp_hdr_t hdr) {
return hdr.begin + 20; /* start of <options> field */
}
/***************************************************************************
* A quick macro in the for(;;) loop that enumerates all the options
* in the <option-list>. It has three possibilities based on the KIND:
* 0x00 - we've reached the end of the options-list
* 0x01 - padding NOP byte, which we skipo
* 0x?? - some option, the following byte is the length. We skip
* that `len` bytes.
***************************************************************************/
static inline size_t
_opt_next(struct tcp_hdr_t hdr, size_t offset, const unsigned char *buf) {
unsigned kind = buf[offset];
if (kind == 0x00) {
return hdr.max;
} else if (kind == 0x01) {
return offset + 1;
} else if (offset + 2 > hdr.max) {
return hdr.max; /* corruption */
} else {
unsigned len = buf[offset+1];
if (len < 2 || offset + len > hdr.max)
return hdr.max; /* corruption */
else
return offset + len;
}
}
/***************************************************************************
***************************************************************************/
static void
_HEXDUMPopt(const unsigned char *buf, size_t length, const char *name) {
struct tcp_hdr_t hdr;
hdr = _find_tcp_header(buf, length);
if (!hdr.is_found) {
fprintf(stderr, "[-] templ.tcp.hdr: failure\n");
}
_HEXDUMP(buf, hdr, _opt_begin(hdr), name);
}
/***************************************************************************
* Search throgh the <option-list> until we find the specified option,
* 'kind', or reach the end of the list. An impossible 'kind', like 0x100,
* will force finding the end of the list before padding starts.
***************************************************************************/
static size_t
_find_opt(const unsigned char *buf, struct tcp_hdr_t hdr, unsigned in_kind,
unsigned *nop_count) {
size_t offset;
/* This field is optional, if used, set it to zero */
if (nop_count)
*nop_count = 0;
/* enumerate all <options> looking for a match */
for (offset = _opt_begin(hdr);
offset < hdr.max;
offset = _opt_next(hdr, offset, buf)) {
unsigned kind;
/* get the option type/kind */
kind = buf[offset];
/* Stop search if we hit an EOL marker */
if (kind == 0x00)
break;
/* Stop search when we find our option */
if (kind == in_kind)
break;
/* Count the number of NOPs leading up to where we end */
if (nop_count) {
if (kind == 0x01)
(*nop_count)++;
else
(*nop_count) = 0;
}
}
return offset;
}
/***************************************************************************
* Search the TCP header's <options> field for the specified kind/type.
* Typical kinds of options are MSS, window scale, SACK, timestamp.
***************************************************************************/
static struct tcp_opt_t
tcp_find_opt(const unsigned char *buf, size_t length, unsigned in_kind) {
struct tcp_opt_t result = {0};
struct tcp_hdr_t hdr;
size_t offset;
/* Get the TCP header in the packet */
hdr = _find_tcp_header(buf, length);
if (!hdr.is_found)
goto fail;
/* Search for a matchin <option> */
offset = _find_opt(buf, hdr, in_kind, 0);
if (offset >= hdr.max || buf[offset] != in_kind)
goto fail;
/* We've found it! If we've passed all the checks above, we have
* a well formatted field, so just return it. */
result.kind = in_kind;
result.buf = buf + offset + 2;
result.length = buf[offset+1] - 2;
if (offset + result.length >= hdr.max)
goto fail;
result.is_found = true;
return result;
fail:
result.is_found = false;
return result;
}
/***************************************************************************
* Adjusts the IP "total length" and TCP "header length" fields to match
* recent additions/removals of options in the <option-list>
***************************************************************************/
static void
_adjust_length(unsigned char *buf, size_t length, int adjustment, struct tcp_hdr_t hdr) {
size_t ip_offset = hdr.ip_offset;
/* The adjustment should already have been aligned on an even 4 byte
* boundary */
if ((adjustment & 0x3) != 0) {
fprintf(stderr, "[-] templ.tcp: impossible alignment error\n");
return;
}
/* Adjust the IP header length */
switch (hdr.ip_version) {
case 4: {
unsigned total_length;
total_length = buf[ip_offset+2] << 8 | buf[ip_offset+3] << 0;
total_length += adjustment;
buf[ip_offset+2] = (unsigned char)(total_length>>8);
buf[ip_offset+3] = (unsigned char)(total_length>>0);
total_length = buf[ip_offset+2] << 8 |buf[ip_offset+3] << 0;
if (total_length + 14 != length) {
fprintf(stderr, "[-] IP length mismatch\n");
}
break;
}
case 6: {
unsigned payload_length;
payload_length = buf[ip_offset+4] << 8 | buf[ip_offset+5] << 0;
payload_length += adjustment;
buf[ip_offset+4] = (unsigned char)(payload_length>>8);
buf[ip_offset+5] = (unsigned char)(payload_length>>0);
break;
}
}
/* Adjust the TCP header length */
{
size_t hdr_length;
size_t offset = hdr.begin + 12;
hdr_length = (buf[offset] >> 4) * 4;
hdr_length += adjustment;
if (hdr_length % 4 != 0) {
fprintf(stderr, "[-] templ.tcp corruptoin\n");
}
buf[offset] = (unsigned char)((buf[offset] & 0x0F) | ((hdr_length/4) << 4));
hdr_length = (buf[offset] >> 4) * 4;
if (hdr.begin + hdr_length > length) {
fprintf(stderr, "[-] templ.tcp corruptoin\n");
}
}
}
/***************************************************************************
* After adding/removing an option, the <option-list> may no longer be
* aligned on an even 4-byte boundary as required. This function
* adds padding as necessary to align to the boundary.
***************************************************************************/
static void
_add_padding(unsigned char **inout_buf, size_t *inout_length, size_t offset, unsigned pad_count) {
unsigned char *buf = *inout_buf;
size_t length = *inout_length;
length += pad_count;
buf = realloc(buf, length);
/* open space between headers and payload */
safe_memmove(buf, length,
offset + pad_count,
offset,
(length - pad_count) - offset);
/* set padding to zero */
safe_memset(buf, length,
offset, 0, pad_count);
/* Set the out parameters */
*inout_buf = buf;
*inout_length = length;
}
/***************************************************************************
* Afte changes, there my be more padding bytes than necessary. This
* reduces the number to 3 or less. Also, it changes any trailing NOPs
* to EOL bytes, since there are no more options after that point.
***************************************************************************/
static bool
_normalize_padding(unsigned char **inout_buf, size_t *inout_length) {
unsigned char *buf = *inout_buf;
size_t length = *inout_length;
struct tcp_hdr_t hdr;
size_t offset;
unsigned nop_count = 0;
/* find TCP header */
hdr = _find_tcp_header(buf, length);
if (!hdr.is_found)
goto fail;
/* find the start of the padding field */
offset = _find_opt(buf, hdr, 0x100, &nop_count);
if (offset >= hdr.max && nop_count == 0)
goto success; /* no padding needing to be removed */
/* If NOPs immediately before EOL, include them too */
offset -= nop_count;
{
size_t remove_count = hdr.max - offset;
/* the amount removed must be aligned on 4-byte boundary */
while (remove_count % 4)
remove_count--;
/* If we have nothing left to remove, then exit.
* THIS IS THE NORMAL CASE -- most of the time, we have no
* extra padding to remove. */
if (remove_count == 0)
goto fail; /* likely, normal*/
//_HEXDUMP(buf, hdr, offset, "before padding removal");
safe_memmove(buf, length,
offset,
offset + remove_count,
length - (offset + remove_count));
hdr.max -= remove_count;
length -= remove_count;
/* normalize all the bytes to zero, in case they aren't already */
safe_memset(buf, length, offset, 0, hdr.max - offset);
//_HEXDUMP(buf, hdr, offset, "after padding removal");
/* fix the IP and TCP length fields */
_adjust_length(buf, length, 0 - (int)remove_count, hdr);
}
success:
*inout_buf = buf;
*inout_length = length;
return true; /* success */
fail:
*inout_buf = buf;
*inout_length = length;
return false; /* failure */
}
/***************************************************************************
***************************************************************************/
static bool
tcp_remove_opt(
unsigned char **inout_buf, size_t *inout_length, unsigned in_kind
) {
unsigned char *buf = *inout_buf;
size_t length = *inout_length;
struct tcp_hdr_t hdr;
size_t offset;
unsigned nop_count = 0;
/* find the TCP header */
hdr = _find_tcp_header(buf, length);
if (!hdr.is_found)
goto fail;
/* enumerate all the <options> looking for a match */
offset = _find_opt(buf, hdr, in_kind, &nop_count);
if (offset + 2 >= hdr.max)
goto success; /* not found, no matching option type/kind */
{
unsigned opt_len = buf[offset+1];
unsigned remove_length = opt_len;
if (offset + opt_len > hdr.max)
goto fail;
/* Remove any trailing NOPs */
while (offset + remove_length < hdr.max
&& buf[offset + remove_length] == 1)
remove_length++;
/* Remove any leading NOPs */
offset -= nop_count;
remove_length += nop_count;
/* Remove the bytes from the current packet buffer.
* Before this will be the ...IP/TCP headers plus maybe some options.
* After this will be maybe some options, padding, then the TCP payload
* */
//_HEXDUMP(buf, hdr, offset, "before removal");
safe_memmove(buf, length,
offset,
offset + remove_length,
length - (offset + remove_length));
hdr.max -= remove_length;
length -= remove_length;
//_HEXDUMP(buf, hdr, offset, "after removal");
/* Now we may need to add back padding */
if (remove_length % 4) {
unsigned add_length = (remove_length % 4);
_add_padding(&buf, &length, hdr.max, add_length);
remove_length -= add_length;
hdr.max += add_length;
}
//_HEXDUMP(buf, hdr, offset, "padding added");
/* fix the IP and TCP length fields */
_adjust_length(buf, length, 0 - remove_length, hdr);
/* In case we've padded the packet with four 0x00, get rid
* of them */
_normalize_padding(&buf, &length);
}
success:
*inout_buf = buf;
*inout_length = length;
return true;
fail:
*inout_buf = buf;
*inout_length = length;
return false;
}
/***************************************************************************
***************************************************************************/
static int
_insert_field(unsigned char **inout_buf,
size_t *inout_length,
size_t offset_begin,
size_t offset_end,
const unsigned char *new_data,
size_t new_length
) {
unsigned char *buf = *inout_buf;
size_t length = *inout_length;
int adjust = 0;
/* can theoreitcally be negative, but that's ok */
adjust = (int)new_length - ((int)offset_end - (int)offset_begin);
if (adjust > 0) {
length += adjust;
buf = realloc(buf, length);
safe_memmove(buf, length,
offset_begin + new_length,
offset_end,
(length - adjust) - offset_end);
}
if (adjust < 0) {
safe_memmove(buf, length,
offset_begin + new_length,
offset_end,
length - offset_end);
length += adjust;
buf = realloc(buf, length);
}
/**/
memcpy(buf + offset_begin,
new_data,
new_length);
*inout_buf = buf;
*inout_length = length;
return adjust;
}
/** Calculate the total number of padding bytes, both NOPs in the middle
* and EOLs at the end. We call this when there's not enough space for
* another option, and we want to remove all the padding. */
#if 0
static unsigned
_calc_padding(const unsigned char *buf, struct tcp_hdr_t hdr) {
size_t offset;
unsigned result = 0;
/* enumerate through all <option> fields */
for (offset = _opt_begin(hdr);
offset < hdr.max;
offset = _opt_next(hdr, offset, buf)) {
unsigned kind;
/* Get the kind: 0=EOL, 1=NOP, 2=MSS, 3=Wscale, etc. */
kind = buf[offset];
/* If EOL, we end here, and all the remainder bytes are counted
* as padding. */
if (kind == 0) {
result += (hdr.max - offset);
break;
}
/* If a NOP, then this is a padding byte */
if (kind == 1)
result++;
}
return result;
}
#endif
/***************************************************************************
* Remove all the padding bytes, and return an offset to the beginning
* of the rest of the option field.
***************************************************************************/
static size_t
_squeeze_padding(unsigned char *buf, size_t length, struct tcp_hdr_t hdr, unsigned in_kind) {
size_t offset;
unsigned nop_count = 0;
for (offset = _opt_begin(hdr);
offset < hdr.max;
offset = _opt_next(hdr, offset, buf)) {
unsigned kind;
unsigned len;
//_HEXDUMP(buf, hdr, offset, "squeeze");
/* Get the kind: 0=EOL, 1=NOP, 2=MSS, 3=Wscale, etc. */
kind = buf[offset];
/* If a NOP padding, simply count it until we reach something
* more interesting */
if (kind == 0x01) {
nop_count++;
continue;
}
/* If end of option list, any remaining padding bytes are added */
if (kind == 0x00) {
/* normalize the padding at the end */
offset -= nop_count;
safe_memset(buf, length, offset, 0, hdr.max - offset);
//_HEXDUMP(buf, hdr, offset, "null");
return offset;
}
/* If we match an existing field, all those bytes become padding */
if (kind == in_kind) {
len = buf[offset+1];
safe_memset(buf, length, offset, 0x01, len);
nop_count++;
//_HEXDUMP(buf, hdr, offset, "VVVVV");
continue;
}
if (nop_count == 0)
continue; /*no squeezing needed */
/* move this field backward overwriting NOPs */
len = buf[offset+1];
safe_memmove(buf, length,
offset - nop_count,
offset,
len);
//_HEXDUMP(buf, hdr, offset - nop_count, "<<<<");
/* now write NOPs where this field used to be */
safe_memset(buf, length,
offset + len - nop_count, 0x01, nop_count);
//_HEXDUMP(buf, hdr, offset + len - nop_count, "!!!!!");
/* reset the <offset> to the end of this relocated field */
offset -= nop_count;
nop_count = 0;
}
/* if we reach the end, then there were only NOPs at the end and no
* EOL byte, so simply zero them out */
safe_memset(buf, length,
offset - nop_count, 0x00, nop_count);
offset -= nop_count;
//_HEXDUMP(buf, hdr, offset, "");
return offset;
}
/***************************************************************************
***************************************************************************/
static bool
tcp_add_opt(unsigned char **inout_buf,
size_t *inout_length,
unsigned opt_kind,
unsigned opt_length,
const unsigned char *opt_data) {
unsigned char *buf = *inout_buf;
size_t length = *inout_length;
struct tcp_hdr_t hdr;
size_t offset;
unsigned nop_count = 0;
int adjust = 0;
/* Check for corruption:
* The maximum size of a TCP header is 60 bytes (0x0F * 4), and the
* rest of the header takes up 20 bytes. The [kind,length] takes up
* another 2 bytes. Thus, the max option length is 38 bytes */
if (opt_length > 38) {
fprintf(stderr, "[-] templ.tcp.add_opt: opt_len too large\n");
goto fail;
}
/* find TCP header */
hdr = _find_tcp_header(buf, length);
if (!hdr.is_found)
goto fail;
/* enumerate all existing options looking match */
offset = _find_opt(buf, hdr, opt_kind, &nop_count);
{
size_t old_begin;
size_t old_end;
unsigned char new_field[64];
size_t new_length;
/* Create a well-formatted field that will be inserted */
new_length = 1 + 1 + opt_length;
new_field[0] = (unsigned char)opt_kind;
new_field[1] = (unsigned char)new_length;
memcpy(new_field + 2, opt_data, opt_length);
/* Calculate the begin/end of the existing field in the packet */
old_begin = offset;
if (old_begin >= hdr.max)
old_end = hdr.max; /* will insert end of header */
else if (buf[offset] == 0x00)
old_end = hdr.max; /* will insert start of padding */
else if (buf[offset] == opt_kind) { /* will replace old field */
size_t len = buf[offset + 1];
old_end = offset + len;
} else {
fprintf(stderr, "[-] not possible i09670t\n");
return false;
}
/* If the existing space is too small, try to expand it by
* using neighboring (leading, trailing) NOPs */
while ((old_end-old_begin) < new_length) {
if (nop_count) {
nop_count--;
old_begin--;
} else if (old_end < hdr.max && buf[old_end] == 0x01) {
old_end++;
} else
break;
}
/* If the existing space is too small, and we are at the end,
* and there's pading, then try to use the padding */
if ((old_end-old_begin) < new_length) {
if (old_end < hdr.max) {
if (buf[old_end] == 0x00) {
/* normalize padding to all zeroes */
safe_memset(buf, length, old_end, 0, hdr.max - old_end);
while ((old_end-old_begin) < new_length) {
if (old_end >= hdr.max)
break;
old_end++;
}
}
}
}
/* Make sure we have enough space in the header */
{
static const size_t max_tcp_hdr = (0xF0>>4) * 4; /* 60 */
size_t added = new_length - (old_end - old_begin);
if (hdr.max + added > hdr.begin + max_tcp_hdr) {
//unsigned total_padding = _calc_padding(buf, hdr);
old_begin = _squeeze_padding(buf, length, hdr, opt_kind);
old_end = hdr.max;
}
}
/* Now insert the option field into packet. This may change the
* sizeof the packet. The amount changed is indicated by 'adjust' */
adjust = _insert_field(&buf, &length,
old_begin, old_end,
new_field, new_length);
hdr.max += adjust;
}
if (adjust) {
/* TCP headers have to be aligned to 4 byte boundaries, so we may need
* to add padding of 0 at the end of the header to handle this */
if (adjust % 4 && adjust > 0) {
unsigned add_length = 4 - (adjust % 4);
_add_padding(&buf, &length, hdr.max, add_length);
hdr.max += add_length;
adjust += add_length;
} else if (adjust % 4 && adjust < 0) {
unsigned add_length = 0 - (adjust % 4);
//_HEXDUMP(buf, hdr, hdr.max, "pad before");
_add_padding(&buf, &length, hdr.max, add_length);
hdr.max += add_length;
adjust += add_length;
//_HEXDUMP(buf, hdr, hdr.max, "pad after");
}
/* fix the IP and TCP length fields */
_adjust_length(buf, length, adjust, hdr);
/* In case we've padded the packet with four 0x00, get rid
* of them */
_normalize_padding(&buf, &length);
}
*inout_buf = buf;
*inout_length = length;
return true;
fail:
/* no changes were made */
*inout_buf = buf;
*inout_length = length;
return false;
}
/***************************************************************************
***************************************************************************/
static unsigned
tcp_get_mss(const unsigned char *buf, size_t length, bool *is_found) {
struct tcp_opt_t opt;
unsigned result = 0;
opt = tcp_find_opt(buf, length, 2 /* MSS */);
if (is_found)
*is_found = opt.is_found;
if (!opt.is_found)
return 0xFFFFffff;