forked from savon-noir/python-libnmap
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhost.py
More file actions
466 lines (390 loc) · 13.7 KB
/
host.py
File metadata and controls
466 lines (390 loc) · 13.7 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
#!/usr/bin/env python
from libnmap.diff import NmapDiff
class NmapHost(object):
"""
NmapHost is a class representing a host object of NmapReport
"""
class NmapOSFingerprint(object):
"""
NmapOSFingerprint is a easier API for using os fingerprinting
"""
def __init__(self, osfp_data):
self.__fingerprint = ''
self.__osmatch = ''
self.__osclass = ''
if 'osfingerprint' in osfp_data:
self.__fingerprint = osfp_data['osfingerprint']
__sortfct = lambda osent: int(osent['accuracy'])
if 'osmatch' in osfp_data:
try:
self.__osmatch = sorted(osfp_data['osmatch'],
key=__sortfct,
reverse=True)
except (KeyError, TypeError):
self.__osmatch = []
if 'osclass' in osfp_data:
try:
self.__osclass = sorted(osfp_data['osclass'],
key=__sortfct,
reverse=True)
except (KeyError, TypeError):
self.__osclass = []
def osmatch(self, min_accuracy=90):
os_array = []
for match_entry in self.__osmatch:
try:
if int(match_entry['accuracy']) >= min_accuracy:
os_array.append(match_entry['name'])
except (KeyError, TypeError):
pass
return os_array
def osclass(self, min_accuracy=90):
os_array = []
for osclass_entry in self.__osclass:
try:
if int(osclass_entry['accuracy']) >= min_accuracy:
_relevantkeys = ['type', 'vendor', 'osfamily', 'osgen']
_ftstr = "|".join([vkey + ": " + osclass_entry[vkey]
for vkey in osclass_entry
if vkey in _relevantkeys])
os_array.append(_ftstr)
except (KeyError, TypeError):
pass
return os_array
def fingerprint(self):
return self.__fingerprint
def __repr__(self):
_fmtstr = ''
if len(self.osmatch()):
_fmtstr += "OS:\r\n"
for _osmline in self.osmatch():
_fmtstr += " {0}\r\n".format(_osmline)
elif len(self.osclass()):
_fmtstr += "OS CLASS:\r\n"
for _oscline in self.osclass():
_fmtstr += " {0}\r\n".format(_oscline)
elif len(self.fingerprint):
_fmtstr += "OS FINGERPRINT:\r\n"
_fmtstr += " {0}".format(self.fingerprint)
return _fmtstr
"""
NmapHost is a class representing a host object of NmapReport
"""
def __init__(self, starttime='', endtime='', address=None, status=None,
hostnames=None, services=None, extras=None):
"""
NmapHost constructor
:param starttime: unix timestamp of when the scan against
that host started
:type starttime: string
:param endtime: unix timestamp of when the scan against
that host ended
:type endtime: string
:param address: dict ie :{'addr': '127.0.0.1', 'addrtype': 'ipv4'}
:param status: dict ie:{'reason': 'localhost-response',
'state': 'up'}
:return: NmapHost:
"""
self._starttime = starttime
self._endtime = endtime
self._hostnames = hostnames if hostnames is not None else []
self._status = status if status is not None else {}
self._address = address if address is not None else {}
self._services = services if services is not None else []
self._extras = extras if extras is not None else {}
self._osfingerprinted = False
if 'os' in self._extras:
self.os = self.NmapOSFingerprint(self._extras['os'])
self._osfingerprinted = True
def __eq__(self, other):
"""
Compare eq NmapHost based on :
- hostnames
- address
- if an associated services has changed
:return: boolean
"""
rval = False
if(self.__class__ == other.__class__ and self.id == other.id):
rval = (self.changed(other) == 0)
return rval
def __ne__(self, other):
"""
Compare ne NmapHost based on:
- hostnames
- address
- if an associated services has changed
:return: boolean
"""
rval = True
if(self.__class__ == other.__class__ and self.id == other.id):
rval = (self.changed(other) > 0)
return rval
def __repr__(self):
"""
String representing the object
:return: string
"""
return "{0}: [{1} ({2}) - {3}]".format(self.__class__.__name__,
self.address,
" ".join(self._hostnames),
self.status)
def __hash__(self):
"""
Hash is needed to be able to use our object in sets
:return: hash
"""
return (hash(self.status) ^ hash(self.address) ^
hash(frozenset(self._services)) ^
hash(frozenset(" ".join(self._hostnames))))
def changed(self, other):
"""
return the number of attribute who have changed
:param other: NmapHost object to compare
:return int
"""
return len(self.diff(other).changed())
@property
def starttime(self):
"""
Accessor for the unix timestamp of when the scan was started
:return: string
"""
return self._starttime
@property
def endtime(self):
"""
Accessor for the unix timestamp of when the scan ended
:return: string
"""
return self._endtime
@property
def address(self):
"""
Accessor for the IP address of the scanned host
:return: IP address as a string
"""
return self._address['addr']
@address.setter
def address(self, addrdict):
"""
Setter for the address dictionnary.
:param addrdict: valid dict is {'addr': '1.1.1.1',
'addrtype': 'ipv4'}
"""
self._address = addrdict
@property
def status(self):
"""
Accessor for the host's status (up, down, unknown...)
:return: string
"""
return self._status['state']
@status.setter
def status(self, statusdict):
"""
Setter for the status dictionnary.
:param statusdict: valid dict is {"state": "open",
"reason": "syn-ack",
"reason_ttl": "0"}
'state' is the only mandatory key.
"""
self._status = statusdict
@property
def hostnames(self):
"""
Accessor returning the list of hostnames (array of strings).
:return: array of string
"""
return self._hostnames
@property
def services(self):
"""
Accessor for the array of scanned services for that host.
An array of NmapService objects is returned.
:return: array of NmapService
"""
return self._services
def get_ports(self):
"""
Retrieve a list of the port used by each service of the NmapHost
:return: list: of tuples (port,'proto') ie:[(22,'tcp'),(25, 'tcp')]
"""
return [(p.port, p.protocol) for p in self._services]
def get_open_ports(self):
"""
Same as get_ports() but only for open ports
:return: list: of tuples (port,'proto') ie:[(22,'tcp'),(25, 'tcp')]
"""
return ([(p.port, p.protocol)
for p in self._services if p.state == 'open'])
def get_service(self, portno, protocol='tcp'):
"""
:param portno: int the portnumber
:param protocol='tcp': string ('tcp','udp')
:return: NmapService or None
"""
plist = [p for p in self._services if
p.port == portno and p.protocol == protocol]
if len(plist) > 1:
raise Exception("Duplicate services found in NmapHost object")
return plist.pop() if len(plist) else None
def get_service_byid(self, service_id):
"""
Returns a NmapService by providing its id.
The id of a nmap service is a python tupl made of (protocol, port)
"""
rval = None
for _tmpservice in self._services:
if _tmpservice.id == service_id:
rval = _tmpservice
return rval
def os_class_probabilities(self):
"""
Returns an array of possible OS class detected during
the OS fingerprinting.
Example [{'accuracy': '96', 'osfamily': 'embedded',
'type': 'WAP', 'vendor': 'Netgear'}, {...}]
:return: dict describing the OS class detected and the accuracy
"""
rval = []
try:
rval = self._extras['os']['osclass']
except (KeyError, TypeError):
pass
return rval
def os_match_probabilities(self):
"""
Returns an array of possible OS match detected during
the OS fingerprinting
:return: dict describing the OS version detected and the accuracy
"""
rval = []
try:
rval = self._extras['os']['osmatch']
except (KeyError, TypeError):
pass
return rval
@property
def os_fingerprinted(self):
"""
Specify if the host has OS fingerprint data available
:return: Boolean
"""
return self._osfingerprinted
@property
def os_fingerprint(self):
"""
Returns the fingerprint of the scanned system.
:return: string
"""
rval = ''
try:
rval = self._extras['os']['osfingerprint']
except (KeyError, TypeError):
pass
return rval
def os_ports_used(self):
"""
Returns an array of the ports used for OS fingerprinting
:return: array of ports used: [{'portid': '22',
'proto': 'tcp',
'state': 'open'},]
"""
rval = []
try:
rval = self._extras['ports_used']
except (KeyError, TypeError):
pass
return rval
@property
def tcpsequence(self):
"""
Returns the difficulty to determine remotely predict
the tcp sequencing.
return: string
"""
rval = ''
try:
rval = self._extras['tcpsequence']['difficulty']
except (KeyError, TypeError):
pass
return rval
@property
def ipsequence(self):
"""
Return the class of ip sequence of the remote hosts.
:return: string
"""
rval = ''
try:
rval = self._extras['ipidsequence']['class']
except (KeyError, TypeError):
pass
return rval
@property
def uptime(self):
"""
uptime of the remote host (if nmap was able to determine it)
:return: string (in seconds)
"""
rval = 0
try:
rval = int(self._extras['uptime']['seconds'])
except (KeyError, TypeError):
pass
return rval
@property
def lastboot(self):
"""
Since when the host was booted.
:return: string
"""
rval = ''
try:
rval = self._extras['uptime']['lastboot']
except (KeyError, TypeError):
pass
return rval
@property
def distance(self):
"""
Number of hops to host
:return: int
"""
rval = 0
try:
rval = int(self._extras['distance']['value'])
except (KeyError, TypeError):
pass
return rval
@property
def id(self):
"""
id of the host. Used for diff()ing NmapObjects
:return: string
"""
return self.address
def get_dict(self):
"""
Return a dict representation of the object.
This is needed by NmapDiff to allow comparaison
:return dict
"""
d = dict([("%s::%s" % (s.__class__.__name__, str(s.id)),
hash(s))
for s in self.services])
d.update({'address': self.address, 'status': self.status,
'hostnames': " ".join(self._hostnames)})
return d
def diff(self, other):
"""
Calls NmapDiff to check the difference between self and
another NmapHost object.
Will return a NmapDiff object.
This objects return python set() of keys describing the elements
which have changed, were added, removed or kept unchanged.
:param other: NmapHost to diff with
:return: NmapDiff object
"""
return NmapDiff(self, other)