aboutsummaryrefslogtreecommitdiffstats
path: root/autoscan/autoscan.py
blob: 182b8ba90650156748bee11c7c75834ce652ca21 (plain) (blame)
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
#!/bin/env python

# autoscan - automatic fingerprint of visited networks
# 2013, Laurent Ghigonis <laurent@gouloum.fr>

# Usage: autoscan.py [-d] [interfaces]
# by default, monitor all network interfaces
# Should work on all Linux versions

# Each time network connectivity become available after a cut-off,
# run some tests and store results in
# YYYYMMDD_hhmmss_interface/testname/output"
# * ifconfig
# * if WIFI, iwconfig
# * /etc/resolv.conf
# * 15s pcap
# * route -n
# * traceroute
# * local net IP scan
# * public IP (curl ifconfig.me)
# * ping 8.8.8.8

import sys
import os
import time
import subprocess
import traceback
import re
import argparse
import shutil
import errno

class Autoscan_iface(object):
        def __init__(self, iface, logpath=".", pubip="8.8.8.8", verbose=0):
                self.iface = iface
                self.logpath = logpath
                self.verbose = verbose
                self.pubip = pubip
                self.date = None # set by _do_tests()
                if 'SUDO_UID' in os.environ and 'SUDO_GID' in os.environ:
                        self.perm_uid = int(os.environ['SUDO_UID'])
                        self.perm_gid = int(os.environ['SUDO_GID'])
                else:
                        self.perm_uid = os.getuid()
                        self.perm_gid = os.getgid()
                self.found_ip4 = None
                self.found_ip6 = None
                self.found_pubip = None
                self.found_dns = list()

        def monitor(self):
                self._do_tests()
                while True:
                        self._wait_down()
                        self._wait_up()
                        self._do_tests()

        def run_now(self):
                self._do_tests()

        def _wait_up(self):
                while True:
                        out, err, code = self._exec(
                                ['ifconfig', self.iface])
                        up = re.search(r'UP', out)
                        ip4 = re.search(r'inet (\S+)', out)
                        ip6 = re.search(r'inet6 (\S+)', out)
                        if up and (ip4 or ip6):
                                break
                        time.sleep(1)

        def _wait_down(self):
                while True:
                        out, err, code = self._exec(
                                ['ifconfig', self.iface])
                        up = re.search(r'UP', out)
                        if not up:
                                break
                        # XXX also consider sleep as interface down
                        time.sleep(1)

        def _do_tests(self):
                self.date = time.strftime("%Y%m%d_%H%M%S", time.gmtime())
                self._do_tests_run(self._test_pcap)
                self._do_tests_run(self._test_ifconfig)
                self._do_tests_run(self._test_iwconfig)
                self._do_tests_run(self._test_route)
                self._do_tests_run(self._test_resolv)
                self._do_tests_run(self._test_pubip_get)
                self._do_tests_run(self._test_pubip_ping)
                self._do_tests_run(self._test_pubip_traceroute)
                self._do_tests_run(self._test_resolv_traceroute)
                self._do_tests_run(self._test_explor_traceroute)
                self._do_tests_run(self._test_explor_scan)
		if self.found_pubip:
			suffix = self.found_pubip
		else:
			suffix = self.found_ip4
		newpath = self._storepath_get() + "_" + suffix
		if self.verbose >= 1:
			print "[*] %s" % newpath
		os.rename(self._storepath_get(), newpath)

        def _do_tests_run(self, func):
                try:
                        if self.verbose >= 1:
                                print "[-] %s" % func.__name__
                        func()
                except Exception, e:
                        print("test %s failed: %s" % (func, e))
                        traceback.print_exc()

        def _test_pcap(self):
                if os.fork() != 0:
                        return
                # child
                os.system("$(tcpdump -ni %s -w %s 2>/dev/null & sleep 15; kill %%1) &" % (
                        self.iface, self._storepath_get("pcap/tcpdump.pcap")))
                sys.exit(0)

        def _test_ifconfig(self):
                out, err, code = self._exec(
                        ['ifconfig', self.iface])
                self._store("ifconfig/out", out)
                up = re.search(r'UP', out)
                if up: self._store("ifconfig/up", "")
                ip4 = re.search(r'inet (\S+)', out)
                if ip4:
                        self._store("ifconfig/ip4", ip4.group(1))
                        self.found_ip4 = ip4.group(1)
                ip6 = re.search(r'inet6 (\S+)', out)
                if ip6:
                        self._store("ifconfig/ip6", ip6.group(1))
                        self.found_ip6 = ip6.group(1)

        def _test_iwconfig(self):
                out, err, code = self._exec(
                        ['iwconfig', self.iface])
                if len(out) == 0:
                        return # not a WIFI interface
                self._store("iwconfig/out", out)
                essid = re.search(r'ESSID:(\S+)', out)
                if essid: self._store("iwconfig/essid", essid.group(1))
                ap = re.search(r'Access Point: (\S+)', out)
                if ap: self._store("iwconfig/ap", ap.group(1))

        def _test_route(self):
                out, err, code = self._exec(
                        ['route', '-n'])
                self._store("route/out", out)
                gw = re.findall(r'(\S+)', out.split('\n')[2])[1]
                if gw: self._store("route/gw", gw)

        def _test_resolv(self):
                shutil.copy("/etc/resolv.conf", self._storepath_get("resolv/resolv.conf"))
                n = 0
                with open("/etc/resolv.conf") as f:
                        for line in f:
                                r = re.search('nameserver (\S+)', line)
                                if r:
                                        dns = r.group(1)
                                        self._store("resolv/dns%d" % n, dns)
                                        self.found_dns.append(dns)
                                        n += 1
                                        

        def _test_pubip_get(self):
                out, err, code = self._exec(
                        ['curl', '--retry', '3', 'ifconfig.me'])
                self._store("pubip_get/ip", out)
                self.found_pubip = out.strip()

        def _test_pubip_ping(self):
                out, err, code = self._exec(
                        ['ping', '-W', '3', '-c', '1', self.pubip])
                self._store("pubip_ping/code", code)
                self._store("pubip_ping/out", out)

        def _test_resolv_traceroute(self):
                for dns in self.found_dns:
                        self._store("resolv_traceroute/out",
                                self._util_traceroute(dns))

        def _test_pubip_traceroute(self):
                self._store("pubip_traceroute/out",
                        self._util_traceroute(self.pubip))

        def _test_explor_traceroute(self):
                targets = ["192.168.0.1", "192.168.1.1", "192.168.2.1", "10.0.0.1", "172.16.0.1"]
                for t in targets:
                        self._store("explor_traceroute/out_%s" % t,
                                self._util_traceroute(t))

        def _util_traceroute(self, target):
                out, err, code = self._exec(
                        ['traceroute', target])
                return out

        def _test_explor_scan(self):
                target = re.sub('\.[0-9]+$', '', self.found_ip4) + "/24" # XXX v6
                out, err, code = self._exec(
                        ['nmap', '-oA', self._storepath_get("explor_scan/localnet"), '-p', '21,22,23,445,80,443,8080,8081,8082,8083', target])
                self._store("explor_scan/out", out)
		if len(err) > 0:
			self._store("explor_scan/err", err)

        def _exec(self, cmd):
                p = subprocess.Popen(cmd,
                                stdout=subprocess.PIPE, stderr=subprocess.PIPE)
                out, err = p.communicate()
                return out, err, p.returncode

        def _store(self, suffix, txt):
                name = self._storepath_get(suffix)
                if self.verbose >= 2:
                        print("%s = %s" % (name, txt))
                f = open(name, "w+")
                f.write(str(txt))
                f.close()
                os.chown(name, self.perm_uid, self.perm_gid)

        def _storepath_get(self, suffix=None):
                path = "%s/%s_%s" % (self.logpath, self.date, self.iface)
		if suffix:
			path += "/" + suffix
                d = os.path.dirname(path)
                if not os.path.isdir(d):
                        os.makedirs(d)
                        subprocess.check_output(['chown', '-R', '%s:%s' % (self.perm_uid, self.perm_gid), self.logpath]) # pythonic way is awefull
                return path

if not os.geteuid() == 0:
        sys.exit('must be root')

# XXX all ifaces by default, use netifaces

parser = argparse.ArgumentParser()
parser.add_argument("interfaces", nargs='+',
                        help="Interface(s) to use")
parser.add_argument("-m", "--monitor", action="store_true",
                        help="Mode monitor: Stay in the background and automaticaly run when interface turns up")
parser.add_argument("-r", "--runnow", action="store_true",
                        help="Mode runnow (default): Run tests/scans now and exit")
parser.add_argument("-f", "--foreground", action="store_true",
                        help="Run in foreground for monitor mode, do not daemonize")
parser.add_argument("-o", "--outdir", action="store", default=".",
                        help="Use DIR as output directory")
parser.add_argument("-p", "--pubip", action="store", default="8.8.8.8",
                        help="Use target IP for public IP tests")
parser.add_argument("-v", "--verbose", action="store_true",
                        help="Increase output verbosity, default=0, max=2")
args = parser.parse_args()

if args.runnow and args.monitor:
	print "Cannot specify both monitor and runnow modes !"
	sys.exit(1)
if args.runnow and args.foreground:
	print "Cannot specify foreground with runnow, it's implicit !"
	sys.exit(1)
if not args.runnow and not args.monitor:
	args.runnow = True
	args.foreground = True

for iface in args.interfaces:
        if os.fork() == 0:
                autoscan = Autoscan_iface(iface, args.outdir, args.pubip,
                                        args.verbose)
                if args.runnow:
                        autoscan.run_now()
                else:
                        autoscan.monitor()
                        # UNREACHED

if args.foreground:
        # wait for all iface forks and subchilds
        while True:
                try: os.wait()
                except: break