/
tests.py
3015 lines (2775 loc) · 127 KB
/
tests.py
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
#! /usr/bin/env python
# This file is part of IVRE.
# Copyright 2011 - 2019 Pierre LALET <pierre.lalet@cea.fr>
#
# IVRE is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# IVRE is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
# License for more details.
#
# You should have received a copy of the GNU General Public License
# along with IVRE. If not, see <http://www.gnu.org/licenses/>.
from __future__ import print_function
from ast import literal_eval
from contextlib import contextmanager
from distutils.spawn import find_executable as which
import errno
from functools import reduce
from glob import glob
from io import BytesIO
import json
import os
import pipes
import random
import re
from select import select
import shutil
import signal
import socket
import subprocess
import sys
import tarfile
import tempfile
import time
try:
from urllib.request import HTTPError, Request, urlopen
except ImportError:
from urllib2 import HTTPError, Request, urlopen
from future.builtins import int as int_types, range
from past.builtins import basestring
if sys.version_info[:2] < (2, 7):
import unittest2 as unittest
else:
import unittest
import ivre
import ivre.config
import ivre.db
import ivre.mathutils
import ivre.parser.bro
import ivre.parser.iptables
import ivre.passive
import ivre.utils
import ivre.web.utils
HTTPD_PORT = 18080
HTTPD_HOSTNAME = socket.gethostname()
# http://schinckel.net/2013/04/15/capture-and-test-sys.stdout-sys.stderr-in-unittest.testcase/
@contextmanager
def capture(function, *args, **kwargs):
out, sys.stdout = sys.stdout, BytesIO()
err, sys.stderr = sys.stderr, BytesIO()
result = function(*args, **kwargs)
sys.stdout.seek(0)
sys.stderr.seek(0)
yield result, sys.stdout.read(), sys.stderr.read()
sys.stdout, sys.stderr = out, err
def run_iter(cmd, interp=None, stdin=None, stdout=subprocess.PIPE,
stderr=subprocess.PIPE):
if interp is not None:
cmd = interp + [which(cmd[0])] + cmd[1:]
return subprocess.Popen(cmd, stdin=stdin, stdout=stdout, stderr=stderr)
def run_cmd(cmd, interp=None, stdin=None):
proc = run_iter(cmd, interp=interp, stdin=stdin)
out, err = proc.communicate()
return proc.returncode, out, err
def python_run(cmd, stdin=None):
return run_cmd(cmd, interp=[sys.executable], stdin=stdin)
def python_run_iter(cmd, stdin=None, stdout=subprocess.PIPE,
stderr=subprocess.PIPE):
return run_iter(cmd, interp=[sys.executable], stdin=stdin, stdout=stdout,
stderr=stderr)
def coverage_run(cmd, stdin=None):
return run_cmd(cmd, interp=COVERAGE + ["run", "--parallel-mode"],
stdin=stdin)
def coverage_run_iter(cmd, stdin=None, stdout=subprocess.PIPE,
stderr=subprocess.PIPE):
return run_iter(cmd, interp=COVERAGE + ["run", "--parallel-mode"],
stdin=stdin, stdout=stdout, stderr=stderr)
def run_passiverecon_worker(bulk_mode=None):
time.sleep(1) # Hack for Travis CI
pid = os.fork()
if pid < 0:
raise Exception("Cannot fork")
elif pid:
# Wait for child process to handle every file in "logs"
while any(walk[2] for walk in os.walk("logs")):
print(u"Waiting for passivereconworker")
time.sleep(2)
os.kill(pid, signal.SIGINT)
os.waitpid(pid, 0)
elif USE_COVERAGE:
os.execvp(
sys.executable,
COVERAGE + [
"run", "--parallel-mode", which("ivre"),
"passivereconworker", "--directory", "logs",
"--progname", " ".join(
pipes.quote(elt) for elt in
COVERAGE + ["run", "--parallel-mode", which("ivre"),
"passiverecon2db", bulk_mode]
),
],
)
else:
os.execlp("ivre", "ivre", "passivereconworker", "--directory",
"logs", "--progname",
"ivre passiverecon2db %s" % bulk_mode)
class AgentScanner(object):
"""This builds an agent, runs it in the background, runs a feed
process (also in the background) and provides an object that can be
used to .scan() targets.
Example:
with AgentScanner(self, nmap_template="http") as agent:
agent.scan(['--net', '192.168.0.0/24'])
"""
def __init__(self, test, nmap_template="default"):
self.test = test
self.pid_agent = self.pid_feed = None
self._build_agent(nmap_template)
self._start_agent()
self._start_feed()
def __enter__(self):
return self
def __delete__(self):
self.stop()
def __exit__(self, *_):
self.wait()
self.stop()
def _build_agent(self, nmap_template):
res, out, _ = RUN(["ivre", "runscans", "--output", "Agent",
"--nmap-template", nmap_template])
self.test.assertEqual(res, 0)
with tempfile.NamedTemporaryFile(delete=False) as fdesc:
fdesc.write(out)
os.chmod(fdesc.name, 0o0755)
self.agent = fdesc.name
def _start_agent(self):
self.agent_dir = tempfile.mkdtemp()
self.pid_agent = subprocess.Popen([self.agent],
preexec_fn=os.setsid,
cwd=self.agent_dir).pid
def _start_feed(self):
feed_cmd = ["runscansagent", "--sync", self.agent_dir]
if USE_COVERAGE:
feed_cmd = COVERAGE + ["run", "--parallel-mode",
which("ivre")] + feed_cmd
else:
feed_cmd = ["ivre"] + feed_cmd
self.pid_feed = subprocess.Popen(feed_cmd).pid
def stop(self):
"""Kills the process backgrounded processes, moves the results to
"output", and removes the temporary files and directories.
"""
if self.pid_agent is not None:
os.kill(self.pid_agent, signal.SIGTERM)
os.waitpid(self.pid_agent, 0)
self.pid_agent = None
if self.pid_feed is not None:
os.kill(self.pid_feed, signal.SIGTERM)
os.waitpid(self.pid_feed, 0)
self.pid_feed = None
os.rename(os.path.join('agentsdata', 'output'), 'output')
for dirname in [self.agent_dir, 'agentsdata']:
if dirname is not None:
try:
shutil.rmtree(dirname)
except OSError as exc:
if exc.errno != errno.ENOENT:
raise
def wait(self):
"""Waits for current and scheduled scans to terminate.
"""
dirnames = [
dirname for subdir in ['input', 'remoteinput', 'remotecur',
'remoteoutput', 'remotedata']
for dirname in glob(os.path.join("agentsdata", "*", subdir))
]
dirnames.extend(os.path.join(self.agent_dir, subdir)
for subdir in ['input', 'cur', 'output'])
while any(walk[2] for dirname in dirnames
for walk in os.walk(dirname)):
print(u"Waiting for runscans sync & agent")
time.sleep(2)
def scan(self, target_options):
"""Runs a scan. `target_options` should be a list of arguments to be
passed to `ivre runscansagent --feed`.
"""
res = RUN(["ivre", "runscansagent", "--feed"] + target_options +
[self.agent_dir], stdin=open(os.devnull, 'wb'))[0]
self.test.assertEqual(res, 0)
class IvreTests(unittest.TestCase):
maxDiff = None
def setUp(self):
try:
with open(os.path.join(SAMPLES, "results")) as fdesc:
self.results = dict([l[:l.index(' = ')],
literal_eval(l[l.index(' = ') + 3:-1])]
for l in fdesc if ' = ' in l)
except IOError as exc:
if exc.errno != errno.ENOENT:
raise exc
self.results = {}
self.new_results = set()
self.used_prefixes = set()
self.unused_results = set(self.results)
def tearDown(self):
ivre.utils.cleandir("logs")
ivre.utils.cleandir(".state")
if self.new_results:
with open(os.path.join(SAMPLES, "results"), 'a') as fdesc:
for valname in self.new_results:
fdesc.write("%s = %r\n" % (valname, self.results[valname]))
for name in self.unused_results:
if any(name.startswith(prefix) for prefix in self.used_prefixes):
sys.stderr.write("UNUSED VALUE key %r\n" % name)
def check_value(self, name, value, check=None):
if check is None:
check = self.assertEqual
try:
self.unused_results.remove(name)
except KeyError:
pass
self.used_prefixes.add(name.split('_', 1)[0] + '_')
if name not in self.results:
self.results[name] = value
sys.stderr.write("NEW VALUE for key %r: %r\n" % (name, value))
self.new_results.add(name)
check(value, self.results[name])
def check_value_cmd(self, name, cmd, errok=False):
res, out, err = RUN(cmd)
self.assertTrue(errok or not err)
self.assertEqual(res, 0)
self.check_value(name, out.decode())
def check_lines_value_cmd(self, name, cmd, errok=False):
res, out, err = RUN(cmd)
self.assertTrue(errok or not err)
self.assertEqual(res, 0)
self.check_value(name, [line for line in out.decode().split('\n')
if line],
check=self.assertItemsEqual)
def check_int_value_cmd(self, name, cmd, errok=False):
res, out, err = RUN(cmd)
self.assertTrue(errok or not err)
self.assertEqual(res, 0)
self.check_value(name, int(out))
def start_web_server(self):
pid = os.fork()
if pid == -1:
raise OSError("Cannot fork()")
if pid:
self.children.append(pid)
time.sleep(2)
else:
def terminate(signum, _):
try:
proc.send_signal(signum)
proc.wait()
signal.signal(signum, signal.SIG_DFL)
sys.exit(0)
except Exception:
pass
for sig in [signal.SIGINT, signal.SIGTERM]:
signal.signal(sig, terminate)
proc = RUN_ITER(["ivre", "httpd", "-p", str(HTTPD_PORT),
"-b", HTTPD_HOSTNAME],
stdout=open("/tmp/webserver.log", 'w'),
stderr=subprocess.STDOUT)
proc.wait()
sys.exit(0)
@classmethod
def stop_children(cls):
for sig in [signal.SIGINT, signal.SIGTERM, signal.SIGKILL]:
for pid in cls.children[:]:
try:
os.kill(pid, sig)
except OSError:
cls.children.remove(pid)
time.sleep(2)
while cls.children:
os.waitpid(cls.children.pop(), 0)
@staticmethod
def _sort_top_values(listval):
maxval = None
values = []
for elem in listval:
if not elem['_id'] or elem['_id'] == "None":
# Hack for Postgresql empty field.
continue
if maxval is None:
maxval = elem['count']
elif maxval != elem['count']:
break
values.append(elem['_id'])
return sorted(values)
def _check_top_value_api(self, name, field, count=10, database=None,
**kwargs):
values = self._sort_top_values(
database.topvalues(field, topnbr=count)
)
self.check_value(name, values, check=self.assertItemsEqual)
def _check_top_value_cli(self, name, field, count=10, command=None,
**kwargs):
res, out, err = RUN(["ivre", command, "--top", field, "--limit",
str(count)])
self.assertTrue(not err)
self.assertEqual(res, 0)
listval = []
for line in out.decode().split('\n'):
if not line:
continue
value, count = line.rsplit(": ", 1)
for function in [int, float, json.loads]:
try:
value = function(value)
except ValueError:
continue
else:
break
listval.append({'_id': value, 'count': int(count)})
self.check_value(name, self._sort_top_values(listval),
check=self.assertItemsEqual)
def _check_top_value_cgi(self, name, field, count=10, **kwargs):
req = Request('http://%s:%d/cgi/scans/top/%s:%d' % (
HTTPD_HOSTNAME, HTTPD_PORT, field, count
))
req.add_header('Referer',
'http://%s:%d/' % (HTTPD_HOSTNAME, HTTPD_PORT))
listval = []
for elem in json.loads(urlopen(req).read().decode()):
listval.append({'_id': elem['label'], 'count': elem['value']})
self.check_value(name, self._sort_top_values(listval),
check=self.assertItemsEqual)
def check_nmap_top_value(self, name, field, count=10):
for method in ['api', 'cli']:
specific_name = "%s_%s" % (name, method)
if name in self.results and specific_name not in self.results:
specific_name = name
getattr(self, "_check_top_value_%s" % method)(
specific_name, field, count=count,
database=ivre.db.db.nmap, command="scancli"
)
def check_view_top_value(self, name, field, count=10):
for method in ['api', 'cli', 'cgi']:
specific_name = "%s_%s" % (name, method)
if name in self.results and specific_name not in self.results:
specific_name = name
getattr(self, "_check_top_value_%s" % method)(
specific_name, field, count=count,
database=ivre.db.db.view, command="view"
)
def check_count_value_api(self, name_or_value, flt, database=None,
**kwargs):
count = database.count(flt)
if name_or_value is None:
pass
elif isinstance(name_or_value, str):
self.check_value(name_or_value, count)
else:
self.assertEqual(name_or_value, count)
return count
def check_count_value_cli(self, name_or_value, cliflt, command="",
**kwargs):
res, out, _ = RUN(["ivre", command, "--count"] + cliflt)
self.assertEqual(res, 0)
count = int(out)
if name_or_value is None:
pass
elif isinstance(name_or_value, str):
self.check_value(name_or_value, count)
else:
self.assertEqual(name_or_value, count)
return count
def check_count_value_cgi(self, name_or_value, webflt):
req = Request('http://%s:%d/cgi/scans/count%s' % (
HTTPD_HOSTNAME, HTTPD_PORT,
'' if webflt is None else '?q=%s' % webflt,
))
req.add_header('Referer', 'http://%s:%d/' % (HTTPD_HOSTNAME,
HTTPD_PORT))
udesc = urlopen(req)
self.assertEqual(udesc.getcode(), 200)
count = json.loads(udesc.read().decode())
if name_or_value is None:
pass
elif isinstance(name_or_value, str):
self.check_value(name_or_value, count)
else:
self.assertEqual(name_or_value, count)
return count
def check_nmap_count_value(self, name_or_value, flt, cliflt, webflt):
cnt1 = self.check_count_value_api(name_or_value, flt,
database=ivre.db.db.nmap)
cnt2 = self.check_count_value_cli(name_or_value, cliflt,
command="scancli")
self.assertEqual(cnt1, cnt2)
return cnt1
def check_view_count_value(self, name_or_value, flt, cliflt, webflt):
cnt1 = self.check_count_value_api(name_or_value, flt,
database=ivre.db.db.view)
cnt2 = self.check_count_value_cli(name_or_value, cliflt,
command="view")
cnt3 = self.check_count_value_cgi(name_or_value, webflt)
self.assertEqual(cnt1, cnt2)
self.assertEqual(cnt1, cnt3)
return cnt1
def find_record_cgi(self, predicate, webflt=None):
"""Browse the results from the JSON interface to find a record for
which `predicate()` is True, given `webflt`.
"""
current = 0
while True:
query = [] if webflt is None else [webflt]
if current:
query.append('skip%%3A%d' % current)
query = "?q=%s" % '%20'.join(query) if query else ""
req = Request('http://%s:%d/cgi/scans%s' % (
HTTPD_HOSTNAME, HTTPD_PORT, query,
))
req.add_header('Referer', 'http://%s:%d/' % (HTTPD_HOSTNAME,
HTTPD_PORT))
udesc = urlopen(req)
self.assertEqual(udesc.getcode(), 200)
count = 0
for record in json.loads(udesc.read().decode()):
if predicate(record):
return True
count += 1
if count < ivre.config.WEB_LIMIT:
return False
current += count
@classmethod
def setUpClass(cls):
cls.nmap_files = (
os.path.join(root, fname)
for root, _, files in os.walk(SAMPLES)
for fname in files
if fname.endswith('.xml') or fname.endswith('.json') or
fname.endswith('.xml.bz2') or fname.endswith('.json.bz2')
)
cls.pcap_files = (
os.path.join(root, fname)
for root, _, files in os.walk(SAMPLES)
for fname in files
if fname.endswith('.pcap')
)
cls.children = []
@classmethod
def tearDownClass(cls):
cls.stop_children()
def init_nmap_db(self):
self.assertEqual(RUN(["ivre", "scancli", "--count"])[1], b"0\n")
self.assertEqual(RUN(["ivre", "scancli", "--init"],
stdin=open(os.devnull))[0], 0)
self.assertEqual(RUN(["ivre", "scancli", "--count"])[1], b"0\n")
def test_30_nmap(self):
#
# Database tests
#
# Init DB
self.init_nmap_db()
# Insertion / "test" insertion (JSON output)
host_counter = 0
scan_counter = 0
host_counter_test = 0
scan_warning = 0
host_stored = re.compile(b"^DEBUG:ivre:HOST STORED: ", re.M)
scan_stored = re.compile(b"^DEBUG:ivre:SCAN STORED: ", re.M)
def host_stored_test(line):
try:
return len(json.loads(line.decode()))
except ValueError:
return 0
scan_duplicate = re.compile(b"^DEBUG:ivre:Scan already present in "
b"Database", re.M)
for fname in self.nmap_files:
# Insertion in DB
options = ["ivre", "scan2db", "--no-update-view", "--port", "-c",
"TEST", "-s", "SOURCE"]
if "-probe-" in fname:
options.extend(["--masscan-probes", fname.split('-probe-')[1]])
options.extend(["--", fname])
res, _, err = RUN(options)
self.assertEqual(res, 0)
host_counter += sum(1 for _ in host_stored.finditer(err))
scan_counter += sum(1 for _ in scan_stored.finditer(err))
for line in err.split(b'\n'):
if line[:11] != b'DEBUG:ivre:':
print(line.decode())
# Insertion test (== parsing only)
res, out, _ = RUN(["ivre", "scan2db", "--port", "--test",
"-c", "TEST", "-s", "SOURCE", fname])
self.assertEqual(res, 0)
host_counter_test += sum(host_stored_test(line)
for line in out.splitlines())
# Duplicate insertion
res, _, err = RUN(["ivre", "scan2db", "--no-update-view", "--port",
"-c", "TEST", "-s", "SOURCE", fname])
self.assertEqual(res, 0)
scan_warning += sum(
1 for _ in scan_duplicate.finditer(err)
)
# Specific test cases
samples = [
# Ignored script with a named table element, followed by
# a script with an unnamed table element
b"""<nmaprun scanner="nmap">
<host>
<script id="fcrdns" output="FAIL (No PTR record)">
<table key="<none>">
<elem key="status">fail</elem>
<elem key="reason">No PTR record</elem>
</table>
</script>
<script id="fake" output="Test output for fake script">
<elem>fake</elem>
</script>
</host>
</nmaprun>
""",
# Masscan with an HTTP banner
b"""<nmaprun scanner="masscan">
<host>
<ports>
<port protocol="tcp" portid="80">
<state state="open"/>
<service name="http" banner="HTTP/1.1 403 Forbidden\\x0d\\x0aServer: test/1.0\\x0d\\x0a\\x0d\\x0a">
</service>
</port>
</ports>
</host>
</nmaprun>
""", # noqa: E501
]
for sample in samples:
fdesc = tempfile.NamedTemporaryFile(delete=False)
fdesc.write(sample)
fdesc.close()
res, out, _ = RUN(["ivre", "scan2db", "--test", fdesc.name])
self.assertEqual(res, 0)
self.assertEqual(sum(host_stored_test(line)
for line in out.splitlines()), 1)
os.unlink(fdesc.name)
# Screenshots: this tests the http-screenshot script
# (including phantomjs) and IVRE's ability to read
# screenshots (including extracting words with tesseract)
ipaddr = socket.gethostbyname('ivre.rocks')
with AgentScanner(self, nmap_template="http") as agent:
agent.scan(['--net', '%s/32' % ipaddr])
data_files, up_files = (
glob("%s.%s*" % (os.path.join('output', 'MISC', subdir,
'*', *ipaddr.split('.')), ext))
for subdir, ext in [('data', 'tar'), ('up', 'xml')]
)
self.assertEqual(len(data_files), 1)
self.assertTrue(os.path.exists(data_files[0]))
self.assertEqual(len(up_files), 1)
self.assertTrue(os.path.exists(up_files[0]))
# TarFile object does not implement __exit__ on Python 2.6,
# cannot use `with`
data_archive = tarfile.open(data_files[0])
data_archive.extractall()
data_archive.close()
self.assertTrue(os.path.exists('screenshot-%s-80.jpg' % ipaddr))
res, out, _ = RUN(["ivre", "scan2db", "--test"] + up_files)
self.assertEqual(res, 0)
def _json_loads(data, deflt=None):
try:
return json.loads(data.decode())
except ValueError:
return deflt
screenshots_count = sum(bool(port.get('screendata'))
for line in out.splitlines()
for host in _json_loads(line, [])
for port in host.get('ports', []))
self.assertEqual(screenshots_count, 1)
screenwords = set(word for line in out.splitlines()
for host in _json_loads(line, [])
for port in host.get('ports', [])
for word in port.get('screenwords', []))
self.assertTrue('IVRE' in screenwords)
shutil.rmtree('output')
RUN(["ivre", "scancli", "--update-schema"])
self.assertEqual(host_counter, host_counter_test)
self.assertEqual(scan_counter, scan_warning)
hosts_count = self.check_nmap_count_value("nmap_get_count",
ivre.db.db.nmap.flt_empty,
[], None)
self.check_count_value_api(0, ivre.db.db.nmap.searchnonexistent(),
database=ivre.db.db.nmap)
# Is the test case OK?
self.assertGreater(hosts_count, 0)
# Counting results
self.assertEqual(hosts_count, host_counter)
# JSON
res, out, err = RUN(['ivre', 'scancli', '--json'])
self.assertEqual(res, 0)
self.assertTrue(not err)
self.assertEqual(len(out.splitlines()), hosts_count)
# SHORT
res, out, err = RUN(['ivre', 'scancli', '--short'])
self.assertEqual(res, 0)
self.assertTrue(not err)
self.assertEqual(len(out.splitlines()), hosts_count)
# GNMAP
res, out, err = RUN(['ivre', 'scancli', '--gnmap'])
self.assertEqual(res, 0)
self.assertTrue(not err)
count = sum(1 for line in out.splitlines() if b'Status: Up' in line)
self.assertEqual(count, hosts_count)
# Object ID
res, out, _ = RUN(["ivre", "scancli", "--json", "--limit", "1"])
self.assertEqual(res, 0)
oid = str(next(ivre.db.db.nmap.get(
ivre.db.db.nmap.searchhost(json.loads(out.decode())['addr']),
limit=1, fields=["_id"],
))['_id'])
res, out, _ = RUN(["ivre", "scancli", "--count", "--id", oid])
self.assertEqual(res, 0)
self.assertEqual(int(out), 1)
res, out, _ = RUN(["ivre", "scancli", "--count", "--no-id", oid])
self.assertEqual(res, 0)
self.assertEqual(int(out) + 1, hosts_count)
portsnb_20 = self.check_nmap_count_value(
"nmap_20_ports",
ivre.db.db.nmap.searchcountopenports(20, 20),
["--countports", "20", "20"], "countports:20",
)
self.check_nmap_count_value(
hosts_count - portsnb_20,
ivre.db.db.nmap.searchcountopenports(20, 20, neg=True),
["--no-countports", "20", "20"], "!countports:20",
)
portsnb_10_100 = self.check_nmap_count_value(
"nmap_10-100_ports",
ivre.db.db.nmap.searchcountopenports(10, 100),
["--countports", "10", "100"], "countports:10-100",
)
self.check_nmap_count_value(
hosts_count - portsnb_10_100,
ivre.db.db.nmap.searchcountopenports(10, 100, neg=True),
["--no-countports", "10", "100"], "-countports:10-100",
)
self.check_nmap_count_value(
"nmap_extended_eu_count",
ivre.db.db.nmap.searchcountry(['EU', 'CH', 'NO']),
["--country=EU,CH,NO"], "country:EU,CH,NO"
)
# Filters
addr = next(ivre.db.db.nmap.get(
ivre.db.db.nmap.flt_empty, fields=["addr"]
))['addr']
self.check_nmap_count_value(1, ivre.db.db.nmap.searchhost(addr),
['--host', ivre.utils.force_int2ip(addr)],
ivre.utils.force_int2ip(addr))
result = next(ivre.db.db.nmap.get(
ivre.db.db.nmap.searchhost(addr)
))
self.assertEqual(result['addr'], addr)
self.check_count_value_api(1, ivre.db.db.nmap.flt_and(
ivre.db.db.nmap.searchhost(addr),
ivre.db.db.nmap.searchhost(addr),
), database=ivre.db.db.nmap)
recid = ivre.db.db.nmap.getid(
next(ivre.db.db.nmap.get(ivre.db.db.nmap.flt_empty))
)
self.check_count_value_api(1, ivre.db.db.nmap.searchid(recid),
database=ivre.db.db.nmap)
self.assertIsNotNone(
ivre.db.db.nmap.getscan(
ivre.db.db.nmap.getscanids(
next(ivre.db.db.nmap.get(ivre.db.db.nmap.flt_empty))
)[0]
)
)
self.check_nmap_count_value(0,
ivre.db.db.nmap.searchhost("127.12.34.56"),
["--host", "127.12.34.56"], "127.12.34.56")
generator = ivre.db.db.nmap.get(ivre.db.db.nmap.flt_empty)
addrrange = sorted((x['addr'] for x in [next(generator),
next(generator)]),
key=ivre.utils.force_ip2int)
addr_range_count = self.check_nmap_count_value(
None, ivre.db.db.nmap.searchrange(*addrrange),
["--range"] + addrrange,
"range:%s-%s" % tuple(addrrange),
)
self.assertGreaterEqual(addr_range_count, 2)
self.check_count_value_api(
hosts_count - addr_range_count,
ivre.db.db.nmap.searchrange(*addrrange, neg=True),
database=ivre.db.db.nmap
)
count = sum(
ivre.db.db.nmap.count(ivre.db.db.nmap.searchnet(net))
for net in ivre.utils.range2nets(addrrange)
)
self.assertEqual(count, addr_range_count)
addrs = set(
ivre.db.db.nmap.internal2ip(addr)
for net in ivre.utils.range2nets(addrrange)
for addr in ivre.db.db.nmap.distinct(
"addr", flt=ivre.db.db.nmap.searchnet(net),
)
)
self.assertTrue(len(addrs) <= addr_range_count)
count = ivre.db.db.nmap.count(
ivre.db.db.nmap.searchhosts(addrrange)
)
self.assertEqual(count, 2)
count_cmpl = ivre.db.db.nmap.count(
ivre.db.db.nmap.searchhosts(addrrange, neg=True)
)
self.assertEqual(count + count_cmpl, hosts_count)
count = ivre.db.db.nmap.count(
ivre.db.db.nmap.searchtimerange(
0, next(ivre.db.db.nmap.get(
ivre.db.db.nmap.flt_empty,
fields=['endtime'],
sort=[['endtime', -1]]
))['endtime']
)
)
self.assertEqual(count, hosts_count)
nets = ivre.utils.range2nets(addrrange)
count = 0
for net in nets:
count += ivre.db.db.nmap.count(
ivre.db.db.nmap.searchnet(net)
)
start, stop = (ivre.utils.ip2int(addr) for addr in
ivre.utils.net2range(net))
for addr in ivre.db.db.nmap.distinct(
"addr",
flt=ivre.db.db.nmap.searchnet(net),
):
addr = ivre.utils.ip2int(ivre.db.db.nmap.internal2ip(addr))
self.assertTrue(start <= addr <= stop)
self.assertEqual(count, addr_range_count)
# Networks in `nets` are separated sets
count = ivre.db.db.nmap.count(
ivre.db.db.nmap.flt_and(
*(ivre.db.db.nmap.searchnet(net) for net in nets)
)
)
self.assertEqual(count, 0 if len(nets) > 1 else addr_range_count)
count = ivre.db.db.nmap.count(
ivre.db.db.nmap.flt_or(
*(ivre.db.db.nmap.searchnet(net) for net in nets)
)
)
self.assertEqual(count, addr_range_count)
count = ivre.db.db.nmap.count(
ivre.db.db.nmap.searchscript(name="http-robots.txt")
)
# Test case OK?
self.assertGreater(count, 0)
self.check_value("nmap_robots.txt_count", count)
# Test for script negate filter
ncount = ivre.db.db.nmap.count(
ivre.db.db.nmap.searchscript(name="http-robots.txt", neg=True)
)
self.assertEqual(ncount, hosts_count - count)
result = ivre.db.db.nmap.get(
ivre.db.db.nmap.searchscript(name="http-robots.txt")
)
addr = next(result)['addr']
count = ivre.db.db.nmap.count(ivre.db.db.nmap.flt_and(
ivre.db.db.nmap.searchscript(name="http-robots.txt"),
ivre.db.db.nmap.searchhost(addr),
))
self.assertEqual(count, 1)
count = ivre.db.db.nmap.count(
ivre.db.db.nmap.searchscript(
name="http-robots.txt",
output=ivre.utils.str2regexp("/cgi-bin"),
))
self.assertGreater(count, 0)
self.check_value("nmap_robots.txt_cgi_count", count)
# Check the opposite condition
ncount = ivre.db.db.nmap.count(
ivre.db.db.nmap.searchscript(
name="http-robots.txt",
output=ivre.utils.str2regexp("/cgi-bin"),
neg=True,
))
self.assertEqual(ncount, hosts_count - count)
count = ivre.db.db.nmap.count(ivre.db.db.nmap.searchftpanon())
# Test case OK?
self.assertGreater(count, 0)
self.check_value("nmap_anonftp_count", count)
# Check .searchsshkey()
def _find_fingerprint():
for host in ivre.db.db.nmap.get(ivre.db.db.nmap.searchsshkey()):
for port in host.get('ports', []):
for script in port.get('scripts', []):
if script['id'] == 'ssh-hostkey':
for key in script.get('ssh-hostkey', []):
if 'fingerprint' in key:
return host['addr'], key['fingerprint']
ip_addr, fingerprint = _find_fingerprint()
self.assertIsNotNone(fingerprint)
# Check .searchsshkey() with a fingerprint
def _has_fingerprint(host):
for port in host.get('ports', []):
for script in port.get('scripts', []):
if script['id'] == 'ssh-hostkey':
for key in script.get('ssh-hostkey', []):
if key.get('fingerprint') == fingerprint:
return True
return False
found_init_host = False
for host in ivre.db.db.nmap.get(ivre.db.db.nmap.searchsshkey(
fingerprint=fingerprint
)):
self.assertTrue(_has_fingerprint(host))
if host['addr'] == ip_addr:
found_init_host = True
self.assertTrue(found_init_host)
count = ivre.db.db.nmap.count(
ivre.db.db.nmap.searchhopdomain(re.compile('.'))
)
# Test case OK?
self.assertGreater(count, 0)
self.check_value("nmap_trace_hostname_count", count)
result = ivre.db.db.nmap.get(
ivre.db.db.nmap.searchhopdomain(re.compile('.'))
)
hop = random.choice([
hop for hop in
reduce(lambda x, y: x['hops'] + y['hops'],
next(result)['traces'],
{'hops': []})
if 'domains' in hop and hop['domains']
])
count = ivre.db.db.nmap.count(
ivre.db.db.nmap.searchhop(hop['ipaddr'])
)
self.assertGreaterEqual(count, 1)
count = ivre.db.db.nmap.count(
ivre.db.db.nmap.searchhopdomain(hop['domains'][0])
)
self.assertGreaterEqual(count, 1)
# Indexes
addr = next(ivre.db.db.nmap.get(
ivre.db.db.nmap.flt_empty
))['addr']
addr_net = '.'.join(addr.split('.')[:3]) + '.0/24'
queries = [
ivre.db.db.nmap.searchhost(addr),
ivre.db.db.nmap.searchnet(addr_net),
ivre.db.db.nmap.searchrange(max(ivre.utils.ip2int(addr) - 256, 0),
min(ivre.utils.ip2int(addr) + 256,
4294967295)),
]
for query in queries:
result = ivre.db.db.nmap.get(query)
count = ivre.db.db.nmap.count(query)
if DATABASE == "mongo":
nscanned = json.loads(ivre.db.db.nmap.explain(
ivre.db.db.nmap._get(query)
))
try:
nscanned = nscanned['nscanned']
except KeyError:
nscanned = nscanned['executionStats']['totalDocsExamined']
self.assertEqual(count, nscanned)
self.assertEqual(
query,
ivre.db.db.nmap.str2flt(ivre.db.db.nmap.flt2str(query))
)
# FIXME: test PostgreSQL indexes
count = ivre.db.db.nmap.count(ivre.db.db.nmap.searchx11())
self.check_value("nmap_x11_count", count)
count = ivre.db.db.nmap.count(ivre.db.db.nmap.searchx11access())
self.check_value("nmap_x11access_count", count)
count = ivre.db.db.nmap.count(ivre.db.db.nmap.searchnfs())