libnmap 0.4.19 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/examples/xml.js CHANGED
@@ -1,22 +1,22 @@
1
1
  /*!
2
2
  * libnmap
3
- * Copyright(c) 2013-2019 Jason Gerfen <jason.gerfen@gmail.com>
4
- * License: MIT
3
+ * Copyright(c) 2013 Jason Gerfen <jason.gerfen@gmail.com>
4
+ * License: NPSL-0.95
5
5
  */
6
6
 
7
7
  'use strict'
8
8
 
9
+ // With json: false the report is the nmap XML document as a string.
10
+
9
11
  const nmap = require('../');
10
12
  const opts = {
11
13
  json: false,
12
- range: ['scanme.nmap.org', '192.168.0.0/26']
14
+ range: ['scanme.nmap.org']
13
15
  };
14
16
 
15
17
 
16
- nmap.scan(opts, function(err, report) {
17
- if (err) throw new Error(err);
18
+ nmap.scan(opts, (err, report) => {
19
+ if (err) throw err;
18
20
 
19
- for (let item in report) {
20
- console.log(report[item], null, 2);
21
- }
22
- });
21
+ console.log(report);
22
+ });
package/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  /*!
2
2
  * libnmap
3
- * Copyright(c) 2013-2019 Jason Gerfen <jason.gerfen@gmail.com>
4
- * License: MIT
3
+ * Copyright(c) 2013 Jason Gerfen <jason.gerfen@gmail.com>
4
+ * License: NPSL-0.95
5
5
  */
6
6
 
7
7
  module.exports = require('./lib/libnmap.js');
@@ -1,190 +1,49 @@
1
1
  /*!
2
2
  * libnmap
3
- * Copyright(c) 2013-2019 Jason Gerfen <jason.gerfen@gmail.com>
4
- * License: MIT
3
+ * Copyright(c) 2013 Jason Gerfen <jason.gerfen@gmail.com>
4
+ * License: NPSL-0.95
5
5
  */
6
6
 
7
7
  'use strict'
8
8
 
9
9
  const os = require('os');
10
- const ip = require('ip-address');
11
- const cidrjs = require('cidr-js');
12
- const netmask = require('netmask').Netmask;
13
-
14
- const validation = require('./validation.js');
15
-
16
- const v6 = ip.Address6;
17
- const cidr = new cidrjs();
18
-
19
10
 
20
11
  class network {
21
-
22
-
23
- /**
24
- * @function range
25
- * Calculates all possible hosts per CIDR
26
- *
27
- * @param {Object} opts Application defaults
28
- * @param {Object} host - CIDR formatted network range
29
- *
30
- * @returns {Array}
31
- */
32
- range(opts, host) {
33
-
34
- const tools = require('./tools.js');
35
-
36
- const blocks = cidr.list(host);
37
- let splitat = Math.round(blocks.length / opts.blocksize);
38
-
39
- const results = [];
40
- let tarray = [];
41
-
42
- // Make sure we account for valid subnet ranges
43
- splitat = (splitat > 256) ? Math.round(splitat / 255) : splitat;
44
-
45
- if (splitat > 1) {
46
-
47
- // Split blocks up by offset
48
- tarray = tools.chunk(blocks, splitat);
49
- tarray.forEach(block => {
50
- results.push(block);
51
- });
52
- } else {
53
- results.push(blocks.join(' '));
54
- }
55
-
56
- return results;
57
- }
58
-
59
-
60
- /**
61
- * @function calculate
62
- * Performs calculation on subnet blocks
63
- *
64
- * @param {Object} opts Application defaults
65
- *
66
- * @returns {Array}
67
- */
68
- calculate(opts) {
69
- const tools = require('./tools.js');
70
- const blocks = [];
71
-
72
- let results = [];
73
-
74
- const tresults = [];
75
- const tests = validation.patterns;
76
-
77
- opts.range.forEach(host => {
78
-
79
- switch (true) {
80
-
81
- /* singular IPv4, IPv6 or RFC-1123 hostname */
82
- case (validation.test(tests.hostname, host) ||
83
- validation.test(tests.IPv4, host) ||
84
- validation.test(tests.IPv6, host)):
85
-
86
- results.push(host);
87
-
88
- break;
89
-
90
- /* IPv4 CIDR notation; break up into chunks for parallel processing */
91
- case (validation.test(tests.IPv4CIDR, host)):
92
-
93
- tresults.push(this.range(opts, host));
94
-
95
- break;
96
-
97
- /* IPv4 range notation */
98
- case (validation.test(tests.IPv4Range, host)):
99
-
100
- results.push(host);
101
-
102
- break;
103
-
104
- case (validation.test(tests.IPv6CIDR, host)):
105
-
106
- /* Add IPv6 calculations to assist with parallel processing */
107
- results.push(host);
108
-
109
- break;
110
-
111
- default:
112
-
113
- /* Silently discard specified element as invalid */
114
- break;
115
- }
12
+ families(range) {
13
+ const result = {
14
+ ipv4: [],
15
+ ipv6: []
16
+ };
17
+
18
+ range.forEach(host => {
19
+ if (host.indexOf(':') !== -1)
20
+ result.ipv6.push(host);
21
+ else
22
+ result.ipv4.push(host);
116
23
  });
117
24
 
118
- if (tresults.length > 0) {
119
- results = tools.merge(results, tresults[0])
120
- }
121
-
122
- return results;
25
+ return result;
123
26
  }
124
27
 
125
-
126
- /**
127
- * @function adapters
128
- * Obtain network adapter information and return an array of
129
- * ranges as an array for CIDR calculations
130
- *
131
- * @param {Object} obj User supplied object
132
- *
133
- * @returns {Array}
134
- */
135
- adapters(obj) {
28
+ adapters() {
136
29
  const ret = [];
137
- let adapter = '';
138
- let subnet = '';
139
30
  const adapters = os.networkInterfaces();
140
31
 
141
- if (obj.verbose)
142
- console.log(adapters);
143
-
144
32
  for (const iface in adapters) {
145
-
146
- for (const dev in adapters[iface]) {
147
- let adapter = adapters[iface][dev];
148
-
149
- // Skip if internal
33
+ adapters[iface].forEach(adapter => {
150
34
  if (adapter.internal)
151
- continue;
152
-
153
- // If cidr provide use and continue
154
- if (adapter.cidr) {
155
- ret.push(`${adapter.cidr}`);
156
- continue;
157
- }
158
-
159
- // If only netmask exists calculate the CIDR
160
- if (adapter.netmask) {
161
-
162
- subnet = adapter.netmask;
35
+ return;
163
36
 
164
- if (validation.test(validation.patterns.IPv6, subnet)) {
37
+ if (adapter.family !== 'IPv4' && adapter.family !== 4)
38
+ return;
165
39
 
166
- /* Convert netmask to CIDR notation if IPv6 */
167
- subnet = new v6(netmask).subnet.substring(1);
168
- } else {
169
-
170
- /* Convert netmask to CIDR */
171
- subnet = new netmask(`${adapter.address}/${subnet}`);
172
- adapter.address = subnet.base;
173
- subnet = subnet.bitmask;
174
- }
175
-
176
- ret.push(`${adapter.address}/${subnet}`);
177
- }
178
- }
40
+ if (ret.indexOf(adapter.cidr) === -1)
41
+ ret.push(adapter.cidr);
42
+ });
179
43
  }
180
44
 
181
- if (obj.verbose)
182
- console.log(ret);
183
-
184
45
  return ret;
185
46
  }
186
-
187
47
  }
188
48
 
189
-
190
49
  module.exports = new network;
@@ -1,51 +1,57 @@
1
1
  /*!
2
2
  * libnmap
3
- * Copyright(c) 2013-2019 Jason Gerfen <jason.gerfen@gmail.com>
4
- * License: MIT
3
+ * Copyright(c) 2013 Jason Gerfen <jason.gerfen@gmail.com>
4
+ * License: NPSL-0.95
5
5
  */
6
6
 
7
7
  'use strict'
8
8
 
9
- const xml2js = require('xml2js');
9
+ const parser = require('./xml.js');
10
10
 
11
+ const same = ['verbose', 'debugging'];
11
12
 
12
13
  class reporting {
14
+ reports(opts, reports, cb) {
15
+ let result;
13
16
 
17
+ try {
18
+ result = (opts.json) ?
19
+ reports.map(xml => parser.parse(xml).nmaprun).reduce(this.json) :
20
+ reports.reduce(this.xml);
21
+ } catch(err) {
22
+ return cb(err);
23
+ }
14
24
 
15
- /**
16
- * @function reports
17
- * Handle results
18
- *
19
- * @param {Obect} opts Application defaults
20
- * @param {Function} cb Return function
21
- *
22
- * @returns {Function}
23
- */
24
- reports(opts, report, cb) {
25
- if ((!/object/.test(typeof report)) || (report.hasOwnProperty('code')))
26
- return cb(report);
25
+ return cb(null, result);
26
+ }
27
27
 
28
- const xml = report.join('');
28
+ json(report, added) {
29
+ Object.keys(added).forEach(name => {
30
+ if (!Array.isArray(added[name]) || same.indexOf(name) !== -1)
31
+ return;
29
32
 
30
- if (!opts.json)
31
- return cb(null, xml);
33
+ report[name] = (report[name] || []).concat(added[name]);
34
+ });
32
35
 
33
- try {
34
- const parserOptions = {
35
- attrkey: "item",
36
- };
36
+ return report;
37
+ }
37
38
 
38
- const xmlParser = new xml2js.Parser(parserOptions);
39
+ xml(report, added) {
40
+ const end = report.lastIndexOf('</nmaprun>');
41
+ const root = added.indexOf('<nmaprun');
42
+ const first = added.indexOf('>', root) + 1;
43
+ const last = added.lastIndexOf('</nmaprun>');
39
44
 
40
- xmlParser.parseString(xml, (err, json) => {
41
- if(err)
42
- return cb(err);
45
+ if (end === -1 || root === -1 || last === -1)
46
+ throw new Error('XML report is not complete: no nmaprun element');
43
47
 
44
- return cb(null, json.nmaprun);
45
- });
46
- } catch(err) {
47
- return cb(err);
48
- }
48
+ let elements = added.slice(first, last).trim();
49
+
50
+ same.forEach(name => {
51
+ elements = elements.replace(new RegExp(`<${name}\\b[^>]*/>\\s*`, 'g'), '');
52
+ });
53
+
54
+ return `${report.slice(0, end)}${elements}\n${report.slice(end)}`;
49
55
  }
50
56
  }
51
57
 
@@ -1,243 +1,178 @@
1
1
  /*!
2
2
  * libnmap
3
- * Copyright(c) 2013-2019 Jason Gerfen <jason.gerfen@gmail.com>
4
- * License: MIT
3
+ * Copyright(c) 2013 Jason Gerfen <jason.gerfen@gmail.com>
4
+ * License: NPSL-0.95
5
5
  */
6
6
 
7
7
  'use strict'
8
8
 
9
- const async = require('async');
10
- const merge = require('deepmerge');
11
- const caller = require('stack-trace');
9
+ const path = require('path');
12
10
  const proc = require('child_process').spawn;
13
- const emitter = require('events').EventEmitter;
14
11
 
15
12
  const network = require('./networking.js');
16
13
  const reporting = require('./reporting.js');
17
14
  const validation = require('./validation.js');
18
15
 
16
+ const worker = path.join(__dirname, '..', 'worker.js');
17
+ const nmapdir = path.join(__dirname, '..', '..', 'src', 'nmap');
19
18
 
20
- class tools extends emitter {
21
-
22
- /**
23
- * @function merge
24
- * Perform preliminary option/default object merge
25
- *
26
- * @param {Object} defaults Application defaults
27
- * @param {Object} obj User supplied object
28
- *
29
- * @returns {Object}
30
- */
19
+ class tools {
31
20
  merge(defaults, obj) {
32
- return merge(defaults, obj);
33
- }
21
+ const result = {};
34
22
 
23
+ [defaults, obj].forEach(source => {
24
+ Object.keys(source || {}).forEach(key => {
25
+ const value = source[key];
35
26
 
36
- /**
37
- * @function chunk
38
- * Defines new property for array's
39
- *
40
- * @param {Array} obj Supplied array
41
- * @param {Integer} offset Supplied offset
42
- *
43
- * @returns {Array}
44
- */
45
- chunk(obj, offset) {
46
- let idx = 0;
47
- const alength = obj.length;
48
- const tarray = [];
49
-
50
- for (idx = 0; idx < alength; idx += offset) {
51
- tarray.push(obj.slice(idx, idx + offset).join(' '));
52
- }
27
+ if (Array.isArray(value))
28
+ result[key] = (Array.isArray(result[key]) ? result[key] : [])
29
+ .concat(value);
30
+ else
31
+ result[key] = value;
32
+ });
33
+ });
53
34
 
54
- return tarray;
35
+ return result;
55
36
  }
56
37
 
38
+ command(opts, hosts, ipv6) {
39
+ let args = [];
57
40
 
58
- /**
59
- * @function flatten
60
- * Flattens nested arrays into one flat array
61
- *
62
- * @param {Array} arr Array combinator
63
- * @param {Array} obj User supplied array
64
- *
65
- * @returns {Array}
66
- */
67
- flatten(arr, obj) {
68
- let value;
69
- const result = [];
70
-
71
- for (let i = 0, length = arr.length; i < length; i++) {
72
-
73
- value = arr[i];
74
-
75
- if (Array.isArray(value)) {
76
- return this.flatten(value, obj);
77
- }
78
- else {
79
- result.push(value);
80
- }
81
- }
82
- return result;
83
- }
41
+ if (opts.udp)
42
+ args.push('-sU');
84
43
 
44
+ args.push(`--host-timeout=${opts.timeout}s`);
85
45
 
86
- /**
87
- * @function funcs
88
- * Create functions for use as callbacks
89
- *
90
- * @param {Obect} opts Application defaults
91
- *
92
- * @returns {Array}
93
- */
94
- funcs(opts) {
95
- const scope = this;
96
- const funcs = {};
97
- let cmd = false;
98
- const errors = [];
99
- const reports = [];
46
+ opts.flags.forEach(flag => {
47
+ flag = String(flag).trim();
48
+
49
+ if (flag[0] === '-')
50
+ args = args.concat(flag.split(/\s+/));
51
+ else if (flag)
52
+ args.push(flag);
53
+ });
54
+
55
+ if (ipv6)
56
+ args.push('-6');
100
57
 
101
- if (opts.range.length <= 0)
102
- return "Range of hosts could not be created";
58
+ if (opts.ports)
59
+ args.push(`-p${opts.ports}`);
60
+
61
+ return args.concat('--', hosts);
62
+ }
103
63
 
104
- Object.keys(opts.range).forEach(function blocks(block) {
64
+ scan(args, cb) {
65
+ const report = [];
66
+ const errors = [];
67
+ let done = false;
105
68
 
106
- // Acquire an array of ranges
107
- const range = opts.range[block];
69
+ const finish = (err, xml) => {
70
+ if (done)
71
+ return;
108
72
 
109
- // Create a new function for each range block
110
- funcs[range] = function block(callback) {
111
- const report = [];
73
+ done = true;
74
+ cb(err, xml);
75
+ };
112
76
 
77
+ const execute = proc(process.execPath, [worker].concat(args), {
78
+ env: Object.assign({}, process.env, {
79
+ NMAPDIR: nmapdir,
80
+ ELECTRON_RUN_AS_NODE: '1'
81
+ })
82
+ });
113
83
 
114
- // Capture the flags, & ranges as a command string
115
- cmd = scope.command(opts, range);
84
+ execute.stderr.on('data', (chunk) => {
85
+ errors.push(chunk);
86
+ });
116
87
 
117
- // Split up cmd for .spawn()
118
- const obj = cmd.split(" ");
119
- cmd = obj[0];
120
- const args = obj.slice(1);
88
+ execute.stdout.on('data', (chunk) => {
89
+ report.push(chunk);
90
+ });
121
91
 
122
- if (opts.verbose)
123
- console.log(`Running: ${cmd} ${args}`);
92
+ execute.on('error', (err) => {
93
+ finish(err);
94
+ });
124
95
 
125
- // Push it on to the heap
126
- const execute = proc(cmd, args);
96
+ execute.on('close', (code, signal) => {
97
+ const messages = Buffer.concat(errors).toString().trim();
127
98
 
128
- // Discard stderr for now, maybe log?
129
- execute.stderr.on('data', (chunk) => {
130
- /* Silently discard stderr messages to not interupt scans */
131
- });
99
+ if (signal)
100
+ return finish(new Error(`nmap was stopped by signal ${signal} ` +
101
+ 'before the scan was complete'));
132
102
 
133
- // Push to array of reports
134
- execute.stdout.on('data', (chunk) => {
135
- report.push(chunk);
136
- });
103
+ if (code !== 0 || report.length === 0)
104
+ return finish(new Error(messages ||
105
+ `nmap stopped with exit code ${code}`));
137
106
 
138
- // Push report array to reporting function on stream end
139
- execute.stdout.on('end', () => {
140
- if (report.length > 0)
141
- return reporting.reports(opts, report, callback);
142
- });
143
- };
107
+ return finish(null, Buffer.concat(report).toString());
144
108
  });
145
109
 
146
- return funcs;
110
+ return execute;
147
111
  }
148
112
 
113
+ worker(opts, fn) {
114
+ const reports = [];
115
+ let remaining = opts.scans.length;
116
+ let failed = false;
149
117
 
150
- /**
151
- * @function command
152
- * Generate nmap command string
153
- *
154
- * @param {Object} opts - User supplied options
155
- * @param {String} block - Network block
156
- *
157
- * @returns {String} NMAP scan string
158
- */
159
- command(opts, block) {
160
- const flags = opts.flags.join(' ');
161
- const proto = (opts.udp) ? ' -sU' : ' ';
162
- const to = `--host-timeout=${opts.timeout}s `;
163
- const ipv6 = (validation.test(validation.patterns.IPv6, block)) ?
164
- ' -6 ' : ' ';
165
-
166
- return (opts.ports) ?
167
- `${opts.nmap+proto} ${to}${flags}${ipv6}-p${opts.ports} ${block}` :
168
- `${opts.nmap+proto} ${to}${flags}${ipv6}${block}`;
169
- }
118
+ opts.scans.forEach((args, idx) => {
119
+ this.scan(args, (err, xml) => {
120
+ if (failed)
121
+ return;
170
122
 
123
+ if (err) {
124
+ failed = true;
125
+ return fn(err);
126
+ }
171
127
 
172
- /**
173
- * @function worker
174
- * Executes object of functions
175
- *
176
- * @param {Object} obj User supplied object
177
- * @param {Function} fn Return function
178
- */
179
- worker(obj, fn) {
180
- async.parallelLimit(obj.funcs, obj.threshold, fn);
181
- }
128
+ reports[idx] = xml;
182
129
 
130
+ if (--remaining === 0)
131
+ reporting.reports(opts, reports, fn);
132
+ });
133
+ });
134
+ }
183
135
 
184
- /**
185
- * @function init
186
- * @scope private
187
- * Merges supplied options & builds functions
188
- *
189
- * @param {Object} defaults libnmap default options
190
- * @param {Object} opts User supplied configuration object
191
- * @param {Function} cb Callback
192
- *
193
- * @returns {Object}
194
- */
195
- init(defaults, opts, cb) {
196
- let funcs = [];
197
- const ranges = [];
198
- const called = caller.get()[1].getFunctionName();
199
-
200
- /* Override 'defaults.flags' array with 'opts.flags' (prevents merge) */
201
- if (/array/.test(typeof opts.flags))
202
- defaults.flags = opts.flags;
136
+ init(defaults, opts, cb, discover) {
137
+ if (typeof opts !== 'object')
138
+ opts = {};
203
139
 
204
140
  opts = this.merge(defaults, opts);
205
141
 
206
- /* Ensure we can always parse the report */
207
142
  if (opts.flags.indexOf('-oX -') === -1)
208
143
  opts.flags.push('-oX -');
209
144
 
210
- /* If we are in a discover mode get adapters for associated network(s) */
211
- if (/nmap.discover/.test(called)) {
145
+ if (discover) {
146
+ opts.range = network.adapters();
212
147
 
213
- /* Bail early if we cannot determine any ranges */
214
- if (!(opts.range = network.adapters(opts)))
215
- return cb(validation.messages.version);
148
+ if (opts.range.length === 0)
149
+ return cb(validation.messages.adapters);
216
150
 
217
- /* Set scan options as static values for 'discover' mode */
218
151
  opts.ports = '';
219
152
  opts.flags = [
220
- '-n',
221
153
  '-oX -',
222
154
  '-sn',
223
155
  '-PR'
224
156
  ];
225
157
  }
226
158
 
227
- validation.init(opts, (err, result) => {
159
+ validation.init(opts, (err) => {
228
160
  if (err)
229
161
  return cb(err);
230
162
 
231
- opts.range = network.calculate(opts);
232
- funcs = this.funcs(opts);
163
+ const hosts = network.families(opts.range);
233
164
 
234
- return cb(null, {
235
- opts,
236
- funcs
237
- });
165
+ opts.scans = [];
166
+
167
+ if (hosts.ipv4.length > 0)
168
+ opts.scans.push(this.command(opts, hosts.ipv4, false));
169
+
170
+ if (hosts.ipv6.length > 0)
171
+ opts.scans.push(this.command(opts, hosts.ipv6, true));
172
+
173
+ return cb(null, opts);
238
174
  });
239
175
  }
240
176
  }
241
177
 
242
-
243
178
  module.exports = new tools;