source: test/blackhat-demo/jregistrate-collect @ 20

Last change on this file since 20 was 18, checked in by tim, 9 years ago

.

  • Property svn:executable set to *
File size: 6.5 KB
Line 
1#!/usr/bin/env python3
2#-*- mode: Python;-*-
3
4import sys
5import os
6import time
7import random
8import tempfile
9import argparse
10import socket
11import json
12try:
13    import requests
14except:
15    sys.stderr.write('ERROR: Could not import requests module.  Ensure it is installed.\n')
16    sys.stderr.write('       Under Debian, the package name is "python3-requests"\n.')
17    sys.exit(1)
18
19VERSION = "{DEVELOPMENT}"
20if VERSION == "{DEVELOPMENT}":
21    script_dir = '.'
22    try:
23        script_dir = os.path.dirname(os.path.realpath(__file__))
24    except:
25        try:
26            script_dir = os.path.dirname(os.path.abspath(sys.argv[0]))
27        except:
28            pass
29    sys.path.append("%s/../../trunk/lib" % script_dir)
30
31from nanownlib import *
32import nanownlib.storage
33
34parser = argparse.ArgumentParser(
35    description="")
36parser.add_argument('--no-tcpts', action='store_true', help='Disable TCP timestamp profiling')
37parser.add_argument('--no-control', action='store_true', help='Do not collect separate control data.  Instead, synthesize it from test and train data.')
38parser.add_argument('session_name', default=None,
39                    help='Name for the sampler session (used in output filenames)')
40parser.add_argument('sample_count', type=int, default=None,
41                    help='Number of samples to collect')
42parser.add_argument('host', default=None,
43                    help='IP address or host name of server')
44parser.add_argument('port', nargs='?', type=int, default=80,
45                    help='TCP port number of HTTP service (default: 80)')
46options = parser.parse_args()
47
48
49session_name = options.session_name
50num_samples=options.sample_count
51hostname = options.host
52port = options.port
53protocol = 'http'
54
55cases = {"valid":"0012-8846","invalid":"0012-9999"}
56
57
58def extractReportedRuntime(headers, body):
59    try:
60        if 'X-Response-Time' in headers:
61            t = headers['X-Response-Time'].split('ms')[0]
62            return int(float(t)*1000000)
63    except:
64        pass
65
66    return None
67
68
69def sendRequest(case_data):
70    method = 'POST'
71    path = '/jregistrate/register'
72    url = "%s://%s:%d%s" % (protocol,hostname,port,path)
73    headers = {"Content-Type":"application/x-www-form-urlencoded"}
74    body = (b'member_id='+case_data.encode('utf-8')+b'&last_four=1111&zip_code=97219&username=bob&password=&conf_pwd=')
75    req = requests.Request(method, url, headers=headers, data=body).prepare()
76
77    retry = True
78    while retry:
79        try:
80            session = requests.Session()
81            response = session.send(req, verify=False)
82            reported = extractReportedRuntime(response.headers, response.text)
83            retry = False
84        except Exception as e:
85            sys.stderr.write("ERROR: HTTP request problem: %s\n" % repr(e))
86            time.sleep(1.0)
87            sys.stderr.write("ERROR: retrying...\n")
88       
89    return {'userspace_rtt':response.elapsed.microseconds*1000,
90            'reported':reported,
91            'local_port':response.raw._original_response.local_address[1]}
92
93
94def fetch(probedata, data):
95    #   http://docs.python-requests.org/en/latest/api/#requests.Response
96    result = sendRequest(data)
97    result.update(probedata)
98   
99    return result
100
101
102setCPUAffinity()
103setTCPTimestamps()
104host_ip = socket.gethostbyname(hostname) #XXX: what about multiple A records?
105
106meta = {'tcpts_mean':None,'tcpts_stddev':None,'tcpts_slopes':None}
107if not options.no_tcpts:
108    sys.stderr.write("INFO: Probing target for TCP timestamp precision...\n")
109    sniffer_fp = tempfile.NamedTemporaryFile('w+t')
110    sniffer = startSniffer(host_ip, port, sniffer_fp.name)
111    time.sleep(1.0)
112    ports = runTimestampProbes(host_ip, port, hostname, 12)
113    time.sleep(1.0)
114    stopSniffer(sniffer)
115    sniffer_fp.seek(0)
116    mean,stddev,slopes = computeTimestampPrecision(sniffer_fp, ports)
117    meta = {'tcpts_mean':mean,'tcpts_stddev':stddev,'tcpts_slopes':json.dumps(slopes)}
118   
119if meta['tcpts_mean'] == None:
120    sys.stderr.write("INFO: TCP timestamps not supported.\n")
121elif meta['tcpts_stddev'] == None:
122    sys.stderr.write("INFO: Not enough TCP timestamp samples.\n")
123elif meta['tcpts_stddev']/meta['tcpts_mean'] > 0.05:
124    sys.stderr.write("INFO: TCP timestamp precision is inconsistent.\n")
125    sys.stderr.write("INFO:     mean=%(tcpts_mean)f,stddev=%(tcpts_stddev)f,samples=%(tcpts_slopes)s\n"
126                     % meta)
127else:
128    sys.stderr.write("INFO: Estimated TCP timestamp precision: %f (stddev: %f, %f%%)\n"
129                     % (meta['tcpts_mean'], meta['tcpts_stddev'], 100*meta['tcpts_stddev']/meta['tcpts_mean']))
130
131
132sniffer_fp = tempfile.NamedTemporaryFile('w+t')
133db_file = "%s.db" % session_name
134
135sniffer = startSniffer(host_ip, port, sniffer_fp.name)
136db = nanownlib.storage.db(db_file)
137db.addMeta(meta)
138time.sleep(0.5) # ensure sniffer is fully ready and our process is migrated
139
140if options.no_control:
141    num_control = 0
142else:
143    num_control = int(num_samples*1/3)
144
145num_train = int((num_samples-num_control)/2)
146num_test = num_samples-num_train-num_control
147
148sample_types = [('train',num_train),
149                ('train_null',num_control),
150                ('test',num_test)]
151
152sid = 0
153report_interval = 20
154start = time.time()
155next_report = start+report_interval
156for st,count in sample_types:
157    if sniffer.poll() != None:
158        sys.stderr.write('ERROR: Sniffer quit, sender exiting...\n')
159        break
160       
161    for k in range(0,count):
162        sample_order = list(cases.items())
163        random.shuffle(sample_order)
164        if st.endswith('null'):
165            for i in range(1,len(sample_order)):
166                sample_order[i] = (sample_order[i][0],sample_order[0][1])
167            random.shuffle(sample_order)
168           
169        results = []
170        now = int(time.time()*1000000000)
171        for i in range(len(sample_order)):
172            results.append(fetch({'sample':sid, 'test_case':sample_order[i][0],
173                                  'type':st, 'tc_order':i, 'time_of_day':now},
174                                 sample_order[i][1]))
175
176        db.addProbes(results)
177        db.conn.commit()
178        sid += 1
179
180        if (time.time() > next_report):
181            reportProgress(db, sample_types, start)
182            next_report += report_interval
183
184print("probes complete in %f" % (time.time()-start))
185time.sleep(2.0) # Give sniffer a chance to collect remaining packets
186stopSniffer(sniffer)
187
188associatePackets(sniffer_fp, db)
189sniffer_fp.close()
190
191if options.no_control:
192    print("TODO: implement control synthesizing!")
193
194start = time.time()
195num_probes = analyzeProbes(db)
196end = time.time()
197print("analyzed %d probes' packets in: %f" % (num_probes, end-start))
Note: See TracBrowser for help on using the repository browser.