• Stars
    star
    360
  • Rank 118,230 (Top 3 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created almost 12 years ago
  • Updated almost 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A cross-platform binding for performing packet capturing with node.js

Description

A cross-platform binding for performing packet capturing with node.js.

Build Status Build status

Requirements

Install

npm install cap

Examples

  • Capture and decode all outgoing TCP data packets destined for port 80 on the interface for 192.168.0.10:
var Cap = require('cap').Cap;
var decoders = require('cap').decoders;
var PROTOCOL = decoders.PROTOCOL;

var c = new Cap();
var device = Cap.findDevice('192.168.0.10');
var filter = 'tcp and dst port 80';
var bufSize = 10 * 1024 * 1024;
var buffer = Buffer.alloc(65535);

var linkType = c.open(device, filter, bufSize, buffer);

c.setMinBytes && c.setMinBytes(0);

c.on('packet', function(nbytes, trunc) {
  console.log('packet: length ' + nbytes + ' bytes, truncated? '
              + (trunc ? 'yes' : 'no'));

  // raw packet data === buffer.slice(0, nbytes)

  if (linkType === 'ETHERNET') {
    var ret = decoders.Ethernet(buffer);

    if (ret.info.type === PROTOCOL.ETHERNET.IPV4) {
      console.log('Decoding IPv4 ...');

      ret = decoders.IPV4(buffer, ret.offset);
      console.log('from: ' + ret.info.srcaddr + ' to ' + ret.info.dstaddr);

      if (ret.info.protocol === PROTOCOL.IP.TCP) {
        var datalen = ret.info.totallen - ret.hdrlen;

        console.log('Decoding TCP ...');

        ret = decoders.TCP(buffer, ret.offset);
        console.log(' from port: ' + ret.info.srcport + ' to port: ' + ret.info.dstport);
        datalen -= ret.hdrlen;
        console.log(buffer.toString('binary', ret.offset, ret.offset + datalen));
      } else if (ret.info.protocol === PROTOCOL.IP.UDP) {
        console.log('Decoding UDP ...');

        ret = decoders.UDP(buffer, ret.offset);
        console.log(' from port: ' + ret.info.srcport + ' to port: ' + ret.info.dstport);
        console.log(buffer.toString('binary', ret.offset, ret.offset + ret.info.length));
      } else
        console.log('Unsupported IPv4 protocol: ' + PROTOCOL.IP[ret.info.protocol]);
    } else
      console.log('Unsupported Ethertype: ' + PROTOCOL.ETHERNET[ret.info.type]);
  }
});
  • Send an arbitrary packet: An arp request for example
var Cap = require('cap').Cap;
var c = new Cap();
var device = Cap.findDevice('192.168.1.200');
var filter = 'arp';
var bufSize = 10 * 1024 * 1024;
var buffer = Buffer.alloc(65535);

var linkType = c.open(device, filter, bufSize, buffer);


// To use this example, change Source Mac, Sender Hardware Address (MAC) and Target Protocol address
var buffer = Buffer.from([
    // ETHERNET
    0xff, 0xff, 0xff, 0xff, 0xff,0xff,                  // 0    = Destination MAC
    0x84, 0x8F, 0x69, 0xB7, 0x3D, 0x92,                 // 6    = Source MAC
    0x08, 0x06,                                         // 12   = EtherType = ARP
    // ARP
    0x00, 0x01,                                         // 14/0   = Hardware Type = Ethernet (or wifi)
    0x08, 0x00,                                         // 16/2   = Protocol type = ipv4 (request ipv4 route info)
    0x06, 0x04,                                         // 18/4   = Hardware Addr Len (Ether/MAC = 6), Protocol Addr Len (ipv4 = 4)
    0x00, 0x01,                                         // 20/6   = Operation (ARP, who-has)
    0x84, 0x8f, 0x69, 0xb7, 0x3d, 0x92,                 // 22/8   = Sender Hardware Addr (MAC)
    0xc0, 0xa8, 0x01, 0xc8,                             // 28/14  = Sender Protocol address (ipv4)
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00,                 // 32/18  = Target Hardware Address (Blank/nulls for who-has)
    0xc0, 0xa8, 0x01, 0xc9                              // 38/24  = Target Protocol address (ipv4)
]);

try {
  // send will not work if pcap_sendpacket is not supported by underlying `device`
  c.send(buffer, buffer.length);
} catch (e) {
  console.log("Error sending packet:", e);
}

// TCPDUMP.  Note: Some values are changed by the network stack when the broadcast arp message is received.
//12:28:33.230319 ARP, Ethernet (len 6), IPv4 (len 4), Request who-has 192.168.1.200 tell 192.168.1.199, length 46
//0x0000:  ffff ffff ffff 848f 69b7 3d92 0806 0001  ........i.=.....
//0x0010:  0800 0604 0001 848f 69b7 3d92 c0a8 01c7  ........i.=.....
//0x0020:  0000 0000 0000 c0a8 01c8 0000 0000 0000  ................
//0x0030:  0000 0000 0000 0000 0000 0000            ............
//12:28:33.230336 ARP, Ethernet (len 6), IPv4 (len 4), Reply 192.168.1.200 is-at 74:ea:3a:a3:e6:69, length 28
//0x0000:  848f 69b7 3d92 74ea 3aa3 e669 0806 0001  ..i.=.t.:..i....
//0x0010:  0800 0604 0002 74ea 3aa3 e669 c0a8 01c8  ......t.:..i....
//0x0020:  848f 69b7 3d92 c0a8 01c7                 ..i.=.....
  • List all network devices:
var Cap = require('cap').Cap;

console.dir(Cap.deviceList());

// example output on Linux:
// [ { name: 'eth0',
//     addresses:
//      [ { addr: '192.168.0.10',
//          netmask: '255.255.255.0',
//          broadaddr: '192.168.0.255' } ] },
//   { name: 'nflog',
//     description: 'Linux netfilter log (NFLOG) interface',
//     addresses: [] },
//   { name: 'any',
//     description: 'Pseudo-device that captures on all interfaces',
//     addresses: [] },
//   { name: 'lo',
//     addresses:
//      [ { addr: '127.0.0.1', netmask: '255.0.0.0' },
//        { addr: '::1',
//          netmask: 'ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff' } ],
//     flags: 'PCAP_IF_LOOPBACK' } ]

API

Cap events

  • packet(< integer >nbytes, < boolean >truncated) - A packet nbytes in size was captured. truncated indicates if the entire packet did not fit inside the Buffer supplied to open().

Cap methods

  • (constructor)() - Creates and returns a new Cap instance.

  • open(< string >device, < string >filter, < integer >bufSize, < Buffer >buffer) - (void) - Opens device and starts capturing packets using filter. To see the syntax for filter check pcap-filter man page. bufSize is the size of the internal buffer that libpcap uses to temporarily store packets until they are emitted. buffer is a Buffer large enough to store one packet. If open() is called again without a previous call to close(), an implicit close() will occur first.

  • close() - (void) - Stops capturing.

  • setMinBytes(< integer >nBytes) - (void) - (Windows ONLY) This sets the minimum number of packet bytes that must be captured before the full packet data is made available. If this value is set too high, you may not receive any packets until WinPCap's internal buffer fills up. Therefore it's generally best to pass in 0 to this function after calling open(), despite it resulting in more syscalls.

  • send(< Buffer >buffer[, < integer >nBytes]) - (void) - Sends an arbitrary, raw packet on the opened device. nBytes is the number of bytes in buffer to send (starting from position 0) and defaults to buffer.length.

Cap static methods

  • findDevice([< string >ip]) - mixed - If ip is given, the (first) device name associated with ip, or undefined is returned if not found. If ip is not given, the device name of the first non-loopback device is returned.

  • deviceList() - array - Returns a list of available devices and related information.

Decoders static methods

The following methods are available off of require('cap').decoders. They parse the relevant protocol header and return an object containing the parsed information:

  • Link Layer Protocols

    • Ethernet(< Buffer buf[, < integer >bufOffset=0])
  • Internet Layer Protocols

    • IPV4(< Buffer buf[, < integer >bufOffset=0])

    • IPV6(< Buffer buf[, < integer >bufOffset=0])

    • ICMPV4(< Buffer buf, < integer >nbytes[, < integer >bufOffset=0])

  • Transport Layer Protocols

    • TCP(< Buffer buf[, < integer >bufOffset=0])

    • UDP(< Buffer buf[, < integer >bufOffset=0])

    • SCTP(< Buffer buf, < integer >nbytes[, < integer >bufOffset=0])

More Repositories

1

ssh2

SSH2 client and server modules written in pure JavaScript for node.js
JavaScript
5,493
star
2

busboy

A streaming parser for HTML form data for node.js
JavaScript
2,825
star
3

node-imap

An IMAP client module for node.js.
JavaScript
2,149
star
4

node-ftp

An FTP client module for node.js
JavaScript
1,128
star
5

mmmagic

An async libmagic binding for node.js for detecting content types by data inspection
C++
617
star
6

node-mariasql

A node.js binding to MariaDB's non-blocking (MySQL-compatible) client library
C++
485
star
7

socksv5

SOCKS protocol version 5 server and client implementations for node.js
JavaScript
400
star
8

node-ncurses

An ncurses binding for node.js
C++
385
star
9

ssh2-streams

SSH2 and SFTP client/server protocol streams for node.js
JavaScript
204
star
10

node-xxhash

An xxhash binding for node.js
C++
193
star
11

sipster

A pjsip/pjsua2 binding for node.js
C++
190
star
12

dicer

A very fast streaming multipart parser for node.js
JavaScript
186
star
13

httpolyglot

Serve http and https connections over the same port with node.js
JavaScript
181
star
14

connect-busboy

Connect middleware for busboy
JavaScript
155
star
15

node-asterisk

An Asterisk module for node.js
JavaScript
96
star
16

spellcheck

An async hunspell binding for node.js
C++
82
star
17

node-nntp

An NNTP client module for node.js
JavaScript
74
star
18

streamsearch

Streaming Boyer-Moore-Horspool searching for node.js
JavaScript
69
star
19

node-rtp

An RTP module in pure JavaScript for node.js
JavaScript
59
star
20

node-oscar

An OSCAR protocol client module for node.js
JavaScript
54
star
21

cpu-features

A simple node.js binding to Google's cpu_features library for obtaining information about installed CPU(s)
C++
40
star
22

node-pcre

A pcre binding for node.js
C++
39
star
23

esqlite

An SQLite binding for node.js with built-in encryption, focused on simplicity and (async) performance
C++
36
star
24

base91.js

basE91 encoding/decoding for node.js and browsers
JavaScript
31
star
25

bellhop

A node.js module that exposes streams for doing Pubsub and RPC.
JavaScript
28
star
26

ssh-repl

SSH into your node.js process and access a REPL
JavaScript
26
star
27

groan

A PHP session file parser written in JavaScript
JavaScript
24
star
28

paclient

PulseAudio client written in pure JavaScript for node.js
JavaScript
23
star
29

pg2

A PostgreSQL driver for node.js that focuses on performance
JavaScript
21
star
30

pmq

A node.js addon for using POSIX message queues
C++
19
star
31

grappler

A minimalistic server for "comet" connections in Node.js.
JavaScript
19
star
32

reformed

A high-level form field handling and validation module for busboy
JavaScript
18
star
33

zup

A simple, fast template engine for node.js
JavaScript
15
star
34

express-optimized

A minimal, optimized version of Express
JavaScript
13
star
35

xfer

Simple binary TLV reader/writer for node.js
JavaScript
12
star
36

youknow

A realtime, multiplayer card game for node.js that supports multiple frontends
JavaScript
11
star
37

odroid-c2-minimal-debian-ubuntu

Fork of various scripts to setup a minimal debian/ubuntu installation for the odroid c2
Shell
8
star
38

print

A node.js module for communicating with printers
JavaScript
7
star
39

filebounce

A server for bouncing files from point A to point B
JavaScript
7
star
40

node-poormansmysql

MySQL driver module for node.js that executes queries using the mysql command-line client.
JavaScript
7
star
41

buffy

Access and manipulate multiple node.js Buffers as if they were one continuous Buffer
JavaScript
6
star
42

nodebench

Node.js Benchmark Results
HTML
6
star
43

xsys

A node.js binding to useful system-level functions
C++
5
star
44

speaky

A binding to the SVOX Pico engine (libttspico) for performing text-to-speech
C++
4
star
45

lrused

An LRU cache for node.js
JavaScript
4
star
46

conveyor

Feed multiple node.js streams sequentially into one stream
JavaScript
3
star
47

benchd

Benchmark JavaScript code across different node.js/io.js versions from the browser
JavaScript
3
star
48

beepjs

A BEEP protocol implementation for node.js
JavaScript
3
star
49

vermal

A VRML 1.0 push parser for node.js
JavaScript
2
star
50

datatables.sortpriorities

Display column sort orders in your Datatables table headers
JavaScript
1
star
51

build-addons

Build node.js addon binaries for releases using Github Actions
JavaScript
1
star
52

buildcheck

Build environment checking (a la autoconf) for node.js
JavaScript
1
star