source: test/blackhat-demo/jregistrate-collect

Last change on this file was 23, checked in by tim, 9 years ago

fixed includes

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