-
Notifications
You must be signed in to change notification settings - Fork 11
/
tcp-scan.c
2219 lines (2149 loc) · 75.3 KB
/
tcp-scan.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
/*
* The TCP Scanner (tcp-scan) is Copyright (C) 2003-2013 Roy Hills,
* NTA Monitor Ltd.
*
* This file is part of tcp-scan.
*
* tcp-scan is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* tcp-scan is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with tcp-scan. If not, see <http://www.gnu.org/licenses/>.
*
* tcp-scan -- The TCP Scanner
*
* Author: Roy Hills
* Date: 16 September 2003
*
* Usage:
* tcp-scan [options] [host...]
*
* Description:
*
* tcp-scan sends the specified TCP packet to the specified hosts
* and displays any responses received.
*
*/
#include "tcp-scan.h"
/* Global variables */
static unsigned retry = DEFAULT_RETRY; /* Number of retries */
static unsigned timeout = DEFAULT_TIMEOUT; /* Per-host timeout */
static float backoff_factor = DEFAULT_BACKOFF_FACTOR; /* Backoff factor */
static int snaplen = SNAPLEN; /* Pcap snap length */
static uint32_t seq_no; /* Initial TCP sequence number */
static uint32_t ack_no; /* TCP acknowledgement number */
static int seq_no_flag=0;
static int ack_no_flag=0;
static uint16_t source_port; /* TCP Source Port */
static int source_port_flag=0;
static uint16_t window=DEFAULT_WINDOW; /* TCP Window size */
static uint16_t mss=DEFAULT_MSS; /* TCP MSS. 0=Don't use MSS option */
static int open_only=0; /* Only show open ports? */
static int wscale_flag=0; /* Add wscale=0 TCP option? */
static int sack_flag=0; /* Add SACKOK TCP option? */
static int timestamp_flag=0; /* Add TIMESTAMP TCP option? */
static int ip_ttl = DEFAULT_TTL; /* IP TTL */
static char *if_name=NULL; /* Interface name, e.g. "eth0" */
static int quiet_flag=0; /* Don't decode the packet */
static int ignore_dups=0; /* Don't display duplicate packets */
static int df_flag=DEFAULT_DF; /* IP DF Flag */
static int ip_tos=DEFAULT_TOS; /* IP TOS Field */
static int portname_flag=0; /* Display port names */
static int tcp_flags_flag=0; /* Specify outbound TCP flags */
static tcp_flags_struct tcp_flags; /* Specified TCP flags */
static char **portnames=NULL;
static unsigned live_count; /* Number of entries awaiting reply */
static char service_file[MAXLINE]; /* TCP Service file name */
static int verbose = 0; /* Verbose level */
static int debug = 0; /* Debug flag */
static char *local_data=NULL; /* Local data from --port option */
static host_entry *helist = NULL; /* Array of host entries */
static host_entry **helistptr; /* Array of pointers to host entries */
static unsigned num_hosts = 0; /* Number of entries in the list */
static unsigned max_iter; /* Max iterations in find_host() */
static pcap_t *pcap_handle; /* pcap handle */
static host_entry **cursor; /* Pointer to current host entry ptr */
static unsigned responders = 0; /* Number of hosts which responded */
static char filename[MAXLINE];
static int filename_flag=0;
static int random_flag=0; /* Randomise the list */
static int numeric_flag=0; /* IP addresses only */
static int ipv6_flag=0; /* IPv6 */
static unsigned bandwidth=DEFAULT_BANDWIDTH; /* Bandwidth in bits per sec */
static unsigned interval=0;
static uint32_t source_address; /* Source IP Address */
static int pcap_fd; /* pcap File Descriptor */
static size_t ip_offset; /* Offset to IP header in pcap pkt */
static uint16_t *port_list=NULL;
static char *ga_err_msg; /* getaddrinfo error message */
static char pcap_savefile[MAXLINE]; /* pcap savefile filename */
static pcap_dumper_t *pcap_dump_handle = NULL; /* pcap savefile handle */
int
main(int argc, char *argv[]) {
int sockfd; /* IP socket file descriptor */
struct timeval now;
struct timeval diff; /* Difference between two timevals */
unsigned select_timeout; /* Select timeout */
TCP_UINT64 loop_timediff; /* Time since last packet sent in us */
TCP_UINT64 host_timediff; /* Time since last pkt sent to this host (us) */
struct timeval last_packet_time; /* Time last packet was sent */
int req_interval; /* Requested per-packet interval */
int cum_err=0; /* Cumulative timing error */
struct timeval start_time; /* Program start time */
struct timeval end_time; /* Program end time */
struct timeval elapsed_time; /* Elapsed time as timeval */
double elapsed_seconds; /* Elapsed time in seconds */
static int reset_cum_err;
static int pass_no;
int first_timeout=1;
const int on = 1; /* For setsockopt */
unsigned i;
/*
* Initialise file names to the empty string.
*/
service_file[0] = '\0';
pcap_savefile[0] = '\0';
/*
* Process options.
*/
process_options(argc, argv);
/*
* Get program start time for statistics displayed on completion.
*/
Gettimeofday(&start_time);
if (debug) {print_times(); printf("main: Start\n");}
/*
* Create raw IP socket and set IP_HDRINCL
*/
if ((sockfd = socket(AF_INET, SOCK_RAW, IPPROTO_RAW)) < 0)
err_sys("socket");
if ((setsockopt(sockfd, IPPROTO_IP, IP_HDRINCL, &on, sizeof(on))) != 0)
err_sys("setsockopt");
if ((setsockopt(sockfd, SOL_SOCKET, SO_BROADCAST, &on, sizeof(on))) != 0)
err_sys("setsockopt");
/*
* Call initialisation routine to perform initial setup.
*/
initialise();
/*
* Drop privileges.
*/
if ((setuid(getuid())) < 0) {
err_sys("setuid");
}
/*
* If we're not reading from a file, then we must have some hosts
* given as command line arguments.
*/
if (!filename_flag)
if ((argc - optind) < 1)
usage(EXIT_FAILURE, 0);
/*
* Populate the list from the specified file if --file was specified, or
* otherwise from the remaining command line arguments.
*/
if (filename_flag) { /* Populate list from file */
FILE *fp;
char line[MAXLINE];
char *cp;
if ((strcmp(filename, "-")) == 0) { /* Filename "-" means stdin */
fp = stdin;
} else {
if ((fp = fopen(filename, "r")) == NULL) {
err_sys("fopen");
}
}
while (fgets(line, MAXLINE, fp)) {
cp = line;
while (!isspace(*cp) && *cp != '\0')
cp++;
*cp = '\0';
add_host(line, timeout);
}
fclose(fp);
} else { /* Populate list from command line arguments */
argv=&argv[optind];
while (*argv) {
add_host(*argv, timeout);
argv++;
}
}
/*
* Check that we have at least one entry in the list.
*/
if (!num_hosts)
err_msg("No hosts to process.");
/*
* Check that the combination of specified options and arguments is
* valid.
*/
if (interval && bandwidth != DEFAULT_BANDWIDTH)
err_msg("ERROR: You cannot specify both --bandwidth and --interval.");
/*
* Create and initialise array of pointers to host entries.
*/
helistptr = Malloc(num_hosts * sizeof(host_entry *));
for (i=0; i<num_hosts; i++)
helistptr[i] = &helist[i];
/*
* Randomise the list if required.
*/
if (random_flag) {
int r;
host_entry *temp;
for (i=num_hosts-1; i>0; i--) {
r = (int)(genrand_real2() * i); /* 0<=r<i */
temp = helistptr[i];
helistptr[i] = helistptr[r];
helistptr[r] = temp;
}
}
/*
* Set current host pointer (cursor) to start of list, zero
* last packet sent time, and set last receive time to now.
*/
live_count = num_hosts;
cursor = helistptr;
last_packet_time.tv_sec=0;
last_packet_time.tv_usec=0;
/*
* Calculate the required interval to achieve the required outgoing
* bandwidth unless the interval was manually specified with --interval.
*/
if (!interval) {
size_t packet_out_len;
packet_out_len=send_packet(0, NULL, 1, NULL); /* Get packet size */
if (packet_out_len < MINIMUM_FRAME_SIZE)
packet_out_len = MINIMUM_FRAME_SIZE; /* Adjust to minimum size */
packet_out_len += PACKET_OVERHEAD; /* Add layer 2 overhead */
interval = ((TCP_UINT64)packet_out_len * 8 * 1000000) / bandwidth;
if (verbose) {
warn_msg("DEBUG: Ethernet frame len=%zu bytes, bandwidth=%u bps, "
"interval=%u us",
packet_out_len, bandwidth, interval);
}
}
/*
* Display initial message.
*/
printf("Starting %s with %u ports\n", PACKAGE_STRING, num_hosts);
/*
* Display the lists if verbose setting is 3 or more.
*/
if (verbose > 2)
dump_list();
/*
* Main loop: send packets to all hosts in order until a response
* has been received or the host has exhausted its retry limit.
*
* The loop exits when all hosts have either responded or timed out.
*/
reset_cum_err = 1;
req_interval = interval;
while (live_count) {
if (debug) {print_times(); printf("main: Top of loop.\n");}
/*
* Obtain current time and calculate deltas since last packet and
* last packet to this host.
*/
Gettimeofday(&now);
/*
* If the last packet was sent more than interval us ago, then we can
* potentially send a packet to the current host.
*/
timeval_diff(&now, &last_packet_time, &diff);
loop_timediff = (TCP_UINT64)1000000*diff.tv_sec + diff.tv_usec;
if (loop_timediff >= (unsigned)req_interval) {
if (debug) {print_times(); printf("main: Can send packet now. loop_timediff=" TCP_UINT64_FORMAT "\n", loop_timediff);}
/*
* If the last packet to this host was sent more than the current
* timeout for this host us ago, then we can potentially send a packet
* to it.
*/
timeval_diff(&now, &((*cursor)->last_send_time), &diff);
host_timediff = (TCP_UINT64)1000000*diff.tv_sec + diff.tv_usec;
if (host_timediff >= (*cursor)->timeout) {
if (reset_cum_err) {
if (debug) {print_times(); printf("main: Reset cum_err\n");}
cum_err = 0;
req_interval = interval;
reset_cum_err = 0;
} else {
cum_err += loop_timediff - interval;
if (req_interval >= cum_err) {
req_interval = req_interval - cum_err;
} else {
req_interval = 0;
}
}
if (debug) {print_times(); printf("main: Can send packet to host %d now. host_timediff=" TCP_UINT64_FORMAT ", timeout=%u, req_interval=%d, cum_err=%d\n", (*cursor)->n, host_timediff, (*cursor)->timeout, req_interval, cum_err);}
select_timeout = req_interval;
/*
* If we've exceeded our retry limit, then this host has timed out so
* remove it from the list. Otherwise, increase the timeout by the
* backoff factor if this is not the first packet sent to this host
* and send a packet.
*/
if (verbose && (*cursor)->num_sent > pass_no) {
warn_msg("---\tPass %d complete", pass_no+1);
pass_no = (*cursor)->num_sent;
}
if ((*cursor)->num_sent >= retry) {
if (verbose > 1)
warn_msg("---\tRemoving host entry %u (%s) - Timeout", (*cursor)->n, my_ntoa((*cursor)->addr,ipv6_flag));
if (debug) {print_times(); printf("main: Timing out host %d.\n", (*cursor)->n);}
remove_host(cursor); /* Automatically calls advance_cursor() */
if (first_timeout) {
timeval_diff(&now, &((*cursor)->last_send_time), &diff);
host_timediff = (TCP_UINT64)1000000*diff.tv_sec +
diff.tv_usec;
while (host_timediff >= (*cursor)->timeout && live_count) {
if ((*cursor)->live) {
if (verbose > 1)
warn_msg("---\tRemoving host %u (%s) - Catch-Up Timeout", (*cursor)->n, my_ntoa((*cursor)->addr,ipv6_flag));
remove_host(cursor);
} else {
advance_cursor();
}
timeval_diff(&now, &((*cursor)->last_send_time), &diff);
host_timediff = (TCP_UINT64)1000000*diff.tv_sec +
diff.tv_usec;
}
first_timeout=0;
}
Gettimeofday(&last_packet_time);
} else { /* Retry limit not reached for this host */
if ((*cursor)->num_sent)
(*cursor)->timeout *= backoff_factor;
send_packet(sockfd, *cursor, IP_PROTOCOL, &last_packet_time);
advance_cursor();
}
} else { /* We can't send a packet to this host yet */
/*
* Note that there is no point calling advance_cursor() here because if
* host n is not ready to send, then host n+1 will not be ready either.
*/
select_timeout = (*cursor)->timeout - host_timediff;
reset_cum_err = 1; /* Zero cumulative error */
if (debug) {print_times(); printf("main: Can't send packet to host %d yet. host_timediff=" TCP_UINT64_FORMAT "\n", (*cursor)->n, host_timediff);}
} /* End If */
} else { /* We can't send a packet yet */
select_timeout = req_interval - loop_timediff;
if (debug) {print_times(); printf("main: Can't send packet yet. loop_timediff=" TCP_UINT64_FORMAT "\n", loop_timediff);}
} /* End If */
recvfrom_wto(pcap_fd, select_timeout);
} /* End While */
printf("\n"); /* Ensure we have a blank line */
close(sockfd);
clean_up();
Gettimeofday(&end_time);
timeval_diff(&end_time, &start_time, &elapsed_time);
elapsed_seconds = (elapsed_time.tv_sec*1000 +
elapsed_time.tv_usec/1000) / 1000.0;
printf("Ending %s: %u ports scanned in %.3f seconds (%.2f ports/sec). %u responded\n",
PACKAGE_STRING, num_hosts, elapsed_seconds, num_hosts/elapsed_seconds,
responders);
if (debug) {print_times(); printf("main: End\n");}
return 0;
}
/*
* display_packet -- Check and display received packet
*
* Inputs:
*
* n The length of the received packet in bytes.
* Note that this can be more or less than the IP packet
* size because of minimum frame sizes or snaplength
* cutoff respectively.
* packet_in The received packet
* he The host entry corresponding to the received packet
* recv_addr IP address that the packet was received from
*
* Returns:
*
* None.
*
* This checks the received packet and displays details of what
* was received in the format: <IP-Address><TAB><Details>.
*/
void
display_packet(unsigned n, const unsigned char *packet_in,
const host_entry *he, const struct in_addr *recv_addr) {
const struct iphdr *iph;
const struct tcphdr *tcph;
char *msg;
char *cp;
char *flags;
int data_len;
unsigned data_offset;
const char *df;
int optlen;
/*
* Set msg to the IP address of the host entry, plus the address of the
* responder if different, and a tab.
*/
msg = make_message("%s\t", my_ntoa(he->addr,ipv6_flag));
if ((he->addr).v4.s_addr != recv_addr->s_addr) { /* XXXX */
cp = msg;
msg = make_message("%s(%s) ", cp, inet_ntoa(*recv_addr));
free(cp);
}
/*
* Check that the packet is large enough to decode.
* This should never happen because the packet length should have
* already been checked in callback().
*/
if (n < ip_offset + sizeof(struct iphdr) + sizeof(struct tcphdr)) {
printf("%s%u byte packet too short to decode\n", msg, n);
free(msg);
return;
}
/*
* Overlay IP and TCP headers on packet buffer.
* ip_offset is size of layer-2 header.
* Note that iph.ihl is in 32-bit units. We multiply by 4 to get bytes.
* iph.lhl is normally 5, but can be larger if IP options are present.
*/
iph = (const struct iphdr *) (packet_in + ip_offset);
tcph = (const struct tcphdr *) (packet_in + ip_offset + 4*(iph->ihl));
/*
* Add TCP port to message.
*/
cp = msg;
if (portname_flag) {
char *portname = portnames[ntohs(tcph->source)];
msg = make_message("%s%u (%s)\t", cp, ntohs(tcph->source),
portname?portname:"unknown");
} else {
msg = make_message("%s%u\t", cp, ntohs(tcph->source));
}
free(cp);
/*
* Determine type of response: SYN-ACK, RST or something else and
* add to message.
*/
cp = msg;
if (tcph->syn && tcph->ack) { /* SYN + ACK = Open */
msg = make_message("%sOPEN", cp);
} else if (tcph->rst) { /* RST = Closed */
msg = make_message("%sCLOSED", cp);
} else { /* Shouldn't happen */
msg = make_message("%sUNKNOWN", cp);
}
free(cp);
if (!quiet_flag) {
/*
* Add DF, TCP Flags, TTL, IPIP, and IP packet length to the message.
*/
flags = NULL;
if (tcph->cwr) {
if (flags) {
cp = flags;
flags = make_message("%s,CWR", cp);
free(cp);
} else {
flags = make_message("CWR");
}
}
if (tcph->ecn) {
if (flags) {
cp = flags;
flags = make_message("%s,ECN", cp);
free(cp);
} else {
flags = make_message("ECN");
}
}
if (tcph->urg) {
if (flags) {
cp = flags;
flags = make_message("%s,URG", cp);
free(cp);
} else {
flags = make_message("URG");
}
}
if (tcph->ack) {
if (flags) {
cp = flags;
flags = make_message("%s,ACK", cp);
free(cp);
} else {
flags = make_message("ACK");
}
}
if (tcph->psh) {
if (flags) {
cp = flags;
flags = make_message("%s,PSH", cp);
free(cp);
} else {
flags = make_message("PSH");
}
}
if (tcph->rst) {
if (flags) {
cp = flags;
flags = make_message("%s,RST", cp);
free(cp);
} else {
flags = make_message("RST");
}
}
if (tcph->syn) {
if (flags) {
cp = flags;
flags = make_message("%s,SYN", cp);
free(cp);
} else {
flags = make_message("SYN");
}
}
if (tcph->fin) {
if (flags) {
cp = flags;
flags = make_message("%s,FIN", cp);
free(cp);
} else {
flags = make_message("FIN");
}
}
if (!flags)
flags=make_message(""); /* Ensure flags not NULL if no TCP flags set */
if (ntohs(iph->frag_off) & 0x4000) { /* If DF flag set */
df = "yes";
} else {
df = "no";
}
cp = msg;
msg=make_message("%s\tDF=%s TOS=%u flags=%s win=%u ttl=%u id=%u ip_len=%d",
cp, df, iph->tos, flags, ntohs(tcph->window), iph->ttl,
ntohs(iph->id), ntohs(iph->tot_len));
free(cp);
free(flags);
/*
* Determine TCP options.
*/
optlen = 4*(tcph->doff) - sizeof(struct tcphdr);
if (optlen > 0) {
char *options=NULL;
int trunc=0;
const unsigned char *optptr=(const unsigned char *)
(packet_in + ip_offset +
4*(iph->ihl) +
sizeof(struct tcphdr));
const uint16_t *sptr; /* 16-bit ptr - used for MSS */
const uint32_t *lptr1; /* 32-bit ptr - used for timestamp value */
const uint32_t *lptr2; /* 32-bit ptr - used for timestamp value */
unsigned char uc;
/*
* Check if options have been truncated.
*/
if (n - ip_offset - sizeof(struct iphdr) - sizeof(struct tcphdr)
< (unsigned)optlen) {
if (verbose)
warn_msg("---\tCaptured packet length %u is too short for calculated TCP options length %d. Adjusting options length", n, optlen);
optlen = n - ip_offset - sizeof(struct iphdr) - sizeof(struct tcphdr);
trunc=1;
}
if (ntohs(iph->tot_len) - sizeof(struct iphdr) - sizeof(struct tcphdr)
< (unsigned)optlen) {
if (verbose)
warn_msg("---\tClaimed IP packet length %d is too short for calculated TCP options length %d. Adjusting options length", ntohs(iph->tot_len), optlen);
optlen = ntohs(iph->tot_len) - sizeof(struct iphdr) -
sizeof(struct tcphdr);
trunc=1;
}
while (optlen > 0) {
switch (*optptr) {
case TCPOPT_EOL:
optlen--;
optptr++;
if (options) {
cp = options;
options = make_message("%s,EOL", cp);
free(cp);
} else {
options = make_message("EOL");
}
break;
case TCPOPT_NOP:
optlen--;
optptr++;
if (options) {
cp = options;
options = make_message("%s,NOP", cp);
free(cp);
} else {
options = make_message("NOP");
}
break;
case TCPOPT_MAXSEG:
optlen -= 4;
sptr = (const uint16_t *) (optptr+2);
optptr += 4;
if (options) {
cp = options;
options = make_message("%s,MSS=%u", cp, ntohs(*sptr));
free(cp);
} else {
options = make_message("MSS=%u", ntohs(*sptr));
}
break;
case TCPOPT_WINDOW:
uc = *(optptr+2);
optlen -= 3;
optptr += 3;
if (options) {
cp = options;
options = make_message("%s,WSCALE=%u", cp, uc);
free(cp);
} else {
options = make_message("WSCALE=%u", uc);
}
break;
case TCPOPT_SACK_PERMITTED:
optlen -= 2;
optptr += 2;
if (options) {
cp = options;
options = make_message("%s,SACKOK", cp);
free(cp);
} else {
options = make_message("SACKOK");
}
break;
case TCPOPT_TIMESTAMP:
optlen -= 10;
lptr1 = (const uint32_t *) (optptr+2); /* TS Value */
lptr2 = (const uint32_t *) (optptr+6); /* TS Echo Reply */
optptr += 10;
if (options) {
cp = options;
options = make_message("%s,TIMESTAMP=%u,%u", cp,
ntohl(*lptr1), ntohl(*lptr2));
free(cp);
} else {
options = make_message("TIMESTAMP=%u,%u", ntohl(*lptr1),
ntohl(*lptr2));
}
break;
default:
uc = *optptr;
if (options) {
cp = options;
options = make_message("%s,opt-%u", cp, uc);
free(cp);
} else {
options = make_message("opt-%u", uc);
}
uc = *(optptr+1);
optlen -= uc;
optptr += uc;
break;
}
}
if (!options)
options=make_message(""); /* Ensure options not NULL */
cp = msg;
if (trunc) {
msg = make_message("%s <%s,...>", cp, options);
} else {
msg = make_message("%s <%s>", cp, options);
}
free(cp);
free(options);
}
/*
* Determine length of TCP data. If this is non-zero, then display the
* data.
*/
data_len = ntohs(iph->tot_len) - 4*(iph->ihl) - 4*(tcph->doff);
data_offset = ip_offset + 4*(iph->ihl) + 4*(tcph->doff);
if (data_len > 0) {
char *data_str;
cp = msg;
if (n >= data_offset + data_len) {
data_str=printable(packet_in+data_offset, data_len);
msg = make_message("%s data_len=%d data=\"%s\"", cp, data_len,
data_str);
free(data_str);
} else {
msg = make_message("%s data_len=%d data=(packet too short to decode)",
cp, data_len);
}
free(cp);
}
/*
* If the host entry is not live, then flag this as a duplicate.
*/
if (!he->live) {
cp = msg;
msg = make_message("%s (DUP: %u)", cp, he->num_recv);
free(cp);
}
} /* End if (!quiet_flag) */
/*
* Print the message.
*/
printf("%s\n", msg);
free(msg);
}
/*
* send_packet -- Construct and send a packet to the specified host
*
* Inputs:
*
* s IP socket file descriptor
* he Host entry to send to. If NULL, then no packet is sent
* ip_protocol IP Protocol to use
* last_packet_time Time when last packet was sent
*
* Returns:
*
* The size of the packet that was sent.
*
* This constructs an appropriate packet and sends it to the host
* identified by "he" using the socket "s".
* It also updates the "last_send_time" field for this host entry.
*/
int
send_packet(int s, host_entry *he, int ip_protocol,
struct timeval *last_packet_time) {
struct sockaddr_in sa_peer;
char buf[MAXIP];
int buflen;
NET_SIZE_T sa_peer_len;
struct iphdr *iph = (struct iphdr *) buf;
struct tcphdr *tcph = (struct tcphdr *) (buf + sizeof(struct iphdr));
/* Position pseudo header just before the TCP header */
pseudo_hdr *pseudo = (pseudo_hdr *) (buf + sizeof(struct iphdr)
- sizeof(pseudo_hdr));
unsigned char *options = (unsigned char *) (buf + sizeof(struct iphdr) +
sizeof(struct tcphdr));
unsigned char *optptr;
size_t options_len=0;
/*
* Determine length of TCP options.
* We do this early because we need it for the packet length.
*/
if (mss) {
options_len += 4;
}
if (timestamp_flag) {
options_len += 12;
} else if (sack_flag) {
options_len += 4;
}
if (wscale_flag) {
options_len += 4;
}
/*
* If he is NULL, just return with the packet length.
*/
if (he == NULL)
return sizeof(struct iphdr) + sizeof(struct tcphdr) + options_len;
/*
* Check that the host is live. Complain if not.
*/
if (!he->live) {
warn_msg("***\tsend_packet called on non-live host entry: SHOULDN'T HAPPEN");
return 0;
}
/*
* Set up the sockaddr_in structure for the host.
*/
memset(&sa_peer, '\0', sizeof(sa_peer));
sa_peer.sin_family = AF_INET;
sa_peer.sin_addr.s_addr = he->addr.v4.s_addr;
sa_peer_len = sizeof(sa_peer);
/*
* Update the last send times for this host.
* We do this here because we can also use this value for the TCP
* timestamp option.
*/
Gettimeofday(last_packet_time);
he->last_send_time.tv_sec = last_packet_time->tv_sec;
he->last_send_time.tv_usec = last_packet_time->tv_usec;
he->num_sent++;
/*
* Construct the pseudo header (for TCP checksum purposes).
* Note that this overlaps the IP header and gets overwritten later.
*/
memset(pseudo, '\0', sizeof(pseudo_hdr));
pseudo->s_addr = source_address;
pseudo->d_addr = he->addr.v4.s_addr;
pseudo->proto = ip_protocol;
pseudo->len = htons(sizeof(struct tcphdr) + options_len);
/*
* Add TCP options. We do this before the TCP header because the
* options must be covered by the TCP checksum calculation.
*
* We put the options in the same order, and with the same padding,
* as Linux 2.4.24.
*/
optptr = options;
if (mss) {
*optptr++ = 2; /* Kind=2 (MSS) */
*optptr++ = 4; /* Len=4 Bytes */
*optptr++ = mss / 256; /* MSS high byte */
*optptr++ = mss % 256; /* MSS low byte */
}
if (timestamp_flag) {
uint32_t tsval=htonl(last_packet_time->tv_sec);
if (sack_flag) {
*optptr++ = 4; /* Kind=4 (SACKOK) */
*optptr++ = 2; /* Len=2 bytes */
} else {
*optptr++ = 1; /* Kind=1 (NOP) - pad */
*optptr++ = 1; /* Kind=1 (NOP) - pad */
}
*optptr++ = 8; /* Kind=8 (TIMESTAMP) */
*optptr++ = 10; /* Len=10 bytes */
memcpy(optptr, &tsval, sizeof(tsval)); /* TS Value */
optptr += sizeof(tsval);
*optptr++ = 0; /* TS Echo Reply */
*optptr++ = 0;
*optptr++ = 0;
*optptr++ = 0;
} else if (sack_flag) {
*optptr++ = 1; /* Kind=1 (NOP) - pad */
*optptr++ = 1; /* Kind=1 (NOP) - pad */
*optptr++ = 4; /* Kind=4 (SACKOK) */
*optptr++ = 2; /* Len=2 bytes */
}
if (wscale_flag) {
*optptr++ = 1; /* Kind=1 (NOP) - pad */
*optptr++ = 3; /* Kind=3 (WSCALE) */
*optptr++ = 3; /* Len=3 bytes */
*optptr++ = 0; /* Value=0 */
}
/*
* Construct the TCP header.
*/
memset(tcph, '\0', sizeof(struct tcphdr));
tcph->source = htons(source_port);
tcph->dest = htons(he->dport);
tcph->seq = htonl(seq_no);
tcph->doff = (sizeof(struct tcphdr) + options_len) / 4;
if (tcp_flags_flag) { /* Set specified TCP flags */
if (tcp_flags.cwr)
tcph->cwr = 1;
if (tcp_flags.ecn)
tcph->ecn = 1;
if (tcp_flags.urg)
tcph->urg = 1;
if (tcp_flags.ack) {
tcph->ack = 1;
tcph->ack_seq = htonl(ack_no);
}
if (tcp_flags.psh)
tcph->psh = 1;
if (tcp_flags.rst)
tcph->rst = 1;
if (tcp_flags.syn)
tcph->syn = 1;
if (tcp_flags.fin)
tcph->fin = 1;
} else { /* Default: Set SYN flag */
tcph->syn = 1;
}
tcph->window = htons(window);
tcph->check = in_cksum((uint16_t *)pseudo, sizeof(pseudo_hdr) +
sizeof(struct tcphdr) + options_len);
/*
* Construct the IP Header.
* This overwrites the now unneeded pseudo header.
*/
memset(iph, '\0', sizeof(struct iphdr));
iph->ihl = 5; /* 5 * 32-bit longwords = 20 bytes */
iph->version = 4;
iph->tos = ip_tos;
iph->tot_len = sizeof(struct iphdr) + sizeof(struct tcphdr);
iph->id = 0; /* Linux kernel fills this in */
if (df_flag)
iph->frag_off = htons(0x4000);
else
iph->frag_off = htons(0x0);
iph->ttl = ip_ttl;
iph->protocol = ip_protocol;
iph->check = 0; /* Linux kernel fills this in */
iph->saddr = source_address;
iph->daddr = he->addr.v4.s_addr;
/*
* Copy the required data into the output buffer "buf" and set "buflen"
* to the number of bytes in this buffer.
*/
buflen=sizeof(struct iphdr) + sizeof(struct tcphdr) + options_len;
/*
* Send the packet.
*/
if (debug) {print_times(); printf("send_packet: #%u to host entry %u (%s) tmo %d\n", he->num_sent, he->n, my_ntoa(he->addr,ipv6_flag), he->timeout);}
if (verbose > 1)
warn_msg("---\tSending packet #%u to host entry %u (%s) tmo %d", he->num_sent, he->n, my_ntoa(he->addr,ipv6_flag), he->timeout);
if ((sendto(s, buf, buflen, 0, (struct sockaddr *) &sa_peer, sa_peer_len)) < 0) {
err_sys("sendto");
}
return buflen;
}
/*
* initialise -- initialisation routine.
*
* Inputs:
*
* None.
*
* Returns:
*
* None.
*
* This is called once before any packets have been sent. It can be
* used to perform any required initialisation. It does not have to
* do anything.
*/
void
initialise(void) {
char errbuf[PCAP_ERRBUF_SIZE];
struct bpf_program filter;
char *filter_string;
bpf_u_int32 netmask;
bpf_u_int32 localnet;
int datalink;
unsigned random_seed;
struct timeval tv;
int ret_status;
/*
* Seed PRNG.
*/
Gettimeofday(&tv);
random_seed = tv.tv_usec ^ getpid(); /* Unpredictable value */
init_genrand(random_seed);
/*
* Set the sequence number, ack number and source port using random
* values if they have not been set with command line options.
* We set the top bit of source port to make sure that it's
* above 32768 and therefore out of the way of reserved ports
* (1-1024).
*/
if (!seq_no_flag)
seq_no = genrand_int32();
if (!ack_no_flag)
ack_no = genrand_int32();
if (!source_port_flag) {
source_port = genrand_int32() & 0x0000ffff;
source_port |= 0x8000;
}
/*
* Determine network interface to use and associated IP address.
* If the interface was specified with the --interface option then use
* that, otherwise use my_lookupdev() to pick a suitable interface.
*/
if (!if_name) { /* i/f not specified with --interface */
if (!(if_name=my_lookupdev(errbuf))) {
err_msg("my_lookupdev: %s", errbuf);
}
}
source_address = get_source_ip(if_name);
/*
* Prepare pcap
*/
if (!(pcap_handle = pcap_create(if_name, errbuf)))
err_msg("pcap_create: %s", errbuf);
if ((pcap_set_snaplen(pcap_handle, snaplen)) < 0)
err_msg("pcap_set_snaplen: %s", pcap_geterr(pcap_handle));
if ((pcap_set_promisc(pcap_handle, PROMISC)) < 0)
err_msg("pcap_set_promisc: %s", pcap_geterr(pcap_handle));
if ((pcap_set_immediate_mode(pcap_handle, 1)) < 0)
err_msg("pcap_set_immediate_mode: %s", pcap_geterr(pcap_handle));
if ((pcap_set_timeout(pcap_handle, TO_MS)) < 0) /* Is this still needed? */
err_msg("pcap_set_timeout: %s", pcap_geterr(pcap_handle));
ret_status = pcap_activate(pcap_handle);
if (ret_status < 0) { /* Error from pcap_activate() */
char *cp;
cp = pcap_geterr(pcap_handle);
if (ret_status == PCAP_ERROR)
err_msg("pcap_activate: %s", cp);
else if ((ret_status == PCAP_ERROR_NO_SUCH_DEVICE ||
ret_status == PCAP_ERROR_PERM_DENIED) && *cp != '\0')
err_msg("pcap_activate: %s: %s\n(%s)", if_name,
pcap_statustostr(ret_status), cp);
else
err_msg("pcap_activate: %s: %s", if_name,
pcap_statustostr(ret_status));
} else if (ret_status > 0) { /* Warning from pcap_activate() */
char *cp;