forked from nmap/npcap
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnpcap-tutorial.xml
1743 lines (1446 loc) · 59.9 KB
/
npcap-tutorial.xml
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
<sect1 id="npcap-tutorial">
<title>Npcap Development Tutorial</title>
<sect1info>
<abstract>
<para>A step-by-step guide to writing software that uses Npcap to list
network adapters, capture packets, and send network traffic.</para>
</abstract>
</sect1info>
<para>This section shows how to use the features of the Npcap API. It is
organized as a tutorial, subdivided into a set of lessons that will
introduce the reader, in a step-by-step fashion, to program development
using Npcap, from the basic functions (obtaining the adapter list,
starting a capture, etc.) to the most advanced ones (handling send queues
and gathering statistics about network traffic).</para>
<!-- REVISE
<para>Several code snippets, as well as simple but complete programs are
provided as a reference: all of the source code contains links to the rest
of the manual, making it is possible to click on functions and data
structures to jump to the corresponding documentation.</para>
-->
<para>The samples are written in plain C, so a basic knowledge of C
programming is required. Also, since this is a tutorial about a library
dealing with "raw" networking packets, good knowledge of networks and
network protocols is assumed.</para>
<para>The code in this section is copied from the <xref
linkend="npcap-examples">Examples directory</xref> in the source
distribution and the SDK. The code is released under a BSD-3-clause license and
copyright: NetGroup, Politecnico di Torino (Italy); CACE Technologies,
Davis (California); and Insecure.com, LLC. Full text of the code license
can be found in each source file.</para>
<sect2 id="npcap-tutorial-devlist">
<title>Obtaining the device list</title>
<para>Typically, the first thing that a Npcap-based application does is
get a list of attached network adapters. Both libpcap and Npcap provide
the <ulink url="wpcap/pcap_findalldevs.html">pcap_findalldevs_ex()</ulink> function for this purpose:
this function returns a linked list of <literal>pcap_if</literal> structures, each of which contains
comprehensive information about an attached adapter. In particular, the
fields <literal>name</literal> and <literal>description</literal> contain the name and a
human readable description, respectively, of the corresponding
device.</para>
<para>The following code retrieves the adapter list and shows it on the
screen, printing an error if no adapters are found.</para>
<programlisting language="C"><!-- inline --><![CDATA[
#include "pcap.h"
main()
{
pcap_if_t *alldevs;
pcap_if_t *d;
int i=0;
char errbuf[PCAP_ERRBUF_SIZE];
/* Retrieve the device list from the local machine */
if (pcap_findalldevs_ex(PCAP_SRC_IF_STRING, NULL /* auth is not needed */, &alldevs, errbuf) == -1)
{
fprintf(stderr,"Error in pcap_findalldevs_ex: %s\n", errbuf);
exit(1);
}
/* Print the list */
for(d= alldevs; d != NULL; d= d->next)
{
printf("%d. %s", ++i, d->name);
if (d->description)
printf(" (%s)\n", d->description);
else
printf(" (No description available)\n");
}
if (i == 0)
{
printf("\nNo interfaces found! Make sure Npcap is installed.\n");
return;
}
/* We don't need any more the device list. Free it */
pcap_freealldevs(alldevs);
}
]]></programlisting>
<para>Some comments about this code.</para>
<para>First of all, <ulink
url="./wpcap/pcap_findalldevs.html">pcap_findalldevs_ex()</ulink>, like
other libpcap functions, has an <literal>errbuf</literal> parameter. This
parameter points to a string filled by libpcap with a description of the
error if something goes wrong.</para>
<para>Second, remember that not all the OSes supported by libpcap provide a
description of the network interfaces, therefore if we want to write a
portable application, we must consider the case in which
<literal>description</literal> is null: we print the string "No
description available" in that situation.</para>
<para>Note finally that we free the list with <ulink
url="wpcap/pcap_findalldevs.html">pcap_freealldevs()</ulink> once when
we have finished with it.</para>
<para>Assuming we have compiled the program, let's try to run it. On a
particular Windows workstation, the result we optained is</para>
<screen>
1. \Device\NPF_{4E273621-5161-46C8-895A-48D0E52A0B83} (Realtek RTL8029(AS) Ethernet Adapter)
2. \Device\NPF_{5D24AE04-C486-4A96-83FB-8B5EC6C7F430} (3Com EtherLink PCI)
</screen>
<para>As you can see, the name of the network adapters (that will be passed
to libpcap when opening the devices) under Windows are quite unreadable,
so the parenthetical descriptions can be very helpful.</para>
</sect2>
<sect2 id="npcap-tutorial-devdetails">
<title>Obtaining advanced information about installed devices</title>
<para>Lesson 1 (<xref linkend="npcap-tutorial-devlist" />) demonstrated how
to get basic information (i.e. device name and description) about
available adapters. Actually, Npcap provides also other advanced
information. In particular, every <literal>pcap_if</literal> structure
returned by <ulink
url="wpcap/pcap_findalldevs.html">pcap_findalldevs_ex()</ulink>
contains also a list of <literal>pcap_addr</literal> structures,
with:</para>
<itemizedlist>
<listitem>a list of addresses for that interface.</listitem>
<listitem>a list of netmasks (each of which corresponds to an entry in
the addresses list).</listitem>
<listitem>a list of broadcast addresses (each of which corresponds to an
entry in the addresses list).</listitem>
<listitem>a list of destination addresses (each of which corresponds to
an entry in the addresses list).</listitem>
</itemizedlist>
<para>Additionally, <literal>pcap_findalldevs_ex()</literal> can also
return remote adapters and a list of pcap files that are located in a
given local folder.</para>
<para>The following sample provides an ifprint() function that prints the
complete contents of a <literal>pcap_if</literal> structure. It is
invoked by the program for every entry returned by
<literal>pcap_findalldevs_ex()</literal>.</para>
<programlisting language="C"><!-- Examples/iflist/iflist.c --><![CDATA[
/* Print all the available information on the given interface */
void ifprint(pcap_if_t *d)
{
pcap_addr_t *a;
char ip6str[128];
/* Name */
printf("%s\n",d->name);
/* Description */
if (d->description)
printf("\tDescription: %s\n",d->description);
/* Loopback Address*/
printf("\tLoopback: %s\n",(d->flags & PCAP_IF_LOOPBACK)?"yes":"no");
/* IP addresses */
for(a=d->addresses;a;a=a->next) {
printf("\tAddress Family: #%d\n",a->addr->sa_family);
switch(a->addr->sa_family)
{
case AF_INET:
printf("\tAddress Family Name: AF_INET\n");
if (a->addr)
printf("\tAddress: %s\n",iptos(((struct sockaddr_in *)a->addr)->sin_addr.s_addr));
if (a->netmask)
printf("\tNetmask: %s\n",iptos(((struct sockaddr_in *)a->netmask)->sin_addr.s_addr));
if (a->broadaddr)
printf("\tBroadcast Address: %s\n",iptos(((struct sockaddr_in *)a->broadaddr)->sin_addr.s_addr));
if (a->dstaddr)
printf("\tDestination Address: %s\n",iptos(((struct sockaddr_in *)a->dstaddr)->sin_addr.s_addr));
break;
case AF_INET6:
printf("\tAddress Family Name: AF_INET6\n");
if (a->addr)
printf("\tAddress: %s\n", ip6tos(a->addr, ip6str, sizeof(ip6str)));
break;
default:
printf("\tAddress Family Name: Unknown\n");
break;
}
}
printf("\n");
}
]]></programlisting>
</sect2>
<sect2 id="npcap-tutorial-openadapter">
<title>Opening an adapter and capturing the packets</title>
<para>Now that we've seen how to obtain an adapter to play with, let's
start the real job, opening an adapter and capturing some traffic. In
this lesson we'll write a program that prints some information about each
packet flowing through the adapter.</para>
<para>The function that opens a capture device is <ulink
url="wpcap/pcap_open.htl">pcap_open()</ulink>. The parameters,
<literal>snaplen</literal>, <literal>flags</literal> and
<literal>to_ms</literal> deserve some explanation.</para>
<para><literal>snaplen</literal> specifies the portion of the packet to capture. On
some OSes (like xBSD and Win32), the packet driver can be configured to
capture only the initial part of any packet: this decreases the amount of
data to copy to the application and therefore improves the efficiency of
the capture. In this case we use the value 65536 which is higher than the
greatest MTU that we could encounter. In this manner we ensure that the
application will always receive the whole packet.</para>
<para><literal>flags:</literal> the most important flag is the one that
indicates if the adapter will be put in promiscuous mode. In normal
operation, an adapter only captures packets from the network that are
destined to it; the packets exchanged by other hosts are therefore
ignored. Instead, when the adapter is in promiscuous mode it captures all
packets whether they are destined to it or not. This means that on shared
media (like non-switched Ethernet), Npcap will be able to capture the
packets of other hosts. Promiscuous mode is the default for most capture
applications, so we enable it in the following example.</para>
<para><literal>to_ms</literal> specifies the read timeout, in milliseconds.
A read on the adapter (for example, with <ulink
url="wpcap/pcap_loop.html">pcap_dispatch()</ulink> or <ulink
url="wpcap/pcap_next_ex.html">pcap_next_ex()</ulink>) will always
return after <literal>to_ms</literal> milliseconds, even if no packets
are available from the network. <literal>to_ms</literal> also defines the
interval between statistical reports if the adapter is in statistical
mode (see the lesson "\ref wpcap_tut9" for information about statistical
mode). Setting <literal>to_ms</literal> to 0 means no timeout, a read on
the adapter never returns if no packets arrive. A -1 timeout on the other
side causes a read on the adapter to always return immediately.</para>
<programlisting language="C"><!-- Examples/misc/basic_dump.c --><![CDATA[
#include <pcap.h>
#include "misc.h" /* LoadNpcapDlls */
/* prototype of the packet handler */
void packet_handler(u_char *param, const struct pcap_pkthdr *header, const u_char *pkt_data);
int main()
{
pcap_if_t *alldevs;
pcap_if_t *d;
int inum;
int i=0;
pcap_t *adhandle;
char errbuf[PCAP_ERRBUF_SIZE];
/* Load Npcap and its functions. */
if (!LoadNpcapDlls())
{
fprintf(stderr, "Couldn't load Npcap\n");
exit(1);
}
/* Retrieve the device list on the local machine */
if (pcap_findalldevs_ex(PCAP_SRC_IF_STRING, NULL, &alldevs, errbuf) == -1)
{
fprintf(stderr,"Error in pcap_findalldevs: %s\n", errbuf);
exit(1);
}
/* Print the list */
for(d=alldevs; d; d=d->next)
{
printf("%d. %s", ++i, d->name);
if (d->description)
printf(" (%s)\n", d->description);
else
printf(" (No description available)\n");
}
if(i==0)
{
printf("\nNo interfaces found! Make sure Npcap is installed.\n");
return -1;
}
printf("Enter the interface number (1-%d):",i);
scanf_s("%d", &inum);
if(inum < 1 || inum > i)
{
printf("\nInterface number out of range.\n");
/* Free the device list */
pcap_freealldevs(alldevs);
return -1;
}
/* Jump to the selected adapter */
for(d=alldevs, i=0; i< inum-1 ;d=d->next, i++);
/* Open the device */
if ( (adhandle= pcap_open(d->name, // name of the device
65536, // portion of the packet to capture
// 65536 guarantees that the whole packet will be captured on all the link layers
PCAP_OPENFLAG_PROMISCUOUS, // promiscuous mode
1000, // read timeout
NULL, // authentication on the remote machine
errbuf // error buffer
) ) == NULL)
{
fprintf(stderr,"\nUnable to open the adapter. %s is not supported by Npcap\n", d->name);
/* Free the device list */
pcap_freealldevs(alldevs);
return -1;
}
printf("\nlistening on %s...\n", d->description);
/* At this point, we don't need any more the device list. Free it */
pcap_freealldevs(alldevs);
/* start the capture */
pcap_loop(adhandle, 0, packet_handler, NULL);
return 0;
}
/* Callback function invoked by libpcap for every incoming packet */
void packet_handler(u_char *param, const struct pcap_pkthdr *header, const u_char *pkt_data)
{
struct tm ltime;
char timestr[16];
time_t local_tv_sec;
/*
* unused variables
*/
(VOID)(param);
(VOID)(pkt_data);
/* convert the timestamp to readable format */
local_tv_sec = header->ts.tv_sec;
localtime_s(<ime, &local_tv_sec);
strftime( timestr, sizeof timestr, "%H:%M:%S", <ime);
printf("%s,%.6d len:%d\n", timestr, header->ts.tv_usec, header->len);
}
]]></programlisting>
<para>Once the adapter is opened, the capture can be started with <ulink
url="wpcap/pcap_loop.html">pcap_dispatch()</ulink> or <ulink
url="wpcap/pcap_loop.html">pcap_loop()</ulink>. These two functions are
very similar, the difference is that <literal>pcap_dispatch()</literal>
returns (although not guaranteed) when the timeout expires while
<literal>pcap_loop()</literal> doesn't return until
<literal>cnt</literal> packets have been captured, so it can block for an
arbitrary period on an under-utilized network.
<literal>pcap_loop()</literal> is enough for the purpose of this sample,
while <literal>pcap_dispatch()</literal> is normally used in a more
complex program.</para>
<para>Both of these functions have a <literal>callback</literal> parameter,
<literal>packet_handler</literal>, pointing to a function that will
receive the packets. This function is invoked by libpcap for every new
packet coming from the network and receives a generic status
(corresponding to the <literal>user</literal> parameter of <ulink
url="wpcap/pcap_loop.html">pcap_loop()</ulink> and <ulink
url="wpcap/pcap_loop.html">pcap_dispatch()</ulink>), a header with some
information on the packet like the timestamp and the length and the
actual data of the packet including all the protocol headers. Note that
the frame CRC is normally not present, because it is removed by the
network adapter after frame validation. Note also that most adapters
discard packets with wrong CRCs, therefore Npcap is normally not able
to capture them.</para>
<para>The above example extracts the timestamp and the length of every
packet from the <literal>pcap_pkthdr</literal> header and prints them on
the screen.</para>
<para>Please note that there may be a drawback using <ulink
url="wpcap/pcap_loop.html">pcap_loop()</ulink> mainly related to the
fact that the handler is called by the packet capture driver; therefore
the user application does not have direct control over it. Another
approach (and to have more readable programs) is to use the <ulink
url="wpcap/pcap_next_ex.html">pcap_next_ex()</ulink> function, which is
presented in the next example (<xref linkend="npcap-tutorial-pcap-next-ex"
/>).</para>
</sect2>
<sect2 id="npcap-tutorial-pcap-next-ex">
<title>Capturing the packets without the callback</title>
<para>The example program in this lesson behaves exactly like the previous
program (<xref linkend="npcap-tutorial-openadapter" />), but it uses
<ulink url="wpcap/pcap_next_ex.html">pcap_next_ex()</ulink> instead of
<ulink url="wpcap/pcap_loop.html">pcap_loop()</ulink>.</para>
<para>The callback-based capture mechanism of <ulink
url="wpcap/pcap_loop.html">pcap_loop()</ulink> is elegant and it could
be a good choice in some situations. However, handling a callback is
sometimes not practical—it often makes the program more complex
especially in situations with multithreaded applications or C++
classes.</para>
<para>In these cases, <ulink
url="wpcap/pcap_next_ex.html">pcap_next_ex()</ulink> retrievs a packet
with a direct call—using <literal>pcap_next_ex()</literal>,
packets are received only when the programmer wants them.</para>
<para>The parameters of this function are the same as a capture callback.
It takes an adapter descriptor and a couple of pointers that will be
initialized and returned to the user (one to a
<literal>pcap_pkthdr</literal> structure and another to a buffer with the
packet data).</para>
<para>In the following program, we recycle the callback code of the
previous lesson's example and move it inside main() right after the call
to <ulink url="wpcap/pcap_next_ex.html">pcap_next_ex()</ulink>.</para>
<programlisting language="C"><!-- Examples/misc/basic_dump_ex.c --><![CDATA[
/* Open the device */
if ( (adhandle= pcap_open(d->name, // name of the device
65536, // portion of the packet to capture.
// 65536 guarantees that the whole packet will be captured on all the link layers
PCAP_OPENFLAG_PROMISCUOUS, // promiscuous mode
1000, // read timeout
NULL, // authentication on the remote machine
errbuf // error buffer
) ) == NULL)
{
fprintf(stderr,"\nUnable to open the adapter. %s is not supported by Npcap\n", d->name);
/* Free the device list */
pcap_freealldevs(alldevs);
return -1;
}
printf("\nlistening on %s...\n", d->description);
/* At this point, we don't need any more the device list. Free it */
pcap_freealldevs(alldevs);
/* Retrieve the packets */
while((res = pcap_next_ex( adhandle, &header, &pkt_data)) >= 0){
if(res == 0)
/* Timeout elapsed */
continue;
/* convert the timestamp to readable format */
local_tv_sec = header->ts.tv_sec;
localtime_s(<ime, &local_tv_sec);
strftime( timestr, sizeof timestr, "%H:%M:%S", <ime);
printf("%s,%.6d len:%d\n", timestr, header->ts.tv_usec, header->len);
}
if(res == -1){
printf("Error reading the packets: %s\n", pcap_geterr(adhandle));
return -1;
}
]]></programlisting>
<para>Why do we use <ulink
url="wpcap/pcap_next_ex.html">pcap_next_ex()</ulink> instead of the old
<ulink url="wpcap/pcap_loop.html">pcap_next()</ulink>? Because
<literal>pcap_next()</literal> has some drawbacks. First of all, it is
inefficient because it hides the callback method but still relies on
<literal>pcap_dispatch()</literal>. Second, it is not able to detect EOF,
so it's not very useful when gathering packets from a file.</para>
<para>Notice also that <literal>pcap_next_ex()</literal> returns different
values for success, timeout elapsed, error and EOF conditions.</para>
</sect2>
<sect2 id="npcap-tutorial-filtering">
<title>Filtering the traffic</title>
<para>One of the most powerful features offered by Npcap (and by libpcap as
well) is the filtering engine. It provides a very efficient way to
receive subsets of the network traffic, and is (usually) integrated with
the capture mechanism provided by Npcap. The functions used to filter
packets are <ulink url="wpcap/pcap_compile.html">pcap_compile()</ulink>
and <ulink
url="wpcap/pcap_setfilter.html">pcap_setfilter()</ulink>.</para>
<para><ulink url="wpcap/pcap_compile.html">pcap_compile()</ulink> takes a
string containing a high-level Boolean (filter) expression and produces a
low-level byte code that can be interpreted by the fileter engine in the
packet driver. The syntax of the boolean expression can be found in the
<ulink url="wpcap/pcap-filter.html">Filtering expression syntax</ulink>
section of this documentation.</para>
<para><ulink url="wpcap/pcap_setfilter.html">pcap_setfilter()</ulink>
associates a filter with a capture session in the kernel driver. Once
<literal>pcap_setfilter()</literal> is called, the associated filter will
be applied to all the packets coming from the network, and all the
conformant packets (i.e., packets for which the Boolean expression
evaluates to true) will be actually copied to the application.</para>
<para>The following code shows how to compile and set a filter. Note that
we must retrieve the netmask from the <literal>pcap_if</literal>
structure that describes the adapter, because some filters created by
<literal>pcap_compile()</literal> require it.</para>
<para>The filter passed to <literal>pcap_compile()</literal> in this code
snippet is "ip and tcp", which means to "keep only the packets that are
both IPv4 and TCP and deliver them to the application".</para>
<!-- TODO: PCAP_NETMASK_UNKNOWN? -->
<programlisting language="C"><!-- inline --><![CDATA[
if (d->addresses != NULL)
/* Retrieve the mask of the first address of the interface */
netmask=((struct sockaddr_in *)(d->addresses->netmask))->sin_addr.S_un.S_addr;
else
/* If the interface is without an address we suppose to be in a C class network */
netmask=0xffffff;
//compile the filter
if (pcap_compile(adhandle, &fcode, "ip and tcp", 1, netmask) < 0)
{
fprintf(stderr,"\nUnable to compile the packet filter. Check the syntax.\n");
/* Free the device list */
pcap_freealldevs(alldevs);
return -1;
}
//set the filter
if (pcap_setfilter(adhandle, &fcode) < 0)
{
fprintf(stderr,"\nError setting the filter.\n");
/* Free the device list */
pcap_freealldevs(alldevs);
return -1;
}
]]></programlisting>
<para>If you want to see some code that uses the filtering functions shown
in this lesson, look at the example presented in the next Lesson, <xref
linkend="npcap-tutorial-interpreting" />.</para>
</sect2>
<sect2 id="npcap-tutorial-interpreting">
<title>Interpreting the packets</title>
<para>Now that we are able to capture and filter network traffic, we want
to put our knowledge to work with a simple "real world"
application.</para>
<para>In this lesson we will take code from the previous lessons and use
these pieces to build a more useful program. the main purpose of the
current program is to show how the protocol headers of a captured packet
can be parsed and interpreted. The resulting application, called UDPdump,
prints a summary of the UDP traffic on our network.</para>
<para>We have chosen to parse and display the UDP protocol because it is
more accessible than other protocols such as TCP and consequently is an
excellent initial example. Let's look at the code:</para>
<programlisting language="C"><!-- Examples/UDPdump/udpdump.c --><![CDATA[
#include <pcap.h>
#include <Winsock2.h>
#include <tchar.h>
BOOL LoadNpcapDlls()
{
_TCHAR npcap_dir[512];
UINT len;
len = GetSystemDirectory(npcap_dir, 480);
if (!len) {
fprintf(stderr, "Error in GetSystemDirectory: %x", GetLastError());
return FALSE;
}
_tcscat_s(npcap_dir, 512, _T("\\Npcap"));
if (SetDllDirectory(npcap_dir) == 0) {
fprintf(stderr, "Error in SetDllDirectory: %x", GetLastError());
return FALSE;
}
return TRUE;
}
/* 4 bytes IP address */
typedef struct ip_address{
u_char byte1;
u_char byte2;
u_char byte3;
u_char byte4;
}ip_address;
/* IPv4 header */
typedef struct ip_header{
u_char ver_ihl; // Version (4 bits) + Internet header length (4 bits)
u_char tos; // Type of service
u_short tlen; // Total length
u_short identification; // Identification
u_short flags_fo; // Flags (3 bits) + Fragment offset (13 bits)
u_char ttl; // Time to live
u_char proto; // Protocol
u_short crc; // Header checksum
ip_address saddr; // Source address
ip_address daddr; // Destination address
u_int op_pad; // Option + Padding
}ip_header;
/* UDP header*/
typedef struct udp_header{
u_short sport; // Source port
u_short dport; // Destination port
u_short len; // Datagram length
u_short crc; // Checksum
}udp_header;
/* prototype of the packet handler */
void packet_handler(u_char *param, const struct pcap_pkthdr *header, const u_char *pkt_data);
int main()
{
pcap_if_t *alldevs;
pcap_if_t *d;
int inum;
int i=0;
pcap_t *adhandle;
char errbuf[PCAP_ERRBUF_SIZE];
u_int netmask;
char packet_filter[] = "ip and udp";
struct bpf_program fcode;
/* Load Npcap and its functions. */
if (!LoadNpcapDlls())
{
fprintf(stderr, "Couldn't load Npcap\n");
exit(1);
}
/* Retrieve the device list */
if (pcap_findalldevs_ex(PCAP_SRC_IF_STRING, NULL, &alldevs, errbuf) == -1)
{
fprintf(stderr,"Error in pcap_findalldevs: %s\n", errbuf);
exit(1);
}
/* Print the list */
for(d=alldevs; d; d=d->next)
{
printf("%d. %s", ++i, d->name);
if (d->description)
printf(" (%s)\n", d->description);
else
printf(" (No description available)\n");
}
if(i==0)
{
printf("\nNo interfaces found! Make sure Npcap is installed.\n");
return -1;
}
printf("Enter the interface number (1-%d):",i);
scanf_s("%d", &inum);
if(inum < 1 || inum > i)
{
printf("\nInterface number out of range.\n");
/* Free the device list */
pcap_freealldevs(alldevs);
return -1;
}
/* Jump to the selected adapter */
for(d=alldevs, i=0; i< inum-1 ;d=d->next, i++);
/* Open the adapter */
if ( (adhandle= pcap_open(d->name, // name of the device
65536, // portion of the packet to capture.
// 65536 grants that the whole packet will be captured on all the MACs.
PCAP_OPENFLAG_PROMISCUOUS, // promiscuous mode
1000, // read timeout
NULL, // remote authentication
errbuf // error buffer
) ) == NULL)
{
fprintf(stderr,"\nUnable to open the adapter. %s is not supported by Npcap\n", d->name);
/* Free the device list */
pcap_freealldevs(alldevs);
return -1;
}
/* Check the link layer. We support only Ethernet for simplicity. */
if(pcap_datalink(adhandle) != DLT_EN10MB)
{
fprintf(stderr,"\nThis program works only on Ethernet networks.\n");
/* Free the device list */
pcap_freealldevs(alldevs);
return -1;
}
if(d->addresses != NULL)
/* Retrieve the mask of the first address of the interface */
netmask=((struct sockaddr_in *)(d->addresses->netmask))->sin_addr.S_un.S_addr;
else
/* If the interface is without addresses we suppose to be in a C class network */
netmask=0xffffff;
//compile the filter
if (pcap_compile(adhandle, &fcode, packet_filter, 1, netmask) <0 )
{
fprintf(stderr,"\nUnable to compile the packet filter. Check the syntax.\n");
/* Free the device list */
pcap_freealldevs(alldevs);
return -1;
}
//set the filter
if (pcap_setfilter(adhandle, &fcode)<0)
{
fprintf(stderr,"\nError setting the filter.\n");
/* Free the device list */
pcap_freealldevs(alldevs);
return -1;
}
printf("\nlistening on %s...\n", d->description);
/* At this point, we don't need any more the device list. Free it */
pcap_freealldevs(alldevs);
/* start the capture */
pcap_loop(adhandle, 0, packet_handler, NULL);
return 0;
}
/* Callback function invoked by libpcap for every incoming packet */
void packet_handler(u_char *param, const struct pcap_pkthdr *header, const u_char *pkt_data)
{
struct tm ltime;
char timestr[16];
ip_header *ih;
udp_header *uh;
u_int ip_len;
u_short sport,dport;
time_t local_tv_sec;
/*
* Unused variable
*/
(VOID)(param);
/* convert the timestamp to readable format */
local_tv_sec = header->ts.tv_sec;
localtime_s(<ime, &local_tv_sec);
strftime( timestr, sizeof timestr, "%H:%M:%S", <ime);
/* print timestamp and length of the packet */
printf("%s.%.6d len:%d ", timestr, header->ts.tv_usec, header->len);
/* retireve the position of the ip header */
ih = (ip_header *) (pkt_data +
14); //length of ethernet header
/* retireve the position of the udp header */
ip_len = (ih->ver_ihl & 0xf) * 4;
uh = (udp_header *) ((u_char*)ih + ip_len);
/* convert from network byte order to host byte order */
sport = ntohs( uh->sport );
dport = ntohs( uh->dport );
/* print ip addresses and udp ports */
printf("%d.%d.%d.%d.%d -> %d.%d.%d.%d.%d\n",
ih->saddr.byte1,
ih->saddr.byte2,
ih->saddr.byte3,
ih->saddr.byte4,
sport,
ih->daddr.byte1,
ih->daddr.byte2,
ih->daddr.byte3,
ih->daddr.byte4,
dport);
}
]]></programlisting>
<para>First of all, we set the filter to "ip and udp". In this way we are
sure that packet_handler() will receive only UDP packets over IPv4: this
simplifies the parsing and increases the efficiency of the
program.</para>
<para>We have also created a couple of structs that describe the IP and UDP
headers. These structs are used by packet_handler() to properly locate
the various header fields.</para>
<para>packet_handler(), although limited to a single protocol dissector
(UDP over IPv4), shows how complex "sniffers" like tcpdump/WinDump decode
the network traffic. Since we aren't interested in the MAC header, we
skip it. For simplicity and before starting the capture, we check the MAC
layer with <ulink url="wpcap/pcap_datalink.html">pcap_datalink()</ulink>
to make sure that we are dealing with an Ethernet network. This way we
can be sure that the MAC header is exactly 14 bytes.</para>
<para>The IP header is located just after the MAC header. We will extract
the IP source and destination addresses from the IP header.</para>
<para>Reaching the UDP header is a bit more complicated, because the IP
header doesn't have a fixed length. Therefore, we use the IP header's
length field to know its size. Once we know the location of the UDP
header, we extract the source and destination ports.</para>
<para>The extracted values are printed on the screen, and the result is
something like:</para>
<screen>
\Device\Packet_{A7FD048A-5D4B-478E-B3C1-34401AC3B72F} (Xircom t 10/100 Adapter)
Enter the interface number (1-2):1
listening on Xircom CardBus Ethernet 10/100 Adapter...
16:13:15.312784 len:87 130.192.31.67.2682 -> 130.192.3.21.53
16:13:15.314796 len:137 130.192.3.21.53 -> 130.192.31.67.2682
16:13:15.322101 len:78 130.192.31.67.2683 -> 130.192.3.21.53
</screen>
<para>Each of the final 3 lines represents a different packet.</para>
</sect2>
<sect2 id="npcap-tutorial-offline">
<title>Handling offline dump files</title>
<para>In this lession we are going to learn how to handle packet capture to
a file (dump to file). Npcap offers a wide range of functions to save
the network traffic to a file and to read the content of
dumps—this lesson will teach how to use all of these
functions.</para>
<para>The format for dump files is the libpcap one. This format contains
the data of the captured packets in binary form and is a standard used by
many network tools including WinDump, Wireshark and Snort.</para>
<sect3 id="npcap-tutorial-offline-saving">
<title>Saving packets to a dump file</title>
<para>First of all, let's see how to write packets in libpcap
format.</para>
<para>The following example captures the packets from the selected
interface and saves them on a file whose name is provided by the
user.</para>
<programlisting language="C"><!-- Examples/misc/savedump.c --><![CDATA[
#include <pcap.h>
#include "misc.h" /* LoadNpcapDlls */
/* prototype of the packet handler */
void packet_handler(u_char *param, const struct pcap_pkthdr *header, const u_char *pkt_data);
int main(int argc, char **argv)
{
pcap_if_t *alldevs;
pcap_if_t *d;
int inum;
int i=0;
pcap_t *adhandle;
char errbuf[PCAP_ERRBUF_SIZE];
pcap_dumper_t *dumpfile;
/* Load Npcap and its functions. */
if (!LoadNpcapDlls())
{
fprintf(stderr, "Couldn't load Npcap\n");
exit(1);
}
/* Check command line */
if(argc != 2)
{
printf("usage: %s filename", argv[0]);
return -1;
}
/* Retrieve the device list on the local machine */
if (pcap_findalldevs_ex(PCAP_SRC_IF_STRING, NULL, &alldevs, errbuf) == -1)
{
fprintf(stderr,"Error in pcap_findalldevs: %s\n", errbuf);
exit(1);
}
/* Print the list */
for(d=alldevs; d; d=d->next)
{
printf("%d. %s", ++i, d->name);
if (d->description)
printf(" (%s)\n", d->description);
else
printf(" (No description available)\n");
}
if(i==0)
{
printf("\nNo interfaces found! Make sure Npcap is installed.\n");
return -1;
}
printf("Enter the interface number (1-%d):",i);
scanf_s("%d", &inum);
if(inum < 1 || inum > i)
{
printf("\nInterface number out of range.\n");
/* Free the device list */
pcap_freealldevs(alldevs);
return -1;
}
/* Jump to the selected adapter */
for(d=alldevs, i=0; i< inum-1 ;d=d->next, i++);
/* Open the device */
if ( (adhandle= pcap_open(d->name, // name of the device
65536, // portion of the packet to capture
// 65536 guarantees that the whole packet will be captured on all the link layers
PCAP_OPENFLAG_PROMISCUOUS, // promiscuous mode
1000, // read timeout
NULL, // authentication on the remote machine
errbuf // error buffer
) ) == NULL)
{
fprintf(stderr,"\nUnable to open the adapter. %s is not supported by Npcap\n", d->name);
/* Free the device list */
pcap_freealldevs(alldevs);
return -1;
}
/* Open the dump file */
dumpfile = pcap_dump_open(adhandle, argv[1]);
if(dumpfile==NULL)
{
fprintf(stderr,"\nError opening output file\n");
return -1;
}
printf("\nlistening on %s... Press Ctrl+C to stop...\n", d->description);
/* At this point, we no longer need the device list. Free it */
pcap_freealldevs(alldevs);
/* start the capture */
pcap_loop(adhandle, 0, packet_handler, (unsigned char *)dumpfile);
return 0;
}
/* Callback function invoked by libpcap for every incoming packet */
void packet_handler(u_char *dumpfile, const struct pcap_pkthdr *header, const u_char *pkt_data)
{
/* save the packet on the dump file */
pcap_dump(dumpfile, header, pkt_data);
}
]]></programlisting>
<para>As you can see, the structure of the program is very similar to the
ones we have seen in the previous lessons. The differences
are:</para>
<itemizedlist>
<listitem>a call to <ulink
url="wpcap/pcap_dump_open.html">pcap_dump_open()</ulink> is issued
once the interface is opened. This call opens a dump file and
associates it with the interface.</listitem>
<listitem>the packets are written to this file with a <ulink
url="wpcap/pcap_dump.html">pcap_dump()</ulink> from the
packet_handler() callback. The parameters of
<literal>pcap_dump()</literal> are in 1-1 correspondence with the
parameters of <ulink
url="wpcap/pcap_loop.html">pcap_handler()</ulink>.</listitem>
</itemizedlist>
</sect3>
<sect3 id="npcap-tutorial-offline-reading">
<title>Reading packets from a dump file</title>
<para>Now that we have a dump file available, we can try to read its
content. The following code opens a Npcap/libpcap dump file and
displays every packet contained in the file. The file is opened with
<ulink url="wpcap/pcap_open_offline.html">pcap_open_offline()</ulink>,
then the usual <ulink url="wpcap/pcap_loop.html">pcap_loop()</ulink> is
used to sequence through the packets. As you can see, reading packets
from an offline capture is nearly identical to receiving them from a
physical interface.</para>
<para>This example introduces another function:
<literal>pcap_createsrcstr()</literal>. This function is required to
create a source string that begins with a marker used to tell Npcap the
type of the source, e.g. "rpcap://" if we are going to open an adapter,
or "file://" if we are going to open a file. This step is not required