forked from bodik/python-libnmap
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprocess.py
More file actions
692 lines (590 loc) · 21.5 KB
/
process.py
File metadata and controls
692 lines (590 loc) · 21.5 KB
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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import platform
import shlex
import subprocess
import warnings
from threading import Thread
from xml.dom import pulldom
try:
import pwd
except ImportError:
pass
__all__ = ["NmapProcess"]
class NmapTask(object):
"""
NmapTask is a internal class used by process. Each time nmap
starts a new task during the scan, a new class will be instanciated.
Classes examples are: "Ping Scan", "NSE script", "DNS Resolve",..
To each class an estimated time to complete is assigned and updated
at least every second within the NmapProcess.
A property NmapProcess.current_task points to the running task at
time T and a dictionnary NmapProcess.tasks with "task name" as key
is built during scan execution
"""
def __init__(self, name, starttime=0, extrainfo=""):
self.name = name
self.etc = 0
self.progress = 0
self.percent = 0
self.remaining = 0
self.status = "started"
self.starttime = starttime
self.endtime = 0
self.extrainfo = extrainfo
self.updated = 0
class NmapProcess(Thread):
"""
NmapProcess is a class which wraps around the nmap executable.
Consequently, in order to run an NmapProcess, nmap should be installed
on the host running the script. By default NmapProcess will produce
the output of the nmap scan in the nmap XML format. This could be then
parsed out via the NmapParser class from libnmap.parser module.
"""
def __init__(
self,
targets="127.0.0.1",
options="-sT",
event_callback=None,
safe_mode=True,
fqp=None,
):
"""
Constructor of NmapProcess class.
:param targets: hosts to be scanned. Could be a string of hosts \
separated with a coma or a python list of hosts/ip.
:type targets: string or list
:param options: list of nmap options to be applied to scan. \
These options are all documented in nmap's man pages.
:param event_callback: callable function which will be ran \
each time nmap process outputs data. This function will receive \
two parameters:
1. the nmap process object
2. the data produced by nmap process. See readme for examples.
:param safe_mode: parameter to protect unsafe options like -oN, -oG, \
-iL, -oA,...
:param fqp: full qualified path, if None, nmap will be searched \
in the PATH
:return: NmapProcess object
"""
Thread.__init__(self)
unsafe_opts = set(
[
"-oG",
"-oN",
"-iL",
"-oA",
"-oS",
"-oX",
"--iflist",
"--resume",
"--stylesheet",
"--datadir",
]
)
# more reliable than just using os.name() (cygwin)
self.__is_windows = platform.system() == "Windows"
if fqp:
if os.path.isfile(fqp) and os.access(fqp, os.X_OK):
self.__nmap_binary = fqp
else:
raise EnvironmentError(1, "wrong path or not executable", fqp)
else:
nmap_binary_name = "nmap"
self.__nmap_binary = self._whereis(nmap_binary_name)
self.__nmap_fixed_options = "-oX - -vvv --stats-every 1s"
if self.__nmap_binary is None:
em = "nmap is not installed or could not be found in system path"
raise EnvironmentError(1, em)
if isinstance(targets, str):
self.__nmap_targets = targets.replace(" ", "").split(",")
elif isinstance(targets, list):
self.__nmap_targets = targets
else:
raise Exception(
"Supplied target list should be either a string or a list"
)
self._nmap_options = set(options.split())
if safe_mode and not self._nmap_options.isdisjoint(unsafe_opts):
raise Exception(
"unsafe options activated while safe_mode is set True"
)
self.__nmap_dynamic_options = options
self.__sudo_run = ""
self.__nmap_command_line = self.get_command_line()
if event_callback and callable(event_callback):
self.__nmap_event_callback = event_callback
else:
self.__nmap_event_callback = None
(
self.DONE,
self.READY,
self.RUNNING,
self.CANCELLED,
self.FAILED,
) = range(5)
self._run_init()
def _run_init(self):
self.__nmap_command_line = self.get_command_line()
# API usable in callback function
self.__nmap_proc = None
self.__nmap_rc = 0
self.__state = self.RUNNING
self.__starttime = 0
self.__endtime = 0
self.__version = ""
self.__elapsed = ""
self.__summary = ""
self.__stdout = ""
self.__stderr = ""
self.__current_task = ""
self.__nmap_tasks = {}
def _whereis(self, program):
"""
Protected method enabling the object to find the full path of a binary
from its PATH environment variable.
:param program: name of a binary for which the full path needs to
be discovered.
:return: the full path to the binary.
:todo: add a default path list in case PATH is empty.
"""
split_char = ";" if self.__is_windows else ":"
program = program + ".exe" if self.__is_windows else program
for path in os.environ.get("PATH", "").split(split_char):
_file_path = os.path.join(path, program)
if os.path.exists(_file_path) and not os.path.isdir(_file_path):
return os.path.join(path, program)
return None
def get_command_line(self):
"""
Public method returning the reconstructed command line ran via the lib
:return: the full nmap command line to run
:rtype: string
"""
return "{0} {1} {2} {3} {4}".format(
self.__sudo_run,
self.__nmap_binary,
self.__nmap_fixed_options,
self.__nmap_dynamic_options,
" ".join(self.__nmap_targets),
)
def _ensure_user_exists(self, username=""):
try:
pwd.getpwnam(username).pw_uid
except KeyError as eobj:
_exmsg = (
"Username {0} does not exists. Please supply"
" a valid username: {1}".format(username, eobj)
)
raise EnvironmentError(_exmsg)
def sudo_run(self, run_as="root"):
"""
Public method enabling the library's user to run the scan with
priviledges via sudo. The sudo configuration should be set manually
on the local system otherwise sudo will prompt for a password.
This method alters the command line by prefixing the sudo command to
nmap and will then call self.run()
:param run_as: user name to which the lib needs to sudo to run the scan
:return: return code from nmap execution
"""
sudo_user = run_as.split().pop()
self._ensure_user_exists(sudo_user)
sudo_path = self._whereis("sudo")
if sudo_path is None:
raise EnvironmentError(
2,
"sudo is not installed or "
"could not be found in system path: "
"cannot run nmap with sudo",
)
self.__sudo_run = "{0} -u {1}".format(sudo_path, sudo_user)
rc = self.run()
self.__sudo_run = ""
return rc
def sudo_run_background(self, run_as="root"):
"""
Public method enabling the library's user to run in background a
nmap scan with priviledges via sudo.
The sudo configuration should be set manually on the local system
otherwise sudo will prompt for a password.
This method alters the command line by prefixing the sudo command to
nmap and will then call self.run()
:param run_as: user name to which the lib needs to sudo to run the scan
:return: return code from nmap execution
"""
sudo_user = run_as.split().pop()
self._ensure_user_exists(sudo_user)
sudo_path = self._whereis("sudo")
if sudo_path is None:
raise EnvironmentError(
2,
"sudo is not installed or "
"could not be found in system path: "
"cannot run nmap with sudo",
)
self.__sudo_run = "{0} -u {1}".format(sudo_path, sudo_user)
super(NmapProcess, self).start()
def run(self):
"""
Public method which is usually called right after the constructor
of NmapProcess. This method starts the nmap executable's subprocess.
It will also bind a Process that will read from subprocess' stdout
and stderr and push the lines read in a python queue for futher
processing. This processing is waken-up each time data is pushed
from the nmap binary into the stdout reading routine. Processing
could be performed by a user-provided callback. The whole
NmapProcess object could be accessible asynchroneously.
return: return code from nmap execution
"""
self._run_init()
_tmp_cmdline = (
self.__build_windows_cmdline()
if self.__is_windows
else shlex.split(self.__nmap_command_line)
)
try:
self.__nmap_proc = subprocess.Popen(
args=_tmp_cmdline,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
universal_newlines=True,
bufsize=0,
)
self.__state = self.RUNNING
except OSError as emsg:
self.__state = self.FAILED
raise EnvironmentError(
1,
"nmap is not installed or could "
"not be found in system path: {0}".format(emsg),
)
while self.__nmap_proc.poll() is None:
self.__process_nmap_proc_stdout()
self.__process_nmap_proc_stdout()
self.__stderr += self.__nmap_proc.stderr.read()
self.__nmap_rc = self.__nmap_proc.poll()
if self.rc is None:
self.__state = self.CANCELLED
elif self.rc == 0:
self.__state = self.DONE
if self.current_task:
self.__nmap_tasks[self.current_task.name].progress = 100
else:
self.__state = self.FAILED
# Call the callback one last time to signal the new state
if self.__nmap_event_callback:
self.__nmap_event_callback(self)
return self.rc
def run_background(self):
"""
run nmap scan in background as a thread.
For privileged scans, consider NmapProcess.sudo_run_background()
"""
self.__state = self.RUNNING
super(NmapProcess, self).start()
def is_running(self):
"""
Checks if nmap is still running.
:return: True if nmap is still running
"""
return self.state == self.RUNNING
def has_terminated(self):
"""
Checks if nmap has terminated. Could have failed or succeeded
:return: True if nmap process is not running anymore.
"""
return (
self.state == self.DONE
or self.state == self.FAILED
or self.state == self.CANCELLED
)
def has_failed(self):
"""
Checks if nmap has failed.
:return: True if nmap process errored.
"""
return self.state == self.FAILED
def is_successful(self):
"""
Checks if nmap terminated successfully.
:return: True if nmap terminated successfully.
"""
return self.state == self.DONE
def stop(self):
"""
Send KILL -15 to the nmap subprocess and gently ask the threads to
stop.
"""
self.__state = self.CANCELLED
if self.__nmap_proc.poll() is None:
self.__nmap_proc.kill()
def __process_nmap_proc_stdout(self):
for streamline in iter(self.__nmap_proc.stdout.readline, ""):
self.__stdout += streamline
evnt = self.__process_event(streamline)
if self.__nmap_event_callback and evnt:
self.__nmap_event_callback(self)
def __process_event(self, eventdata):
"""
Private method called while nmap process is running. It enables the
library to handle specific data/events produced by nmap process.
So far, the following events are supported:
1. task progress: updates estimated time to completion and percentage
done while scan is running. Could be used in combination with a
callback function which could then handle this data while scan is
running.
2. nmap run: header of the scan. Usually displayed when nmap is started
3. finished: when nmap scan ends.
:return: True is event is known.
:todo: handle parsing directly via NmapParser.parse()
"""
rval = False
try:
edomdoc = pulldom.parseString(eventdata)
for xlmnt, xmlnode in edomdoc:
if xlmnt is not None and xlmnt == pulldom.START_ELEMENT:
if (
xmlnode.nodeName == "taskbegin"
and xmlnode.attributes.keys()
):
xt = xmlnode.attributes
taskname = xt["task"].value
starttime = xt["time"].value
xinfo = ""
if "extrainfo" in xt.keys():
xinfo = xt["extrainfo"].value
newtask = NmapTask(taskname, starttime, xinfo)
self.__nmap_tasks[newtask.name] = newtask
self.__current_task = newtask.name
rval = True
elif (
xmlnode.nodeName == "taskend"
and xmlnode.attributes.keys()
):
xt = xmlnode.attributes
tname = xt["task"].value
xinfo = ""
self.__nmap_tasks[tname].endtime = xt["time"].value
if "extrainfo" in xt.keys():
xinfo = xt["extrainfo"].value
self.__nmap_tasks[tname].extrainfo = xinfo
self.__nmap_tasks[tname].status = "ended"
rval = True
elif (
xmlnode.nodeName == "taskprogress"
and xmlnode.attributes.keys()
):
xt = xmlnode.attributes
tname = xt["task"].value
percent = xt["percent"].value
etc = xt["etc"].value
remaining = xt["remaining"].value
updated = xt["time"].value
self.__nmap_tasks[tname].percent = percent
self.__nmap_tasks[tname].progress = percent
self.__nmap_tasks[tname].etc = etc
self.__nmap_tasks[tname].remaining = remaining
self.__nmap_tasks[tname].updated = updated
rval = True
elif (
xmlnode.nodeName == "nmaprun"
and xmlnode.attributes.keys()
):
self.__starttime = xmlnode.attributes["start"].value
self.__version = xmlnode.attributes["version"].value
rval = True
elif (
xmlnode.nodeName == "finished"
and xmlnode.attributes.keys()
):
self.__endtime = xmlnode.attributes["time"].value
self.__elapsed = xmlnode.attributes["elapsed"].value
self.__summary = xmlnode.attributes["summary"].value
rval = True
except Exception:
pass
return rval
def __build_windows_cmdline(self):
cmdline = []
cmdline.append(self.__nmap_binary)
if self.__nmap_fixed_options:
cmdline += self.__nmap_fixed_options.split()
if self.__nmap_dynamic_options:
cmdline += self.__nmap_dynamic_options.split()
if self.__nmap_targets:
cmdline += self.__nmap_targets # already a list
return cmdline
@property
def command(self):
"""
return the constructed nmap command or empty string if not
constructed yet.
:return: string
"""
return self.__nmap_command_line or ""
@property
def targets(self):
"""
Provides the list of targets to scan
:return: list of string
"""
return self.__nmap_targets
@property
def options(self):
"""
Provides the list of options for that scan
:return: list of string (nmap options)
"""
return self._nmap_options
@property
def state(self):
"""
Accessor for nmap execution state. Possible states are:
- self.READY
- self.RUNNING
- self.FAILED
- self.CANCELLED
- self.DONE
:return: integer (from above documented enum)
"""
return self.__state
@property
def starttime(self):
"""
Accessor for time when scan started
:return: string. Unix timestamp
"""
return self.__starttime
@property
def endtime(self):
"""
Accessor for time when scan ended
:return: string. Unix timestamp
"""
warnings.warn(
"data collected from finished events are deprecated."
"Use NmapParser.parse()",
DeprecationWarning,
)
return self.__endtime
@property
def elapsed(self):
"""
Accessor returning for how long the scan ran (in seconds)
:return: string
"""
warnings.warn(
"data collected from finished events are deprecated."
"Use NmapParser.parse()",
DeprecationWarning,
)
return self.__elapsed
@property
def summary(self):
"""
Accessor returning a short summary of the scan's results
:return: string
"""
warnings.warn(
"data collected from finished events are deprecated."
"Use NmapParser.parse()",
DeprecationWarning,
)
return self.__summary
@property
def tasks(self):
"""
Accessor returning for the list of tasks ran during nmap scan
:return: dict of NmapTask object
"""
return self.__nmap_tasks
@property
def version(self):
"""
Accessor for nmap binary version number
:return: version number of nmap binary
:rtype: string
"""
return self.__version
@property
def current_task(self):
"""
Accessor for the current NmapTask beeing run
:return: NmapTask or None if no task started yet
"""
rval = None
if len(self.__current_task):
rval = self.tasks[self.__current_task]
return rval
@property
def etc(self):
"""
Accessor for estimated time to completion
:return: estimated time to completion
"""
rval = 0
if self.current_task:
rval = self.current_task.etc
return rval
@property
def progress(self):
"""
Accessor for progress status in percentage
:return: percentage of job processed.
"""
rval = 0
if self.current_task:
rval = self.current_task.progress
return rval
@property
def rc(self):
"""
Accessor for nmap execution's return code
:return: nmap execution's return code
"""
return self.__nmap_rc
@property
def stdout(self):
"""
Accessor for nmap standart output
:return: output from nmap scan in XML
:rtype: string
"""
return self.__stdout
@property
def stderr(self):
"""
Accessor for nmap standart error
:return: output from nmap when errors occured.
:rtype: string
"""
return self.__stderr
def main():
def mycallback(nmapscan=None):
if nmapscan.is_running() and nmapscan.current_task:
ntask = nmapscan.current_task
print(
"Task {0} ({1}): ETC: {2} DONE: {3}%".format(
ntask.name, ntask.status, ntask.etc, ntask.progress
)
)
nm = NmapProcess(
"scanme.nmap.org", options="-A", event_callback=mycallback
)
rc = nm.run()
if rc == 0:
print(
"Scan started at {0} nmap version: {1}".format(
nm.starttime, nm.version
)
)
print("state: {0} (rc: {1})".format(nm.state, nm.rc))
print("results size: {0}".format(len(nm.stdout)))
print("Scan ended {0}: {1}".format(nm.endtime, nm.summary))
else:
print("state: {0} (rc: {1})".format(nm.state, nm.rc))
print("Error: {stderr}".format(stderr=nm.stderr))
print("Result: {0}".format(nm.stdout))
if __name__ == "__main__":
main()