Debian Codegraph @

deps/curl/tests/python_dependencies/impacket/spnego.py

raw
1 from __future__ import print_function
2 # Copyright (c) 2003-2016 CORE Security Technologies
3 #
4 # This software is provided under under a slightly modified version
5 # of the Apache Software License. See the accompanying LICENSE file
6 # for more information.
7 #
8 # Author: Alberto Solino ([email protected])
9 #
10 # Description:
11 # SPNEGO functions used by SMB, SMB2/3 and DCERPC
12 #
13
14 from struct import pack, unpack, calcsize
15
16 ############### GSS Stuff ################
17 GSS_API_SPNEGO_UUID = '\x2b\x06\x01\x05\x05\x02'
18 ASN1_SEQUENCE = 0x30
19 ASN1_AID = 0x60
20 ASN1_OID = 0x06
21 ASN1_OCTET_STRING = 0x04
22 ASN1_MECH_TYPE = 0xa0
23 ASN1_MECH_TOKEN = 0xa2
24 ASN1_SUPPORTED_MECH = 0xa1
25 ASN1_RESPONSE_TOKEN = 0xa2
26 ASN1_ENUMERATED = 0x0a
27 MechTypes = {
28 '+\x06\x01\x04\x01\x827\x02\x02\x1e': 'SNMPv2-SMI::enterprises.311.2.2.30',
29 '+\x06\x01\x04\x01\x827\x02\x02\n': 'NTLMSSP - Microsoft NTLM Security Support Provider',
30 '*\x86H\x82\xf7\x12\x01\x02\x02': 'MS KRB5 - Microsoft Kerberos 5',
31 '*\x86H\x86\xf7\x12\x01\x02\x02': 'KRB5 - Kerberos 5',
32 '*\x86H\x86\xf7\x12\x01\x02\x02\x03': 'KRB5 - Kerberos 5 - User to User'
33 }
34 TypesMech = dict((v,k) for k, v in MechTypes.iteritems())
35
36 def asn1encode(data = ''):
37 #res = asn1.SEQUENCE(str).encode()
38 #import binascii
39 #print '\nalex asn1encode str: %s\n' % binascii.hexlify(str)
40 if 0 <= len(data) <= 0x7F:
41 res = pack('B', len(data)) + data
42 elif 0x80 <= len(data) <= 0xFF:
43 res = pack('BB', 0x81, len(data)) + data
44 elif 0x100 <= len(data) <= 0xFFFF:
45 res = pack('!BH', 0x82, len(data)) + data
46 elif 0x10000 <= len(data) <= 0xffffff:
47 res = pack('!BBH', 0x83, len(data) >> 16, len(data) & 0xFFFF) + data
48 elif 0x1000000 <= len(data) <= 0xffffffff:
49 res = pack('!BL', 0x84, len(data)) + data
50 else:
51 raise Exception('Error in asn1encode')
52 return str(res)
53
54 def asn1decode(data = ''):
55 len1 = unpack('B', data[:1])[0]
56 data = data[1:]
57 if len1 == 0x81:
58 pad = calcsize('B')
59 len2 = unpack('B',data[:pad])[0]
60 data = data[pad:]
61 ans = data[:len2]
62 elif len1 == 0x82:
63 pad = calcsize('H')
64 len2 = unpack('!H', data[:pad])[0]
65 data = data[pad:]
66 ans = data[:len2]
67 elif len1 == 0x83:
68 pad = calcsize('B') + calcsize('!H')
69 len2, len3 = unpack('!BH', data[:pad])
70 data = data[pad:]
71 ans = data[:len2 << 16 + len3]
72 elif len1 == 0x84:
73 pad = calcsize('!L')
74 len2 = unpack('!L', data[:pad])[0]
75 data = data[pad:]
76 ans = data[:len2]
77 # 1 byte length, string <= 0x7F
78 else:
79 pad = 0
80 ans = data[:len1]
81 return ans, len(ans)+pad+1
82
83 class GSSAPI:
84 # Generic GSSAPI Header Format
85 def __init__(self, data = None):
86 self.fields = {}
87 self['UUID'] = GSS_API_SPNEGO_UUID
88 if data:
89 self.fromString(data)
90 pass
91
92 def __setitem__(self,key,value):
93 self.fields[key] = value
94
95 def __getitem__(self, key):
96 return self.fields[key]
97
98 def __delitem__(self, key):
99 del self.fields[key]
100
101 def __len__(self):
102 return len(self.getData())
103
104 def __str__(self):
105 return len(self.getData())
106
107 def fromString(self, data = None):
108 # Manual parse of the GSSAPI Header Format
109 # It should be something like
110 # AID = 0x60 TAG, BER Length
111 # OID = 0x06 TAG
112 # GSSAPI OID
113 # UUID data (BER Encoded)
114 # Payload
115 next_byte = unpack('B',data[:1])[0]
116 if next_byte != ASN1_AID:
117 raise Exception('Unknown AID=%x' % next_byte)
118 data = data[1:]
119 decode_data, total_bytes = asn1decode(data)
120 # Now we should have a OID tag
121 next_byte = unpack('B',decode_data[:1])[0]
122 if next_byte != ASN1_OID:
123 raise Exception('OID tag not found %x' % next_byte)
124 decode_data = decode_data[1:]
125 # Now the OID contents, should be SPNEGO UUID
126 uuid, total_bytes = asn1decode(decode_data)
127 self['OID'] = uuid
128 # the rest should be the data
129 self['Payload'] = decode_data[total_bytes:]
130 #pass
131
132 def dump(self):
133 for i in self.fields.keys():
134 print("%s: {%r}" % (i,self[i]))
135
136 def getData(self):
137 ans = pack('B',ASN1_AID)
138 ans += asn1encode(
139 pack('B',ASN1_OID) +
140 asn1encode(self['UUID']) +
141 self['Payload'] )
142 return ans
143
144 class SPNEGO_NegTokenResp:
145 # http://tools.ietf.org/html/rfc4178#page-9
146 # NegTokenResp ::= SEQUENCE {
147 # negState [0] ENUMERATED {
148 # accept-completed (0),
149 # accept-incomplete (1),
150 # reject (2),
151 # request-mic (3)
152 # } OPTIONAL,
153 # -- REQUIRED in the first reply from the target
154 # supportedMech [1] MechType OPTIONAL,
155 # -- present only in the first reply from the target
156 # responseToken [2] OCTET STRING OPTIONAL,
157 # mechListMIC [3] OCTET STRING OPTIONAL,
158 # ...
159 # }
160 # This structure is not prepended by a GSS generic header!
161 SPNEGO_NEG_TOKEN_RESP = 0xa1
162 SPNEGO_NEG_TOKEN_TARG = 0xa0
163
164 def __init__(self, data = None):
165 self.fields = {}
166 if data:
167 self.fromString(data)
168 pass
169
170 def __setitem__(self,key,value):
171 self.fields[key] = value
172
173 def __getitem__(self, key):
174 return self.fields[key]
175
176 def __delitem__(self, key):
177 del self.fields[key]
178
179 def __len__(self):
180 return len(self.getData())
181
182 def __str__(self):
183 return len(self.getData())
184
185 def fromString(self, data = 0):
186 payload = data
187 next_byte = unpack('B', payload[:1])[0]
188 if next_byte != SPNEGO_NegTokenResp.SPNEGO_NEG_TOKEN_RESP:
189 raise Exception('NegTokenResp not found %x' % next_byte)
190 payload = payload[1:]
191 decode_data, total_bytes = asn1decode(payload)
192 next_byte = unpack('B', decode_data[:1])[0]
193 if next_byte != ASN1_SEQUENCE:
194 raise Exception('SEQUENCE tag not found %x' % next_byte)
195 decode_data = decode_data[1:]
196 decode_data, total_bytes = asn1decode(decode_data)
197 next_byte = unpack('B',decode_data[:1])[0]
198
199 if next_byte != ASN1_MECH_TYPE:
200 # MechType not found, could be an AUTH answer
201 if next_byte != ASN1_RESPONSE_TOKEN:
202 raise Exception('MechType/ResponseToken tag not found %x' % next_byte)
203 else:
204 decode_data2 = decode_data[1:]
205 decode_data2, total_bytes = asn1decode(decode_data2)
206 next_byte = unpack('B', decode_data2[:1])[0]
207 if next_byte != ASN1_ENUMERATED:
208 raise Exception('Enumerated tag not found %x' % next_byte)
209 item, total_bytes2 = asn1decode(decode_data)
210 self['NegResult'] = item
211 decode_data = decode_data[1:]
212 decode_data = decode_data[total_bytes:]
213
214 # Do we have more data?
215 if len(decode_data) == 0:
216 return
217
218 next_byte = unpack('B', decode_data[:1])[0]
219 if next_byte != ASN1_SUPPORTED_MECH:
220 if next_byte != ASN1_RESPONSE_TOKEN:
221 raise Exception('Supported Mech/ResponseToken tag not found %x' % next_byte)
222 else:
223 decode_data2 = decode_data[1:]
224 decode_data2, total_bytes = asn1decode(decode_data2)
225 next_byte = unpack('B', decode_data2[:1])[0]
226 if next_byte != ASN1_OID:
227 raise Exception('OID tag not found %x' % next_byte)
228 decode_data2 = decode_data2[1:]
229 item, total_bytes2 = asn1decode(decode_data2)
230 self['SupportedMech'] = item
231
232 decode_data = decode_data[1:]
233 decode_data = decode_data[total_bytes:]
234 next_byte = unpack('B', decode_data[:1])[0]
235 if next_byte != ASN1_RESPONSE_TOKEN:
236 raise Exception('Response token tag not found %x' % next_byte)
237
238 decode_data = decode_data[1:]
239 decode_data, total_bytes = asn1decode(decode_data)
240 next_byte = unpack('B', decode_data[:1])[0]
241 if next_byte != ASN1_OCTET_STRING:
242 raise Exception('Octet string token tag not found %x' % next_byte)
243 decode_data = decode_data[1:]
244 decode_data, total_bytes = asn1decode(decode_data)
245 self['ResponseToken'] = decode_data
246
247 def dump(self):
248 for i in self.fields.keys():
249 print("%s: {%r}" % (i,self[i]))
250
251 def getData(self):
252 ans = pack('B',SPNEGO_NegTokenResp.SPNEGO_NEG_TOKEN_RESP)
253 if 'NegResult' in self.fields and 'SupportedMech' in self.fields:
254 # Server resp
255 ans += asn1encode(
256 pack('B', ASN1_SEQUENCE) +
257 asn1encode(
258 pack('B',SPNEGO_NegTokenResp.SPNEGO_NEG_TOKEN_TARG) +
259 asn1encode(
260 pack('B',ASN1_ENUMERATED) +
261 asn1encode( self['NegResult'] )) +
262 pack('B',ASN1_SUPPORTED_MECH) +
263 asn1encode(
264 pack('B',ASN1_OID) +
265 asn1encode(self['SupportedMech'])) +
266 pack('B',ASN1_RESPONSE_TOKEN ) +
267 asn1encode(
268 pack('B', ASN1_OCTET_STRING) + asn1encode(self['ResponseToken']))))
269 elif 'NegResult' in self.fields:
270 # Server resp
271 ans += asn1encode(
272 pack('B', ASN1_SEQUENCE) +
273 asn1encode(
274 pack('B', SPNEGO_NegTokenResp.SPNEGO_NEG_TOKEN_TARG) +
275 asn1encode(
276 pack('B',ASN1_ENUMERATED) +
277 asn1encode( self['NegResult'] ))))
278 else:
279 # Client resp
280 ans += asn1encode(
281 pack('B', ASN1_SEQUENCE) +
282 asn1encode(
283 pack('B', ASN1_RESPONSE_TOKEN) +
284 asn1encode(
285 pack('B', ASN1_OCTET_STRING) + asn1encode(self['ResponseToken']))))
286 return ans
287
288 class SPNEGO_NegTokenInit(GSSAPI):
289 # http://tools.ietf.org/html/rfc4178#page-8
290 # NegTokeInit :: = SEQUENCE {
291 # mechTypes [0] MechTypeList,
292 # reqFlags [1] ContextFlags OPTIONAL,
293 # mechToken [2] OCTET STRING OPTIONAL,
294 # mechListMIC [3] OCTET STRING OPTIONAL,
295 # }
296 SPNEGO_NEG_TOKEN_INIT = 0xa0
297 def fromString(self, data = 0):
298 GSSAPI.fromString(self, data)
299 payload = self['Payload']
300 next_byte = unpack('B', payload[:1])[0]
301 if next_byte != SPNEGO_NegTokenInit.SPNEGO_NEG_TOKEN_INIT:
302 raise Exception('NegTokenInit not found %x' % next_byte)
303 payload = payload[1:]
304 decode_data, total_bytes = asn1decode(payload)
305 # Now we should have a SEQUENCE Tag
306 next_byte = unpack('B', decode_data[:1])[0]
307 if next_byte != ASN1_SEQUENCE:
308 raise Exception('SEQUENCE tag not found %x' % next_byte)
309 decode_data = decode_data[1:]
310 decode_data, total_bytes2 = asn1decode(decode_data)
311 next_byte = unpack('B',decode_data[:1])[0]
312 if next_byte != ASN1_MECH_TYPE:
313 raise Exception('MechType tag not found %x' % next_byte)
314 decode_data = decode_data[1:]
315 remaining_data = decode_data
316 decode_data, total_bytes3 = asn1decode(decode_data)
317 next_byte = unpack('B', decode_data[:1])[0]
318 if next_byte != ASN1_SEQUENCE:
319 raise Exception('SEQUENCE tag not found %x' % next_byte)
320 decode_data = decode_data[1:]
321 decode_data, total_bytes4 = asn1decode(decode_data)
322 # And finally we should have the MechTypes
323 self['MechTypes'] = []
324 while decode_data:
325 next_byte = unpack('B', decode_data[:1])[0]
326 if next_byte != ASN1_OID:
327 # Not a valid OID, there must be something else we won't unpack
328 break
329 decode_data = decode_data[1:]
330 item, total_bytes = asn1decode(decode_data)
331 self['MechTypes'].append(item)
332 decode_data = decode_data[total_bytes:]
333
334 # Do we have MechTokens as well?
335 decode_data = remaining_data[total_bytes3:]
336 if len(decode_data) > 0:
337 next_byte = unpack('B', decode_data[:1])[0]
338 if next_byte == ASN1_MECH_TOKEN:
339 # We have tokens in here!
340 decode_data = decode_data[1:]
341 decode_data, total_bytes = asn1decode(decode_data)
342 next_byte = unpack('B', decode_data[:1])[0]
343 if next_byte == ASN1_OCTET_STRING:
344 decode_data = decode_data[1:]
345 decode_data, total_bytes = asn1decode(decode_data)
346 self['MechToken'] = decode_data
347
348 def getData(self):
349 mechTypes = ''
350 for i in self['MechTypes']:
351 mechTypes += pack('B', ASN1_OID)
352 mechTypes += asn1encode(i)
353
354 mechToken = ''
355 # Do we have tokens to send?
356 if 'MechToken' in self.fields:
357 mechToken = pack('B', ASN1_MECH_TOKEN) + asn1encode(
358 pack('B', ASN1_OCTET_STRING) + asn1encode(
359 self['MechToken']))
360
361 ans = pack('B',SPNEGO_NegTokenInit.SPNEGO_NEG_TOKEN_INIT)
362 ans += asn1encode(
363 pack('B', ASN1_SEQUENCE) +
364 asn1encode(
365 pack('B', ASN1_MECH_TYPE) +
366 asn1encode(
367 pack('B', ASN1_SEQUENCE) +
368 asn1encode(mechTypes)) + mechToken ))
369
370
371 self['Payload'] = ans
372 return GSSAPI.getData(self)