Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/scapy/layers/kerberos.py: 34%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1954 statements  

1# SPDX-License-Identifier: GPL-2.0-only 

2# This file is part of Scapy 

3# See https://scapy.net/ for more information 

4# Copyright (C) Gabriel Potter 

5 

6r""" 

7Kerberos V5 

8 

9Implements parts of: 

10 

11- Kerberos Network Authentication Service (V5): RFC4120 

12- Kerberos Version 5 GSS-API: RFC1964, RFC4121 

13- Kerberos Pre-Authentication: RFC6113 (FAST) 

14- Kerberos Principal Name Canonicalization and Cross-Realm Referrals: RFC6806 

15- Microsoft Windows 2000 Kerberos Change Password and Set Password Protocols: RFC3244 

16- PKINIT and its extensions: RFC4556, RFC8070, RFC8636 and [MS-PKCA] 

17- User to User Kerberos Authentication: draft-ietf-cat-user2user-03 

18- Public Key Cryptography Based User-to-User Authentication (PKU2U): draft-zhu-pku2u-09 

19- Initial and Pass Through Authentication Using Kerberos V5 (IAKERB): 

20 draft-ietf-kitten-iakerb-03 

21- Kerberos Protocol Extensions: [MS-KILE] 

22- Kerberos Protocol Extensions: Service for User: [MS-SFU] 

23- Kerberos Key Distribution Center Proxy Protocol: [MS-KKDCP] 

24 

25 

26.. note:: 

27 You will find more complete documentation for this layer over at 

28 `Kerberos <https://scapy.readthedocs.io/en/latest/layers/kerberos.html>`_ 

29 

30Example decryption:: 

31 

32 >>> from scapy.libs.rfc3961 import Key, EncryptionType 

33 >>> pkt = Ether(hex_bytes("525400695813525400216c2b08004500015da71840008006dc\ 

34 83c0a87a9cc0a87a11c209005854f6ab2392c25bd650182014b6e00000000001316a8201\ 

35 2d30820129a103020105a20302010aa3633061304ca103020102a24504433041a0030201\ 

36 12a23a043848484decb01c9b62a1cabfbc3f2d1ed85aa5e093ba8358a8cea34d4393af93\ 

37 bf211e274fa58e814878db9f0d7a28d94e7327660db4f3704b3011a10402020080a20904\ 

38 073005a0030101ffa481b73081b4a00703050040810010a1123010a003020101a1093007\ 

39 1b0577696e3124a20e1b0c444f4d41494e2e4c4f43414ca321301fa003020102a1183016\ 

40 1b066b72627467741b0c444f4d41494e2e4c4f43414ca511180f32303337303931333032\ 

41 343830355aa611180f32303337303931333032343830355aa7060204701cc5d1a8153013\ 

42 0201120201110201170201180202ff79020103a91d301b3019a003020114a11204105749\ 

43 4e31202020202020202020202020")) 

44 >>> enc = pkt[Kerberos].root.padata[0].padataValue 

45 >>> k = Key(enc.etype.val, key=hex_bytes("7fada4e566ae4fb270e2800a23a\ 

46 e87127a819d42e69b5e22de0ddc63da80096d")) 

47 >>> enc.decrypt(k) 

48""" 

49 

50from collections import namedtuple, deque 

51from datetime import datetime, timedelta, timezone 

52from enum import IntEnum 

53 

54import os 

55import re 

56import socket 

57import struct 

58import threading 

59 

60from scapy.error import warning 

61import scapy.asn1.mib # noqa: F401 

62from scapy.asn1.ber import BER_id_dec, BER_Decoding_Error 

63from scapy.asn1.asn1 import ( 

64 ASN1_BIT_STRING, 

65 ASN1_BOOLEAN, 

66 ASN1_Class, 

67 ASN1_Codecs, 

68 ASN1_GENERAL_STRING, 

69 ASN1_GENERALIZED_TIME, 

70 ASN1_INTEGER, 

71 ASN1_OID, 

72 ASN1_STRING, 

73 ASN1_UTF8_STRING, 

74) 

75from scapy.asn1fields import ( 

76 ASN1F_BIT_STRING_ENCAPS, 

77 ASN1F_BOOLEAN, 

78 ASN1F_CHOICE, 

79 ASN1F_enum_INTEGER, 

80 ASN1F_FLAGS, 

81 ASN1F_GENERAL_STRING, 

82 ASN1F_GENERALIZED_TIME, 

83 ASN1F_INTEGER, 

84 ASN1F_OID, 

85 ASN1F_optional, 

86 ASN1F_PACKET, 

87 ASN1F_SEQUENCE_OF, 

88 ASN1F_SEQUENCE, 

89 ASN1F_STRING_ENCAPS, 

90 ASN1F_STRING_PacketField, 

91 ASN1F_STRING, 

92 ASN1F_UTF8_STRING, 

93) 

94from scapy.asn1packet import ASN1_Packet 

95from scapy.automaton import Automaton, ATMT, ObjectPipe 

96from scapy.config import conf 

97from scapy.compat import bytes_encode 

98from scapy.error import log_runtime 

99from scapy.fields import ( 

100 ConditionalField, 

101 FieldLenField, 

102 FlagsField, 

103 IntEnumField, 

104 IntField, 

105 LEIntEnumField, 

106 LEShortEnumField, 

107 LEShortField, 

108 LenField, 

109 LongField, 

110 MayEnd, 

111 MultipleTypeField, 

112 PacketField, 

113 PacketLenField, 

114 PacketListField, 

115 PadField, 

116 ScalingField, 

117 ShortEnumField, 

118 ShortField, 

119 StrField, 

120 StrFieldUtf16, 

121 StrFixedLenEnumField, 

122 XByteField, 

123 XLEIntEnumField, 

124 XLEIntField, 

125 XLEShortField, 

126 XStrField, 

127 XStrFixedLenField, 

128 XStrLenField, 

129) 

130from scapy.packet import Packet, bind_bottom_up, bind_top_down, bind_layers 

131from scapy.supersocket import StreamSocket, SuperSocket 

132from scapy.utils import strrot, strxor 

133from scapy.volatile import GeneralizedTime, RandNum, RandBin 

134 

135from scapy.layers.gssapi import ( 

136 _GSSAPI_OIDS, 

137 _GSSAPI_SIGNATURE_OIDS, 

138 GSS_C_FLAGS, 

139 GSS_C_NO_CHANNEL_BINDINGS, 

140 GSS_QOP_REQ_FLAGS, 

141 GSS_S_BAD_BINDINGS, 

142 GSS_S_BAD_MECH, 

143 GSS_S_COMPLETE, 

144 GSS_S_CONTINUE_NEEDED, 

145 GSS_S_CREDENTIALS_EXPIRED, 

146 GSS_S_DEFECTIVE_CREDENTIAL, 

147 GSS_S_DEFECTIVE_TOKEN, 

148 GSS_S_DUPLICATE_TOKEN, 

149 GSS_S_FAILURE, 

150 GSS_S_FLAGS, 

151 GSSAPI_BLOB, 

152 GssChannelBindings, 

153 SSP, 

154) 

155from scapy.layers.inet import TCP, UDP 

156from scapy.layers.tls.cert import ( 

157 Cert, 

158 CertList, 

159 CertTree, 

160 CMS_Engine, 

161 PrivKey, 

162) 

163from scapy.layers.tls.crypto.hash import ( 

164 Hash_SHA, 

165 Hash_SHA256, 

166 Hash_SHA384, 

167 Hash_SHA512, 

168) 

169from scapy.layers.tls.crypto.groups import _ffdh_groups 

170from scapy.layers.windows.erref import STATUS_ERREF 

171from scapy.layers.x509 import ( 

172 _CMS_ENCAPSULATED, 

173 CMS_ContentInfo, 

174 CMS_IssuerAndSerialNumber, 

175 DHPublicKey, 

176 X509_AlgorithmIdentifier, 

177 X509_DirectoryName, 

178 X509_SubjectPublicKeyInfo, 

179 DomainParameters, 

180) 

181 

182# Redirect exports from RFC3961 

183try: 

184 from scapy.libs.rfc3961 import * # noqa: F401,F403 

185 from scapy.libs.rfc3961 import ( 

186 _rfc1964pad, 

187 ChecksumType, 

188 Cipher, 

189 decrepit_algorithms, 

190 EncryptionType, 

191 Hmac_MD5, 

192 Key, 

193 KRB_FX_CF2, 

194 octetstring2key, 

195 ) 

196except ImportError: 

197 pass 

198 

199 

200# Crypto imports 

201if conf.crypto_valid: 

202 from cryptography.hazmat.primitives.serialization import pkcs12 

203 from cryptography.hazmat.primitives.asymmetric import dh 

204 

205# Typing imports 

206from typing import ( 

207 List, 

208 Optional, 

209 Union, 

210) 

211 

212# kerberos APPLICATION 

213 

214 

215class ASN1_Class_KRB(ASN1_Class): 

216 name = "Kerberos" 

217 # APPLICATION + CONSTRUCTED = 0x40 | 0x20 

218 Token = 0x60 | 0 # GSSAPI 

219 Ticket = 0x60 | 1 

220 Authenticator = 0x60 | 2 

221 EncTicketPart = 0x60 | 3 

222 AS_REQ = 0x60 | 10 

223 AS_REP = 0x60 | 11 

224 TGS_REQ = 0x60 | 12 

225 TGS_REP = 0x60 | 13 

226 AP_REQ = 0x60 | 14 

227 AP_REP = 0x60 | 15 

228 PRIV = 0x60 | 21 

229 CRED = 0x60 | 22 

230 EncASRepPart = 0x60 | 25 

231 EncTGSRepPart = 0x60 | 26 

232 EncAPRepPart = 0x60 | 27 

233 EncKrbPrivPart = 0x60 | 28 

234 EncKrbCredPart = 0x60 | 29 

235 ERROR = 0x60 | 30 

236 

237 

238# RFC4120 sect 5.2 

239 

240 

241KerberosString = ASN1F_GENERAL_STRING 

242Realm = KerberosString 

243Int32 = ASN1F_INTEGER 

244UInt32 = ASN1F_INTEGER 

245 

246_PRINCIPAL_NAME_TYPES = { 

247 0: "NT-UNKNOWN", 

248 1: "NT-PRINCIPAL", 

249 2: "NT-SRV-INST", 

250 3: "NT-SRV-HST", 

251 4: "NT-SRV-XHST", 

252 5: "NT-UID", 

253 6: "NT-X500-PRINCIPAL", 

254 7: "NT-SMTP-NAME", 

255 10: "NT-ENTERPRISE", 

256} 

257 

258 

259class PrincipalName(ASN1_Packet): 

260 ASN1_codec = ASN1_Codecs.BER 

261 ASN1_root = ASN1F_SEQUENCE( 

262 ASN1F_enum_INTEGER( 

263 "nameType", 

264 0, 

265 _PRINCIPAL_NAME_TYPES, 

266 explicit_tag=0xA0, 

267 ), 

268 ASN1F_SEQUENCE_OF("nameString", [], KerberosString, explicit_tag=0xA1), 

269 ) 

270 

271 def toString(self): 

272 """ 

273 Convert a PrincipalName back into its string representation. 

274 """ 

275 return "/".join(x.val.decode() for x in self.nameString) 

276 

277 @staticmethod 

278 def fromUPN(upn: str, canonicalize: bool = False): 

279 """ 

280 Create a PrincipalName from a UPN string. 

281 """ 

282 if canonicalize: 

283 return PrincipalName( 

284 nameString=[ASN1_GENERAL_STRING(upn)], 

285 nameType=ASN1_INTEGER(10), # NT-ENTERPRISE 

286 ) 

287 else: 

288 user, _ = _parse_upn(upn) 

289 return PrincipalName( 

290 nameString=[ASN1_GENERAL_STRING(user)], 

291 nameType=ASN1_INTEGER(1), # NT-PRINCIPAL 

292 ) 

293 

294 @staticmethod 

295 def fromSPN(spn: str): 

296 """ 

297 Create a PrincipalName from a SPN string. 

298 """ 

299 spn, _ = _parse_spn(spn) 

300 if spn.startswith("krbtgt"): 

301 return PrincipalName( 

302 nameString=[ASN1_GENERAL_STRING(x) for x in spn.split("/")], 

303 nameType=ASN1_INTEGER(2), # NT-SRV-INST 

304 ) 

305 elif "/" in spn: 

306 return PrincipalName( 

307 nameString=[ASN1_GENERAL_STRING(x) for x in spn.split("/")], 

308 nameType=ASN1_INTEGER(3), # NT-SRV-HST 

309 ) 

310 else: 

311 # In case of U2U 

312 return PrincipalName( 

313 nameString=[ASN1_GENERAL_STRING(spn)], 

314 nameType=ASN1_INTEGER(1), # NT-PRINCIPAL 

315 ) 

316 

317 

318KerberosTime = ASN1F_GENERALIZED_TIME 

319Microseconds = ASN1F_INTEGER 

320 

321 

322# https://www.iana.org/assignments/kerberos-parameters/kerberos-parameters.xhtml#kerberos-parameters-1 

323 

324_KRB_E_TYPES = { 

325 1: "DES-CBC-CRC", 

326 2: "DES-CBC-MD4", 

327 3: "DES-CBC-MD5", 

328 5: "DES3-CBC-MD5", 

329 7: "DES3-CBC-SHA1", 

330 9: "DSAWITHSHA1-CMSOID", 

331 10: "MD5WITHRSAENCRYPTION-CMSOID", 

332 11: "SHA1WITHRSAENCRYPTION-CMSOID", 

333 12: "RC2CBC-ENVOID", 

334 13: "RSAENCRYPTION-ENVOID", 

335 14: "RSAES-OAEP-ENV-OID", 

336 15: "DES-EDE3-CBC-ENV-OID", 

337 16: "DES3-CBC-SHA1-KD", 

338 17: "AES128-CTS-HMAC-SHA1-96", 

339 18: "AES256-CTS-HMAC-SHA1-96", 

340 19: "AES128-CTS-HMAC-SHA256-128", 

341 20: "AES256-CTS-HMAC-SHA384-192", 

342 23: "RC4-HMAC", 

343 24: "RC4-HMAC-EXP", 

344 25: "CAMELLIA128-CTS-CMAC", 

345 26: "CAMELLIA256-CTS-CMAC", 

346} 

347 

348# https://www.iana.org/assignments/kerberos-parameters/kerberos-parameters.xhtml#kerberos-parameters-2 

349 

350_KRB_S_TYPES = { 

351 1: "CRC32", 

352 2: "RSA-MD4", 

353 3: "RSA-MD4-DES", 

354 4: "DES-MAC", 

355 5: "DES-MAC-K", 

356 6: "RSA-MD4-DES-K", 

357 7: "RSA-MD5", 

358 8: "RSA-MD5-DES", 

359 9: "RSA-MD5-DES3", 

360 10: "SHA1", 

361 12: "HMAC-SHA1-DES3-KD", 

362 13: "HMAC-SHA1-DES3", 

363 14: "SHA1", 

364 15: "HMAC-SHA1-96-AES128", 

365 16: "HMAC-SHA1-96-AES256", 

366 17: "CMAC-CAMELLIA128", 

367 18: "CMAC-CAMELLIA256", 

368 19: "HMAC-SHA256-128-AES128", 

369 20: "HMAC-SHA384-192-AES256", 

370 # RFC 4121 

371 0x8003: "KRB-AUTHENTICATOR", 

372 # [MS-KILE] 

373 0xFFFFFF76: "MD5", 

374 -138: "MD5", 

375} 

376 

377 

378class EncryptedData(ASN1_Packet): 

379 ASN1_codec = ASN1_Codecs.BER 

380 ASN1_root = ASN1F_SEQUENCE( 

381 ASN1F_enum_INTEGER("etype", 0x17, _KRB_E_TYPES, explicit_tag=0xA0), 

382 ASN1F_optional(UInt32("kvno", None, explicit_tag=0xA1)), 

383 ASN1F_STRING("cipher", "", explicit_tag=0xA2), 

384 ) 

385 

386 def get_usage(self): 

387 """ 

388 Get current key usage number and encrypted class 

389 """ 

390 # RFC 4120 sect 7.5.1 

391 if self.underlayer: 

392 if isinstance(self.underlayer, PADATA): 

393 patype = self.underlayer.padataType 

394 if patype == 2: 

395 # AS-REQ PA-ENC-TIMESTAMP padata timestamp 

396 return 1, PA_ENC_TS_ENC 

397 elif patype == 138: 

398 # RFC6113 PA-ENC-TS-ENC 

399 return 54, PA_ENC_TS_ENC 

400 elif isinstance(self.underlayer, KRB_Ticket): 

401 # AS-REP Ticket and TGS-REP Ticket 

402 return 2, EncTicketPart 

403 elif isinstance(self.underlayer, KRB_AS_REP): 

404 # AS-REP encrypted part 

405 return 3, EncASRepPart 

406 elif isinstance(self.underlayer, KRB_KDC_REQ_BODY): 

407 # KDC-REQ enc-authorization-data 

408 return 4, AuthorizationData 

409 elif isinstance(self.underlayer, KRB_AP_REQ) and isinstance( 

410 self.underlayer.underlayer, PADATA 

411 ): 

412 # TGS-REQ PA-TGS-REQ Authenticator 

413 return 7, KRB_Authenticator 

414 elif isinstance(self.underlayer, KRB_TGS_REP): 

415 # TGS-REP encrypted part 

416 return 8, EncTGSRepPart 

417 elif isinstance(self.underlayer, KRB_AP_REQ): 

418 # AP-REQ Authenticator 

419 return 11, KRB_Authenticator 

420 elif isinstance(self.underlayer, KRB_AP_REP): 

421 # AP-REP encrypted part 

422 return 12, EncAPRepPart 

423 elif isinstance(self.underlayer, KRB_PRIV): 

424 # KRB-PRIV encrypted part 

425 return 13, EncKrbPrivPart 

426 elif isinstance(self.underlayer, KRB_CRED): 

427 # KRB-CRED encrypted part 

428 return 14, EncKrbCredPart 

429 elif isinstance(self.underlayer, KrbFastArmoredReq): 

430 # KEY_USAGE_FAST_ENC 

431 return 51, KrbFastReq 

432 elif isinstance(self.underlayer, KrbFastArmoredRep): 

433 # KEY_USAGE_FAST_REP 

434 return 52, KrbFastResponse 

435 raise ValueError( 

436 "Could not guess key usage number. Please specify key_usage_number" 

437 ) 

438 

439 def decrypt(self, key, key_usage_number=None, cls=None): 

440 """ 

441 Decrypt and return the data contained in cipher. 

442 

443 :param key: the key to use for decryption 

444 :param key_usage_number: (optional) specify the key usage number. 

445 Guessed otherwise 

446 :param cls: (optional) the class of the decrypted payload 

447 Guessed otherwise (or bytes) 

448 """ 

449 if key_usage_number is None: 

450 key_usage_number, cls = self.get_usage() 

451 d = key.decrypt(key_usage_number, self.cipher.val) 

452 if cls: 

453 try: 

454 return cls(d) 

455 except BER_Decoding_Error: 

456 if cls == EncASRepPart: 

457 # https://datatracker.ietf.org/doc/html/rfc4120#section-5.4.2 

458 # "Compatibility note: Some implementations unconditionally send an 

459 # encrypted EncTGSRepPart (application tag number 26) in this field 

460 # regardless of whether the reply is a AS-REP or a TGS-REP. In the 

461 # interest of compatibility, implementors MAY relax the check on the 

462 # tag number of the decrypted ENC-PART." 

463 try: 

464 res = EncTGSRepPart(d) 

465 # https://github.com/krb5/krb5/blob/48ccd81656381522d1f9ccb8705c13f0266a46ab/src/lib/krb5/asn.1/asn1_k_encode.c#L1128 

466 # This is a bug because as the RFC clearly says above, we're 

467 # perfectly in our right to be strict on this. (MAY) 

468 log_runtime.warning( 

469 "Implementation bug detected. This looks like MIT Kerberos." 

470 ) 

471 return res 

472 except BER_Decoding_Error: 

473 pass 

474 raise 

475 return d 

476 

477 def encrypt(self, key, text, confounder=None, key_usage_number=None): 

478 """ 

479 Encrypt text and set it into cipher. 

480 

481 :param key: the key to use for encryption 

482 :param text: the bytes value to encode 

483 :param confounder: (optional) specify the confounder bytes. Random otherwise 

484 :param key_usage_number: (optional) specify the key usage number. 

485 Guessed otherwise 

486 """ 

487 if key_usage_number is None: 

488 key_usage_number = self.get_usage()[0] 

489 self.etype = key.etype 

490 self.cipher = ASN1_STRING( 

491 key.encrypt(key_usage_number, text, confounder=confounder) 

492 ) 

493 

494 

495class EncryptionKey(ASN1_Packet): 

496 ASN1_codec = ASN1_Codecs.BER 

497 ASN1_root = ASN1F_SEQUENCE( 

498 ASN1F_enum_INTEGER("keytype", 0, _KRB_E_TYPES, explicit_tag=0xA0), 

499 ASN1F_STRING("keyvalue", "", explicit_tag=0xA1), 

500 ) 

501 

502 def toKey(self): 

503 return Key( 

504 etype=self.keytype.val, 

505 key=self.keyvalue.val, 

506 ) 

507 

508 @classmethod 

509 def fromKey(self, key): 

510 return EncryptionKey( 

511 keytype=key.etype, 

512 keyvalue=key.key, 

513 ) 

514 

515 

516class _Checksum_Field(ASN1F_STRING_PacketField): 

517 def m2i(self, pkt, s): 

518 val = super(_Checksum_Field, self).m2i(pkt, s) 

519 if not val[0].val: 

520 return val 

521 if pkt.cksumtype.val == 0x8003: 

522 # Special case per RFC 4121 

523 return KRB_AuthenticatorChecksum(val[0].val, _underlayer=pkt), val[1] 

524 return val 

525 

526 

527class Checksum(ASN1_Packet): 

528 ASN1_codec = ASN1_Codecs.BER 

529 ASN1_root = ASN1F_SEQUENCE( 

530 ASN1F_enum_INTEGER( 

531 "cksumtype", 

532 0, 

533 _KRB_S_TYPES, 

534 explicit_tag=0xA0, 

535 ), 

536 _Checksum_Field("checksum", "", explicit_tag=0xA1), 

537 ) 

538 

539 def get_usage(self): 

540 """ 

541 Get current key usage number 

542 """ 

543 # RFC 4120 sect 7.5.1 

544 if self.underlayer: 

545 if isinstance(self.underlayer, KRB_Authenticator): 

546 # TGS-REQ PA-TGS-REQ padata AP-REQ Authenticator cksum 

547 # (n°10 should never happen as we use RFC4121) 

548 return 6 

549 elif isinstance(self.underlayer, PA_FOR_USER): 

550 # [MS-SFU] sect 2.2.1 

551 return 17 

552 elif isinstance(self.underlayer, PA_S4U_X509_USER): 

553 # [MS-SFU] sect 2.2.2 

554 return 26 

555 elif isinstance(self.underlayer, AD_KDCIssued): 

556 # AD-KDC-ISSUED checksum 

557 return 19 

558 elif isinstance(self.underlayer, KrbFastArmoredReq): 

559 # KEY_USAGE_FAST_REQ_CHKSUM 

560 return 50 

561 elif isinstance(self.underlayer, KrbFastFinished): 

562 # KEY_USAGE_FAST_FINISHED 

563 return 53 

564 raise ValueError( 

565 "Could not guess key usage number. Please specify key_usage_number" 

566 ) 

567 

568 def verify(self, key, text, key_usage_number=None): 

569 """ 

570 Verify a signature of text using a key. 

571 

572 :param key: the key to use to check the checksum 

573 :param text: the bytes to verify 

574 :param key_usage_number: (optional) specify the key usage number. 

575 Guessed otherwise 

576 """ 

577 if key_usage_number is None: 

578 key_usage_number = self.get_usage() 

579 key.verify_checksum(key_usage_number, text, self.checksum.val) 

580 

581 def make(self, key, text, key_usage_number=None, cksumtype=None): 

582 """ 

583 Make a signature. 

584 

585 :param key: the key to use to make the checksum 

586 :param text: the bytes to make a checksum of 

587 :param key_usage_number: (optional) specify the key usage number. 

588 Guessed otherwise 

589 """ 

590 if key_usage_number is None: 

591 key_usage_number = self.get_usage() 

592 self.cksumtype = cksumtype or key.cksumtype 

593 self.checksum = ASN1_STRING( 

594 key.make_checksum( 

595 keyusage=key_usage_number, 

596 text=text, 

597 cksumtype=self.cksumtype, 

598 ) 

599 ) 

600 

601 

602KerberosFlags = ASN1F_FLAGS 

603 

604_ADDR_TYPES = { 

605 # RFC4120 sect 7.5.3 

606 0x02: "IPv4", 

607 0x03: "Directional", 

608 0x05: "ChaosNet", 

609 0x06: "XNS", 

610 0x07: "ISO", 

611 0x0C: "DECNET Phase IV", 

612 0x10: "AppleTalk DDP", 

613 0x14: "NetBios", 

614 0x18: "IPv6", 

615} 

616 

617 

618class HostAddress(ASN1_Packet): 

619 ASN1_codec = ASN1_Codecs.BER 

620 ASN1_root = ASN1F_SEQUENCE( 

621 ASN1F_enum_INTEGER( 

622 "addrType", 

623 0, 

624 _ADDR_TYPES, 

625 explicit_tag=0xA0, 

626 ), 

627 ASN1F_STRING("address", "", explicit_tag=0xA1), 

628 ) 

629 

630 

631HostAddresses = lambda name, **kwargs: ASN1F_SEQUENCE_OF( 

632 name, [], HostAddress, **kwargs 

633) 

634 

635 

636_AUTHORIZATIONDATA_VALUES = { 

637 # Filled below 

638} 

639 

640 

641class _AuthorizationData_value_Field(ASN1F_STRING_PacketField): 

642 def m2i(self, pkt, s): 

643 val = super(_AuthorizationData_value_Field, self).m2i(pkt, s) 

644 if not val[0].val: 

645 return val 

646 if pkt.adType.val in _AUTHORIZATIONDATA_VALUES: 

647 return ( 

648 _AUTHORIZATIONDATA_VALUES[pkt.adType.val](val[0].val, _underlayer=pkt), 

649 val[1], 

650 ) 

651 return val 

652 

653 

654_AD_TYPES = { 

655 # RFC4120 sect 7.5.4 

656 1: "AD-IF-RELEVANT", 

657 2: "AD-INTENDED-FOR-SERVER", 

658 3: "AD-INTENDED-FOR-APPLICATION-CLASS", 

659 4: "AD-KDC-ISSUED", 

660 5: "AD-AND-OR", 

661 6: "AD-MANDATORY-TICKET-EXTENSIONS", 

662 7: "AD-IN-TICKET-EXTENSIONS", 

663 8: "AD-MANDATORY-FOR-KDC", 

664 64: "OSF-DCE", 

665 65: "SESAME", 

666 66: "AD-OSD-DCE-PKI-CERTID", 

667 128: "AD-WIN2K-PAC", 

668 129: "AD-ETYPE-NEGOTIATION", 

669 # [MS-KILE] additions 

670 141: "KERB-AUTH-DATA-TOKEN-RESTRICTIONS", 

671 142: "KERB-LOCAL", 

672 143: "AD-AUTH-DATA-AP-OPTIONS", 

673 144: "KERB-AUTH-DATA-CLIENT-TARGET", 

674} 

675 

676 

677class AuthorizationDataItem(ASN1_Packet): 

678 ASN1_codec = ASN1_Codecs.BER 

679 ASN1_root = ASN1F_SEQUENCE( 

680 ASN1F_enum_INTEGER( 

681 "adType", 

682 0, 

683 _AD_TYPES, 

684 explicit_tag=0xA0, 

685 ), 

686 _AuthorizationData_value_Field("adData", "", explicit_tag=0xA1), 

687 ) 

688 

689 

690class AuthorizationData(ASN1_Packet): 

691 ASN1_codec = ASN1_Codecs.BER 

692 ASN1_root = ASN1F_SEQUENCE_OF( 

693 "seq", [AuthorizationDataItem()], AuthorizationDataItem 

694 ) 

695 

696 def getAuthData(self, adType): 

697 return next((x.adData for x in self.seq if x.adType == adType), None) 

698 

699 

700AD_IF_RELEVANT = AuthorizationData 

701_AUTHORIZATIONDATA_VALUES[1] = AD_IF_RELEVANT 

702 

703 

704class AD_KDCIssued(ASN1_Packet): 

705 ASN1_codec = ASN1_Codecs.BER 

706 ASN1_root = ASN1F_SEQUENCE( 

707 ASN1F_PACKET("adChecksum", Checksum(), Checksum, explicit_tag=0xA0), 

708 ASN1F_optional( 

709 Realm("iRealm", "", explicit_tag=0xA1), 

710 ), 

711 ASN1F_optional(ASN1F_PACKET("iSname", None, PrincipalName, explicit_tag=0xA2)), 

712 ASN1F_PACKET("elements", None, AuthorizationData, explicit_tag=0xA3), 

713 ) 

714 

715 

716_AUTHORIZATIONDATA_VALUES[4] = AD_KDCIssued 

717 

718 

719class AD_AND_OR(ASN1_Packet): 

720 ASN1_codec = ASN1_Codecs.BER 

721 ASN1_root = ASN1F_SEQUENCE( 

722 Int32("conditionCount", 0, explicit_tag=0xA0), 

723 ASN1F_PACKET("elements", None, AuthorizationData, explicit_tag=0xA1), 

724 ) 

725 

726 

727_AUTHORIZATIONDATA_VALUES[5] = AD_AND_OR 

728 

729ADMANDATORYFORKDC = AuthorizationData 

730_AUTHORIZATIONDATA_VALUES[8] = ADMANDATORYFORKDC 

731 

732 

733# https://www.iana.org/assignments/kerberos-parameters/kerberos-parameters.xml 

734_PADATA_TYPES = { 

735 1: "PA-TGS-REQ", 

736 2: "PA-ENC-TIMESTAMP", 

737 3: "PA-PW-SALT", 

738 11: "PA-ETYPE-INFO", 

739 14: "PA-PK-AS-REQ-OLD", 

740 15: "PA-PK-AS-REP-OLD", 

741 16: "PA-PK-AS-REQ", 

742 17: "PA-PK-AS-REP", 

743 18: "PA-PK-OCSP-RESPONSE", 

744 19: "PA-ETYPE-INFO2", 

745 20: "PA-SVR-REFERRAL-INFO", 

746 111: "TD-CMS-DIGEST-ALGORITHMS", 

747 128: "PA-PAC-REQUEST", 

748 129: "PA-FOR-USER", 

749 130: "PA-FOR-X509-USER", 

750 131: "PA-FOR-CHECK_DUPS", 

751 132: "PA-AS-CHECKSUM", 

752 133: "PA-FX-COOKIE", 

753 134: "PA-AUTHENTICATION-SET", 

754 135: "PA-AUTH-SET-SELECTED", 

755 136: "PA-FX-FAST", 

756 137: "PA-FX-ERROR", 

757 138: "PA-ENCRYPTED-CHALLENGE", 

758 141: "PA-OTP-CHALLENGE", 

759 142: "PA-OTP-REQUEST", 

760 143: "PA-OTP-CONFIRM", 

761 144: "PA-OTP-PIN-CHANGE", 

762 145: "PA-EPAK-AS-REQ", 

763 146: "PA-EPAK-AS-REP", 

764 147: "PA-PKINIT-KX", 

765 148: "PA-PKU2U-NAME", 

766 149: "PA-REQ-ENC-PA-REP", 

767 150: "PA-AS-FRESHNESS", 

768 151: "PA-SPAKE", 

769 161: "KERB-KEY-LIST-REQ", 

770 162: "KERB-KEY-LIST-REP", 

771 165: "PA-SUPPORTED-ENCTYPES", 

772 166: "PA-EXTENDED-ERROR", 

773 167: "PA-PAC-OPTIONS", 

774 170: "KERB-SUPERSEDED-BY-USER", 

775 171: "KERB-DMSA-KEY-PACKAGE", 

776} 

777 

778_PADATA_CLASSES = { 

779 # Filled elsewhere in this file 

780} 

781 

782 

783# RFC4120 

784 

785 

786class _PADATA_value_Field(ASN1F_STRING_PacketField): 

787 """ 

788 A special field that properly dispatches PA-DATA values according to 

789 padata-type and if the paquet is a request or a response. 

790 """ 

791 

792 def m2i(self, pkt, s): 

793 val = super(_PADATA_value_Field, self).m2i(pkt, s) 

794 if pkt.padataType.val in _PADATA_CLASSES: 

795 cls = _PADATA_CLASSES[pkt.padataType.val] 

796 if isinstance(cls, tuple): 

797 parent = pkt.underlayer or pkt.parent 

798 is_reply = False 

799 if parent is not None: 

800 if isinstance(parent, (KRB_AS_REP, KRB_TGS_REP)): 

801 is_reply = True 

802 else: 

803 parent = parent.underlayer or parent.parent 

804 is_reply = isinstance(parent, KRB_ERROR) 

805 cls = cls[is_reply] 

806 if not val[0].val: 

807 return val 

808 return cls(val[0].val, _underlayer=pkt), val[1] 

809 return val 

810 

811 

812class PADATA(ASN1_Packet): 

813 ASN1_codec = ASN1_Codecs.BER 

814 ASN1_root = ASN1F_SEQUENCE( 

815 ASN1F_enum_INTEGER("padataType", 0, _PADATA_TYPES, explicit_tag=0xA1), 

816 _PADATA_value_Field( 

817 "padataValue", 

818 "", 

819 explicit_tag=0xA2, 

820 ), 

821 ) 

822 

823 

824# RFC 4120 sect 5.2.7.2 

825 

826 

827class PA_ENC_TS_ENC(ASN1_Packet): 

828 ASN1_codec = ASN1_Codecs.BER 

829 ASN1_root = ASN1F_SEQUENCE( 

830 KerberosTime("patimestamp", GeneralizedTime(), explicit_tag=0xA0), 

831 ASN1F_optional(Microseconds("pausec", 0, explicit_tag=0xA1)), 

832 ) 

833 

834 

835_PADATA_CLASSES[2] = EncryptedData # PA-ENC-TIMESTAMP 

836_PADATA_CLASSES[138] = EncryptedData # PA-ENCRYPTED-CHALLENGE 

837 

838 

839# RFC 4120 sect 5.2.7.4 

840 

841 

842class ETYPE_INFO_ENTRY(ASN1_Packet): 

843 ASN1_codec = ASN1_Codecs.BER 

844 ASN1_root = ASN1F_SEQUENCE( 

845 ASN1F_enum_INTEGER("etype", 0x1, _KRB_E_TYPES, explicit_tag=0xA0), 

846 ASN1F_optional( 

847 ASN1F_STRING("salt", "", explicit_tag=0xA1), 

848 ), 

849 ) 

850 

851 

852class ETYPE_INFO(ASN1_Packet): 

853 ASN1_codec = ASN1_Codecs.BER 

854 ASN1_root = ASN1F_SEQUENCE_OF("seq", [ETYPE_INFO_ENTRY()], ETYPE_INFO_ENTRY) 

855 

856 

857_PADATA_CLASSES[11] = ETYPE_INFO 

858 

859# RFC 4120 sect 5.2.7.5 

860 

861 

862class ETYPE_INFO_ENTRY2(ASN1_Packet): 

863 ASN1_codec = ASN1_Codecs.BER 

864 ASN1_root = ASN1F_SEQUENCE( 

865 ASN1F_enum_INTEGER("etype", 0x1, _KRB_E_TYPES, explicit_tag=0xA0), 

866 ASN1F_optional( 

867 KerberosString("salt", "", explicit_tag=0xA1), 

868 ), 

869 ASN1F_optional( 

870 ASN1F_STRING("s2kparams", "", explicit_tag=0xA2), 

871 ), 

872 ) 

873 

874 

875class ETYPE_INFO2(ASN1_Packet): 

876 ASN1_codec = ASN1_Codecs.BER 

877 ASN1_root = ASN1F_SEQUENCE_OF("seq", [ETYPE_INFO_ENTRY2()], ETYPE_INFO_ENTRY2) 

878 

879 

880_PADATA_CLASSES[19] = ETYPE_INFO2 

881 

882 

883# RFC8636 - PKINIT Algorithm Agility 

884 

885 

886class TD_CMS_DIGEST_ALGORITHMS(ASN1_Packet): 

887 ASN1_codec = ASN1_Codecs.BER 

888 ASN1_root = ASN1F_SEQUENCE_OF("seq", [], X509_AlgorithmIdentifier) 

889 

890 

891_PADATA_CLASSES[111] = TD_CMS_DIGEST_ALGORITHMS 

892 

893 

894# PADATA Extended with RFC6113 

895 

896 

897class PA_AUTHENTICATION_SET_ELEM(ASN1_Packet): 

898 ASN1_codec = ASN1_Codecs.BER 

899 ASN1_root = ASN1F_SEQUENCE( 

900 Int32("paType", 0, explicit_tag=0xA0), 

901 ASN1F_optional( 

902 ASN1F_STRING("paHint", "", explicit_tag=0xA1), 

903 ), 

904 ASN1F_optional( 

905 ASN1F_STRING("paValue", "", explicit_tag=0xA2), 

906 ), 

907 ) 

908 

909 

910class PA_AUTHENTICATION_SET(ASN1_Packet): 

911 ASN1_codec = ASN1_Codecs.BER 

912 ASN1_root = ASN1F_SEQUENCE_OF( 

913 "elems", [PA_AUTHENTICATION_SET_ELEM()], PA_AUTHENTICATION_SET_ELEM 

914 ) 

915 

916 

917_PADATA_CLASSES[134] = PA_AUTHENTICATION_SET 

918 

919 

920# [MS-KILE] sect 2.2.3 

921 

922 

923class PA_PAC_REQUEST(ASN1_Packet): 

924 ASN1_codec = ASN1_Codecs.BER 

925 ASN1_root = ASN1F_SEQUENCE( 

926 ASN1F_BOOLEAN("includePac", True, explicit_tag=0xA0), 

927 ) 

928 

929 

930_PADATA_CLASSES[128] = PA_PAC_REQUEST 

931 

932 

933# [MS-KILE] sect 2.2.5 

934 

935 

936class LSAP_TOKEN_INFO_INTEGRITY(Packet): 

937 fields_desc = [ 

938 FlagsField( 

939 "Flags", 

940 0, 

941 -32, 

942 { 

943 0x00000001: "UAC-Restricted", 

944 }, 

945 ), 

946 LEIntEnumField( 

947 "TokenIL", 

948 0x00002000, 

949 { 

950 0x00000000: "Untrusted", 

951 0x00001000: "Low", 

952 0x00002000: "Medium", 

953 0x00003000: "High", 

954 0x00004000: "System", 

955 0x00005000: "Protected process", 

956 }, 

957 ), 

958 MayEnd(XStrFixedLenField("MachineID", b"", length=32)), 

959 XStrFixedLenField("CrossBootMachineID", b"", length=32), 

960 ] 

961 

962 

963# [MS-KILE] sect 2.2.6 

964 

965 

966class _KerbAdRestrictionEntry_Field(ASN1F_STRING_PacketField): 

967 def m2i(self, pkt, s): 

968 val = super(_KerbAdRestrictionEntry_Field, self).m2i(pkt, s) 

969 if not val[0].val: 

970 return val 

971 if pkt.restrictionType.val == 0x0000: # LSAP_TOKEN_INFO_INTEGRITY 

972 return LSAP_TOKEN_INFO_INTEGRITY(val[0].val, _underlayer=pkt), val[1] 

973 return val 

974 

975 

976class KERB_AD_RESTRICTION_ENTRY(ASN1_Packet): 

977 name = "KERB-AD-RESTRICTION-ENTRY" 

978 ASN1_codec = ASN1_Codecs.BER 

979 ASN1_root = ASN1F_SEQUENCE( 

980 ASN1F_SEQUENCE( 

981 ASN1F_enum_INTEGER( 

982 "restrictionType", 

983 0, 

984 {0: "LSAP_TOKEN_INFO_INTEGRITY"}, 

985 explicit_tag=0xA0, 

986 ), 

987 _KerbAdRestrictionEntry_Field("restriction", b"", explicit_tag=0xA1), 

988 ) 

989 ) 

990 

991 

992_AUTHORIZATIONDATA_VALUES[141] = KERB_AD_RESTRICTION_ENTRY 

993 

994 

995# [MS-KILE] sect 3.2.5.8 

996 

997 

998class KERB_AUTH_DATA_AP_OPTIONS(Packet): 

999 name = "KERB-AUTH-DATA-AP-OPTIONS" 

1000 fields_desc = [ 

1001 FlagsField( 

1002 "apOptions", 

1003 0x4000, 

1004 -32, 

1005 { 

1006 0x4000: "KERB_AP_OPTIONS_CBT", 

1007 0x8000: "KERB_AP_OPTIONS_UNVERIFIED_TARGET_NAME", 

1008 }, 

1009 ), 

1010 ] 

1011 

1012 

1013_AUTHORIZATIONDATA_VALUES[143] = KERB_AUTH_DATA_AP_OPTIONS 

1014 

1015 

1016# This has no doc..? [MS-KILE] only mentions its name. 

1017 

1018 

1019class KERB_AUTH_DATA_CLIENT_TARGET(Packet): 

1020 name = "KERB-AD-TARGET-PRINCIPAL" 

1021 fields_desc = [ 

1022 StrFieldUtf16("spn", ""), 

1023 ] 

1024 

1025 

1026_AUTHORIZATIONDATA_VALUES[144] = KERB_AUTH_DATA_CLIENT_TARGET 

1027 

1028 

1029# RFC6806 sect 6 

1030 

1031 

1032class KERB_AD_LOGIN_ALIAS(ASN1_Packet): 

1033 ASN1_codec = ASN1_Codecs.BER 

1034 ASN1_root = ASN1F_SEQUENCE(ASN1F_SEQUENCE_OF("loginAliases", [], PrincipalName)) 

1035 

1036 

1037_AUTHORIZATIONDATA_VALUES[80] = KERB_AD_LOGIN_ALIAS 

1038 

1039 

1040# [MS-KILE] sect 2.2.8 

1041 

1042 

1043class PA_SUPPORTED_ENCTYPES(Packet): 

1044 fields_desc = [ 

1045 FlagsField( 

1046 "flags", 

1047 0, 

1048 -32, 

1049 [ 

1050 "DES-CBC-CRC", 

1051 "DES-CBC-MD5", 

1052 "RC4-HMAC", 

1053 "AES128-CTS-HMAC-SHA1-96", 

1054 "AES256-CTS-HMAC-SHA1-96", 

1055 ] 

1056 + ["bit_%d" % i for i in range(11)] 

1057 + [ 

1058 "FAST-supported", 

1059 "Compount-identity-supported", 

1060 "Claims-supported", 

1061 "Resource-SID-compression-disabled", 

1062 ], 

1063 ) 

1064 ] 

1065 

1066 

1067_PADATA_CLASSES[165] = PA_SUPPORTED_ENCTYPES 

1068 

1069# [MS-KILE] sect 2.2.10 

1070 

1071 

1072class PA_PAC_OPTIONS(ASN1_Packet): 

1073 ASN1_codec = ASN1_Codecs.BER 

1074 ASN1_root = ASN1F_SEQUENCE( 

1075 KerberosFlags( 

1076 "options", 

1077 "", 

1078 [ 

1079 "Claims", 

1080 "Branch-Aware", 

1081 "Forward-to-Full-DC", 

1082 "Resource-based-constrained-delegation", # [MS-SFU] 2.2.5 

1083 ], 

1084 explicit_tag=0xA0, 

1085 ) 

1086 ) 

1087 

1088 

1089_PADATA_CLASSES[167] = PA_PAC_OPTIONS 

1090 

1091# [MS-KILE] sect 2.2.11 

1092 

1093 

1094class KERB_KEY_LIST_REQ(ASN1_Packet): 

1095 ASN1_codec = ASN1_Codecs.BER 

1096 ASN1_root = ASN1F_SEQUENCE_OF( 

1097 "keytypes", 

1098 [], 

1099 ASN1F_enum_INTEGER("", 0, _KRB_E_TYPES), 

1100 ) 

1101 

1102 

1103_PADATA_CLASSES[161] = KERB_KEY_LIST_REQ 

1104 

1105# [MS-KILE] sect 2.2.12 

1106 

1107 

1108class KERB_KEY_LIST_REP(ASN1_Packet): 

1109 ASN1_codec = ASN1_Codecs.BER 

1110 ASN1_root = ASN1F_SEQUENCE_OF( 

1111 "keys", 

1112 [], 

1113 ASN1F_PACKET("", None, EncryptionKey), 

1114 ) 

1115 

1116 

1117_PADATA_CLASSES[162] = KERB_KEY_LIST_REP 

1118 

1119# [MS-KILE] sect 2.2.13 

1120 

1121 

1122class KERB_SUPERSEDED_BY_USER(ASN1_Packet): 

1123 ASN1_codec = ASN1_Codecs.BER 

1124 ASN1_root = ASN1F_SEQUENCE( 

1125 ASN1F_PACKET("name", None, PrincipalName, explicit_tag=0xA0), 

1126 Realm("realm", None, explicit_tag=0xA1), 

1127 ) 

1128 

1129 

1130_PADATA_CLASSES[170] = KERB_SUPERSEDED_BY_USER 

1131 

1132 

1133# [MS-KILE] sect 2.2.14 

1134 

1135 

1136class KERB_DMSA_KEY_PACKAGE(ASN1_Packet): 

1137 ASN1_codec = ASN1_Codecs.BER 

1138 ASN1_root = ASN1F_SEQUENCE( 

1139 ASN1F_SEQUENCE_OF( 

1140 "currentKeys", 

1141 [], 

1142 ASN1F_PACKET("", None, EncryptionKey), 

1143 explicit_tag=0xA0, 

1144 ), 

1145 ASN1F_optional( 

1146 ASN1F_SEQUENCE_OF( 

1147 "previousKeys", 

1148 [], 

1149 ASN1F_PACKET("", None, EncryptionKey), 

1150 explicit_tag=0xA1, 

1151 ), 

1152 ), 

1153 KerberosTime("expirationInterval", GeneralizedTime(), explicit_tag=0xA2), 

1154 KerberosTime("fetchInterval", GeneralizedTime(), explicit_tag=0xA4), 

1155 ) 

1156 

1157 

1158_PADATA_CLASSES[171] = KERB_DMSA_KEY_PACKAGE 

1159 

1160 

1161# RFC6113 sect 5.4.1 

1162 

1163 

1164class _KrbFastArmor_value_Field(ASN1F_STRING_PacketField): 

1165 def m2i(self, pkt, s): 

1166 val = super(_KrbFastArmor_value_Field, self).m2i(pkt, s) 

1167 if not val[0].val: 

1168 return val 

1169 if pkt.armorType.val == 1: # FX_FAST_ARMOR_AP_REQUEST 

1170 return KRB_AP_REQ(val[0].val, _underlayer=pkt), val[1] 

1171 return val 

1172 

1173 

1174class KrbFastArmor(ASN1_Packet): 

1175 ASN1_codec = ASN1_Codecs.BER 

1176 ASN1_root = ASN1F_SEQUENCE( 

1177 ASN1F_enum_INTEGER( 

1178 "armorType", 1, {1: "FX_FAST_ARMOR_AP_REQUEST"}, explicit_tag=0xA0 

1179 ), 

1180 _KrbFastArmor_value_Field("armorValue", "", explicit_tag=0xA1), 

1181 ) 

1182 

1183 

1184# RFC6113 sect 5.4.2 

1185 

1186 

1187class KrbFastArmoredReq(ASN1_Packet): 

1188 ASN1_codec = ASN1_Codecs.BER 

1189 ASN1_root = ASN1F_SEQUENCE( 

1190 ASN1F_SEQUENCE( 

1191 ASN1F_optional( 

1192 ASN1F_PACKET("armor", None, KrbFastArmor, explicit_tag=0xA0) 

1193 ), 

1194 ASN1F_PACKET("reqChecksum", Checksum(), Checksum, explicit_tag=0xA1), 

1195 ASN1F_PACKET("encFastReq", None, EncryptedData, explicit_tag=0xA2), 

1196 ) 

1197 ) 

1198 

1199 

1200class PA_FX_FAST_REQUEST(ASN1_Packet): 

1201 ASN1_codec = ASN1_Codecs.BER 

1202 ASN1_root = ASN1F_CHOICE( 

1203 "armoredData", 

1204 ASN1_STRING(""), 

1205 ASN1F_PACKET("req", KrbFastArmoredReq, KrbFastArmoredReq, implicit_tag=0xA0), 

1206 ) 

1207 

1208 

1209# RFC6113 sect 5.4.3 

1210 

1211 

1212class KrbFastArmoredRep(ASN1_Packet): 

1213 ASN1_codec = ASN1_Codecs.BER 

1214 ASN1_root = ASN1F_SEQUENCE( 

1215 ASN1F_SEQUENCE( 

1216 ASN1F_PACKET("encFastRep", None, EncryptedData, explicit_tag=0xA0), 

1217 ) 

1218 ) 

1219 

1220 

1221class PA_FX_FAST_REPLY(ASN1_Packet): 

1222 ASN1_codec = ASN1_Codecs.BER 

1223 ASN1_root = ASN1F_CHOICE( 

1224 "armoredData", 

1225 ASN1_STRING(""), 

1226 ASN1F_PACKET("req", KrbFastArmoredRep, KrbFastArmoredRep, implicit_tag=0xA0), 

1227 ) 

1228 

1229 

1230class KrbFastFinished(ASN1_Packet): 

1231 ASN1_codec = ASN1_Codecs.BER 

1232 ASN1_root = ASN1F_SEQUENCE( 

1233 KerberosTime("timestamp", GeneralizedTime(), explicit_tag=0xA0), 

1234 Microseconds("usec", 0, explicit_tag=0xA1), 

1235 Realm("crealm", "", explicit_tag=0xA2), 

1236 ASN1F_PACKET("cname", None, PrincipalName, explicit_tag=0xA3), 

1237 ASN1F_PACKET("ticketChecksum", Checksum(), Checksum, explicit_tag=0xA4), 

1238 ) 

1239 

1240 

1241class KrbFastResponse(ASN1_Packet): 

1242 ASN1_codec = ASN1_Codecs.BER 

1243 ASN1_root = ASN1F_SEQUENCE( 

1244 ASN1F_SEQUENCE_OF("padata", [PADATA()], PADATA, explicit_tag=0xA0), 

1245 ASN1F_optional( 

1246 ASN1F_PACKET("strengthenKey", None, EncryptionKey, explicit_tag=0xA1) 

1247 ), 

1248 ASN1F_optional( 

1249 ASN1F_PACKET( 

1250 "finished", KrbFastFinished(), KrbFastFinished, explicit_tag=0xA2 

1251 ) 

1252 ), 

1253 UInt32("nonce", 0, explicit_tag=0xA3), 

1254 ) 

1255 

1256 

1257_PADATA_CLASSES[136] = (PA_FX_FAST_REQUEST, PA_FX_FAST_REPLY) 

1258 

1259 

1260# RFC 4556 - PKINIT 

1261 

1262 

1263# sect 3.2.1 

1264 

1265 

1266class ExternalPrincipalIdentifier(ASN1_Packet): 

1267 ASN1_codec = ASN1_Codecs.BER 

1268 ASN1_root = ASN1F_SEQUENCE( 

1269 ASN1F_optional( 

1270 ASN1F_STRING_ENCAPS( 

1271 "subjectName", None, X509_DirectoryName, implicit_tag=0x80 

1272 ), 

1273 ), 

1274 ASN1F_optional( 

1275 ASN1F_STRING_ENCAPS( 

1276 "issuerAndSerialNumber", 

1277 None, 

1278 CMS_IssuerAndSerialNumber, 

1279 implicit_tag=0x81, 

1280 ), 

1281 ), 

1282 ASN1F_optional( 

1283 ASN1F_STRING("subjectKeyIdentifier", "", implicit_tag=0x82), 

1284 ), 

1285 ) 

1286 

1287 

1288class PA_PK_AS_REQ(ASN1_Packet): 

1289 ASN1_codec = ASN1_Codecs.BER 

1290 ASN1_root = ASN1F_SEQUENCE( 

1291 ASN1F_STRING_ENCAPS( 

1292 "signedAuthpack", 

1293 CMS_ContentInfo(), 

1294 CMS_ContentInfo, 

1295 implicit_tag=0x80, 

1296 ), 

1297 ASN1F_optional( 

1298 ASN1F_SEQUENCE_OF( 

1299 "trustedCertifiers", 

1300 None, 

1301 ExternalPrincipalIdentifier, 

1302 explicit_tag=0xA1, 

1303 ), 

1304 ), 

1305 ASN1F_optional( 

1306 ASN1F_STRING("kdcPkId", "", implicit_tag=0xA2), 

1307 ), 

1308 ) 

1309 

1310 

1311_PADATA_CLASSES[16] = PA_PK_AS_REQ 

1312 

1313 

1314# [MS-PKCA] sect 2.2.3 

1315 

1316 

1317class PAChecksum2(ASN1_Packet): 

1318 ASN1_codec = ASN1_Codecs.BER 

1319 ASN1_root = ASN1F_SEQUENCE( 

1320 ASN1F_STRING("checksum", "", explicit_tag=0xA0), 

1321 ASN1F_PACKET( 

1322 "algorithmIdentifier", 

1323 X509_AlgorithmIdentifier(), 

1324 X509_AlgorithmIdentifier, 

1325 explicit_tag=0xA1, 

1326 ), 

1327 ) 

1328 

1329 def verify(self, text): 

1330 """ 

1331 Verify a checksum of text. 

1332 

1333 :param text: the bytes to verify 

1334 """ 

1335 # [MS-PKCA] 2.2.3 - PAChecksum2 

1336 

1337 # Only some OIDs are supported. Dumb but readable code. 

1338 oid = self.algorithmIdentifier.algorithm.val 

1339 if oid == "1.3.14.3.2.26": 

1340 hashcls = Hash_SHA 

1341 elif oid == "2.16.840.1.101.3.4.2.1": 

1342 hashcls = Hash_SHA256 

1343 elif oid == "2.16.840.1.101.3.4.2.2": 

1344 hashcls = Hash_SHA384 

1345 elif oid == "2.16.840.1.101.3.4.2.3": 

1346 hashcls = Hash_SHA512 

1347 else: 

1348 raise ValueError("Bad PAChecksum2 checksum !") 

1349 

1350 if hashcls().digest(text) != self.checksum.val: 

1351 raise ValueError("Bad PAChecksum2 checksum !") 

1352 

1353 def make(self, text, h="sha256"): 

1354 """ 

1355 Make a checksum. 

1356 

1357 :param text: the bytes to make a checksum of 

1358 """ 

1359 # Only some OIDs are supported. Dumb but readable code. 

1360 if h == "sha1": 

1361 hashcls = Hash_SHA 

1362 self.algorithmIdentifier.algorithm = ASN1_OID("1.3.14.3.2.26") 

1363 elif h == "sha256": 

1364 hashcls = Hash_SHA256 

1365 self.algorithmIdentifier.algorithm = ASN1_OID("2.16.840.1.101.3.4.2.1") 

1366 elif h == "sha384": 

1367 hashcls = Hash_SHA384 

1368 self.algorithmIdentifier.algorithm = ASN1_OID("2.16.840.1.101.3.4.2.2") 

1369 elif h == "sha512": 

1370 hashcls = Hash_SHA512 

1371 self.algorithmIdentifier.algorithm = ASN1_OID("2.16.840.1.101.3.4.2.3") 

1372 else: 

1373 raise ValueError("Bad PAChecksum2 checksum !") 

1374 

1375 self.checksum = ASN1_STRING(hashcls().digest(text)) 

1376 

1377 

1378# still RFC 4556 sect 3.2.1 

1379 

1380 

1381class KRB_PKAuthenticator(ASN1_Packet): 

1382 ASN1_codec = ASN1_Codecs.BER 

1383 ASN1_root = ASN1F_SEQUENCE( 

1384 Microseconds("cusec", 0, explicit_tag=0xA0), 

1385 KerberosTime("ctime", GeneralizedTime(), explicit_tag=0xA1), 

1386 UInt32("nonce", 0, explicit_tag=0xA2), 

1387 ASN1F_optional( 

1388 ASN1F_STRING("paChecksum", "", explicit_tag=0xA3), 

1389 ), 

1390 # RFC8070 extension 

1391 ASN1F_optional( 

1392 ASN1F_STRING("freshnessToken", None, explicit_tag=0xA4), 

1393 ), 

1394 # [MS-PKCA] sect 2.2.3 

1395 ASN1F_optional( 

1396 ASN1F_PACKET("paChecksum2", None, PAChecksum2, explicit_tag=0xA5), 

1397 ), 

1398 ) 

1399 

1400 def getClientTime(self): 

1401 """ 

1402 Return time from ctime + cusec 

1403 """ 

1404 return self.ctime.datetime + timedelta(microseconds=self.cusec.val) 

1405 

1406 def make_checksum(self, text, h: str = "sha256"): 

1407 """ 

1408 Populate paChecksum 

1409 """ 

1410 # paChecksum (always sha-1) 

1411 self.paChecksum = ASN1_STRING(Hash_SHA().digest(text)) 

1412 

1413 # paChecksum2 

1414 if h != "sha1": 

1415 self.paChecksum2 = PAChecksum2() 

1416 self.paChecksum2.make(text, h=h) 

1417 

1418 def verify_checksum(self, text): 

1419 """ 

1420 Verify paChecksum and paChecksum2 

1421 """ 

1422 if self.paChecksum.val != Hash_SHA().digest(text): 

1423 raise ValueError("Bad paChecksum checksum !") 

1424 

1425 if self.paChecksum2 is not None: 

1426 self.paChecksum2.verify(text) 

1427 

1428 

1429# RFC8636 sect 6 

1430 

1431 

1432class KDFAlgorithmId(ASN1_Packet): 

1433 ASN1_codec = ASN1_Codecs.BER 

1434 ASN1_root = ASN1F_SEQUENCE( 

1435 ASN1F_OID("kdfId", "", explicit_tag=0xA0), 

1436 ) 

1437 

1438 

1439# still RFC 4556 sect 3.2.1 

1440 

1441 

1442class KRB_AuthPack(ASN1_Packet): 

1443 ASN1_codec = ASN1_Codecs.BER 

1444 ASN1_root = ASN1F_SEQUENCE( 

1445 ASN1F_PACKET( 

1446 "pkAuthenticator", 

1447 KRB_PKAuthenticator(), 

1448 KRB_PKAuthenticator, 

1449 explicit_tag=0xA0, 

1450 ), 

1451 ASN1F_optional( 

1452 ASN1F_PACKET( 

1453 "clientPublicValue", 

1454 X509_SubjectPublicKeyInfo(), 

1455 X509_SubjectPublicKeyInfo, 

1456 explicit_tag=0xA1, 

1457 ), 

1458 ), 

1459 ASN1F_optional( 

1460 ASN1F_SEQUENCE_OF( 

1461 "supportedCMSTypes", 

1462 None, 

1463 X509_AlgorithmIdentifier, 

1464 explicit_tag=0xA2, 

1465 ), 

1466 ), 

1467 ASN1F_optional( 

1468 ASN1F_STRING("clientDHNonce", None, explicit_tag=0xA3), 

1469 ), 

1470 # RFC8636 extension 

1471 ASN1F_optional( 

1472 ASN1F_SEQUENCE_OF("supportedKDFs", None, KDFAlgorithmId, explicit_tag=0xA4), 

1473 ), 

1474 ) 

1475 

1476 

1477_CMS_ENCAPSULATED["1.3.6.1.5.2.3.1"] = KRB_AuthPack 

1478 

1479# sect 3.2.3 

1480 

1481 

1482class DHRepInfo(ASN1_Packet): 

1483 ASN1_codec = ASN1_Codecs.BER 

1484 ASN1_root = ASN1F_SEQUENCE( 

1485 ASN1F_STRING_ENCAPS( 

1486 "dhSignedData", 

1487 CMS_ContentInfo(), 

1488 CMS_ContentInfo, 

1489 implicit_tag=0x80, 

1490 ), 

1491 ASN1F_optional( 

1492 ASN1F_STRING("serverDHNonce", "", explicit_tag=0xA1), 

1493 ), 

1494 # RFC8636 extension 

1495 ASN1F_optional( 

1496 ASN1F_PACKET("kdf", None, KDFAlgorithmId, explicit_tag=0xA2), 

1497 ), 

1498 ) 

1499 

1500 

1501class EncKeyPack(ASN1_Packet): 

1502 ASN1_codec = ASN1_Codecs.BER 

1503 ASN1_root = ASN1F_STRING("encKeyPack", "") 

1504 

1505 

1506class PA_PK_AS_REP(ASN1_Packet): 

1507 ASN1_codec = ASN1_Codecs.BER 

1508 ASN1_root = ASN1F_CHOICE( 

1509 "rep", 

1510 ASN1_STRING(""), 

1511 ASN1F_PACKET("dhInfo", DHRepInfo(), DHRepInfo, explicit_tag=0xA0), 

1512 ASN1F_PACKET("encKeyPack", EncKeyPack(), EncKeyPack, explicit_tag=0xA1), 

1513 ) 

1514 

1515 

1516_PADATA_CLASSES[17] = PA_PK_AS_REP 

1517 

1518 

1519class KDCDHKeyInfo(ASN1_Packet): 

1520 ASN1_codec = ASN1_Codecs.BER 

1521 ASN1_root = ASN1F_SEQUENCE( 

1522 ASN1F_BIT_STRING_ENCAPS( 

1523 "subjectPublicKey", DHPublicKey(), DHPublicKey, explicit_tag=0xA0 

1524 ), 

1525 UInt32("nonce", 0, explicit_tag=0xA1), 

1526 ASN1F_optional( 

1527 KerberosTime("dhKeyExpiration", None, explicit_tag=0xA2), 

1528 ), 

1529 ) 

1530 

1531 

1532_CMS_ENCAPSULATED["1.3.6.1.5.2.3.2"] = KDCDHKeyInfo 

1533 

1534# [MS-SFU] 

1535 

1536 

1537# sect 2.2.1 

1538class PA_FOR_USER(ASN1_Packet): 

1539 ASN1_codec = ASN1_Codecs.BER 

1540 ASN1_root = ASN1F_SEQUENCE( 

1541 ASN1F_PACKET("userName", PrincipalName(), PrincipalName, explicit_tag=0xA0), 

1542 Realm("userRealm", "", explicit_tag=0xA1), 

1543 ASN1F_PACKET("cksum", Checksum(), Checksum, explicit_tag=0xA2), 

1544 KerberosString("authPackage", "Kerberos", explicit_tag=0xA3), 

1545 ) 

1546 

1547 

1548_PADATA_CLASSES[129] = PA_FOR_USER 

1549 

1550 

1551# sect 2.2.2 

1552 

1553 

1554class S4UUserID(ASN1_Packet): 

1555 ASN1_codec = ASN1_Codecs.BER 

1556 ASN1_root = ASN1F_SEQUENCE( 

1557 UInt32("nonce", 0, explicit_tag=0xA0), 

1558 ASN1F_optional( 

1559 ASN1F_PACKET("cname", None, PrincipalName, explicit_tag=0xA1), 

1560 ), 

1561 Realm("crealm", "", explicit_tag=0xA2), 

1562 ASN1F_optional( 

1563 ASN1F_STRING("subjectCertificate", None, explicit_tag=0xA3), 

1564 ), 

1565 ASN1F_optional( 

1566 ASN1F_FLAGS( 

1567 "options", 

1568 "", 

1569 [ 

1570 "reserved", 

1571 "KDC_CHECK_LOGON_HOUR_RESTRICTIONS", 

1572 "USE_REPLY_KEY_USAGE", 

1573 "NT_AUTH_POLICY_NOT_REQUIRED", 

1574 "UNCONDITIONAL_DELEGATION", 

1575 ], 

1576 explicit_tag=0xA4, 

1577 ) 

1578 ), 

1579 ) 

1580 

1581 

1582class PA_S4U_X509_USER(ASN1_Packet): 

1583 ASN1_codec = ASN1_Codecs.BER 

1584 ASN1_root = ASN1F_SEQUENCE( 

1585 ASN1F_PACKET("userId", S4UUserID(), S4UUserID, explicit_tag=0xA0), 

1586 ASN1F_PACKET("checksum", Checksum(), Checksum, explicit_tag=0xA1), 

1587 ) 

1588 

1589 

1590_PADATA_CLASSES[130] = PA_S4U_X509_USER 

1591 

1592 

1593# Back to RFC4120 

1594 

1595# sect 5.10 

1596KRB_MSG_TYPES = { 

1597 1: "Ticket", 

1598 2: "Authenticator", 

1599 3: "EncTicketPart", 

1600 10: "AS-REQ", 

1601 11: "AS-REP", 

1602 12: "TGS-REQ", 

1603 13: "TGS-REP", 

1604 14: "AP-REQ", 

1605 15: "AP-REP", 

1606 16: "KRB-TGT-REQ", # U2U 

1607 17: "KRB-TGT-REP", # U2U 

1608 20: "KRB-SAFE", 

1609 21: "KRB-PRIV", 

1610 22: "KRB-CRED", 

1611 25: "EncASRepPart", 

1612 26: "EncTGSRepPart", 

1613 27: "EncAPRepPart", 

1614 28: "EncKrbPrivPart", 

1615 29: "EnvKrbCredPart", 

1616 30: "KRB-ERROR", 

1617} 

1618 

1619# sect 5.3 

1620 

1621 

1622class KRB_Ticket(ASN1_Packet): 

1623 ASN1_codec = ASN1_Codecs.BER 

1624 ASN1_root = ASN1F_SEQUENCE( 

1625 ASN1F_SEQUENCE( 

1626 ASN1F_INTEGER("tktVno", 5, explicit_tag=0xA0), 

1627 Realm("realm", "", explicit_tag=0xA1), 

1628 ASN1F_PACKET("sname", PrincipalName(), PrincipalName, explicit_tag=0xA2), 

1629 ASN1F_PACKET("encPart", EncryptedData(), EncryptedData, explicit_tag=0xA3), 

1630 ), 

1631 implicit_tag=ASN1_Class_KRB.Ticket, 

1632 ) 

1633 

1634 def getSPN(self): 

1635 return "%s@%s" % ( 

1636 self.sname.toString(), 

1637 self.realm.val.decode(), 

1638 ) 

1639 

1640 

1641class TransitedEncoding(ASN1_Packet): 

1642 ASN1_codec = ASN1_Codecs.BER 

1643 ASN1_root = ASN1F_SEQUENCE( 

1644 Int32("trType", 0, explicit_tag=0xA0), 

1645 ASN1F_STRING("contents", "", explicit_tag=0xA1), 

1646 ) 

1647 

1648 

1649_TICKET_FLAGS = [ 

1650 "reserved", 

1651 "forwardable", 

1652 "forwarded", 

1653 "proxiable", 

1654 "proxy", 

1655 "may-postdate", 

1656 "postdated", 

1657 "invalid", 

1658 "renewable", 

1659 "initial", 

1660 "pre-authent", 

1661 "hw-authent", 

1662 "transited-since-policy-checked", 

1663 "ok-as-delegate", 

1664 "unused", 

1665 "canonicalize", # RFC6806 

1666 "anonymous", # RFC6112 + RFC8129 

1667] 

1668 

1669 

1670class EncTicketPart(ASN1_Packet): 

1671 ASN1_codec = ASN1_Codecs.BER 

1672 ASN1_root = ASN1F_SEQUENCE( 

1673 ASN1F_SEQUENCE( 

1674 KerberosFlags( 

1675 "flags", 

1676 "", 

1677 _TICKET_FLAGS, 

1678 explicit_tag=0xA0, 

1679 ), 

1680 ASN1F_PACKET("key", EncryptionKey(), EncryptionKey, explicit_tag=0xA1), 

1681 Realm("crealm", "", explicit_tag=0xA2), 

1682 ASN1F_PACKET("cname", PrincipalName(), PrincipalName, explicit_tag=0xA3), 

1683 ASN1F_PACKET( 

1684 "transited", TransitedEncoding(), TransitedEncoding, explicit_tag=0xA4 

1685 ), 

1686 KerberosTime("authtime", GeneralizedTime(), explicit_tag=0xA5), 

1687 ASN1F_optional( 

1688 KerberosTime("starttime", GeneralizedTime(), explicit_tag=0xA6) 

1689 ), 

1690 KerberosTime("endtime", GeneralizedTime(), explicit_tag=0xA7), 

1691 ASN1F_optional( 

1692 KerberosTime("renewTill", GeneralizedTime(), explicit_tag=0xA8), 

1693 ), 

1694 ASN1F_optional( 

1695 HostAddresses("addresses", explicit_tag=0xA9), 

1696 ), 

1697 ASN1F_optional( 

1698 ASN1F_PACKET( 

1699 "authorizationData", None, AuthorizationData, explicit_tag=0xAA 

1700 ), 

1701 ), 

1702 ), 

1703 implicit_tag=ASN1_Class_KRB.EncTicketPart, 

1704 ) 

1705 

1706 

1707# sect 5.4.1 

1708 

1709 

1710class KRB_KDC_REQ_BODY(ASN1_Packet): 

1711 ASN1_codec = ASN1_Codecs.BER 

1712 ASN1_root = ASN1F_SEQUENCE( 

1713 KerberosFlags( 

1714 "kdcOptions", 

1715 "", 

1716 [ 

1717 "reserved", 

1718 "forwardable", 

1719 "forwarded", 

1720 "proxiable", 

1721 "proxy", 

1722 "allow-postdate", 

1723 "postdated", 

1724 "unused7", 

1725 "renewable", 

1726 "unused9", 

1727 "unused10", 

1728 "opt-hardware-auth", 

1729 "unused12", 

1730 "unused13", 

1731 "cname-in-addl-tkt", # [MS-SFU] sect 2.2.3 

1732 "canonicalize", # RFC6806 

1733 "request-anonymous", # RFC6112 + RFC8129 

1734 ] 

1735 + ["unused%d" % i for i in range(17, 26)] 

1736 + [ 

1737 "disable-transited-check", 

1738 "renewable-ok", 

1739 "enc-tkt-in-skey", 

1740 "unused29", 

1741 "renew", 

1742 "validate", 

1743 ], 

1744 explicit_tag=0xA0, 

1745 ), 

1746 ASN1F_optional(ASN1F_PACKET("cname", None, PrincipalName, explicit_tag=0xA1)), 

1747 Realm("realm", "", explicit_tag=0xA2), 

1748 ASN1F_optional( 

1749 ASN1F_PACKET("sname", None, PrincipalName, explicit_tag=0xA3), 

1750 ), 

1751 ASN1F_optional(KerberosTime("from_", None, explicit_tag=0xA4)), 

1752 KerberosTime("till", GeneralizedTime(), explicit_tag=0xA5), 

1753 ASN1F_optional(KerberosTime("rtime", GeneralizedTime(), explicit_tag=0xA6)), 

1754 UInt32("nonce", 0, explicit_tag=0xA7), 

1755 ASN1F_SEQUENCE_OF("etype", [], Int32, explicit_tag=0xA8), 

1756 ASN1F_optional( 

1757 HostAddresses("addresses", explicit_tag=0xA9), 

1758 ), 

1759 ASN1F_optional( 

1760 ASN1F_PACKET( 

1761 "encAuthorizationData", None, EncryptedData, explicit_tag=0xAA 

1762 ), 

1763 ), 

1764 ASN1F_optional( 

1765 ASN1F_SEQUENCE_OF("additionalTickets", [], KRB_Ticket, explicit_tag=0xAB) 

1766 ), 

1767 ) 

1768 

1769 

1770KRB_KDC_REQ = ASN1F_SEQUENCE( 

1771 ASN1F_INTEGER("pvno", 5, explicit_tag=0xA1), 

1772 ASN1F_enum_INTEGER("msgType", 10, KRB_MSG_TYPES, explicit_tag=0xA2), 

1773 ASN1F_optional(ASN1F_SEQUENCE_OF("padata", [], PADATA, explicit_tag=0xA3)), 

1774 ASN1F_PACKET("reqBody", KRB_KDC_REQ_BODY(), KRB_KDC_REQ_BODY, explicit_tag=0xA4), 

1775) 

1776 

1777 

1778class KrbFastReq(ASN1_Packet): 

1779 # RFC6113 sect 5.4.2 

1780 ASN1_codec = ASN1_Codecs.BER 

1781 ASN1_root = ASN1F_SEQUENCE( 

1782 KerberosFlags( 

1783 "fastOptions", 

1784 "", 

1785 [ 

1786 "RESERVED", 

1787 "hide-client-names", 

1788 ] 

1789 + ["res%d" % i for i in range(2, 16)] 

1790 + ["kdc-follow-referrals"], 

1791 explicit_tag=0xA0, 

1792 ), 

1793 ASN1F_SEQUENCE_OF("padata", [PADATA()], PADATA, explicit_tag=0xA1), 

1794 ASN1F_PACKET("reqBody", None, KRB_KDC_REQ_BODY, explicit_tag=0xA2), 

1795 ) 

1796 

1797 

1798class KRB_AS_REQ(ASN1_Packet): 

1799 ASN1_codec = ASN1_Codecs.BER 

1800 ASN1_root = ASN1F_SEQUENCE( 

1801 KRB_KDC_REQ, 

1802 implicit_tag=ASN1_Class_KRB.AS_REQ, 

1803 ) 

1804 

1805 

1806class KRB_TGS_REQ(ASN1_Packet): 

1807 ASN1_codec = ASN1_Codecs.BER 

1808 ASN1_root = ASN1F_SEQUENCE( 

1809 KRB_KDC_REQ, 

1810 implicit_tag=ASN1_Class_KRB.TGS_REQ, 

1811 ) 

1812 msgType = ASN1_INTEGER(12) 

1813 

1814 

1815# sect 5.4.2 

1816 

1817KRB_KDC_REP = ASN1F_SEQUENCE( 

1818 ASN1F_INTEGER("pvno", 5, explicit_tag=0xA0), 

1819 ASN1F_enum_INTEGER("msgType", 11, KRB_MSG_TYPES, explicit_tag=0xA1), 

1820 ASN1F_optional( 

1821 ASN1F_SEQUENCE_OF("padata", [], PADATA, explicit_tag=0xA2), 

1822 ), 

1823 Realm("crealm", "", explicit_tag=0xA3), 

1824 ASN1F_PACKET("cname", None, PrincipalName, explicit_tag=0xA4), 

1825 ASN1F_PACKET("ticket", None, KRB_Ticket, explicit_tag=0xA5), 

1826 ASN1F_PACKET("encPart", None, EncryptedData, explicit_tag=0xA6), 

1827) 

1828 

1829 

1830class KRB_AS_REP(ASN1_Packet): 

1831 ASN1_codec = ASN1_Codecs.BER 

1832 ASN1_root = ASN1F_SEQUENCE( 

1833 KRB_KDC_REP, 

1834 implicit_tag=ASN1_Class_KRB.AS_REP, 

1835 ) 

1836 

1837 def getUPN(self): 

1838 return "%s@%s" % ( 

1839 self.cname.toString(), 

1840 self.crealm.val.decode(), 

1841 ) 

1842 

1843 

1844class KRB_TGS_REP(ASN1_Packet): 

1845 ASN1_codec = ASN1_Codecs.BER 

1846 ASN1_root = ASN1F_SEQUENCE( 

1847 KRB_KDC_REP, 

1848 implicit_tag=ASN1_Class_KRB.TGS_REP, 

1849 ) 

1850 

1851 def getUPN(self): 

1852 return "%s@%s" % ( 

1853 self.cname.toString(), 

1854 self.crealm.val.decode(), 

1855 ) 

1856 

1857 

1858class LastReqItem(ASN1_Packet): 

1859 ASN1_codec = ASN1_Codecs.BER 

1860 ASN1_root = ASN1F_SEQUENCE( 

1861 Int32("lrType", 0, explicit_tag=0xA0), 

1862 KerberosTime("lrValue", GeneralizedTime(), explicit_tag=0xA1), 

1863 ) 

1864 

1865 

1866EncKDCRepPart = ASN1F_SEQUENCE( 

1867 ASN1F_PACKET("key", None, EncryptionKey, explicit_tag=0xA0), 

1868 ASN1F_SEQUENCE_OF("lastReq", [], LastReqItem, explicit_tag=0xA1), 

1869 UInt32("nonce", 0, explicit_tag=0xA2), 

1870 ASN1F_optional( 

1871 KerberosTime("keyExpiration", GeneralizedTime(), explicit_tag=0xA3), 

1872 ), 

1873 KerberosFlags( 

1874 "flags", 

1875 "", 

1876 _TICKET_FLAGS, 

1877 explicit_tag=0xA4, 

1878 ), 

1879 KerberosTime("authtime", GeneralizedTime(), explicit_tag=0xA5), 

1880 ASN1F_optional( 

1881 KerberosTime("starttime", GeneralizedTime(), explicit_tag=0xA6), 

1882 ), 

1883 KerberosTime("endtime", GeneralizedTime(), explicit_tag=0xA7), 

1884 ASN1F_optional( 

1885 KerberosTime("renewTill", GeneralizedTime(), explicit_tag=0xA8), 

1886 ), 

1887 Realm("srealm", "", explicit_tag=0xA9), 

1888 ASN1F_PACKET("sname", PrincipalName(), PrincipalName, explicit_tag=0xAA), 

1889 ASN1F_optional( 

1890 HostAddresses("caddr", explicit_tag=0xAB), 

1891 ), 

1892 # RFC6806 sect 11 

1893 ASN1F_optional( 

1894 ASN1F_SEQUENCE_OF("encryptedPaData", [], PADATA, explicit_tag=0xAC), 

1895 ), 

1896) 

1897 

1898 

1899class EncASRepPart(ASN1_Packet): 

1900 ASN1_codec = ASN1_Codecs.BER 

1901 ASN1_root = ASN1F_SEQUENCE( 

1902 EncKDCRepPart, 

1903 implicit_tag=ASN1_Class_KRB.EncASRepPart, 

1904 ) 

1905 

1906 

1907class EncTGSRepPart(ASN1_Packet): 

1908 ASN1_codec = ASN1_Codecs.BER 

1909 ASN1_root = ASN1F_SEQUENCE( 

1910 EncKDCRepPart, 

1911 implicit_tag=ASN1_Class_KRB.EncTGSRepPart, 

1912 ) 

1913 

1914 

1915# sect 5.5.1 

1916 

1917 

1918class KRB_AP_REQ(ASN1_Packet): 

1919 ASN1_codec = ASN1_Codecs.BER 

1920 ASN1_root = ASN1F_SEQUENCE( 

1921 ASN1F_SEQUENCE( 

1922 ASN1F_INTEGER("pvno", 5, explicit_tag=0xA0), 

1923 ASN1F_enum_INTEGER("msgType", 14, KRB_MSG_TYPES, explicit_tag=0xA1), 

1924 KerberosFlags( 

1925 "apOptions", 

1926 "", 

1927 [ 

1928 "reserved", 

1929 "use-session-key", 

1930 "mutual-required", 

1931 ], 

1932 explicit_tag=0xA2, 

1933 ), 

1934 ASN1F_PACKET("ticket", None, KRB_Ticket, explicit_tag=0xA3), 

1935 ASN1F_PACKET("authenticator", None, EncryptedData, explicit_tag=0xA4), 

1936 ), 

1937 implicit_tag=ASN1_Class_KRB.AP_REQ, 

1938 ) 

1939 

1940 

1941_PADATA_CLASSES[1] = KRB_AP_REQ 

1942 

1943 

1944class KRB_Authenticator(ASN1_Packet): 

1945 ASN1_codec = ASN1_Codecs.BER 

1946 ASN1_root = ASN1F_SEQUENCE( 

1947 ASN1F_SEQUENCE( 

1948 ASN1F_INTEGER("authenticatorPvno", 5, explicit_tag=0xA0), 

1949 Realm("crealm", "", explicit_tag=0xA1), 

1950 ASN1F_PACKET("cname", None, PrincipalName, explicit_tag=0xA2), 

1951 ASN1F_optional( 

1952 ASN1F_PACKET("cksum", None, Checksum, explicit_tag=0xA3), 

1953 ), 

1954 Microseconds("cusec", 0, explicit_tag=0xA4), 

1955 KerberosTime("ctime", GeneralizedTime(), explicit_tag=0xA5), 

1956 ASN1F_optional( 

1957 ASN1F_PACKET("subkey", None, EncryptionKey, explicit_tag=0xA6), 

1958 ), 

1959 ASN1F_optional( 

1960 UInt32("seqNumber", 0, explicit_tag=0xA7), 

1961 ), 

1962 ASN1F_optional( 

1963 ASN1F_PACKET( 

1964 "encAuthorizationData", None, AuthorizationData, explicit_tag=0xA8 

1965 ), 

1966 ), 

1967 ), 

1968 implicit_tag=ASN1_Class_KRB.Authenticator, 

1969 ) 

1970 

1971 def getUPN(self): 

1972 return "%s@%s" % ( 

1973 self.cname.toString(), 

1974 self.crealm.val.decode(), 

1975 ) 

1976 

1977 def getClientTime(self): 

1978 """ 

1979 Return time from ctime + cusec 

1980 """ 

1981 return self.ctime.datetime + timedelta(microseconds=self.cusec.val) 

1982 

1983 

1984# sect 5.5.2 

1985 

1986 

1987class KRB_AP_REP(ASN1_Packet): 

1988 ASN1_codec = ASN1_Codecs.BER 

1989 ASN1_root = ASN1F_SEQUENCE( 

1990 ASN1F_SEQUENCE( 

1991 ASN1F_INTEGER("pvno", 5, explicit_tag=0xA0), 

1992 ASN1F_enum_INTEGER("msgType", 15, KRB_MSG_TYPES, explicit_tag=0xA1), 

1993 ASN1F_PACKET("encPart", None, EncryptedData, explicit_tag=0xA2), 

1994 ), 

1995 implicit_tag=ASN1_Class_KRB.AP_REP, 

1996 ) 

1997 

1998 

1999class EncAPRepPart(ASN1_Packet): 

2000 ASN1_codec = ASN1_Codecs.BER 

2001 ASN1_root = ASN1F_SEQUENCE( 

2002 ASN1F_SEQUENCE( 

2003 KerberosTime("ctime", GeneralizedTime(), explicit_tag=0xA0), 

2004 Microseconds("cusec", 0, explicit_tag=0xA1), 

2005 ASN1F_optional( 

2006 ASN1F_PACKET("subkey", None, EncryptionKey, explicit_tag=0xA2), 

2007 ), 

2008 ASN1F_optional( 

2009 UInt32("seqNumber", 0, explicit_tag=0xA3), 

2010 ), 

2011 ), 

2012 implicit_tag=ASN1_Class_KRB.EncAPRepPart, 

2013 ) 

2014 

2015 def getClientTime(self): 

2016 """ 

2017 Return time from ctime + cusec 

2018 """ 

2019 return self.ctime.datetime + timedelta(microseconds=self.cusec.val) 

2020 

2021 

2022# sect 5.7 

2023 

2024 

2025class KRB_PRIV(ASN1_Packet): 

2026 ASN1_codec = ASN1_Codecs.BER 

2027 ASN1_root = ASN1F_SEQUENCE( 

2028 ASN1F_SEQUENCE( 

2029 ASN1F_INTEGER("pvno", 5, explicit_tag=0xA0), 

2030 ASN1F_enum_INTEGER("msgType", 21, KRB_MSG_TYPES, explicit_tag=0xA1), 

2031 ASN1F_PACKET("encPart", None, EncryptedData, explicit_tag=0xA3), 

2032 ), 

2033 implicit_tag=ASN1_Class_KRB.PRIV, 

2034 ) 

2035 

2036 

2037class EncKrbPrivPart(ASN1_Packet): 

2038 ASN1_codec = ASN1_Codecs.BER 

2039 ASN1_root = ASN1F_SEQUENCE( 

2040 ASN1F_SEQUENCE( 

2041 ASN1F_STRING("userData", ASN1_STRING(""), explicit_tag=0xA0), 

2042 ASN1F_optional( 

2043 KerberosTime("timestamp", None, explicit_tag=0xA1), 

2044 ), 

2045 ASN1F_optional( 

2046 Microseconds("usec", None, explicit_tag=0xA2), 

2047 ), 

2048 ASN1F_optional( 

2049 UInt32("seqNumber", None, explicit_tag=0xA3), 

2050 ), 

2051 ASN1F_PACKET("sAddress", None, HostAddress, explicit_tag=0xA4), 

2052 ASN1F_optional( 

2053 ASN1F_PACKET("cAddress", None, HostAddress, explicit_tag=0xA5), 

2054 ), 

2055 ), 

2056 implicit_tag=ASN1_Class_KRB.EncKrbPrivPart, 

2057 ) 

2058 

2059 

2060# sect 5.8 

2061 

2062 

2063class KRB_CRED(ASN1_Packet): 

2064 ASN1_codec = ASN1_Codecs.BER 

2065 ASN1_root = ASN1F_SEQUENCE( 

2066 ASN1F_SEQUENCE( 

2067 ASN1F_INTEGER("pvno", 5, explicit_tag=0xA0), 

2068 ASN1F_enum_INTEGER("msgType", 22, KRB_MSG_TYPES, explicit_tag=0xA1), 

2069 ASN1F_SEQUENCE_OF("tickets", [KRB_Ticket()], KRB_Ticket, explicit_tag=0xA2), 

2070 ASN1F_PACKET("encPart", None, EncryptedData, explicit_tag=0xA3), 

2071 ), 

2072 implicit_tag=ASN1_Class_KRB.CRED, 

2073 ) 

2074 

2075 

2076class KrbCredInfo(ASN1_Packet): 

2077 ASN1_codec = ASN1_Codecs.BER 

2078 ASN1_root = ASN1F_SEQUENCE( 

2079 ASN1F_PACKET("key", EncryptionKey(), EncryptionKey, explicit_tag=0xA0), 

2080 ASN1F_optional( 

2081 Realm("prealm", None, explicit_tag=0xA1), 

2082 ), 

2083 ASN1F_optional( 

2084 ASN1F_PACKET("pname", None, PrincipalName, explicit_tag=0xA2), 

2085 ), 

2086 ASN1F_optional( 

2087 KerberosFlags( 

2088 "flags", 

2089 None, 

2090 _TICKET_FLAGS, 

2091 explicit_tag=0xA3, 

2092 ), 

2093 ), 

2094 ASN1F_optional( 

2095 KerberosTime("authtime", None, explicit_tag=0xA4), 

2096 ), 

2097 ASN1F_optional(KerberosTime("starttime", None, explicit_tag=0xA5)), 

2098 ASN1F_optional( 

2099 KerberosTime("endtime", None, explicit_tag=0xA6), 

2100 ), 

2101 ASN1F_optional( 

2102 KerberosTime("renewTill", None, explicit_tag=0xA7), 

2103 ), 

2104 ASN1F_optional( 

2105 Realm("srealm", None, explicit_tag=0xA8), 

2106 ), 

2107 ASN1F_optional( 

2108 ASN1F_PACKET("sname", None, PrincipalName, explicit_tag=0xA9), 

2109 ), 

2110 ASN1F_optional( 

2111 HostAddresses("caddr", explicit_tag=0xAA), 

2112 ), 

2113 ) 

2114 

2115 

2116class EncKrbCredPart(ASN1_Packet): 

2117 ASN1_codec = ASN1_Codecs.BER 

2118 ASN1_root = ASN1F_SEQUENCE( 

2119 ASN1F_SEQUENCE( 

2120 ASN1F_SEQUENCE_OF( 

2121 "ticketInfo", 

2122 [KrbCredInfo()], 

2123 KrbCredInfo, 

2124 explicit_tag=0xA0, 

2125 ), 

2126 ASN1F_optional( 

2127 UInt32("nonce", None, explicit_tag=0xA1), 

2128 ), 

2129 ASN1F_optional( 

2130 KerberosTime("timestamp", None, explicit_tag=0xA2), 

2131 ), 

2132 ASN1F_optional( 

2133 Microseconds("usec", None, explicit_tag=0xA3), 

2134 ), 

2135 ASN1F_optional( 

2136 ASN1F_PACKET("sAddress", None, HostAddress, explicit_tag=0xA4), 

2137 ), 

2138 ASN1F_optional( 

2139 ASN1F_PACKET("cAddress", None, HostAddress, explicit_tag=0xA5), 

2140 ), 

2141 ), 

2142 implicit_tag=ASN1_Class_KRB.EncKrbCredPart, 

2143 ) 

2144 

2145 

2146# sect 5.9.1 

2147 

2148 

2149class MethodData(ASN1_Packet): 

2150 ASN1_codec = ASN1_Codecs.BER 

2151 ASN1_root = ASN1F_SEQUENCE_OF("seq", [PADATA()], PADATA) 

2152 

2153 

2154class _KRBERROR_data_Field(ASN1F_STRING_PacketField): 

2155 def m2i(self, pkt, s): 

2156 val = super(_KRBERROR_data_Field, self).m2i(pkt, s) 

2157 if not val[0].val: 

2158 return val 

2159 if pkt.errorCode.val in [14, 24, 25, 36, 80]: 

2160 # 14: KDC_ERR_ETYPE_NOSUPP 

2161 # 24: KDC_ERR_PREAUTH_FAILED 

2162 # 25: KDC_ERR_PREAUTH_REQUIRED 

2163 # 36: KRB_AP_ERR_BADMATCH 

2164 # 80: KDC_ERR_DIGEST_IN_SIGNED_DATA_NOT_ACCEPTED 

2165 return MethodData(val[0].val, _underlayer=pkt), val[1] 

2166 elif pkt.errorCode.val in [6, 7, 12, 13, 18, 23, 29, 32, 41, 60, 62]: 

2167 # 6: KDC_ERR_C_PRINCIPAL_UNKNOWN 

2168 # 7: KDC_ERR_S_PRINCIPAL_UNKNOWN 

2169 # 12: KDC_ERR_POLICY 

2170 # 13: KDC_ERR_BADOPTION 

2171 # 18: KDC_ERR_CLIENT_REVOKED 

2172 # 23: KDC_ERR_KEY_EXPIRED 

2173 # 29: KDC_ERR_SVC_UNAVAILABLE 

2174 # 32: KRB_AP_ERR_TKT_EXPIRED 

2175 # 41: KRB_AP_ERR_MODIFIED 

2176 # 60: KRB_ERR_GENERIC 

2177 # 62: KERB_ERR_TYPE_EXTENDED 

2178 try: 

2179 return KERB_ERROR_DATA(val[0].val, _underlayer=pkt), val[1] 

2180 except BER_Decoding_Error: 

2181 if pkt.errorCode.val in [12, 18, 41]: 

2182 # Some types can also happen in FAST sessions 

2183 # 18: KDC_ERR_CLIENT_REVOKED 

2184 return MethodData(val[0].val, _underlayer=pkt), val[1] 

2185 elif pkt.errorCode.val == 7: 

2186 # This looks like an undocumented structure. 

2187 # 7: KDC_ERR_S_PRINCIPAL_UNKNOWN 

2188 return KERB_ERROR_UNK(val[0].val, _underlayer=pkt), val[1] 

2189 raise 

2190 elif pkt.errorCode.val == 69: 

2191 # KRB_AP_ERR_USER_TO_USER_REQUIRED 

2192 return KRB_TGT_REP(val[0].val, _underlayer=pkt), val[1] 

2193 return val 

2194 

2195 

2196class KRB_ERROR(ASN1_Packet): 

2197 ASN1_codec = ASN1_Codecs.BER 

2198 ASN1_root = ASN1F_SEQUENCE( 

2199 ASN1F_SEQUENCE( 

2200 ASN1F_INTEGER("pvno", 5, explicit_tag=0xA0), 

2201 ASN1F_enum_INTEGER("msgType", 30, KRB_MSG_TYPES, explicit_tag=0xA1), 

2202 ASN1F_optional( 

2203 KerberosTime("ctime", None, explicit_tag=0xA2), 

2204 ), 

2205 ASN1F_optional( 

2206 Microseconds("cusec", None, explicit_tag=0xA3), 

2207 ), 

2208 KerberosTime("stime", GeneralizedTime(), explicit_tag=0xA4), 

2209 Microseconds("susec", 0, explicit_tag=0xA5), 

2210 ASN1F_enum_INTEGER( 

2211 "errorCode", 

2212 0, 

2213 { 

2214 # RFC4120 sect 7.5.9 

2215 0: "KDC_ERR_NONE", 

2216 1: "KDC_ERR_NAME_EXP", 

2217 2: "KDC_ERR_SERVICE_EXP", 

2218 3: "KDC_ERR_BAD_PVNO", 

2219 4: "KDC_ERR_C_OLD_MAST_KVNO", 

2220 5: "KDC_ERR_S_OLD_MAST_KVNO", 

2221 6: "KDC_ERR_C_PRINCIPAL_UNKNOWN", 

2222 7: "KDC_ERR_S_PRINCIPAL_UNKNOWN", 

2223 8: "KDC_ERR_PRINCIPAL_NOT_UNIQUE", 

2224 9: "KDC_ERR_NULL_KEY", 

2225 10: "KDC_ERR_CANNOT_POSTDATE", 

2226 11: "KDC_ERR_NEVER_VALID", 

2227 12: "KDC_ERR_POLICY", 

2228 13: "KDC_ERR_BADOPTION", 

2229 14: "KDC_ERR_ETYPE_NOSUPP", 

2230 15: "KDC_ERR_SUMTYPE_NOSUPP", 

2231 16: "KDC_ERR_PADATA_TYPE_NOSUPP", 

2232 17: "KDC_ERR_TRTYPE_NOSUPP", 

2233 18: "KDC_ERR_CLIENT_REVOKED", 

2234 19: "KDC_ERR_SERVICE_REVOKED", 

2235 20: "KDC_ERR_TGT_REVOKED", 

2236 21: "KDC_ERR_CLIENT_NOTYET", 

2237 22: "KDC_ERR_SERVICE_NOTYET", 

2238 23: "KDC_ERR_KEY_EXPIRED", 

2239 24: "KDC_ERR_PREAUTH_FAILED", 

2240 25: "KDC_ERR_PREAUTH_REQUIRED", 

2241 26: "KDC_ERR_SERVER_NOMATCH", 

2242 27: "KDC_ERR_MUST_USE_USER2USER", 

2243 28: "KDC_ERR_PATH_NOT_ACCEPTED", 

2244 29: "KDC_ERR_SVC_UNAVAILABLE", 

2245 31: "KRB_AP_ERR_BAD_INTEGRITY", 

2246 32: "KRB_AP_ERR_TKT_EXPIRED", 

2247 33: "KRB_AP_ERR_TKT_NYV", 

2248 34: "KRB_AP_ERR_REPEAT", 

2249 35: "KRB_AP_ERR_NOT_US", 

2250 36: "KRB_AP_ERR_BADMATCH", 

2251 37: "KRB_AP_ERR_SKEW", 

2252 38: "KRB_AP_ERR_BADADDR", 

2253 39: "KRB_AP_ERR_BADVERSION", 

2254 40: "KRB_AP_ERR_MSG_TYPE", 

2255 41: "KRB_AP_ERR_MODIFIED", 

2256 42: "KRB_AP_ERR_BADORDER", 

2257 44: "KRB_AP_ERR_BADKEYVER", 

2258 45: "KRB_AP_ERR_NOKEY", 

2259 46: "KRB_AP_ERR_MUT_FAIL", 

2260 47: "KRB_AP_ERR_BADDIRECTION", 

2261 48: "KRB_AP_ERR_METHOD", 

2262 49: "KRB_AP_ERR_BADSEQ", 

2263 50: "KRB_AP_ERR_INAPP_CKSUM", 

2264 51: "KRB_AP_PATH_NOT_ACCEPTED", 

2265 52: "KRB_ERR_RESPONSE_TOO_BIG", 

2266 60: "KRB_ERR_GENERIC", 

2267 61: "KRB_ERR_FIELD_TOOLONG", 

2268 # RFC4556 

2269 62: "KDC_ERR_CLIENT_NOT_TRUSTED", 

2270 63: "KDC_ERR_KDC_NOT_TRUSTED", 

2271 64: "KDC_ERR_INVALID_SIG", 

2272 65: "KDC_ERR_KEY_TOO_WEAK", 

2273 66: "KDC_ERR_CERTIFICATE_MISMATCH", 

2274 67: "KRB_AP_ERR_NO_TGT", 

2275 68: "KDC_ERR_WRONG_REALM", 

2276 69: "KRB_AP_ERR_USER_TO_USER_REQUIRED", 

2277 70: "KDC_ERR_CANT_VERIFY_CERTIFICATE", 

2278 71: "KDC_ERR_INVALID_CERTIFICATE", 

2279 72: "KDC_ERR_REVOKED_CERTIFICATE", 

2280 73: "KDC_ERR_REVOCATION_STATUS_UNKNOWN", 

2281 74: "KDC_ERR_REVOCATION_STATUS_UNAVAILABLE", 

2282 75: "KDC_ERR_CLIENT_NAME_MISMATCH", 

2283 76: "KDC_ERR_KDC_NAME_MISMATCH", 

2284 77: "KDC_ERR_INCONSISTENT_KEY_PURPOSE", 

2285 78: "KDC_ERR_DIGEST_IN_CERT_NOT_ACCEPTED", 

2286 79: "KDC_ERR_PA_CHECKSUM_MUST_BE_INCLUDED", 

2287 80: "KDC_ERR_DIGEST_IN_SIGNED_DATA_NOT_ACCEPTED", 

2288 81: "KDC_ERR_PUBLIC_KEY_ENCRYPTION_NOT_SUPPORTED", 

2289 # draft-ietf-kitten-iakerb 

2290 85: "KRB_AP_ERR_IAKERB_KDC_NOT_FOUND", 

2291 86: "KRB_AP_ERR_IAKERB_KDC_NO_RESPONSE", 

2292 # RFC6113 

2293 90: "KDC_ERR_PREAUTH_EXPIRED", 

2294 91: "KDC_ERR_MORE_PREAUTH_DATA_REQUIRED", 

2295 92: "KDC_ERR_PREAUTH_BAD_AUTHENTICATION_SET", 

2296 93: "KDC_ERR_UNKNOWN_CRITICAL_FAST_OPTIONS", 

2297 # RFC8636 

2298 100: "KDC_ERR_NO_ACCEPTABLE_KDF", 

2299 }, 

2300 explicit_tag=0xA6, 

2301 ), 

2302 ASN1F_optional(Realm("crealm", None, explicit_tag=0xA7)), 

2303 ASN1F_optional( 

2304 ASN1F_PACKET("cname", None, PrincipalName, explicit_tag=0xA8), 

2305 ), 

2306 Realm("realm", "", explicit_tag=0xA9), 

2307 ASN1F_PACKET("sname", PrincipalName(), PrincipalName, explicit_tag=0xAA), 

2308 ASN1F_optional(KerberosString("eText", "", explicit_tag=0xAB)), 

2309 ASN1F_optional(_KRBERROR_data_Field("eData", "", explicit_tag=0xAC)), 

2310 ), 

2311 implicit_tag=ASN1_Class_KRB.ERROR, 

2312 ) 

2313 

2314 def getSPN(self): 

2315 return "%s@%s" % ( 

2316 self.sname.toString(), 

2317 self.realm.val.decode(), 

2318 ) 

2319 

2320 def getServerTime(self): 

2321 """ 

2322 Return time from stime + susec 

2323 """ 

2324 return self.stime.datetime + timedelta(microseconds=self.susec.val) 

2325 

2326 

2327# PA-FX-ERROR 

2328_PADATA_CLASSES[137] = KRB_ERROR 

2329 

2330 

2331# [MS-KILE] sect 2.2.1 

2332 

2333 

2334class KERB_EXT_ERROR(Packet): 

2335 fields_desc = [ 

2336 XLEIntEnumField("status", 0, STATUS_ERREF), 

2337 XLEIntField("reserved", 0), 

2338 XLEIntField("flags", 0x00000001), 

2339 ] 

2340 

2341 

2342class KERB_EXT_ERROR_NTSTATUS(Packet): 

2343 fields_desc = [ 

2344 XLEIntEnumField("status", 0, STATUS_ERREF), 

2345 ] 

2346 

2347 

2348# [MS-KILE] sect 2.2.2 

2349 

2350 

2351class _Error_Field(ASN1F_STRING_PacketField): 

2352 def m2i(self, pkt, s): 

2353 val = super(_Error_Field, self).m2i(pkt, s) 

2354 if not val[0].val: 

2355 return val 

2356 if pkt.dataType.val == 1: # KERB_AP_ERR_TYPE_NTSTATUS 

2357 return KERB_EXT_ERROR_NTSTATUS(val[0].val, _underlayer=pkt), val[1] 

2358 if pkt.dataType.val == 3: # KERB_ERR_TYPE_EXTENDED 

2359 return KERB_EXT_ERROR(val[0].val, _underlayer=pkt), val[1] 

2360 return val 

2361 

2362 

2363class KERB_ERROR_DATA(ASN1_Packet): 

2364 ASN1_codec = ASN1_Codecs.BER 

2365 ASN1_root = ASN1F_SEQUENCE( 

2366 ASN1F_enum_INTEGER( 

2367 "dataType", 

2368 2, 

2369 { 

2370 1: "KERB_AP_ERR_TYPE_NTSTATUS", # from the wdk 

2371 2: "KERB_AP_ERR_TYPE_SKEW_RECOVERY", 

2372 3: "KERB_ERR_TYPE_EXTENDED", 

2373 }, 

2374 explicit_tag=0xA1, 

2375 ), 

2376 ASN1F_optional(_Error_Field("dataValue", None, explicit_tag=0xA2)), 

2377 ) 

2378 

2379 

2380# This looks like an undocumented structure. 

2381 

2382 

2383class KERB_ERROR_UNK(ASN1_Packet): 

2384 ASN1_codec = ASN1_Codecs.BER 

2385 ASN1_root = ASN1F_SEQUENCE( 

2386 ASN1F_SEQUENCE( 

2387 ASN1F_enum_INTEGER( 

2388 "dataType", 

2389 0, 

2390 { 

2391 -128: "KDC_ERR_MUST_USE_USER2USER", 

2392 }, 

2393 explicit_tag=0xA0, 

2394 ), 

2395 ASN1F_STRING("dataValue", None, explicit_tag=0xA1), 

2396 ) 

2397 ) 

2398 

2399 

2400# Kerberos U2U - draft-ietf-cat-user2user-03 

2401 

2402 

2403class KRB_TGT_REQ(ASN1_Packet): 

2404 ASN1_codec = ASN1_Codecs.BER 

2405 ASN1_root = ASN1F_SEQUENCE( 

2406 ASN1F_INTEGER("pvno", 5, explicit_tag=0xA0), 

2407 ASN1F_enum_INTEGER("msgType", 16, KRB_MSG_TYPES, explicit_tag=0xA1), 

2408 ASN1F_optional( 

2409 ASN1F_PACKET("sname", None, PrincipalName, explicit_tag=0xA2), 

2410 ), 

2411 ASN1F_optional( 

2412 Realm("realm", None, explicit_tag=0xA3), 

2413 ), 

2414 ) 

2415 

2416 

2417class KRB_TGT_REP(ASN1_Packet): 

2418 ASN1_codec = ASN1_Codecs.BER 

2419 ASN1_root = ASN1F_SEQUENCE( 

2420 ASN1F_INTEGER("pvno", 5, explicit_tag=0xA0), 

2421 ASN1F_enum_INTEGER("msgType", 17, KRB_MSG_TYPES, explicit_tag=0xA1), 

2422 ASN1F_PACKET("ticket", None, KRB_Ticket, explicit_tag=0xA2), 

2423 ) 

2424 

2425 

2426# draft-ietf-kitten-iakerb-03 sect 4 

2427 

2428 

2429class KRB_FINISHED(ASN1_Packet): 

2430 ASN1_codec = ASN1_Codecs.BER 

2431 ASN1_root = ASN1F_SEQUENCE( 

2432 ASN1F_PACKET("gssMic", Checksum(), Checksum, explicit_tag=0xA1), 

2433 ) 

2434 

2435 

2436# RFC 6542 sect 3.1 

2437 

2438 

2439class KRB_GSS_EXT(Packet): 

2440 fields_desc = [ 

2441 IntEnumField( 

2442 "type", 

2443 0, 

2444 { 

2445 # https://www.iana.org/assignments/kerberos-v-gss-api/kerberos-v-gss-api.xhtml 

2446 0x00000000: "GSS_EXTS_CHANNEL_BINDING", # RFC 6542 sect 3.2 

2447 0x00000001: "GSS_EXTS_IAKERB_FINISHED", # not standard 

2448 0x00000002: "GSS_EXTS_FINISHED", # PKU2U / IAKERB 

2449 }, 

2450 ), 

2451 FieldLenField("length", None, length_of="data", fmt="!I"), 

2452 MultipleTypeField( 

2453 [ 

2454 ( 

2455 PacketField("data", KRB_FINISHED(), KRB_FINISHED), 

2456 lambda pkt: pkt.type == 0x00000002, 

2457 ), 

2458 ], 

2459 XStrLenField("data", b"", length_from=lambda pkt: pkt.length), 

2460 ), 

2461 ] 

2462 

2463 

2464# RFC 4121 sect 4.1.1 

2465 

2466 

2467class KRB_AuthenticatorChecksum(Packet): 

2468 fields_desc = [ 

2469 FieldLenField("Lgth", None, length_of="Bnd", fmt="<I"), 

2470 XStrLenField("Bnd", b"\x00" * 16, length_from=lambda pkt: pkt.Lgth), 

2471 FlagsField( 

2472 "Flags", 

2473 0, 

2474 -32, 

2475 { 

2476 0x01: "GSS_C_DELEG_FLAG", 

2477 0x02: "GSS_C_MUTUAL_FLAG", 

2478 0x04: "GSS_C_REPLAY_FLAG", 

2479 0x08: "GSS_C_SEQUENCE_FLAG", 

2480 0x10: "GSS_C_CONF_FLAG", # confidentiality 

2481 0x20: "GSS_C_INTEG_FLAG", # integrity 

2482 # RFC4757 

2483 0x1000: "GSS_C_DCE_STYLE", 

2484 0x2000: "GSS_C_IDENTIFY_FLAG", 

2485 0x4000: "GSS_C_EXTENDED_ERROR_FLAG", 

2486 }, 

2487 ), 

2488 ConditionalField( 

2489 LEShortField("DlgOpt", 1), 

2490 lambda pkt: pkt.Flags.GSS_C_DELEG_FLAG, 

2491 ), 

2492 ConditionalField( 

2493 FieldLenField("Dlgth", None, length_of="Deleg", fmt="<H"), 

2494 lambda pkt: pkt.Flags.GSS_C_DELEG_FLAG, 

2495 ), 

2496 ConditionalField( 

2497 PacketLenField( 

2498 "Deleg", KRB_CRED(), KRB_CRED, length_from=lambda pkt: pkt.Dlgth 

2499 ), 

2500 lambda pkt: pkt.Flags.GSS_C_DELEG_FLAG, 

2501 ), 

2502 # Extensions: RFC 6542 sect 3.1 

2503 PacketListField("Exts", KRB_GSS_EXT(), KRB_GSS_EXT), 

2504 ] 

2505 

2506 

2507# Kerberos V5 GSS-API - RFC1964 and RFC4121 

2508 

2509_TOK_IDS = { 

2510 # RFC 1964 

2511 b"\x01\x00": "KRB-AP-REQ", 

2512 b"\x02\x00": "KRB-AP-REP", 

2513 b"\x03\x00": "KRB-ERROR", 

2514 b"\x01\x01": "GSS_GetMIC-RFC1964", 

2515 b"\x02\x01": "GSS_Wrap-RFC1964", 

2516 b"\x01\x02": "GSS_Delete_sec_context-RFC1964", 

2517 # U2U: [draft-ietf-cat-user2user-03] 

2518 b"\x04\x00": "KRB-TGT-REQ", 

2519 b"\x04\x01": "KRB-TGT-REP", 

2520 # RFC 4121 

2521 b"\x04\x04": "GSS_GetMIC", 

2522 b"\x05\x04": "GSS_Wrap", 

2523 # IAKERB: [draft-ietf-kitten-iakerb-03] 

2524 b"\x05\x01": "IAKERB_PROXY", 

2525} 

2526_SGN_ALGS = { 

2527 0x00: "DES MAC MD5", 

2528 0x01: "MD2.5", 

2529 0x02: "DES MAC", 

2530 # RFC 4757 

2531 0x11: "HMAC", 

2532} 

2533_SEAL_ALGS = { 

2534 0: "DES", 

2535 0xFFFF: "none", 

2536 # RFC 4757 

2537 0x10: "RC4", 

2538} 

2539 

2540 

2541# RFC 1964 - sect 1.1 

2542 

2543# See https://www.iana.org/assignments/kerberos-v-gss-api/kerberos-v-gss-api.xhtml 

2544_InitialContextTokens = {} # filled below 

2545 

2546 

2547class KRB_InnerToken(Packet): 

2548 name = "Kerberos v5 InnerToken" 

2549 fields_desc = [ 

2550 StrFixedLenEnumField("TOK_ID", b"\x01\x00", _TOK_IDS, length=2), 

2551 PacketField( 

2552 "root", 

2553 KRB_AP_REQ(), 

2554 lambda x, _parent: _InitialContextTokens.get( 

2555 _parent.TOK_ID, conf.raw_layer 

2556 )(x), 

2557 ), 

2558 ] 

2559 

2560 def mysummary(self): 

2561 return self.sprintf( 

2562 "Kerberos %s" % _TOK_IDS.get(self.TOK_ID, repr(self.TOK_ID)) 

2563 ) 

2564 

2565 def guess_payload_class(self, payload): 

2566 if self.TOK_ID in [b"\x01\x01", b"\x02\x01", b"\x04\x04", b"\x05\x04"]: 

2567 return conf.padding_layer 

2568 return Kerberos 

2569 

2570 @classmethod 

2571 def dispatch_hook(cls, _pkt=None, *args, **kargs): 

2572 if _pkt and len(_pkt) >= 13: 

2573 # Older RFC1964 variants of the token have KRB_GSSAPI_Token wrapper 

2574 if _pkt[2:13] == b"\x06\t*\x86H\x86\xf7\x12\x01\x02\x02": 

2575 return KRB_GSSAPI_Token 

2576 return cls 

2577 

2578 

2579# RFC 4121 - sect 4.1 

2580 

2581 

2582class KRB_GSSAPI_Token(GSSAPI_BLOB): 

2583 name = "Kerberos GSSAPI-Token" 

2584 ASN1_codec = ASN1_Codecs.BER 

2585 ASN1_root = ASN1F_SEQUENCE( 

2586 ASN1F_OID("MechType", "1.2.840.113554.1.2.2"), 

2587 ASN1F_PACKET( 

2588 "innerToken", 

2589 KRB_InnerToken(), 

2590 KRB_InnerToken, 

2591 implicit_tag=0x0, 

2592 ), 

2593 implicit_tag=ASN1_Class_KRB.Token, 

2594 ) 

2595 

2596 

2597# RFC 1964 - sect 1.2.1 

2598 

2599 

2600class KRB_GSS_MIC_RFC1964(Packet): 

2601 name = "Kerberos v5 MIC Token (RFC1964)" 

2602 fields_desc = [ 

2603 LEShortEnumField("SGN_ALG", 0, _SGN_ALGS), 

2604 XLEIntField("Filler", 0xFFFFFFFF), 

2605 XStrFixedLenField("SND_SEQ", b"", length=8), 

2606 PadField( # sect 1.2.2.3 

2607 XStrFixedLenField("SGN_CKSUM", b"", length=8), 

2608 align=8, 

2609 padwith=b"\x04", 

2610 ), 

2611 ] 

2612 

2613 def default_payload_class(self, payload): 

2614 return conf.padding_layer 

2615 

2616 

2617_InitialContextTokens[b"\x01\x01"] = KRB_GSS_MIC_RFC1964 

2618 

2619# RFC 1964 - sect 1.2.2 

2620 

2621 

2622class KRB_GSS_Wrap_RFC1964(Packet): 

2623 name = "Kerberos v5 GSS_Wrap (RFC1964)" 

2624 fields_desc = [ 

2625 LEShortEnumField("SGN_ALG", 0, _SGN_ALGS), 

2626 LEShortEnumField("SEAL_ALG", 0, _SEAL_ALGS), 

2627 XLEShortField("Filler", 0xFFFF), 

2628 XStrFixedLenField("SND_SEQ", b"", length=8), 

2629 PadField( # sect 1.2.2.3 

2630 XStrFixedLenField("SGN_CKSUM", b"", length=8), 

2631 align=8, 

2632 padwith=b"\x04", 

2633 ), 

2634 # sect 1.2.2.3 

2635 XStrFixedLenField("CONFOUNDER", b"", length=8), 

2636 ] 

2637 

2638 def default_payload_class(self, payload): 

2639 return conf.padding_layer 

2640 

2641 

2642_InitialContextTokens[b"\x02\x01"] = KRB_GSS_Wrap_RFC1964 

2643 

2644 

2645# RFC 1964 - sect 1.2.2 

2646 

2647 

2648class KRB_GSS_Delete_sec_context_RFC1964(Packet): 

2649 name = "Kerberos v5 GSS_Delete_sec_context (RFC1964)" 

2650 fields_desc = KRB_GSS_MIC_RFC1964.fields_desc 

2651 

2652 

2653_InitialContextTokens[b"\x01\x02"] = KRB_GSS_Delete_sec_context_RFC1964 

2654 

2655 

2656# RFC 4121 - sect 4.2.2 

2657_KRB5_GSS_Flags = [ 

2658 "SentByAcceptor", 

2659 "Sealed", 

2660 "AcceptorSubkey", 

2661] 

2662 

2663 

2664# RFC 4121 - sect 4.2.6.1 

2665 

2666 

2667class KRB_GSS_MIC(Packet): 

2668 name = "Kerberos v5 MIC Token" 

2669 fields_desc = [ 

2670 FlagsField("Flags", 0, 8, _KRB5_GSS_Flags), 

2671 XStrFixedLenField("Filler", b"\xff\xff\xff\xff\xff", length=5), 

2672 LongField("SND_SEQ", 0), # Big endian 

2673 XStrField("SGN_CKSUM", b"\x00" * 12), 

2674 ] 

2675 

2676 def default_payload_class(self, payload): 

2677 return conf.padding_layer 

2678 

2679 

2680_InitialContextTokens[b"\x04\x04"] = KRB_GSS_MIC 

2681 

2682 

2683# RFC 4121 - sect 4.2.6.2 

2684 

2685 

2686class KRB_GSS_Wrap(Packet): 

2687 name = "Kerberos v5 Wrap Token" 

2688 fields_desc = [ 

2689 FlagsField("Flags", 0, 8, _KRB5_GSS_Flags), 

2690 XByteField("Filler", 0xFF), 

2691 ShortField("EC", 0), # Big endian 

2692 ShortField("RRC", 0), # Big endian 

2693 LongField("SND_SEQ", 0), # Big endian 

2694 MultipleTypeField( 

2695 [ 

2696 ( 

2697 XStrField("Data", b""), 

2698 lambda pkt: pkt.Flags.Sealed, 

2699 ) 

2700 ], 

2701 XStrLenField("Data", b"", length_from=lambda pkt: pkt.EC), 

2702 ), 

2703 ] 

2704 

2705 def default_payload_class(self, payload): 

2706 return conf.padding_layer 

2707 

2708 

2709_InitialContextTokens[b"\x05\x04"] = KRB_GSS_Wrap 

2710 

2711 

2712# [MS-NRPC] 3.5.4.3.1 in theory, dsgetdc.h (WinSDK) for details 

2713 

2714_GetDcName_Flags = [ 

2715 "DS_RETURN_FLAT_NAME", # 0x80000000 

2716 "DS_RETURN_DNS_NAME", # 0x40000000 

2717 "reserved2", # 0x20000000 

2718 "reserved3", # 0x10000000 

2719 "reserved4", # 0x08000000 

2720 "reserved5", # 0x04000000 

2721 "DS_DIRECTORY_SERVICE_13_REQUIRED", # 0x02000000 - Windows Server 2025 or later 

2722 "DS_KEY_LIST_SUPPORT_REQUIRED", # 0x01000000 

2723 "DS_DIRECTORY_SERVICE_10_REQUIRED", # 0x00800000 - Windows Server 2016 or later 

2724 "DS_DIRECTORY_SERVICE_9_REQUIRED", # 0x00400000 - Windows Server 2012R2 or later 

2725 "DS_DIRECTORY_SERVICE_8_REQUIRED", # 0x00200000 - Windows Server 2012 or later 

2726 "DS_WEB_SERVICE_REQUIRED", # 0x00100000 

2727 "DS_DIRECTORY_SERVICE_6_REQUIRED", # 0x00080000 - Windows Server 2008 or later 

2728 "DS_TRY_NEXTCLOSEST_SITE", # 0x00040000 

2729 "DS_IS_DNS_NAME", # 0x00020000 

2730 "DS_IS_FLAT_NAME", # 0x00010000 

2731 "DS_ONLY_LDAP_NEEDED", # 0x00008000 

2732 "DS_AVOID_SELF", # 0x00004000 

2733 "DS_GOOD_TIMESERV_PREFERRED", # 0x00002000 

2734 "DS_WRITABLE_REQUIRED", # 0x00001000 

2735 "DS_TIMESERV_REQUIRED", # 0x00000800 

2736 "DS_KDC_REQUIRED", # 0x00000400 

2737 "DS_IP_REQUIRED", # 0x00000200 

2738 "DS_BACKGROUND_ONLY", # 0x00000100 

2739 "DS_PDC_REQUIRED", # 0x00000080 

2740 "DS_GC_SERVER_REQUIRED", # 0x00000040 

2741 "DS_DIRECTORY_SERVICE_PREFERRED", # 0x00000020 

2742 "DS_DIRECTORY_SERVICE_REQUIRED", # 0x00000010 

2743 "reserved-28", # 0x00000008 

2744 "reserved-29", # 0x00000004 

2745 "reserved-30", # 0x00000002 

2746 "DS_FORCE_REDISCOVERY", # 0x00000001 

2747] 

2748 

2749 

2750# Kerberos IAKERB - draft-ietf-kitten-iakerb-03 

2751 

2752 

2753class IAKERB_HEADER(ASN1_Packet): 

2754 ASN1_codec = ASN1_Codecs.BER 

2755 ASN1_root = ASN1F_SEQUENCE( 

2756 ASN1F_UTF8_STRING("targetRealm", "", explicit_tag=0xA1), 

2757 ASN1F_optional( 

2758 ASN1F_STRING("cookie", None, explicit_tag=0xA2), 

2759 ), 

2760 # [MS-SPNG] addition. This is mentioned on [kitten] IETF mailing list 

2761 # (and dochelp@ answered with details, should be updated soon) 

2762 ASN1F_optional( 

2763 ASN1F_FLAGS( 

2764 "headerFlags", 

2765 None, 

2766 _GetDcName_Flags, 

2767 explicit_tag=0xA3, 

2768 ) 

2769 ), 

2770 ) 

2771 

2772 def default_payload_class(self, payload): 

2773 return conf.padding_layer 

2774 

2775 

2776_InitialContextTokens[b"\x05\x01"] = IAKERB_HEADER 

2777 

2778 

2779# Register for GSSAPI 

2780 

2781# Kerberos 5 

2782_GSSAPI_OIDS["1.2.840.113554.1.2.2"] = KRB_InnerToken 

2783_GSSAPI_SIGNATURE_OIDS["1.2.840.113554.1.2.2"] = KRB_InnerToken 

2784# Kerberos 5 - U2U 

2785_GSSAPI_OIDS["1.2.840.113554.1.2.2.3"] = KRB_InnerToken 

2786# Kerberos 5 - IAKERB 

2787_GSSAPI_OIDS["1.3.6.1.5.2.5"] = KRB_InnerToken 

2788 

2789 

2790# Entry class 

2791 

2792# RFC4120 sect 5.10 

2793 

2794 

2795class Kerberos(ASN1_Packet): 

2796 ASN1_codec = ASN1_Codecs.BER 

2797 ASN1_root = ASN1F_CHOICE( 

2798 "root", 

2799 None, 

2800 # RFC4120 

2801 KRB_GSSAPI_Token, # [APPLICATION 0] 

2802 KRB_Ticket, # [APPLICATION 1] 

2803 KRB_Authenticator, # [APPLICATION 2] 

2804 KRB_AS_REQ, # [APPLICATION 10] 

2805 KRB_AS_REP, # [APPLICATION 11] 

2806 KRB_TGS_REQ, # [APPLICATION 12] 

2807 KRB_TGS_REP, # [APPLICATION 13] 

2808 KRB_AP_REQ, # [APPLICATION 14] 

2809 KRB_AP_REP, # [APPLICATION 15] 

2810 # RFC4120 

2811 KRB_ERROR, # [APPLICATION 30] 

2812 ) 

2813 

2814 def mysummary(self): 

2815 return self.root.summary() 

2816 

2817 

2818bind_bottom_up(UDP, Kerberos, sport=88) 

2819bind_bottom_up(UDP, Kerberos, dport=88) 

2820bind_layers(UDP, Kerberos, sport=88, dport=88) 

2821 

2822_InitialContextTokens[b"\x01\x00"] = KRB_AP_REQ 

2823_InitialContextTokens[b"\x02\x00"] = KRB_AP_REP 

2824_InitialContextTokens[b"\x03\x00"] = KRB_ERROR 

2825_InitialContextTokens[b"\x04\x00"] = KRB_TGT_REQ 

2826_InitialContextTokens[b"\x04\x01"] = KRB_TGT_REP 

2827 

2828 

2829# RFC4120 sect 7.2.2 

2830 

2831 

2832class KerberosTCPHeader(Packet): 

2833 # According to RFC 5021, first bit to 1 has a special meaning and 

2834 # negotiates Kerberos TCP extensions... But apart from rfc6251 no one used that 

2835 # https://www.iana.org/assignments/kerberos-parameters/kerberos-parameters.xhtml#kerberos-parameters-4 

2836 fields_desc = [LenField("len", None, fmt="!I")] 

2837 

2838 @classmethod 

2839 def tcp_reassemble(cls, data, *args, **kwargs): 

2840 if len(data) < 4: 

2841 return None 

2842 length = struct.unpack("!I", data[:4])[0] 

2843 if len(data) == length + 4: 

2844 return cls(data) 

2845 if len(data) > length + 4: 

2846 return cls(data[: length + 4]) / conf.padding_layer(data[length + 4 :]) 

2847 

2848 

2849bind_layers(KerberosTCPHeader, Kerberos) 

2850 

2851bind_bottom_up(TCP, KerberosTCPHeader, sport=88) 

2852bind_layers(TCP, KerberosTCPHeader, dport=88) 

2853 

2854 

2855# RFC3244 sect 2 

2856 

2857 

2858class KPASSWD_REQ(Packet): 

2859 fields_desc = [ 

2860 ShortField("len", None), 

2861 ShortField("pvno", 0xFF80), 

2862 ShortField("apreqlen", None), 

2863 PacketLenField( 

2864 "apreq", KRB_AP_REQ(), KRB_AP_REQ, length_from=lambda pkt: pkt.apreqlen 

2865 ), 

2866 ConditionalField( 

2867 PacketLenField( 

2868 "krbpriv", 

2869 KRB_PRIV(), 

2870 KRB_PRIV, 

2871 length_from=lambda pkt: pkt.len - 6 - pkt.apreqlen, 

2872 ), 

2873 lambda pkt: pkt.apreqlen != 0, 

2874 ), 

2875 ConditionalField( 

2876 PacketLenField( 

2877 "error", KRB_ERROR(), KRB_ERROR, length_from=lambda pkt: pkt.len - 6 

2878 ), 

2879 lambda pkt: pkt.apreqlen == 0, 

2880 ), 

2881 ] 

2882 

2883 def post_build(self, p, pay): 

2884 if self.len is None: 

2885 p = struct.pack("!H", len(p)) + p[2:] 

2886 if self.apreqlen is None and self.krbpriv is not None: 

2887 p = p[:4] + struct.pack("!H", len(self.apreq)) + p[6:] 

2888 return p + pay 

2889 

2890 

2891class ChangePasswdData(ASN1_Packet): 

2892 ASN1_codec = ASN1_Codecs.BER 

2893 ASN1_root = ASN1F_SEQUENCE( 

2894 ASN1F_STRING("newpasswd", ASN1_STRING(""), explicit_tag=0xA0), 

2895 ASN1F_optional( 

2896 ASN1F_PACKET("targname", None, PrincipalName, explicit_tag=0xA1) 

2897 ), 

2898 ASN1F_optional(Realm("targrealm", None, explicit_tag=0xA2)), 

2899 ) 

2900 

2901 

2902class KPASSWD_REP(Packet): 

2903 fields_desc = [ 

2904 ShortField("len", None), 

2905 ShortField("pvno", 0x0001), 

2906 ShortField("apreplen", None), 

2907 PacketLenField( 

2908 "aprep", KRB_AP_REP(), KRB_AP_REP, length_from=lambda pkt: pkt.apreplen 

2909 ), 

2910 ConditionalField( 

2911 PacketLenField( 

2912 "krbpriv", 

2913 KRB_PRIV(), 

2914 KRB_PRIV, 

2915 length_from=lambda pkt: pkt.len - 6 - pkt.apreplen, 

2916 ), 

2917 lambda pkt: pkt.apreplen != 0, 

2918 ), 

2919 ConditionalField( 

2920 PacketLenField( 

2921 "error", KRB_ERROR(), KRB_ERROR, length_from=lambda pkt: pkt.len - 6 

2922 ), 

2923 lambda pkt: pkt.apreplen == 0, 

2924 ), 

2925 ] 

2926 

2927 def post_build(self, p, pay): 

2928 if self.len is None: 

2929 p = struct.pack("!H", len(p)) + p[2:] 

2930 if self.apreplen is None and self.krbpriv is not None: 

2931 p = p[:4] + struct.pack("!H", len(self.aprep)) + p[6:] 

2932 return p + pay 

2933 

2934 def answers(self, other): 

2935 return isinstance(other, KPASSWD_REQ) 

2936 

2937 

2938KPASSWD_RESULTS = { 

2939 0: "KRB5_KPASSWD_SUCCESS", 

2940 1: "KRB5_KPASSWD_MALFORMED", 

2941 2: "KRB5_KPASSWD_HARDERROR", 

2942 3: "KRB5_KPASSWD_AUTHERROR", 

2943 4: "KRB5_KPASSWD_SOFTERROR", 

2944 5: "KRB5_KPASSWD_ACCESSDENIED", 

2945 6: "KRB5_KPASSWD_BAD_VERSION", 

2946 7: "KRB5_KPASSWD_INITIAL_FLAG_NEEDED", 

2947} 

2948 

2949 

2950class DOMAIN_PASSWORD_INFORMATION(Packet): 

2951 # [MS-SAMR] sect 2.2.3.5 

2952 fields_desc = [ 

2953 IntField("MinPasswordLength", 0), 

2954 IntField("PasswordHistoryLength", 0), 

2955 FlagsField( 

2956 "PasswordProperties", 

2957 0, 

2958 32, 

2959 { 

2960 0x00000001: "DOMAIN_PASSWORD_COMPLEX", 

2961 0x00000002: "DOMAIN_PASSWORD_NO_ANON_CHANGE", 

2962 0x00000004: "DOMAIN_PASSWORD_NO_CLEAR_CHANGE", 

2963 0x00000008: "DOMAIN_LOCKOUT_ADMINS", 

2964 0x00000010: "DOMAIN_PASSWORD_STORE_CLEARTEXT", 

2965 0x00000020: "DOMAIN_REFUSE_PASSWORD_CHANGE", 

2966 0x00000040: "DOMAIN_NO_LM_OWF_CHANGE", 

2967 }, 

2968 ), 

2969 ScalingField("MaxPasswordAge", 30 * 24 * 3600, scaling=1 / 1e7, fmt="!Q"), 

2970 ScalingField("MinPasswordAge", 0, scaling=1 / 1e7, fmt="!Q"), 

2971 ] 

2972 

2973 

2974class KPasswdResult(Packet): 

2975 # This is guessed from looking at MIT's implementation + ntsecapi.h 

2976 fields_desc = [ 

2977 ShortField("PasswordInfoValid", 0), 

2978 PacketField( 

2979 "DomainPasswordInfo", 

2980 DOMAIN_PASSWORD_INFORMATION(), 

2981 DOMAIN_PASSWORD_INFORMATION, 

2982 ), 

2983 ] 

2984 

2985 

2986class _KPasswdRepDataResult_Field(StrField): 

2987 def m2i(self, pkt, s): 

2988 val = super(_KPasswdRepDataResult_Field, self).m2i(pkt, s) 

2989 if len(val or b"") == 30: 

2990 # A 30 octets blob is most likely the AD policy block 

2991 return KPasswdResult(val) 

2992 return val 

2993 

2994 

2995class KPasswdRepData(Packet): 

2996 fields_desc = [ 

2997 ShortEnumField("resultCode", 0, KPASSWD_RESULTS), 

2998 _KPasswdRepDataResult_Field("resultString", ""), 

2999 ] 

3000 

3001 

3002class Kpasswd(Packet): 

3003 @classmethod 

3004 def dispatch_hook(cls, _pkt=None, *args, **kargs): 

3005 if _pkt and len(_pkt) >= 4: 

3006 if _pkt[2:4] == b"\xff\x80": 

3007 return KPASSWD_REQ 

3008 elif _pkt[2:4] == b"\x00\x01": 

3009 asn1_tag = BER_id_dec(_pkt[6:8])[0] & 0x1F 

3010 if asn1_tag == 14: 

3011 return KPASSWD_REQ 

3012 elif asn1_tag == 15: 

3013 return KPASSWD_REP 

3014 return KPASSWD_REQ 

3015 

3016 

3017bind_bottom_up(UDP, Kpasswd, sport=464) 

3018bind_bottom_up(UDP, Kpasswd, dport=464) 

3019bind_top_down(UDP, KPASSWD_REQ, sport=464, dport=464) 

3020bind_top_down(UDP, KPASSWD_REP, sport=464, dport=464) 

3021 

3022 

3023class KpasswdTCPHeader(Packet): 

3024 fields_desc = [LenField("len", None, fmt="!I")] 

3025 

3026 @classmethod 

3027 def tcp_reassemble(cls, data, *args, **kwargs): 

3028 if len(data) < 4: 

3029 return None 

3030 length = struct.unpack("!I", data[:4])[0] 

3031 if len(data) == length + 4: 

3032 return cls(data) 

3033 if len(data) > length + 4: 

3034 return cls(data[: length + 4]) / conf.padding_layer(data[length + 4 :]) 

3035 

3036 

3037bind_layers(KpasswdTCPHeader, Kpasswd) 

3038 

3039bind_bottom_up(TCP, KpasswdTCPHeader, sport=464) 

3040bind_layers(TCP, KpasswdTCPHeader, dport=464) 

3041 

3042# [MS-KKDCP] 

3043 

3044 

3045class KDC_PROXY_MESSAGE(ASN1_Packet): 

3046 ASN1_codec = ASN1_Codecs.BER 

3047 ASN1_root = ASN1F_SEQUENCE( 

3048 ASN1F_STRING_ENCAPS( 

3049 "kerbMessage", 

3050 KerberosTCPHeader(), 

3051 KerberosTCPHeader, 

3052 explicit_tag=0xA0, 

3053 ), 

3054 ASN1F_optional(Realm("targetDomain", None, explicit_tag=0xA1)), 

3055 ASN1F_optional( 

3056 ASN1F_FLAGS( 

3057 "dclocatorHint", 

3058 None, 

3059 _GetDcName_Flags, 

3060 explicit_tag=0xA2, 

3061 ) 

3062 ), 

3063 ) 

3064 

3065 

3066class KdcProxySocket(SuperSocket): 

3067 """ 

3068 This is a wrapper of a HTTP_Client that does KKDCP proxying, 

3069 disguised as a SuperSocket to be compatible with the rest of the KerberosClient. 

3070 """ 

3071 

3072 def __init__( 

3073 self, 

3074 url, 

3075 targetDomain, 

3076 dclocatorHint=None, 

3077 no_check_certificate=False, 

3078 **kwargs, 

3079 ): 

3080 self.url = url 

3081 self.targetDomain = targetDomain 

3082 self.dclocatorHint = dclocatorHint 

3083 self.no_check_certificate = no_check_certificate 

3084 self.queue = deque() 

3085 super(KdcProxySocket, self).__init__(**kwargs) 

3086 

3087 def recv(self, x=None): 

3088 return self.queue.popleft() 

3089 

3090 def send(self, x, **kwargs): 

3091 from scapy.layers.http import HTTP_Client 

3092 

3093 cli = HTTP_Client(no_check_certificate=self.no_check_certificate) 

3094 try: 

3095 # sr it via the web client 

3096 resp = cli.request( 

3097 self.url, 

3098 Method="POST", 

3099 data=bytes( 

3100 # Wrap request in KDC_PROXY_MESSAGE 

3101 KDC_PROXY_MESSAGE( 

3102 kerbMessage=bytes(x), 

3103 targetDomain=ASN1_GENERAL_STRING(self.targetDomain.encode()), 

3104 # dclocatorHint is optional 

3105 dclocatorHint=self.dclocatorHint, 

3106 ) 

3107 ), 

3108 http_headers={ 

3109 "Cache-Control": "no-cache", 

3110 "Pragma": "no-cache", 

3111 "User-Agent": "kerberos/1.0", 

3112 }, 

3113 ) 

3114 if resp and conf.raw_layer in resp: 

3115 # Parse the payload 

3116 resp = KDC_PROXY_MESSAGE(resp.load).kerbMessage 

3117 # We have an answer, queue it. 

3118 self.queue.append(resp) 

3119 else: 

3120 raise EOFError 

3121 finally: 

3122 cli.close() 

3123 

3124 @staticmethod 

3125 def select(sockets, remain=None): 

3126 return [x for x in sockets if isinstance(x, KdcProxySocket) and x.queue] 

3127 

3128 

3129class IAKerbSocket(SuperSocket): 

3130 """ 

3131 Wrapper to forward messages back to our SPNEGO caller. 

3132 """ 

3133 

3134 def __init__( 

3135 self, 

3136 Context, 

3137 realm: str, 

3138 **kwargs, 

3139 ): 

3140 self.Context = Context 

3141 self.realm = realm.upper() 

3142 self.incoming = ObjectPipe("iak_incoming") 

3143 self.results = ObjectPipe("iak_results") 

3144 self.t = None 

3145 super(IAKerbSocket, self).__init__(**kwargs) 

3146 

3147 def recv(self, n=0, options=socket.MsgFlag(0)): 

3148 """ 

3149 recv when acting as a socket 

3150 """ 

3151 return self.incoming.recv(n=n, options=options) 

3152 

3153 def send(self, x, **kwargs): 

3154 """ 

3155 send when acting as a socket 

3156 """ 

3157 x = x[KerberosTCPHeader].payload 

3158 

3159 # Wrap in the IAKERB header 

3160 pkt = KRB_GSSAPI_Token( 

3161 MechType="1.3.6.1.5.2.5", # Kerberos 5 - IAKERB 

3162 innerToken=KRB_InnerToken( 

3163 TOK_ID=b"\x05\x01", 

3164 root=IAKERB_HEADER( 

3165 targetRealm=ASN1_UTF8_STRING( 

3166 self.realm, 

3167 ), 

3168 headerFlags="DS_FORCE_REDISCOVERY", 

3169 ) 

3170 / x, 

3171 ), 

3172 ) 

3173 self.results.send( 

3174 ( 

3175 self.Context, 

3176 pkt, 

3177 GSS_S_CONTINUE_NEEDED, 

3178 ) 

3179 ) 

3180 

3181 def handler(self, func, **kwargs): 

3182 """ 

3183 Handler to catch exceptions as part of the IAKerb socket thread 

3184 """ 

3185 try: 

3186 # Call initial function 

3187 result = func(**kwargs) 

3188 

3189 # Send result 

3190 self.results.send(result) 

3191 

3192 # If this isn't a GSS_S_CONTINUE_NEEDED status, then 

3193 # the IAKERB part is done ! (failure or success) 

3194 _, _, status = result 

3195 if status != GSS_S_CONTINUE_NEEDED: 

3196 self.Context.IAKerbSocket = None 

3197 self.shutdown() 

3198 

3199 except Exception as ex: 

3200 self.results.send(ex) 

3201 

3202 def run(self, func, **kwargs): 

3203 """ 

3204 Run the sub-function asynchronously as part of this IAKerb socket 

3205 """ 

3206 self.t = threading.Thread(target=self.handler, args=(func,), kwargs=kwargs) 

3207 self.t.start() 

3208 

3209 def unpack(self, input_token): 

3210 """ 

3211 Extract Kerberos token from IAKERB if it is, or return None if it's not 

3212 an IAKERB token. 

3213 """ 

3214 try: 

3215 # GSSAPI wrapping 

3216 input_token = input_token.root 

3217 except AttributeError: 

3218 pass 

3219 

3220 if input_token.MechType.val == "1.3.6.1.5.2.5": 

3221 return input_token.innerToken.payload 

3222 

3223 return None 

3224 

3225 def next(self, input_token=None): 

3226 """ 

3227 Called by GSS_Init_sec_context when the input token is a IAKERB proxy. 

3228 """ 

3229 if input_token is not None: 

3230 # Make available in the incoming buffer of the socket 

3231 self.incoming.send(input_token) 

3232 

3233 # Now wait for a response that the client will generate 

3234 try: 

3235 res = self.results.recv() 

3236 except IndexError: 

3237 raise EOFError 

3238 if isinstance(res, Exception): 

3239 # We also get the exceptions back from the thread 

3240 raise res 

3241 return res 

3242 

3243 def close(self): 

3244 # We don't want this to be closed when used as a socket. 

3245 pass 

3246 

3247 def shutdown(self): 

3248 self.incoming.close() 

3249 self.results.close() 

3250 

3251 def __del__(self): 

3252 self.shutdown() 

3253 

3254 @staticmethod 

3255 def select(sockets, remain=None): 

3256 mapping = {x.incoming: x for x in sockets if isinstance(x, IAKerbSocket)} 

3257 return [mapping[x] for x in ObjectPipe.select(mapping.keys(), remain=remain)] 

3258 

3259 

3260# Util functions 

3261 

3262 

3263class PKINIT_KEX_METHOD(IntEnum): 

3264 DIFFIE_HELLMAN = 1 

3265 PUBLIC_KEY = 2 

3266 

3267 

3268class KerberosClient(Automaton): 

3269 """ 

3270 Implementation of a Kerberos client. 

3271 

3272 Prefer to use the ``krb_as_req`` and ``krb_tgs_req`` functions which 

3273 wrap this client. 

3274 

3275 Common parameters: 

3276 

3277 :param mode: the mode to use for the client (default: AS_REQ). 

3278 :param ip: the IP of the DC (default: discovered by dclocator) 

3279 :param upn: the UPN of the client. 

3280 :param canonicalize: request the UPN to be canonicalized. 

3281 :param password: the password of the client. 

3282 :param key: the Key of the client (instead of the password) 

3283 :param realm: the realm of the domain. (default: from the UPN) 

3284 :param host: the name of the host doing the request 

3285 :param port: the Kerberos port (default 88) 

3286 :param timeout: timeout of each request (default 5) 

3287 

3288 Advanced common parameters: 

3289 

3290 :param kdc_proxy: specify a KDC proxy url 

3291 :param kdc_proxy_no_check_certificate: do not check the KDC proxy certificate 

3292 :param fast: use FAST armoring 

3293 :param armor_ticket: an external ticket to use for armoring 

3294 :param armor_ticket_upn: the UPN of the client of the armoring ticket 

3295 :param armor_ticket_skey: the session Key object of the armoring ticket 

3296 :param etypes: specify the list of encryption types to support 

3297 :param dhashes: specify the list of supported digest algorithms for PKINIT 

3298 (defaults to ["sha1", "sha256", "sha384", "sha512"]) 

3299 

3300 AS-REQ only: 

3301 

3302 :param x509: a X509 certificate to use for PKINIT AS_REQ or S4U2Proxy 

3303 :param x509key: the private key of the X509 certificate (in an AS_REQ) 

3304 :param ca: the CA list that verifies the peer (KDC) certificate. Typically 

3305 only the ROOT CA is required. 

3306 :param p12: (optional) use a pfx/p12 instead of x509 and x509key. In this case, 

3307 'password' is the password of the p12. 

3308 :param pkinit_kex_method: (advanced) whether to use the DIFFIE-HELLMAN method or the 

3309 Certificate based one for PKINIT. 

3310 

3311 TGS-REQ only: 

3312 

3313 :param spn: the SPN to request in a TGS-REQ 

3314 :param ticket: the existing ticket to use in a TGS-REQ 

3315 :param renew: sets the Renew flag in a TGS-REQ 

3316 :param additional_tickets: in U2U or S4U2Proxy, the additional tickets 

3317 :param u2u: sets the U2U flag 

3318 :param for_user: the UPN of another user in TGS-REQ, to do a S4U2Self 

3319 :param s4u2proxy: sets the S4U2Proxy flag 

3320 :param dmsa: sets the 'unconditional delegation' mode for DMSA TGT retrieval 

3321 """ 

3322 

3323 RES_AS_MODE = namedtuple( 

3324 "AS_Result", ["asrep", "sessionkey", "kdcrep", "upn", "pa_type"] 

3325 ) 

3326 RES_TGS_MODE = namedtuple("TGS_Result", ["tgsrep", "sessionkey", "kdcrep", "upn"]) 

3327 

3328 class MODE(IntEnum): 

3329 AS_REQ = 0 

3330 TGS_REQ = 1 

3331 GET_SALT = 2 

3332 

3333 def __init__( 

3334 self, 

3335 mode=MODE.AS_REQ, 

3336 ip: Optional[str] = None, 

3337 upn: Optional[str] = None, 

3338 canonicalize: bool = False, 

3339 password: Optional[str] = None, 

3340 key: Optional["Key"] = None, 

3341 realm: Optional[str] = None, 

3342 x509: Optional[Union[Cert, str]] = None, 

3343 x509key: Optional[Union[PrivKey, str]] = None, 

3344 ca: Optional[Union[CertTree, str]] = None, 

3345 no_verify_cert: bool = False, 

3346 p12: Optional[str] = None, 

3347 spn: Optional[str] = None, 

3348 ticket: Optional[KRB_Ticket] = None, 

3349 host: Optional[str] = None, 

3350 renew: bool = False, 

3351 additional_tickets: List[KRB_Ticket] = [], 

3352 u2u: bool = False, 

3353 for_user: Optional[str] = None, 

3354 s4u2proxy: bool = False, 

3355 dmsa: bool = False, 

3356 kdc_proxy: Optional[str] = None, 

3357 kdc_proxy_no_check_certificate: bool = False, 

3358 iakerb: bool = False, 

3359 iakerb_socket: Optional[IAKerbSocket] = None, 

3360 fast: bool = False, 

3361 armor_ticket: KRB_Ticket = None, 

3362 armor_ticket_upn: Optional[str] = None, 

3363 armor_ticket_skey: Optional["Key"] = None, 

3364 key_list_req: List["EncryptionType"] = [], 

3365 etypes: Optional[List["EncryptionType"]] = None, 

3366 dhashes: Optional[List[str]] = None, 

3367 pkinit_kex_method: PKINIT_KEX_METHOD = PKINIT_KEX_METHOD.DIFFIE_HELLMAN, 

3368 port: int = 88, 

3369 timeout: int = 5, 

3370 verbose: bool = True, 

3371 **kwargs, 

3372 ): 

3373 import scapy.libs.rfc3961 # Trigger error if any # noqa: F401 

3374 from scapy.layers.ldap import dclocator 

3375 

3376 # PKINIT checks 

3377 if p12 is not None: 

3378 # password should be None or bytes 

3379 if isinstance(password, str): 

3380 password = password.encode() 

3381 

3382 # Read p12/pfx. If it fails and no password was provided, prompt and 

3383 # retry once. 

3384 while True: 

3385 try: 

3386 with open(p12, "rb") as fd: 

3387 x509key, x509, _ = pkcs12.load_key_and_certificates( 

3388 fd.read(), 

3389 password=password, 

3390 ) 

3391 break 

3392 except ValueError as ex: 

3393 if password is None: 

3394 # We don't have a password. Prompt and retry. 

3395 try: 

3396 from prompt_toolkit import prompt 

3397 

3398 password = prompt( 

3399 "Enter PKCS12 password: ", is_password=True 

3400 ) 

3401 except ImportError: 

3402 password = input("Enter PKCS12 password: ") 

3403 password = password.encode() 

3404 else: 

3405 raise ex 

3406 

3407 x509 = Cert(cryptography_obj=x509) 

3408 x509key = PrivKey(cryptography_obj=x509key) 

3409 elif x509 and x509key: 

3410 if not isinstance(x509, Cert): 

3411 x509 = Cert(x509) 

3412 if not isinstance(x509key, PrivKey): 

3413 x509key = PrivKey(x509key) 

3414 if ca and not isinstance(ca, CertList): 

3415 ca = CertList(ca) 

3416 if upn is None and x509: 

3417 # For PKINIT, get the UPN from the SAN, if possible and present 

3418 if realm is None: 

3419 raise ValueError( 

3420 "When using PKINIT, you must at least specify the realm= !" 

3421 ) 

3422 for ext in x509.extensions: 

3423 if ext.extnID.val == "2.5.29.17": # subjectAltName 

3424 generalName = ext.extnValue.subjectAltName[0].generalName 

3425 upn = generalName.value.val.decode("utf-8") 

3426 break 

3427 if upn is None: 

3428 raise ValueError( 

3429 "Could not find subjectAltName in certificate !" 

3430 " Please provide a UPN." 

3431 ) 

3432 canonicalize = True 

3433 

3434 # UPN, SPN and realm calculation 

3435 if not upn: 

3436 raise ValueError("Invalid upn") 

3437 if realm is None: 

3438 if mode in [self.MODE.AS_REQ, self.MODE.GET_SALT]: 

3439 _, realm = _parse_upn(upn) 

3440 elif mode == self.MODE.TGS_REQ: 

3441 _, realm = _parse_spn(spn) 

3442 if not realm and ticket: 

3443 # if no realm is specified, but there's a ticket, take the realm 

3444 # of the ticket. 

3445 realm = ticket.realm.val.decode() 

3446 else: 

3447 raise ValueError("Invalid realm") 

3448 if not spn and mode == self.MODE.AS_REQ and realm: 

3449 spn = "krbtgt/" + realm 

3450 elif not spn: 

3451 raise ValueError("Invalid spn") 

3452 

3453 # Extra checks for specific requests 

3454 if mode in [self.MODE.AS_REQ, self.MODE.GET_SALT]: 

3455 if not host: 

3456 raise ValueError("Invalid host") 

3457 if x509 is not None: 

3458 if x509key and not ca: 

3459 if not no_verify_cert: 

3460 raise ValueError( 

3461 "Using PKINIT without specifying the remote CA is unsafe !" 

3462 " Set no_verify_cert=True to bypass this check." 

3463 ) 

3464 else: 

3465 ca = [] 

3466 elif not x509key or not ca: 

3467 raise ValueError("Must provide both 'x509', 'x509key' and 'ca' !") 

3468 elif mode == self.MODE.TGS_REQ: 

3469 if not ticket: 

3470 raise ValueError("Invalid ticket") 

3471 

3472 if not ip and not kdc_proxy and not iakerb: 

3473 # No KDC IP provided. Find it by querying the DNS 

3474 ip = dclocator( 

3475 realm, 

3476 timeout=1, 

3477 # Use connect mode instead of ldap for compatibility 

3478 # with MIT kerberos servers 

3479 mode="connect", 

3480 port=port, 

3481 debug=kwargs.get("debug", 0), 

3482 ).ip 

3483 

3484 # Armoring checks 

3485 if fast: 

3486 if mode == self.MODE.AS_REQ: 

3487 # Requires an external ticket 

3488 if not armor_ticket or not armor_ticket_upn or not armor_ticket_skey: 

3489 raise ValueError( 

3490 "Implicit armoring is not possible on AS-REQ: " 

3491 "please provide the 3 required armor arguments" 

3492 ) 

3493 elif mode == self.MODE.TGS_REQ: 

3494 if armor_ticket and (not armor_ticket_upn or not armor_ticket_skey): 

3495 raise ValueError( 

3496 "Cannot specify armor_ticket without armor_ticket_{upn,skey}" 

3497 ) 

3498 

3499 # Provide default supported encryption types. For SALT mode, we discard 

3500 # the encryption types that don't have a salt. 

3501 if mode == self.MODE.GET_SALT: 

3502 if etypes is not None: 

3503 raise ValueError("Cannot specify etypes in GET_SALT mode !") 

3504 

3505 etypes = [ 

3506 EncryptionType.AES256_CTS_HMAC_SHA1_96, 

3507 EncryptionType.AES128_CTS_HMAC_SHA1_96, 

3508 ] 

3509 elif etypes is None: 

3510 etypes = [ 

3511 EncryptionType.AES256_CTS_HMAC_SHA1_96, 

3512 EncryptionType.AES128_CTS_HMAC_SHA1_96, 

3513 EncryptionType.RC4_HMAC, 

3514 EncryptionType.DES_CBC_MD5, 

3515 ] 

3516 self.etypes = etypes 

3517 

3518 self.mode = mode 

3519 

3520 self.result = None # Result 

3521 

3522 self._timeout = timeout 

3523 self._verbose = verbose 

3524 self._ip = ip 

3525 self._port = port 

3526 self.kdc_proxy = kdc_proxy 

3527 self.kdc_proxy_no_check_certificate = kdc_proxy_no_check_certificate 

3528 self.iakerb = iakerb 

3529 self.iakerb_socket = iakerb_socket 

3530 

3531 if self.mode in [self.MODE.AS_REQ, self.MODE.GET_SALT]: 

3532 self.host = host.upper() 

3533 self.password = password and bytes_encode(password) 

3534 self.spn = spn 

3535 self.upn = upn 

3536 self.canonicalize = canonicalize # Whether we request canonicalization 

3537 self.realm = realm.upper() 

3538 self.x509 = x509 

3539 self.x509key = x509key 

3540 self.pkinit_kex_method = pkinit_kex_method 

3541 self.ticket = ticket 

3542 self.fast = fast 

3543 self.armor_ticket = armor_ticket 

3544 self.armor_ticket_upn = armor_ticket_upn 

3545 self.armor_ticket_skey = armor_ticket_skey 

3546 self.key_list_req = key_list_req 

3547 self.renew = renew 

3548 self.additional_tickets = additional_tickets # U2U + S4U2Proxy 

3549 self.u2u = u2u # U2U 

3550 self.for_user = for_user # FOR-USER 

3551 self.s4u2proxy = s4u2proxy # S4U2Proxy 

3552 self.dmsa = dmsa # DMSA 

3553 self.key = key 

3554 self.subkey = None # In the AP-REQ authenticator 

3555 self.replykey = None # Key used for reply 

3556 # See RFC4120 - sect 7.2.2 

3557 # This marks whether we should follow-up after an EOF 

3558 self.should_followup = False 

3559 # This marks that we sent a FAST-req and are awaiting for an answer 

3560 self.fast_req_sent = False 

3561 # Session parameters 

3562 if self.x509: 

3563 # Windows only assumes it needs a pre-auth when PKINIT is used, 

3564 # otherwise it waits to have a PREAUTH_REQUIRED error first. 

3565 self.pre_auth = True 

3566 else: 

3567 self.pre_auth = False 

3568 self.pa_type = None # preauth-type that's used 

3569 self.fast_rep = None 

3570 self.fast_error = None 

3571 self.fast_skey = None # The random subkey used for fast 

3572 self.fast_armorkey = None # The armor key 

3573 self.fxcookie = None 

3574 self.pkinit_dh_key = None 

3575 self.no_verify_cert = no_verify_cert 

3576 if ca is not None: 

3577 self.pkinit_cms = CMS_Engine(ca) 

3578 else: 

3579 self.pkinit_cms = None 

3580 if dhashes is None: 

3581 self.dhashes = ["sha1", "sha256", "sha384", "sha512"] 

3582 else: 

3583 self.dhashes = dhashes 

3584 

3585 # Launch the client 

3586 sock = self._connect() 

3587 super(KerberosClient, self).__init__( 

3588 sock=sock, 

3589 **kwargs, 

3590 ) 

3591 

3592 def _connect(self): 

3593 """ 

3594 Internal function to bind a socket to the DC. 

3595 This also takes care of an eventual KDC proxy and IAKERB. 

3596 """ 

3597 if self.kdc_proxy: 

3598 # If we are using a KDC Proxy, wrap the socket with the KdcProxySocket, 

3599 # that takes our messages and transport them over HTTP. 

3600 sock = KdcProxySocket( 

3601 url=self.kdc_proxy, 

3602 targetDomain=self.realm, 

3603 no_check_certificate=self.kdc_proxy_no_check_certificate, 

3604 ) 

3605 elif self.iakerb: 

3606 # If we are using IAKERB, use the IAKerbSocket we were given that 

3607 # takes our messages and transport them over GSSAPI. 

3608 sock = self.iakerb_socket 

3609 else: 

3610 sock = socket.socket() 

3611 sock.settimeout(self._timeout) 

3612 sock.connect((self._ip, self._port)) 

3613 sock = StreamSocket(sock, KerberosTCPHeader) 

3614 return sock 

3615 

3616 def send(self, pkt): 

3617 """ 

3618 Sends a wrapped Kerberos packet 

3619 """ 

3620 super(KerberosClient, self).send(KerberosTCPHeader() / pkt) 

3621 

3622 def _show_krb_error(self, error): 

3623 """ 

3624 Displays a Kerberos error 

3625 """ 

3626 if error.root.errorCode == 0x07: 

3627 # KDC_ERR_S_PRINCIPAL_UNKNOWN 

3628 if ( 

3629 isinstance(error.root.eData, KERB_ERROR_UNK) 

3630 and error.root.eData.dataType == -128 

3631 ): 

3632 log_runtime.error( 

3633 "KerberosSSP: KDC requires U2U for SPN '%s' !" % error.root.getSPN() 

3634 ) 

3635 else: 

3636 log_runtime.error( 

3637 "KerberosSSP: KDC_ERR_S_PRINCIPAL_UNKNOWN for SPN '%s'" 

3638 % error.root.getSPN() 

3639 ) 

3640 else: 

3641 log_runtime.error(error.root.sprintf("KerberosSSP: Received %errorCode% !")) 

3642 if self._verbose: 

3643 error.show() 

3644 

3645 def _base_kdc_req(self, now_time): 

3646 """ 

3647 Return the KRB_KDC_REQ_BODY used in both AS-REQ and TGS-REQ 

3648 """ 

3649 kdcreq = KRB_KDC_REQ_BODY( 

3650 etype=[ASN1_INTEGER(x) for x in self.etypes], 

3651 additionalTickets=None, 

3652 # Windows default 

3653 kdcOptions="forwardable+renewable+canonicalize+renewable-ok", 

3654 cname=None, 

3655 realm=ASN1_GENERAL_STRING(self.realm), 

3656 till=ASN1_GENERALIZED_TIME(now_time + timedelta(hours=10)), 

3657 rtime=ASN1_GENERALIZED_TIME(now_time + timedelta(hours=10)), 

3658 nonce=ASN1_INTEGER(RandNum(0, 0x7FFFFFFF)._fix()), 

3659 ) 

3660 if self.renew: 

3661 kdcreq.kdcOptions.set(30, 1) # set 'renew' (bit 30) 

3662 self.request_nonce = kdcreq.nonce.val 

3663 return kdcreq 

3664 

3665 def calc_fast_armorkey(self): 

3666 """ 

3667 Calculate and return the FAST armorkey 

3668 """ 

3669 # Generate a random key of the same type than ticket_skey 

3670 if self.mode == self.MODE.AS_REQ: 

3671 # AS-REQ mode 

3672 self.fast_skey = Key.new_random_key(self.armor_ticket_skey.etype) 

3673 

3674 self.fast_armorkey = KRB_FX_CF2( 

3675 self.fast_skey, 

3676 self.armor_ticket_skey, 

3677 b"subkeyarmor", 

3678 b"ticketarmor", 

3679 ) 

3680 elif self.mode == self.MODE.TGS_REQ: 

3681 # TGS-REQ: 2 cases 

3682 

3683 self.subkey = Key.new_random_key(self.key.etype) 

3684 

3685 if not self.armor_ticket: 

3686 # Case 1: Implicit armoring 

3687 self.fast_armorkey = KRB_FX_CF2( 

3688 self.subkey, 

3689 self.key, 

3690 b"subkeyarmor", 

3691 b"ticketarmor", 

3692 ) 

3693 else: 

3694 # Case 2: Explicit armoring, in "Compounded Identity mode". 

3695 # This is a Microsoft extension: see [MS-KILE] sect 3.3.5.7.4 

3696 

3697 self.fast_skey = Key.new_random_key(self.armor_ticket_skey.etype) 

3698 

3699 explicit_armor_key = KRB_FX_CF2( 

3700 self.fast_skey, 

3701 self.armor_ticket_skey, 

3702 b"subkeyarmor", 

3703 b"ticketarmor", 

3704 ) 

3705 

3706 self.fast_armorkey = KRB_FX_CF2( 

3707 explicit_armor_key, 

3708 self.subkey, 

3709 b"explicitarmor", 

3710 b"tgsarmor", 

3711 ) 

3712 

3713 def _fast_wrap(self, kdc_req, padata, now_time, pa_tgsreq_ap=None): 

3714 """ 

3715 :param kdc_req: the KDC_REQ_BODY to wrap 

3716 :param padata: the list of PADATA to wrap 

3717 :param now_time: the current timestamp used by the client 

3718 """ 

3719 

3720 # Create the PA Fast request wrapper 

3721 pafastreq = PA_FX_FAST_REQUEST( 

3722 armoredData=KrbFastArmoredReq( 

3723 reqChecksum=Checksum(), 

3724 encFastReq=EncryptedData(), 

3725 ) 

3726 ) 

3727 

3728 if self.armor_ticket is not None: 

3729 # EXPLICIT mode only (AS-REQ or TGS-REQ) 

3730 

3731 pafastreq.armoredData.armor = KrbFastArmor( 

3732 armorType=1, # FX_FAST_ARMOR_AP_REQUEST 

3733 armorValue=KRB_AP_REQ( 

3734 ticket=self.armor_ticket, 

3735 authenticator=EncryptedData(), 

3736 ), 

3737 ) 

3738 

3739 # Populate the authenticator. Note the client is the wrapper 

3740 _, crealm = _parse_upn(self.armor_ticket_upn) 

3741 authenticator = KRB_Authenticator( 

3742 crealm=ASN1_GENERAL_STRING(crealm), 

3743 cname=PrincipalName.fromUPN(self.armor_ticket_upn), 

3744 cksum=None, 

3745 ctime=ASN1_GENERALIZED_TIME(now_time), 

3746 cusec=ASN1_INTEGER(0), 

3747 subkey=EncryptionKey.fromKey(self.fast_skey), 

3748 seqNumber=ASN1_INTEGER(0), 

3749 encAuthorizationData=None, 

3750 ) 

3751 pafastreq.armoredData.armor.armorValue.authenticator.encrypt( 

3752 self.armor_ticket_skey, 

3753 authenticator, 

3754 ) 

3755 

3756 # Sign the fast request wrapper 

3757 if self.mode == self.MODE.TGS_REQ: 

3758 # "for a TGS-REQ, it is performed over the type AP- 

3759 # REQ in the PA-TGS-REQ padata of the TGS request" 

3760 pafastreq.armoredData.reqChecksum.make( 

3761 self.fast_armorkey, 

3762 bytes(pa_tgsreq_ap), 

3763 ) 

3764 else: 

3765 # "For an AS-REQ, it is performed over the type KDC-REQ- 

3766 # BODY for the req-body field of the KDC-REQ structure of the 

3767 # containing message" 

3768 pafastreq.armoredData.reqChecksum.make( 

3769 self.fast_armorkey, 

3770 bytes(kdc_req), 

3771 ) 

3772 

3773 # Build and encrypt the Fast request 

3774 fastreq = KrbFastReq( 

3775 padata=padata, 

3776 reqBody=kdc_req, 

3777 ) 

3778 pafastreq.armoredData.encFastReq.encrypt( 

3779 self.fast_armorkey, 

3780 fastreq, 

3781 ) 

3782 

3783 # Return the PADATA 

3784 return PADATA( 

3785 padataType=ASN1_INTEGER(136), # PA-FX-FAST 

3786 padataValue=pafastreq, 

3787 ) 

3788 

3789 def as_req(self): 

3790 now_time = datetime.now(timezone.utc) 

3791 

3792 # 1. Build and populate KDC-REQ 

3793 kdc_req = self._base_kdc_req(now_time=now_time) 

3794 kdc_req.addresses = [ 

3795 HostAddress( 

3796 addrType=ASN1_INTEGER(20), # Netbios 

3797 address=ASN1_STRING(self.host.ljust(16, " ")), 

3798 ) 

3799 ] 

3800 kdc_req.addresses = None 

3801 kdc_req.cname = PrincipalName.fromUPN(self.upn, canonicalize=self.canonicalize) 

3802 kdc_req.sname = PrincipalName.fromSPN(self.spn) 

3803 

3804 # 2. Build the list of PADATA 

3805 padata = [ 

3806 PADATA( 

3807 padataType=ASN1_INTEGER(128), # PA-PAC-REQUEST 

3808 padataValue=PA_PAC_REQUEST(includePac=ASN1_BOOLEAN(-1)), 

3809 ) 

3810 ] 

3811 

3812 # Cookie support 

3813 if self.fxcookie: 

3814 padata.insert( 

3815 0, 

3816 PADATA( 

3817 padataType=133, # PA-FX-COOKIE 

3818 padataValue=self.fxcookie, 

3819 ), 

3820 ) 

3821 

3822 # FAST 

3823 if self.fast: 

3824 # Calculate the armor key 

3825 self.calc_fast_armorkey() 

3826 

3827 # [MS-KILE] sect 3.2.5.5 

3828 # "When sending the AS-REQ, add a PA-PAC-OPTIONS [167]" 

3829 padata.append( 

3830 PADATA( 

3831 padataType=ASN1_INTEGER(167), # PA-PAC-OPTIONS 

3832 padataValue=PA_PAC_OPTIONS( 

3833 options="Claims", 

3834 ), 

3835 ) 

3836 ) 

3837 

3838 # Pre-auth is requested 

3839 if self.pre_auth: 

3840 if self.x509: 

3841 # Special PKINIT (RFC4556) factor 

3842 

3843 # RFC4556 - 3.2.1. Generation of Client Request 

3844 

3845 # RFC4556 - 3.2.1 - (5) AuthPack 

3846 authpack = KRB_AuthPack( 

3847 pkAuthenticator=KRB_PKAuthenticator( 

3848 ctime=ASN1_GENERALIZED_TIME(now_time.replace(microsecond=0)), 

3849 cusec=ASN1_INTEGER(now_time.microsecond), 

3850 nonce=ASN1_INTEGER(RandNum(0, 0x7FFFFFFF)._fix()), 

3851 ), 

3852 clientPublicValue=None, # Used only in DH mode 

3853 supportedCMSTypes=[], 

3854 clientDHNonce=None, 

3855 supportedKDFs=None, 

3856 ) 

3857 

3858 if self.pkinit_kex_method == PKINIT_KEX_METHOD.DIFFIE_HELLMAN: 

3859 # RFC4556 - 3.2.3.1. Diffie-Hellman Key Exchange 

3860 

3861 # We (and Windows) use modp2048 

3862 dh_parameters = _ffdh_groups["modp2048"][0] 

3863 self.pkinit_dh_key = dh_parameters.generate_private_key() 

3864 numbers = dh_parameters.parameter_numbers() 

3865 

3866 # We can't use 'public_bytes' because it's the PKCS#3 format, 

3867 # and we want the DomainParameters format. 

3868 authpack.clientPublicValue = X509_SubjectPublicKeyInfo( 

3869 signatureAlgorithm=X509_AlgorithmIdentifier( 

3870 algorithm=ASN1_OID("dhpublicnumber"), 

3871 parameters=DomainParameters( 

3872 p=ASN1_INTEGER(numbers.p), 

3873 g=ASN1_INTEGER(numbers.g), 

3874 # q: see ERRATA 1 of RFC4556 

3875 q=ASN1_INTEGER(numbers.q or (numbers.p - 1) // 2), 

3876 j=None, 

3877 ), 

3878 ), 

3879 subjectPublicKey=DHPublicKey( 

3880 y=ASN1_INTEGER( 

3881 self.pkinit_dh_key.public_key().public_numbers().y 

3882 ), 

3883 ), 

3884 ) 

3885 elif self.pkinit_kex_method == PKINIT_KEX_METHOD.PUBLIC_KEY: 

3886 # RFC4556 - 3.2.3.2. - Public Key Encryption 

3887 

3888 # Set supportedCMSTypes, supportedKDFs 

3889 authpack.supportedCMSTypes = [ 

3890 X509_AlgorithmIdentifier(algorithm=ASN1_OID(x)) 

3891 for x in [ 

3892 "ecdsa-with-SHA512", 

3893 "ecdsa-with-SHA256", 

3894 "sha512WithRSAEncryption", 

3895 "sha256WithRSAEncryption", 

3896 ] 

3897 ] 

3898 authpack.supportedKDFs = [ 

3899 KDFAlgorithmId(kdfId=ASN1_OID(x)) 

3900 for x in [ 

3901 "id-pkinit-kdf-sha256", 

3902 "id-pkinit-kdf-sha1", 

3903 "id-pkinit-kdf-sha512", 

3904 ] 

3905 ] 

3906 

3907 # XXX UNFINISHED 

3908 raise NotImplementedError 

3909 else: 

3910 raise ValueError 

3911 

3912 # Find a supported digest hash. Windows 25H2 still defaults 

3913 # to SHA1 unless a client policy has been applied. 

3914 dhash = next(iter(self.dhashes)) 

3915 

3916 # Populate paChecksum 

3917 authpack.pkAuthenticator.make_checksum( 

3918 bytes(kdc_req), 

3919 h=dhash, 

3920 ) 

3921 

3922 # Sign the AuthPack 

3923 signedAuthpack = self.pkinit_cms.sign( 

3924 authpack, 

3925 ASN1_OID("id-pkinit-authData"), 

3926 self.x509, 

3927 self.x509key, 

3928 dhash=dhash, 

3929 ) 

3930 

3931 # Build PA-DATA 

3932 self.pa_type = 16 # PA-PK-AS-REQ 

3933 pafactor = PADATA( 

3934 padataType=self.pa_type, 

3935 padataValue=PA_PK_AS_REQ( 

3936 signedAuthpack=signedAuthpack, 

3937 trustedCertifiers=None, 

3938 kdcPkId=None, 

3939 ), 

3940 ) 

3941 

3942 # RFC 4557 extension - OCSP 

3943 padata.insert( 

3944 0, 

3945 PADATA( 

3946 padataType=18, # PA-PK-OCSP-RESPONSE 

3947 ), 

3948 ) 

3949 else: 

3950 # Key-based factor 

3951 

3952 if self.fast: 

3953 # Special FAST factor 

3954 # RFC6113 sect 5.4.6 

3955 

3956 # Calculate the 'challenge key' 

3957 ts_key = KRB_FX_CF2( 

3958 self.fast_armorkey, 

3959 self.key, 

3960 b"clientchallengearmor", 

3961 b"challengelongterm", 

3962 ) 

3963 self.pa_type = 138 # PA-ENCRYPTED-CHALLENGE 

3964 pafactor = PADATA( 

3965 padataType=self.pa_type, 

3966 padataValue=EncryptedData(), 

3967 ) 

3968 else: 

3969 # Usual 'timestamp' factor 

3970 ts_key = self.key 

3971 self.pa_type = 2 # PA-ENC-TIMESTAMP 

3972 pafactor = PADATA( 

3973 padataType=self.pa_type, 

3974 padataValue=EncryptedData(), 

3975 ) 

3976 pafactor.padataValue.encrypt( 

3977 ts_key, 

3978 PA_ENC_TS_ENC( 

3979 patimestamp=ASN1_GENERALIZED_TIME( 

3980 now_time.replace(microsecond=0) 

3981 ), 

3982 pausec=ASN1_INTEGER(now_time.microsecond), 

3983 ), 

3984 ) 

3985 

3986 # Insert Pre-Authentication data 

3987 padata.insert( 

3988 0, 

3989 pafactor, 

3990 ) 

3991 

3992 # FAST support 

3993 if self.fast: 

3994 # We are using RFC6113's FAST armoring. The PADATA's are therefore 

3995 # hidden inside the encrypted section. 

3996 padata = [ 

3997 self._fast_wrap( 

3998 kdc_req=kdc_req, 

3999 padata=padata, 

4000 now_time=now_time, 

4001 ) 

4002 ] 

4003 

4004 # 3. Build the request 

4005 asreq = Kerberos( 

4006 root=KRB_AS_REQ( 

4007 padata=padata, 

4008 reqBody=kdc_req, 

4009 ) 

4010 ) 

4011 

4012 # Note the reply key 

4013 self.replykey = self.key 

4014 

4015 return asreq 

4016 

4017 def tgs_req(self): 

4018 now_time = datetime.now(timezone.utc) 

4019 

4020 # Compute armor key for FAST 

4021 if self.fast: 

4022 self.calc_fast_armorkey() 

4023 

4024 # 1. Build and populate KDC-REQ 

4025 kdc_req = self._base_kdc_req(now_time=now_time) 

4026 kdc_req.sname = PrincipalName.fromSPN(self.spn) 

4027 

4028 # Additional tickets 

4029 if self.additional_tickets: 

4030 kdc_req.additionalTickets = self.additional_tickets 

4031 

4032 # U2U 

4033 if self.u2u: 

4034 kdc_req.kdcOptions.set(28, 1) # set 'enc-tkt-in-skey' (bit 28) 

4035 

4036 # 2. Build the list of PADATA 

4037 padata = [] 

4038 

4039 # [MS-SFU] FOR-USER extension 

4040 if self.for_user is not None: 

4041 # [MS-SFU] note 4: 

4042 # "Windows Vista, Windows Server 2008, Windows 7, and Windows Server 

4043 # 2008 R2 send the PA-S4U-X509-USER padata type alone if the user's 

4044 # certificate is available. 

4045 # If the user's certificate is not available, it sends both the 

4046 # PA-S4U-X509-USER padata type and the PA-FOR-USER padata type. 

4047 # When the PA-S4U-X509-USER padata type is used without the user's 

4048 # certificate, the certificate field is not present." 

4049 

4050 # 1. Add PA_S4U_X509_USER 

4051 pasfux509 = PA_S4U_X509_USER( 

4052 userId=S4UUserID( 

4053 nonce=kdc_req.nonce, 

4054 # [MS-SFU] note 5: 

4055 # "Windows S4U clients always set this option." 

4056 options="USE_REPLY_KEY_USAGE", 

4057 cname=PrincipalName.fromUPN(self.for_user), 

4058 crealm=ASN1_GENERAL_STRING(_parse_upn(self.for_user)[1]), 

4059 subjectCertificate=None, # TODO 

4060 ), 

4061 checksum=Checksum(), 

4062 ) 

4063 

4064 if self.dmsa: 

4065 # DMSA = set UNCONDITIONAL_DELEGATION to 1 

4066 pasfux509.userId.options.set(4, 1) 

4067 

4068 if self.key.etype in [EncryptionType.RC4_HMAC, EncryptionType.RC4_HMAC_EXP]: 

4069 # "if the key's encryption type is RC4_HMAC_NT (23) the checksum type 

4070 # is rsa-md4 (2) as defined in section 6.2.6 of [RFC3961]." 

4071 pasfux509.checksum.make( 

4072 self.subkey or self.key, 

4073 bytes(pasfux509.userId), 

4074 cksumtype=ChecksumType.RSA_MD4, 

4075 ) 

4076 else: 

4077 # Use subkey if available (=subkey), else TGT session key (=key). 

4078 # NB: undocumented right now -- gpo2 

4079 pasfux509.checksum.make( 

4080 self.subkey or self.key, 

4081 bytes(pasfux509.userId), 

4082 ) 

4083 padata.append( 

4084 PADATA( 

4085 padataType=ASN1_INTEGER(130), # PA-FOR-X509-USER 

4086 padataValue=pasfux509, 

4087 ) 

4088 ) 

4089 

4090 # 2. Add PA_FOR_USER 

4091 if True: # XXX user's certificate is not available. 

4092 paforuser = PA_FOR_USER( 

4093 userName=PrincipalName.fromUPN(self.for_user), 

4094 userRealm=ASN1_GENERAL_STRING(_parse_upn(self.for_user)[1]), 

4095 cksum=Checksum(), 

4096 ) 

4097 S4UByteArray = struct.pack( # [MS-SFU] sect 2.2.1 

4098 "<I", paforuser.userName.nameType.val 

4099 ) + ( 

4100 ( 

4101 "".join(x.val for x in paforuser.userName.nameString) 

4102 + paforuser.userRealm.val 

4103 + paforuser.authPackage.val 

4104 ).encode() 

4105 ) 

4106 # Always use TGT session key (=key) 

4107 paforuser.cksum.make( 

4108 self.key, 

4109 S4UByteArray, 

4110 cksumtype=ChecksumType.HMAC_MD5, 

4111 ) 

4112 padata.append( 

4113 PADATA( 

4114 padataType=ASN1_INTEGER(129), # PA-FOR-USER 

4115 padataValue=paforuser, 

4116 ) 

4117 ) 

4118 

4119 # [MS-SFU] S4U2proxy - sect 3.1.5.2.1 

4120 if self.s4u2proxy: 

4121 # "PA-PAC-OPTIONS with resource-based constrained-delegation bit set" 

4122 padata.append( 

4123 PADATA( 

4124 padataType=ASN1_INTEGER(167), # PA-PAC-OPTIONS 

4125 padataValue=PA_PAC_OPTIONS( 

4126 options="Resource-based-constrained-delegation", 

4127 ), 

4128 ) 

4129 ) 

4130 # "kdc-options field: MUST include the new cname-in-addl-tkt options flag" 

4131 kdc_req.kdcOptions.set(14, 1) 

4132 

4133 # [MS-KILE] 2.2.11 KERB-KEY-LIST-REQ 

4134 if self.key_list_req: 

4135 padata.append( 

4136 PADATA( 

4137 padataType=ASN1_INTEGER(161), # KERB-KEY-LIST-REQ 

4138 padataValue=KERB_KEY_LIST_REQ( 

4139 keytypes=[ASN1_INTEGER(x) for x in self.key_list_req] 

4140 ), 

4141 ) 

4142 ) 

4143 

4144 # 3. Build the AP-req inside a PA 

4145 apreq = KRB_AP_REQ(ticket=self.ticket, authenticator=EncryptedData()) 

4146 pa_tgs_req = PADATA( 

4147 padataType=ASN1_INTEGER(1), # PA-TGS-REQ 

4148 padataValue=apreq, 

4149 ) 

4150 

4151 # 4. Populate it's authenticator 

4152 _, crealm = _parse_upn(self.upn) 

4153 authenticator = KRB_Authenticator( 

4154 crealm=ASN1_GENERAL_STRING(crealm), 

4155 cname=PrincipalName.fromUPN(self.upn, canonicalize=self.canonicalize), 

4156 cksum=None, 

4157 ctime=ASN1_GENERALIZED_TIME(now_time.replace(microsecond=0)), 

4158 cusec=ASN1_INTEGER(now_time.microsecond), 

4159 subkey=EncryptionKey.fromKey(self.subkey) if self.subkey else None, 

4160 seqNumber=None, 

4161 encAuthorizationData=None, 

4162 ) 

4163 

4164 # Compute checksum 

4165 if self.key.cksumtype: 

4166 authenticator.cksum = Checksum() 

4167 authenticator.cksum.make( 

4168 self.key, 

4169 bytes(kdc_req), 

4170 ) 

4171 

4172 # Encrypt authenticator 

4173 apreq.authenticator.encrypt(self.key, authenticator) 

4174 

4175 # 5. Process FAST if required 

4176 if self.fast: 

4177 padata = [ 

4178 self._fast_wrap( 

4179 kdc_req=kdc_req, 

4180 padata=padata, 

4181 now_time=now_time, 

4182 pa_tgsreq_ap=apreq, 

4183 ) 

4184 ] 

4185 

4186 # 6. Add the final PADATA 

4187 padata.append(pa_tgs_req) 

4188 

4189 # 7. Build the request 

4190 tgsreq = Kerberos( 

4191 root=KRB_TGS_REQ( 

4192 padata=padata, 

4193 reqBody=kdc_req, 

4194 ) 

4195 ) 

4196 

4197 # Note the reply key 

4198 if self.subkey: 

4199 self.replykey = self.subkey 

4200 else: 

4201 self.replykey = self.key 

4202 

4203 return tgsreq 

4204 

4205 @ATMT.state(initial=1) 

4206 def BEGIN(self): 

4207 pass 

4208 

4209 @ATMT.condition(BEGIN) 

4210 def should_send_as_req(self): 

4211 if self.mode in [self.MODE.AS_REQ, self.MODE.GET_SALT]: 

4212 raise self.SENT_AS_REQ() 

4213 

4214 @ATMT.condition(BEGIN) 

4215 def should_send_tgs_req(self): 

4216 if self.mode == self.MODE.TGS_REQ: 

4217 raise self.SENT_TGS_REQ() 

4218 

4219 @ATMT.action(should_send_as_req) 

4220 def send_as_req(self): 

4221 self.send(self.as_req()) 

4222 

4223 @ATMT.action(should_send_tgs_req) 

4224 def send_tgs_req(self): 

4225 self.send(self.tgs_req()) 

4226 

4227 @ATMT.state() 

4228 def SENT_AS_REQ(self): 

4229 pass 

4230 

4231 @ATMT.state() 

4232 def SENT_TGS_REQ(self): 

4233 pass 

4234 

4235 def _process_padatas_and_key(self, padatas, etype: "EncryptionType" = None): 

4236 """ 

4237 Process the PADATA, and generate missing keys if required. 

4238 

4239 :param etype: (optional) If provided, the EncryptionType to use. 

4240 """ 

4241 salt = b"" 

4242 

4243 if etype is not None and etype not in self.etypes: 

4244 raise ValueError("The answered 'etype' key isn't supported by us !") 

4245 

4246 # 1. Process pa-data 

4247 if padatas is not None: 

4248 for padata in padatas: 

4249 if padata.padataType == 0x13 and etype is None: # PA-ETYPE-INFO2 

4250 # We obtain the salt for hash types that need it 

4251 elt = padata.padataValue.seq[0] 

4252 if elt.etype.val in self.etypes: 

4253 etype = elt.etype.val 

4254 if etype != EncryptionType.RC4_HMAC: 

4255 salt = elt.salt.val 

4256 

4257 elif padata.padataType == 0x11: # PA-PK-AS-REP 

4258 # PKINIT handling 

4259 

4260 # The steps are as follows: 

4261 # 1. Verify and extract the CMS response. The expected type 

4262 # is different depending on the used method. 

4263 # 2. Compute the replykey 

4264 

4265 if self.pkinit_kex_method == PKINIT_KEX_METHOD.DIFFIE_HELLMAN: 

4266 # Unpack KDCDHKeyInfo 

4267 keyinfo = self.pkinit_cms.verify( 

4268 padata.padataValue.rep.dhSignedData, 

4269 eContentType=ASN1_OID("id-pkinit-DHKeyData"), 

4270 no_verify_cert=self.no_verify_cert, 

4271 ekus=[ASN1_OID("id-pkinit-KPKdc")], 

4272 ) 

4273 

4274 # If 'etype' is None, we're in an error. Since we verified 

4275 # the CMS successfully, end here. 

4276 if etype is None: 

4277 continue 

4278 

4279 # Extract crypto parameters 

4280 y = keyinfo.subjectPublicKey.y.val 

4281 

4282 # Import into cryptography 

4283 params = self.pkinit_dh_key.parameters().parameter_numbers() 

4284 pubkey = dh.DHPublicNumbers(y, params).public_key() 

4285 

4286 # Calculate DHSharedSecret 

4287 DHSharedSecret = self.pkinit_dh_key.exchange(pubkey) 

4288 

4289 # RFC4556 3.2.3.1 - AS reply key is derived as follows 

4290 self.replykey = octetstring2key( 

4291 etype, 

4292 DHSharedSecret, 

4293 ) 

4294 

4295 else: 

4296 raise ValueError 

4297 

4298 elif padata.padataType == 111: # TD-CMS-DIGEST-ALGORITHMS 

4299 self.dhashes = [x.algorithm.oidname for x in padata.padataValue.seq] 

4300 

4301 elif padata.padataType == 133: # PA-FX-COOKIE 

4302 # Get cookie and store it 

4303 self.fxcookie = padata.padataValue 

4304 

4305 elif padata.padataType == 136: # PA-FX-FAST 

4306 # FAST handling: get the actual inner message and decrypt it 

4307 if isinstance(padata.padataValue, PA_FX_FAST_REPLY): 

4308 self.fast_rep = ( 

4309 padata.padataValue.armoredData.encFastRep.decrypt( 

4310 self.fast_armorkey, 

4311 ) 

4312 ) 

4313 

4314 elif padata.padataType == 137: # PA-FX-ERROR 

4315 # Get error and store it 

4316 self.fast_error = padata.padataValue 

4317 

4318 elif padata.padataType == 130: # PA-FOR-X509-USER 

4319 # Verify S4U checksum 

4320 key_usage_number = None 

4321 pasfux509 = padata.padataValue 

4322 # [MS-SFU] sect 2.2.2 

4323 # "In a reply, indicates that it was signed with key usage 27" 

4324 if pasfux509.userId.options.val[2] == "1": # USE_REPLY_KEY_USAGE 

4325 key_usage_number = 27 

4326 pasfux509.checksum.verify( 

4327 self.key, 

4328 bytes(pasfux509.userId), 

4329 key_usage_number=key_usage_number, 

4330 ) 

4331 

4332 # 2. Update the current keys if necessary 

4333 

4334 # Compute client key if not already provided 

4335 if self.key is None and etype is not None and self.x509 is None: 

4336 self.key = Key.string_to_key( 

4337 etype, 

4338 self.password, 

4339 salt, 

4340 ) 

4341 

4342 # Strengthen the reply key with the fast reply, if necessary 

4343 if self.fast_rep and self.fast_rep.strengthenKey: 

4344 # "The strengthen-key field MAY be set in an AS reply" 

4345 self.replykey = KRB_FX_CF2( 

4346 self.fast_rep.strengthenKey.toKey(), 

4347 self.replykey, 

4348 b"strengthenkey", 

4349 b"replykey", 

4350 ) 

4351 

4352 @ATMT.receive_condition(SENT_AS_REQ, prio=0) 

4353 def receive_salt_mode(self, pkt): 

4354 # This is only for "Salt-Mode", a mode where we get the salt then 

4355 # exit. 

4356 if self.mode == self.MODE.GET_SALT: 

4357 if Kerberos not in pkt: 

4358 raise self.FINAL() 

4359 if not isinstance(pkt.root, KRB_ERROR): 

4360 log_runtime.error("Pre-auth is likely disabled !") 

4361 raise self.FINAL() 

4362 if pkt.root.errorCode == 25: # KDC_ERR_PREAUTH_REQUIRED 

4363 for padata in pkt.root.eData.seq: 

4364 if padata.padataType == 0x13: # PA-ETYPE-INFO2 

4365 elt = padata.padataValue.seq[0] 

4366 if elt.etype.val in self.etypes: 

4367 self.result = elt.salt.val 

4368 raise self.FINAL() 

4369 else: 

4370 log_runtime.error("Failed to retrieve the salt !") 

4371 raise self.FINAL() 

4372 

4373 @ATMT.receive_condition(SENT_AS_REQ, prio=1) 

4374 def receive_krb_error_as_req(self, pkt): 

4375 # We check for Kerberos errors. 

4376 # There is a special case for PREAUTH_REQUIRED error, which means that preauth 

4377 # is required and we need to do a second exchange. 

4378 if Kerberos in pkt and isinstance(pkt.root, KRB_ERROR): 

4379 # Process PAs if available 

4380 if pkt.root.eData and isinstance(pkt.root.eData, MethodData): 

4381 self._process_padatas_and_key(pkt.root.eData.seq) 

4382 

4383 # Special case for FAST errors 

4384 if self.fast_rep: 

4385 # This is actually a fast response error ! 

4386 frep, self.fast_rep = self.fast_rep, None 

4387 # Re-process PAs 

4388 self._process_padatas_and_key(frep.padata) 

4389 # Extract real Kerberos error from FAST message 

4390 ferr = Kerberos(root=self.fast_error) 

4391 self.fast_error = None 

4392 # Recurse 

4393 self.receive_krb_error_as_req(ferr) 

4394 return 

4395 

4396 if pkt.root.errorCode == 25: # KDC_ERR_PREAUTH_REQUIRED 

4397 if not self.key: 

4398 log_runtime.error( 

4399 "Got 'KDC_ERR_PREAUTH_REQUIRED', " 

4400 "but no possible key could be computed." 

4401 ) 

4402 raise self.FINAL() 

4403 self.should_followup = True 

4404 self.pre_auth = True 

4405 raise self.BEGIN() 

4406 elif pkt.root.errorCode == 80: # KDC_ERR_DIGEST_IN_SIGNED_DATA_NOT_ACCEPTED 

4407 self.should_followup = True 

4408 raise self.BEGIN() 

4409 else: 

4410 self._show_krb_error(pkt) 

4411 raise self.FINAL() 

4412 

4413 @ATMT.receive_condition(SENT_AS_REQ, prio=2) 

4414 def receive_as_rep(self, pkt): 

4415 if Kerberos in pkt and isinstance(pkt.root, KRB_AS_REP): 

4416 raise self.FINAL().action_parameters(pkt) 

4417 

4418 @ATMT.eof(SENT_AS_REQ) 

4419 def retry_after_eof_in_apreq(self): 

4420 if self.should_followup: 

4421 # Reconnect and Restart 

4422 self.should_followup = False 

4423 self.update_sock(self._connect()) 

4424 raise self.BEGIN() 

4425 else: 

4426 log_runtime.error("Socket was closed in an unexpected state") 

4427 raise self.FINAL() 

4428 

4429 @ATMT.action(receive_as_rep) 

4430 def decrypt_as_rep(self, pkt): 

4431 # Process PADATAs. This is important for FAST and PKINIT 

4432 self._process_padatas_and_key( 

4433 pkt.root.padata, 

4434 etype=pkt.root.encPart.etype.val, 

4435 ) 

4436 

4437 if not self.pre_auth: 

4438 log_runtime.warning("Pre-authentication was disabled for this account !") 

4439 

4440 # Process FAST response 

4441 if self.fast_rep: 

4442 # Verify the ticket-checksum 

4443 self.fast_rep.finished.ticketChecksum.verify( 

4444 self.fast_armorkey, 

4445 bytes(pkt.root.ticket), 

4446 ) 

4447 # Process pa of FAST response 

4448 self._process_padatas_and_key( 

4449 self.fast_rep.padata, 

4450 etype=pkt.root.encPart.etype.val, 

4451 ) 

4452 self.fast_rep = None 

4453 elif self.fast: 

4454 raise ValueError("Answer was not FAST ! Is it supported?") 

4455 

4456 # Check for PKINIT 

4457 if self.x509 and self.replykey is None: 

4458 raise ValueError("PKINIT was used but no valid PA-PK-AS-REP was found !") 

4459 

4460 # Decrypt AS-REP response 

4461 enc = pkt.root.encPart 

4462 res = enc.decrypt(self.replykey) 

4463 if res.nonce.val != self.request_nonce: 

4464 raise ValueError("KDC reply nonce does not match request") 

4465 self.result = self.RES_AS_MODE( 

4466 pkt.root, 

4467 res.key.toKey(), 

4468 res, 

4469 pkt.root.getUPN(), 

4470 self.pa_type, 

4471 ) 

4472 

4473 @ATMT.receive_condition(SENT_TGS_REQ) 

4474 def receive_krb_error_tgs_req(self, pkt): 

4475 if Kerberos in pkt and isinstance(pkt.root, KRB_ERROR): 

4476 # Process PAs if available 

4477 if pkt.root.eData and isinstance(pkt.root.eData, MethodData): 

4478 self._process_padatas_and_key(pkt.root.eData.seq) 

4479 

4480 if self.fast_rep: 

4481 # This is actually a fast response error ! 

4482 frep, self.fast_rep = self.fast_rep, None 

4483 # Re-process PAs 

4484 self._process_padatas_and_key(frep.padata) 

4485 # Extract real Kerberos error from FAST message 

4486 ferr = Kerberos(root=self.fast_error) 

4487 self.fast_error = None 

4488 # Recurse 

4489 self.receive_krb_error_tgs_req(ferr) 

4490 return 

4491 

4492 self._show_krb_error(pkt) 

4493 raise self.FINAL() 

4494 

4495 @ATMT.receive_condition(SENT_TGS_REQ) 

4496 def receive_tgs_rep(self, pkt): 

4497 if Kerberos in pkt and isinstance(pkt.root, KRB_TGS_REP): 

4498 if ( 

4499 not self.renew 

4500 and not self.dmsa 

4501 and pkt.root.ticket.sname.nameString[0].val == b"krbtgt" 

4502 ): 

4503 log_runtime.warning("Received a cross-realm referral ticket !") 

4504 raise self.FINAL().action_parameters(pkt) 

4505 

4506 @ATMT.action(receive_tgs_rep) 

4507 def decrypt_tgs_rep(self, pkt): 

4508 self._process_padatas_and_key(pkt.root.padata) 

4509 

4510 # Process FAST response 

4511 if self.fast_rep: 

4512 # Verify the ticket-checksum 

4513 self.fast_rep.finished.ticketChecksum.verify( 

4514 self.fast_armorkey, 

4515 bytes(pkt.root.ticket), 

4516 ) 

4517 self.fast_rep = None 

4518 elif self.fast: 

4519 raise ValueError("Answer was not FAST ! Is it supported?") 

4520 

4521 # Decrypt TGS-REP response 

4522 enc = pkt.root.encPart 

4523 if self.subkey: 

4524 # "In a TGS-REP message, the key 

4525 # usage value is 8 if the TGS session key is used, or 9 if a TGS 

4526 # authenticator subkey is used." 

4527 res = enc.decrypt(self.replykey, key_usage_number=9, cls=EncTGSRepPart) 

4528 else: 

4529 res = enc.decrypt(self.replykey) 

4530 

4531 if res.nonce.val != self.request_nonce: 

4532 raise ValueError("KDC reply nonce does not match request") 

4533 

4534 # Store result 

4535 self.result = self.RES_TGS_MODE( 

4536 pkt.root, 

4537 res.key.toKey(), 

4538 res, 

4539 self.upn, 

4540 ) 

4541 

4542 @ATMT.state(final=1) 

4543 def FINAL(self): 

4544 pass 

4545 

4546 

4547def _parse_upn(upn): 

4548 """ 

4549 Extract the username and realm from full UPN 

4550 """ 

4551 m = re.match(r"^([^@\\/]+)(@|\\)([^@\\/]+)$", upn) 

4552 if not m: 

4553 err = "Invalid UPN: '%s'" % upn 

4554 if "/" in upn: 

4555 err += ". Did you mean '%s' ?" % upn.replace("/", "\\") 

4556 elif "@" not in upn and "\\" not in upn: 

4557 err += ". Provide domain as so: '%s@domain.local'" % upn 

4558 raise ValueError(err) 

4559 if m.group(2) == "@": 

4560 user = m.group(1) 

4561 domain = m.group(3) 

4562 else: 

4563 user = m.group(3) 

4564 domain = m.group(1) 

4565 return user, domain 

4566 

4567 

4568def _parse_spn(spn): 

4569 """ 

4570 Extract ServiceName and realm from full SPN 

4571 """ 

4572 # See [MS-ADTS] sect 2.2.21 for SPN format. We discard the servicename. 

4573 m = re.match(r"^((?:[^@\\/]+)/(?:[^@\\/]+))(?:/[^@\\/]+)?(?:@([^@\\/]+))?$", spn) 

4574 if not m: 

4575 try: 

4576 # If SPN is a UPN, we are doing U2U :D 

4577 return _parse_upn(spn) 

4578 except ValueError: 

4579 raise ValueError("Invalid SPN: '%s'" % spn) 

4580 return m.group(1), m.group(2) 

4581 

4582 

4583def _spn_are_equal(spn1, spn2): 

4584 """ 

4585 Check that two SPNs are equal. 

4586 """ 

4587 spn1, _ = _parse_spn(spn1) 

4588 spn2, _ = _parse_spn(spn2) 

4589 return spn1.lower() == spn2.lower() 

4590 

4591 

4592def krb_as_req( 

4593 upn: Optional[str] = None, 

4594 spn: Optional[str] = None, 

4595 ip: Optional[str] = None, 

4596 key: Optional["Key"] = None, 

4597 password: Optional[str] = None, 

4598 realm: Optional[str] = None, 

4599 host: str = "WIN10", 

4600 p12: Optional[str] = None, 

4601 x509: Optional[Union[str, Cert]] = None, 

4602 x509key: Optional[Union[str, PrivKey]] = None, 

4603 **kwargs, 

4604): 

4605 r""" 

4606 Kerberos AS-Req 

4607 

4608 :param upn: the user principal name formatted as "DOMAIN\user", "DOMAIN/user" 

4609 or "user@DOMAIN" 

4610 :param spn: (optional) the full service principal name. 

4611 Defaults to "krbtgt/<realm>" 

4612 :param ip: the KDC ip. (optional. If not provided, Scapy will query the DNS for 

4613 _kerberos._tcp.dc._msdcs.domain.local). 

4614 :param key: (optional) pass the Key object. 

4615 :param password: (optional) otherwise, pass the user's password 

4616 :param x509: (optional) pass a x509 certificate for PKINIT. 

4617 :param x509key: (optional) pass the private key of the x509 certificate for PKINIT. 

4618 :param p12: (optional) use a pfx/p12 instead of x509 and x509key. In this case, 

4619 'password' is the password of the p12. 

4620 :param realm: (optional) the realm to use. Otherwise use the one from UPN. 

4621 :param host: (optional) the host performing the AS-Req. WIN10 by default. 

4622 

4623 :return: returns a named tuple (asrep=<...>, sessionkey=<...>) 

4624 

4625 Example:: 

4626 

4627 >>> # The KDC is found via DC Locator, we ask a TGT for user1 

4628 >>> krb_as_req("user1@DOMAIN.LOCAL", password="Password1") 

4629 

4630 Equivalent:: 

4631 

4632 >>> from scapy.libs.rfc3961 import Key, EncryptionType 

4633 >>> key = Key(EncryptionType.AES256_CTS_HMAC_SHA1_96, key=hex_bytes("6d0748c546 

4634 ...: f4e99205e78f8da7681d4ec5520ae4815543720c2a647c1ae814c9")) 

4635 >>> krb_as_req("user1@DOMAIN.LOCAL", ip="192.168.122.17", key=key) 

4636 

4637 Example using PKINIT with a p12 ("password" is the password of the p12):: 

4638 

4639 >>> krb_as_req(p12="./store.p12", realm="DOMAIN.LOCAL", password="password") 

4640 """ 

4641 if key is None and p12 is None and x509 is None: 

4642 if password is None: 

4643 try: 

4644 from prompt_toolkit import prompt 

4645 

4646 password = prompt("Enter password: ", is_password=True) 

4647 except ImportError: 

4648 password = input("Enter password: ") 

4649 cli = KerberosClient( 

4650 mode=KerberosClient.MODE.AS_REQ, 

4651 realm=realm, 

4652 ip=ip, 

4653 spn=spn, 

4654 host=host, 

4655 upn=upn, 

4656 password=password, 

4657 key=key, 

4658 p12=p12, 

4659 x509=x509, 

4660 x509key=x509key, 

4661 **kwargs, 

4662 ) 

4663 cli.run() 

4664 cli.stop() 

4665 return cli.result 

4666 

4667 

4668def krb_tgs_req( 

4669 upn, 

4670 spn, 

4671 sessionkey, 

4672 ticket, 

4673 ip=None, 

4674 renew=False, 

4675 realm=None, 

4676 additional_tickets=[], 

4677 u2u=False, 

4678 etypes=None, 

4679 for_user=None, 

4680 s4u2proxy=False, 

4681 **kwargs, 

4682): 

4683 r""" 

4684 Kerberos TGS-Req 

4685 

4686 :param upn: the user principal name formatted as "DOMAIN\user", "DOMAIN/user" 

4687 or "user@DOMAIN" 

4688 :param spn: the full service principal name (e.g. "cifs/srv1") 

4689 :param sessionkey: the session key retrieved from the tgt 

4690 :param ticket: the tgt ticket 

4691 :param ip: the KDC ip. (optional. If not provided, Scapy will query the DNS for 

4692 _kerberos._tcp.dc._msdcs.domain.local). 

4693 :param renew: ask for renewal 

4694 :param realm: (optional) the realm to use. Otherwise use the one from SPN. 

4695 :param additional_tickets: (optional) a list of additional tickets to pass. 

4696 :param u2u: (optional) if specified, enable U2U and request the ticket to be 

4697 signed using the session key from the first additional ticket. 

4698 :param etypes: array of EncryptionType values. 

4699 By default: AES128, AES256, RC4, DES_MD5 

4700 :param for_user: a user principal name to request the ticket for. This is the 

4701 S4U2Self extension. 

4702 

4703 :return: returns a named tuple (tgsrep=<...>, sessionkey=<...>) 

4704 

4705 Example:: 

4706 

4707 >>> # The KDC is on 192.168.122.17, we ask a TGT for user1 

4708 >>> krb_as_req("user1@DOMAIN.LOCAL", "192.168.122.17", password="Password1") 

4709 

4710 Equivalent:: 

4711 

4712 >>> from scapy.libs.rfc3961 import Key, EncryptionType 

4713 >>> key = Key(EncryptionType.AES256_CTS_HMAC_SHA1_96, key=hex_bytes("6d0748c546 

4714 ...: f4e99205e78f8da7681d4ec5520ae4815543720c2a647c1ae814c9")) 

4715 >>> krb_as_req("user1@DOMAIN.LOCAL", "192.168.122.17", key=key) 

4716 """ 

4717 cli = KerberosClient( 

4718 mode=KerberosClient.MODE.TGS_REQ, 

4719 realm=realm, 

4720 upn=upn, 

4721 ip=ip, 

4722 spn=spn, 

4723 key=sessionkey, 

4724 ticket=ticket, 

4725 renew=renew, 

4726 additional_tickets=additional_tickets, 

4727 u2u=u2u, 

4728 etypes=etypes, 

4729 for_user=for_user, 

4730 s4u2proxy=s4u2proxy, 

4731 **kwargs, 

4732 ) 

4733 cli.run() 

4734 cli.stop() 

4735 return cli.result 

4736 

4737 

4738def krb_as_and_tgs(upn, spn, ip=None, key=None, password=None, **kwargs): 

4739 """ 

4740 Kerberos AS-Req then TGS-Req 

4741 """ 

4742 res = krb_as_req(upn=upn, ip=ip, key=key, password=password, **kwargs) 

4743 if not res: 

4744 return 

4745 

4746 return krb_tgs_req( 

4747 upn=res.upn, # UPN might get canonicalized 

4748 spn=spn, 

4749 sessionkey=res.sessionkey, 

4750 ticket=res.asrep.ticket, 

4751 ip=ip, 

4752 **kwargs, 

4753 ) 

4754 

4755 

4756def krb_get_salt(upn, ip=None, realm=None, host="WIN10", **kwargs): 

4757 """ 

4758 Kerberos AS-Req only to get the salt associated with the UPN. 

4759 """ 

4760 if realm is None: 

4761 _, realm = _parse_upn(upn) 

4762 cli = KerberosClient( 

4763 mode=KerberosClient.MODE.GET_SALT, 

4764 realm=realm, 

4765 ip=ip, 

4766 spn="krbtgt/" + realm, 

4767 upn=upn, 

4768 host=host, 

4769 **kwargs, 

4770 ) 

4771 cli.run() 

4772 cli.stop() 

4773 return cli.result 

4774 

4775 

4776def kpasswd( 

4777 upn, 

4778 targetupn=None, 

4779 ip=None, 

4780 password=None, 

4781 newpassword=None, 

4782 key=None, 

4783 ticket=None, 

4784 realm=None, 

4785 ssp=None, 

4786 setpassword=None, 

4787 timeout=3, 

4788 port=464, 

4789 debug=0, 

4790 **kwargs, 

4791): 

4792 """ 

4793 Change a password using RFC3244's Kerberos Set / Change Password. 

4794 

4795 :param upn: the UPN to use for authentication 

4796 :param targetupn: (optional) the UPN to change the password of. If not specified, 

4797 same as upn. 

4798 :param ip: the KDC ip. (optional. If not provided, Scapy will query the DNS for 

4799 _kerberos._tcp.dc._msdcs.domain.local). 

4800 :param key: (optional) pass the Key object. 

4801 :param ticket: (optional) a ticket to use. Either a TGT or ST for kadmin/changepw. 

4802 :param password: (optional) otherwise, pass the user's password 

4803 :param realm: (optional) the realm to use. Otherwise use the one from UPN. 

4804 :param setpassword: (optional) use "Set Password" mechanism. 

4805 :param ssp: (optional) a Kerberos SSP for the service kadmin/changepw@REALM. 

4806 If provided, you probably don't need anything else. Otherwise built. 

4807 """ 

4808 from scapy.layers.ldap import dclocator 

4809 

4810 if not realm: 

4811 _, realm = _parse_upn(upn) 

4812 spn = "kadmin/changepw@%s" % realm 

4813 if ip is None: 

4814 ip = dclocator( 

4815 realm, 

4816 timeout=timeout, 

4817 # Use connect mode instead of ldap for compatibility 

4818 # with MIT kerberos servers 

4819 mode="connect", 

4820 port=port, 

4821 debug=debug, 

4822 ).ip 

4823 if ssp is None and ticket is not None: 

4824 tktspn = ticket.getSPN().split("/")[0] 

4825 assert tktspn in ["krbtgt", "kadmin"], "Unexpected ticket type ! %s" % tktspn 

4826 if tktspn == "krbtgt": 

4827 log_runtime.info( 

4828 "Using 'Set Password' mode. This only works with admin privileges." 

4829 ) 

4830 setpassword = True 

4831 resp = krb_tgs_req( 

4832 upn=upn, 

4833 spn=spn, 

4834 ticket=ticket, 

4835 sessionkey=key, 

4836 ip=ip, 

4837 debug=debug, 

4838 ) 

4839 if resp is None: 

4840 return 

4841 ticket = resp.tgsrep.ticket 

4842 key = resp.sessionkey 

4843 if setpassword is None: 

4844 setpassword = bool(targetupn) 

4845 elif setpassword and targetupn is None: 

4846 targetupn = upn 

4847 assert setpassword or not targetupn, "Cannot use targetupn in changepassword mode !" 

4848 # Get a ticket for kadmin/changepw 

4849 if ssp is None: 

4850 if ticket is None: 

4851 # Get a ticket for kadmin/changepw through AS-REQ 

4852 resp = krb_as_req( 

4853 upn=upn, 

4854 spn=spn, 

4855 key=key, 

4856 ip=ip, 

4857 password=password, 

4858 debug=debug, 

4859 ) 

4860 if resp is None: 

4861 return 

4862 ticket = resp.asrep.ticket 

4863 key = resp.sessionkey 

4864 ssp = KerberosSSP( 

4865 UPN=upn, 

4866 SPN=spn, 

4867 ST=ticket, 

4868 KEY=key, 

4869 DC_IP=ip, 

4870 debug=debug, 

4871 **kwargs, 

4872 ) 

4873 Context, tok, status = ssp.GSS_Init_sec_context( 

4874 None, 

4875 req_flags=0, # No GSS_C_MUTUAL_FLAG 

4876 ) 

4877 if status != GSS_S_CONTINUE_NEEDED: 

4878 warning("SSP failed on initial GSS_Init_sec_context !") 

4879 if tok: 

4880 tok.show() 

4881 return 

4882 apreq = tok.innerToken.root 

4883 # Connect 

4884 sock = socket.socket() 

4885 sock.settimeout(timeout) 

4886 sock.connect((ip, port)) 

4887 sock = StreamSocket(sock, KpasswdTCPHeader) 

4888 # Do KPASSWD request 

4889 if newpassword is None: 

4890 try: 

4891 from prompt_toolkit import prompt 

4892 

4893 newpassword = prompt("Enter NEW password: ", is_password=True) 

4894 except ImportError: 

4895 newpassword = input("Enter NEW password: ") 

4896 krbpriv = KRB_PRIV(encPart=EncryptedData()) 

4897 krbpriv.encPart.encrypt( 

4898 Context.KrbSessionKey, 

4899 EncKrbPrivPart( 

4900 sAddress=HostAddress( 

4901 addrType=ASN1_INTEGER(2), # IPv4 

4902 address=ASN1_STRING(b"\xc0\xa8\x00e"), 

4903 ), 

4904 userData=ASN1_STRING( 

4905 bytes( 

4906 ChangePasswdData( 

4907 newpasswd=newpassword, 

4908 targname=PrincipalName.fromUPN(targetupn), 

4909 targrealm=realm, 

4910 ) 

4911 ) 

4912 if setpassword 

4913 else newpassword 

4914 ), 

4915 timestamp=None, 

4916 usec=None, 

4917 seqNumber=Context.SendSeqNum, 

4918 ), 

4919 ) 

4920 resp = sock.sr1( 

4921 KpasswdTCPHeader() 

4922 / KPASSWD_REQ( 

4923 pvno=0xFF80 if setpassword else 1, 

4924 apreq=apreq, 

4925 krbpriv=krbpriv, 

4926 ), 

4927 timeout=timeout, 

4928 verbose=0, 

4929 ) 

4930 # Verify KPASSWD response 

4931 if not resp: 

4932 raise TimeoutError("KPASSWD_REQ timed out !") 

4933 if KPASSWD_REP not in resp: 

4934 resp.show() 

4935 raise ValueError("Invalid response to KPASSWD_REQ !") 

4936 Context, tok, status = ssp.GSS_Init_sec_context( 

4937 Context, 

4938 input_token=resp.aprep, 

4939 ) 

4940 if status != GSS_S_COMPLETE: 

4941 warning("SSP failed on subsequent GSS_Init_sec_context !") 

4942 if tok: 

4943 tok.show() 

4944 return 

4945 # Parse answer KRB_PRIV 

4946 krbanswer = resp.krbpriv.encPart.decrypt(Context.KrbSessionKey) 

4947 userRep = KPasswdRepData(krbanswer.userData.val) 

4948 if userRep.resultCode != 0: 

4949 warning(userRep.sprintf("KPASSWD failed !")) 

4950 userRep.show() 

4951 return 

4952 print(userRep.sprintf("%resultCode%")) 

4953 

4954 

4955# SSP 

4956 

4957# [RFC4120] sect 1.6: "a reasonable value for allowable clock skew is 

4958# 5 minutes" 

4959KRB_MaxClockSkew = timedelta(minutes=5) 

4960 

4961 

4962class KerberosSSP(SSP): 

4963 """ 

4964 The KerberosSSP 

4965 

4966 Client settings: 

4967 

4968 :param ST: the service ticket to use for access. 

4969 If not provided, will be retrieved 

4970 :param SPN: the SPN of the service to use. If not provided, will use the 

4971 target_name provided in the GSS_Init_sec_context 

4972 :param UPN: The client UPN 

4973 :param DC_IP: (optional) is ST+KEY are not provided, will need to contact 

4974 the KDC at this IP. If not provided, will perform dc locator. 

4975 :param TGT: (optional) pass a TGT to use to get the ST. 

4976 :param KEY: the session key associated with the ST if it is provided, 

4977 OR the session key associated with the TGT 

4978 OR the kerberos key associated with the UPN 

4979 :param PASSWORD: (optional) if a UPN is provided and not a KEY, this is the 

4980 password of the UPN. 

4981 :param U2U: (optional) use U2U when requesting the ST. 

4982 :param IAKERB: (optional) use IAKERB when requesting tickets. 

4983 

4984 Server settings: 

4985 

4986 :param SPN: the SPN of the service to use. 

4987 :param KEY: the kerberos key to use to decrypt the AP-req 

4988 :param UPN: (optional) the UPN, if used in U2U mode. 

4989 :param TGT: (optional) pass a TGT to use for U2U. 

4990 :param DC_IP: (optional) if TGT is not provided, request one on the KDC at 

4991 this IP using using the KEY when using U2U. 

4992 """ 

4993 

4994 auth_type = 0x10 

4995 

4996 class STATE(SSP.STATE): 

4997 INIT = 1 

4998 CLI_SENT_TGTREQ = 2 

4999 CLI_SENT_APREQ = 3 

5000 CLI_RCVD_APREP = 4 

5001 SRV_SENT_APREP = 5 

5002 FAILED = -1 

5003 

5004 class CONTEXT(SSP.CONTEXT): 

5005 __slots__ = [ 

5006 "SessionKey", 

5007 "ServerHostname", 

5008 "U2U", 

5009 "IAKERB", 

5010 "KrbSessionKey", # raw Key object 

5011 "ST", # the service ticket 

5012 "STSessionKey", # raw ST Key object (for DCE_STYLE) 

5013 "SeqNum", # for AP 

5014 "SendSeqNum", # for MIC 

5015 "RecvSeqNum", # for MIC 

5016 "IsAcceptor", 

5017 "SendSealKeyUsage", 

5018 "SendSignKeyUsage", 

5019 "RecvSealKeyUsage", 

5020 "RecvSignKeyUsage", 

5021 # server-only 

5022 "UPN", 

5023 "PAC", 

5024 # IAKERB 

5025 "IAKerbSocket", 

5026 ] 

5027 

5028 def __init__(self, IsAcceptor, req_flags=None): 

5029 self.state = KerberosSSP.STATE.INIT 

5030 self.SessionKey = None 

5031 self.ServerHostname = None 

5032 self.U2U = False 

5033 self.IAKERB = False 

5034 self.SendSeqNum = 0 

5035 self.RecvSeqNum = 0 

5036 self.KrbSessionKey = None 

5037 self.ST = None 

5038 self.STSessionKey = None 

5039 self.IsAcceptor = IsAcceptor 

5040 self.UPN = None 

5041 self.PAC = None 

5042 self.IAKerbSocket = None 

5043 # [RFC 4121] sect 2 

5044 if IsAcceptor: 

5045 self.SendSealKeyUsage = 22 

5046 self.SendSignKeyUsage = 23 

5047 self.RecvSealKeyUsage = 24 

5048 self.RecvSignKeyUsage = 25 

5049 else: 

5050 self.SendSealKeyUsage = 24 

5051 self.SendSignKeyUsage = 25 

5052 self.RecvSealKeyUsage = 22 

5053 self.RecvSignKeyUsage = 23 

5054 super(KerberosSSP.CONTEXT, self).__init__(req_flags=req_flags) 

5055 

5056 def clifailure(self): 

5057 self.__init__(self.IsAcceptor, req_flags=self.flags) 

5058 

5059 def __repr__(self): 

5060 if self.U2U: 

5061 return "KerberosSSP-U2U" 

5062 elif self.IAKERB: 

5063 return "KerberosSSP-IAKERB" 

5064 else: 

5065 return "KerberosSSP" 

5066 

5067 def __init__( 

5068 self, 

5069 ST=None, 

5070 UPN=None, 

5071 PASSWORD=None, 

5072 U2U=False, 

5073 IAKERB=False, 

5074 KEY=None, 

5075 SPN=None, 

5076 TGT=None, 

5077 DC_IP=None, 

5078 SKEY_TYPE=None, 

5079 debug=0, 

5080 **kwargs, 

5081 ): 

5082 import scapy.libs.rfc3961 # Trigger error if any # noqa: F401 

5083 

5084 self.ST = ST 

5085 self.UPN = UPN 

5086 self.KEY = KEY 

5087 self.SPN = SPN 

5088 self.TGT = TGT 

5089 self.TGTSessionKey = None 

5090 self.PASSWORD = PASSWORD 

5091 self.U2U = U2U 

5092 self.IAKERB = IAKERB 

5093 self.DC_IP = DC_IP 

5094 self.debug = debug 

5095 self.ReplayCache = {} 

5096 if SKEY_TYPE is None: 

5097 SKEY_TYPE = EncryptionType.AES128_CTS_HMAC_SHA1_96 

5098 self.SKEY_TYPE = SKEY_TYPE 

5099 super(KerberosSSP, self).__init__(**kwargs) 

5100 

5101 def __repr__(self): 

5102 if self.IAKERB: 

5103 return "<%s-IAKERB>" % self.__class__.__name__ 

5104 elif self.U2U: 

5105 return "<%s-U2U>" % self.__class__.__name__ 

5106 else: 

5107 return "<%s>" % self.__class__.__name__ 

5108 

5109 def GSS_Inquire_names_for_mech(self): 

5110 if self.IAKERB: 

5111 return ["1.3.6.1.5.2.5"] # Kerberos 5 - IAKERB 

5112 elif self.U2U: 

5113 return ["1.2.840.113554.1.2.2.3"] # Kerberos 5 - User to User 

5114 else: 

5115 return [ 

5116 "1.2.840.48018.1.2.2", # MS KRB5 - Microsoft Kerberos 5 

5117 "1.2.840.113554.1.2.2", # Kerberos 5 

5118 ] 

5119 

5120 def GSS_GetMICEx(self, Context, msgs, qop_req=0): 

5121 """ 

5122 [MS-KILE] sect 3.4.5.6 

5123 

5124 - AES: RFC4121 sect 4.2.6.1 

5125 """ 

5126 if Context.KrbSessionKey.etype in [17, 18]: # AES 

5127 # Concatenate the ToSign 

5128 ToSign = b"".join(x.data for x in msgs if x.sign) 

5129 sig = KRB_InnerToken( 

5130 TOK_ID=b"\x04\x04", 

5131 root=KRB_GSS_MIC( 

5132 Flags="AcceptorSubkey" 

5133 + ("+SentByAcceptor" if Context.IsAcceptor else ""), 

5134 SND_SEQ=Context.SendSeqNum, 

5135 ), 

5136 ) 

5137 ToSign += bytes(sig)[:16] 

5138 sig.root.SGN_CKSUM = Context.KrbSessionKey.make_checksum( 

5139 keyusage=Context.SendSignKeyUsage, 

5140 text=ToSign, 

5141 ) 

5142 else: 

5143 raise NotImplementedError 

5144 Context.SendSeqNum += 1 

5145 return sig 

5146 

5147 def GSS_VerifyMICEx(self, Context, msgs, signature): 

5148 """ 

5149 [MS-KILE] sect 3.4.5.7 

5150 

5151 - AES: RFC4121 sect 4.2.6.1 

5152 """ 

5153 # [RFC4121] sect 4.2.1: per-message sequence numbers increase by one. 

5154 # [RFC2743] sect 1.2.3: replay detection and sequencing are optional 

5155 if ( 

5156 not Context.passive 

5157 and Context.flags 

5158 & (GSS_C_FLAGS.GSS_C_REPLAY_FLAG | GSS_C_FLAGS.GSS_C_SEQUENCE_FLAG) 

5159 and signature.root.SND_SEQ != Context.RecvSeqNum 

5160 ): 

5161 raise ValueError( 

5162 "ERROR: Sequence numbers don't match: received %s, expected %s" 

5163 % (signature.root.SND_SEQ, Context.RecvSeqNum) 

5164 ) 

5165 

5166 if Context.KrbSessionKey.etype in [17, 18]: # AES 

5167 # Concatenate the ToSign 

5168 ToSign = b"".join(x.data for x in msgs if x.sign) 

5169 ToSign += bytes(signature)[:16] 

5170 sig = Context.KrbSessionKey.make_checksum( 

5171 keyusage=Context.RecvSignKeyUsage, 

5172 text=ToSign, 

5173 ) 

5174 else: 

5175 raise NotImplementedError 

5176 

5177 if sig != signature.root.SGN_CKSUM: 

5178 raise ValueError("ERROR: Checksums don't match") 

5179 

5180 Context.RecvSeqNum += 1 

5181 

5182 def GSS_WrapEx(self, Context, msgs, qop_req: GSS_QOP_REQ_FLAGS = 0): 

5183 """ 

5184 [MS-KILE] sect 3.4.5.4 

5185 

5186 - AES: RFC4121 sect 4.2.6.2 and [MS-KILE] sect 3.4.5.4.1 

5187 - HMAC-RC4: RFC4757 sect 7.3 and [MS-KILE] sect 3.4.5.4.1 

5188 """ 

5189 # Is confidentiality in use? 

5190 confidentiality = (Context.flags & GSS_C_FLAGS.GSS_C_CONF_FLAG) and any( 

5191 x.conf_req_flag for x in msgs 

5192 ) 

5193 if Context.KrbSessionKey.etype in [17, 18]: # AES 

5194 # Build token 

5195 tok = KRB_InnerToken( 

5196 TOK_ID=b"\x05\x04", 

5197 root=KRB_GSS_Wrap( 

5198 Flags="AcceptorSubkey" 

5199 + ("+SentByAcceptor" if Context.IsAcceptor else "") 

5200 + ("+Sealed" if confidentiality else ""), 

5201 SND_SEQ=Context.SendSeqNum, 

5202 RRC=0, 

5203 ), 

5204 ) 

5205 Context.SendSeqNum += 1 

5206 # Real separation starts now: RFC4121 sect 4.2.4 

5207 if confidentiality: 

5208 # Confidentiality is requested (see RFC4121 sect 4.3) 

5209 # {"header" | encrypt(plaintext-data | filler | "header")} 

5210 # 0. Roll confounder 

5211 Confounder = os.urandom(Context.KrbSessionKey.ep.blocksize) 

5212 # 1. Concatenate the data to be encrypted 

5213 Data = b"".join(x.data for x in msgs if x.conf_req_flag) 

5214 DataLen = len(Data) 

5215 # 2. Add filler 

5216 if qop_req & GSS_QOP_REQ_FLAGS.GSS_S_NO_SECBUFFER_PADDING: 

5217 # Special case for compatibility with Windows API. See 

5218 # GSS_QOP_REQ_FLAGS. 

5219 tok.root.EC = 0 

5220 else: 

5221 # [MS-KILE] sect 3.4.5.4.1 - "For AES-SHA1 ciphers, the EC must not 

5222 # be zero" 

5223 tok.root.EC = ( 

5224 (-DataLen) % Context.KrbSessionKey.ep.blocksize 

5225 ) or 16 

5226 Filler = b"\x00" * tok.root.EC 

5227 Data += Filler 

5228 # 3. Add first 16 octets of the Wrap token "header" 

5229 PlainHeader = bytes(tok)[:16] 

5230 Data += PlainHeader 

5231 # 4. Build 'ToSign', exclusively used for checksum 

5232 ToSign = Confounder 

5233 ToSign += b"".join(x.data for x in msgs if x.sign) 

5234 ToSign += Filler 

5235 ToSign += PlainHeader 

5236 # 5. Finalize token for signing 

5237 # "The RRC field is [...] 28 if encryption is requested." 

5238 tok.root.RRC = 28 

5239 # 6. encrypt() is the encryption operation (which provides for 

5240 # integrity protection) 

5241 Data = Context.KrbSessionKey.encrypt( 

5242 keyusage=Context.SendSealKeyUsage, 

5243 plaintext=Data, 

5244 confounder=Confounder, 

5245 signtext=ToSign, 

5246 ) 

5247 # 7. Rotate 

5248 Data = strrot(Data, tok.root.RRC + tok.root.EC) 

5249 # 8. Split (token and encrypted messages) 

5250 toklen = len(Data) - DataLen 

5251 tok.root.Data = Data[:toklen] 

5252 offset = toklen 

5253 for msg in msgs: 

5254 msglen = len(msg.data) 

5255 if msg.conf_req_flag: 

5256 msg.data = Data[offset : offset + msglen] 

5257 offset += msglen 

5258 return msgs, tok 

5259 else: 

5260 # No confidentiality is requested 

5261 # {"header" | plaintext-data | get_mic(plaintext-data | "header")} 

5262 # 0. Concatenate the data 

5263 Data = b"".join(x.data for x in msgs if x.sign) 

5264 DataLen = len(Data) 

5265 # 1. Add first 16 octets of the Wrap token "header" 

5266 ToSign = Data 

5267 ToSign += bytes(tok)[:16] 

5268 # 2. get_mic() is the checksum operation for the required 

5269 # checksum mechanism 

5270 Mic = Context.KrbSessionKey.make_checksum( 

5271 keyusage=Context.SendSealKeyUsage, 

5272 text=ToSign, 

5273 ) 

5274 # In Wrap tokens without confidentiality, the EC field SHALL be used 

5275 # to encode the number of octets in the trailing checksum 

5276 tok.root.EC = 12 # len(tok.root.Data) == 12 for AES 

5277 # "The RRC field ([RFC4121] section 4.2.5) is 12 if no encryption 

5278 # is requested" 

5279 tok.root.RRC = 12 

5280 # 3. Concat and pack 

5281 for msg in msgs: 

5282 if msg.sign: 

5283 msg.data = b"" 

5284 Data = Data + Mic 

5285 # 4. Rotate 

5286 tok.root.Data = strrot(Data, tok.root.RRC) 

5287 return msgs, tok 

5288 elif Context.KrbSessionKey.etype in [23, 24]: # RC4 

5289 # Build token 

5290 seq = struct.pack(">I", Context.SendSeqNum) 

5291 tok = KRB_InnerToken( 

5292 TOK_ID=b"\x02\x01", 

5293 root=KRB_GSS_Wrap_RFC1964( 

5294 SGN_ALG="HMAC", 

5295 SEAL_ALG="RC4" if confidentiality else "none", 

5296 SND_SEQ=seq 

5297 + ( 

5298 # See errata 

5299 b"\xff\xff\xff\xff" 

5300 if Context.IsAcceptor 

5301 else b"\x00\x00\x00\x00" 

5302 ), 

5303 ), 

5304 ) 

5305 Context.SendSeqNum += 1 

5306 # 0. Concatenate data 

5307 ToSign = _rfc1964pad(b"".join(x.data for x in msgs if x.sign)) 

5308 ToEncrypt = b"".join(x.data for x in msgs if x.conf_req_flag) 

5309 Kss = Context.KrbSessionKey.key 

5310 # 1. Roll confounder 

5311 Confounder = os.urandom(8) 

5312 # 2. Compute the 'Kseq' key 

5313 Klocal = strxor(Kss, len(Kss) * b"\xf0") 

5314 if Context.KrbSessionKey.etype == 24: # EXP 

5315 Kcrypt = Hmac_MD5(Klocal).digest(b"fortybits\x00" + b"\x00\x00\x00\x00") 

5316 Kcrypt = Kcrypt[:7] + b"\xab" * 9 

5317 else: 

5318 Kcrypt = Hmac_MD5(Klocal).digest(b"\x00\x00\x00\x00") 

5319 Kcrypt = Hmac_MD5(Kcrypt).digest(seq) 

5320 # 3. Build SGN_CKSUM 

5321 tok.root.SGN_CKSUM = Context.KrbSessionKey.make_checksum( 

5322 keyusage=13, # See errata 

5323 text=bytes(tok)[:8] + Confounder + ToSign, 

5324 )[:8] 

5325 # 4. Populate token + encrypt 

5326 if confidentiality: 

5327 # 'encrypt' is requested 

5328 rc4 = Cipher(decrepit_algorithms.ARC4(Kcrypt), mode=None).encryptor() 

5329 tok.root.CONFOUNDER = rc4.update(Confounder) 

5330 Data = rc4.update(ToEncrypt) 

5331 # Split encrypted data 

5332 offset = 0 

5333 for msg in msgs: 

5334 msglen = len(msg.data) 

5335 if msg.conf_req_flag: 

5336 msg.data = Data[offset : offset + msglen] 

5337 offset += msglen 

5338 else: 

5339 # 'encrypt' is not requested 

5340 tok.root.CONFOUNDER = Confounder 

5341 # 5. Compute the 'Kseq' key 

5342 if Context.KrbSessionKey.etype == 24: # EXP 

5343 Kseq = Hmac_MD5(Kss).digest(b"fortybits\x00" + b"\x00\x00\x00\x00") 

5344 Kseq = Kseq[:7] + b"\xab" * 9 

5345 else: 

5346 Kseq = Hmac_MD5(Kss).digest(b"\x00\x00\x00\x00") 

5347 Kseq = Hmac_MD5(Kseq).digest(tok.root.SGN_CKSUM) 

5348 # 6. Encrypt 'SND_SEQ' 

5349 rc4 = Cipher(decrepit_algorithms.ARC4(Kseq), mode=None).encryptor() 

5350 tok.root.SND_SEQ = rc4.update(tok.root.SND_SEQ) 

5351 # 7. Include 'InitialContextToken pseudo ASN.1 header' 

5352 tok = KRB_GSSAPI_Token( 

5353 MechType="1.2.840.113554.1.2.2", # Kerberos 5 

5354 innerToken=tok, 

5355 ) 

5356 return msgs, tok 

5357 else: 

5358 raise NotImplementedError 

5359 

5360 def GSS_UnwrapEx(self, Context, msgs, signature): 

5361 """ 

5362 [MS-KILE] sect 3.4.5.5 

5363 

5364 - AES: RFC4121 sect 4.2.6.2 

5365 - HMAC-RC4: RFC4757 sect 7.3 

5366 """ 

5367 if Context.KrbSessionKey.etype in [17, 18]: # AES 

5368 # [RFC4121] sect 4.2.1; [RFC2743] sect 1.2.3 

5369 if ( 

5370 not Context.passive 

5371 and Context.flags 

5372 & (GSS_C_FLAGS.GSS_C_REPLAY_FLAG | GSS_C_FLAGS.GSS_C_SEQUENCE_FLAG) 

5373 and signature.root.SND_SEQ != Context.RecvSeqNum 

5374 ): 

5375 raise ValueError("ERROR: Sequence numbers don't match") 

5376 

5377 confidentiality = signature.root.Flags.Sealed 

5378 # Real separation starts now: RFC4121 sect 4.2.4 

5379 if confidentiality: 

5380 # 0. Concatenate the data 

5381 Data = signature.root.Data 

5382 Data += b"".join(x.data for x in msgs if x.conf_req_flag) 

5383 # 1. Un-Rotate 

5384 Data = strrot(Data, signature.root.RRC + signature.root.EC, right=False) 

5385 

5386 # 2. Function to build 'ToSign', exclusively used for checksum 

5387 def MakeToSign(Confounder, DecText): 

5388 offset = 0 

5389 # 2.a Confounder 

5390 ToSign = Confounder 

5391 # 2.b Messages 

5392 for msg in msgs: 

5393 msglen = len(msg.data) 

5394 if msg.conf_req_flag: 

5395 ToSign += DecText[offset : offset + msglen] 

5396 offset += msglen 

5397 elif msg.sign: 

5398 ToSign += msg.data 

5399 # 2.c Filler & Padding 

5400 ToSign += DecText[offset:] 

5401 return ToSign 

5402 

5403 # 3. Decrypt 

5404 Data = Context.KrbSessionKey.decrypt( 

5405 keyusage=Context.RecvSealKeyUsage, 

5406 ciphertext=Data, 

5407 presignfunc=MakeToSign, 

5408 ) 

5409 # 4. Split 

5410 Data, f16header = ( 

5411 Data[:-16], 

5412 Data[-16:], 

5413 ) 

5414 # 5. Check header 

5415 hdr = signature.copy() 

5416 hdr.root.RRC = 0 

5417 if f16header != bytes(hdr)[:16]: 

5418 raise ValueError("ERROR: Headers don't match") 

5419 Context.RecvSeqNum += 1 

5420 # 6. Split (and ignore filler) 

5421 offset = 0 

5422 for msg in msgs: 

5423 msglen = len(msg.data) 

5424 if msg.conf_req_flag: 

5425 msg.data = Data[offset : offset + msglen] 

5426 offset += msglen 

5427 # Case without msgs 

5428 if len(msgs) == 1 and not msgs[0].data: 

5429 msgs[0].data = Data 

5430 return msgs 

5431 else: 

5432 # No confidentiality is requested 

5433 # 0. Concatenate the data 

5434 Data = signature.root.Data 

5435 Data += b"".join(x.data for x in msgs if x.sign) 

5436 # 1. Un-Rotate 

5437 Data = strrot(Data, signature.root.RRC, right=False) 

5438 # 2. Split 

5439 Data, Mic = Data[: -signature.root.EC], Data[-signature.root.EC :] 

5440 # "Both the EC field and the RRC field in 

5441 # the token header SHALL be filled with zeroes for the purpose of 

5442 # calculating the checksum." 

5443 ToSign = Data 

5444 hdr = signature.copy() 

5445 hdr.root.RRC = 0 

5446 hdr.root.EC = 0 

5447 # Concatenate the data 

5448 ToSign += bytes(hdr)[:16] 

5449 # 3. Calculate the signature 

5450 sig = Context.KrbSessionKey.make_checksum( 

5451 keyusage=Context.RecvSealKeyUsage, 

5452 text=ToSign, 

5453 ) 

5454 # 4. Compare 

5455 if sig != Mic: 

5456 raise ValueError("ERROR: Checksums don't match") 

5457 Context.RecvSeqNum += 1 

5458 # Case without msgs 

5459 if len(msgs) == 1 and not msgs[0].data: 

5460 msgs[0].data = Data 

5461 return msgs 

5462 elif Context.KrbSessionKey.etype in [23, 24]: # RC4 

5463 # Drop wrapping 

5464 tok = signature.innerToken 

5465 

5466 # Detect confidentiality 

5467 confidentiality = tok.root.SEAL_ALG != 0xFFFF 

5468 

5469 # 0. Concatenate data 

5470 ToDecrypt = b"".join(x.data for x in msgs if x.conf_req_flag) 

5471 Kss = Context.KrbSessionKey.key 

5472 # 1. Compute the 'Kseq' key 

5473 if Context.KrbSessionKey.etype == 24: # EXP 

5474 Kseq = Hmac_MD5(Kss).digest(b"fortybits\x00" + b"\x00\x00\x00\x00") 

5475 Kseq = Kseq[:7] + b"\xab" * 9 

5476 else: 

5477 Kseq = Hmac_MD5(Kss).digest(b"\x00\x00\x00\x00") 

5478 Kseq = Hmac_MD5(Kseq).digest(tok.root.SGN_CKSUM) 

5479 # 2. Decrypt 'SND_SEQ' 

5480 rc4 = Cipher(decrepit_algorithms.ARC4(Kseq), mode=None).encryptor() 

5481 seq = rc4.update(tok.root.SND_SEQ)[:4] 

5482 # [RFC4757] sect 7.3; [RFC2743] sect 1.2.3 

5483 if ( 

5484 not Context.passive 

5485 and Context.flags 

5486 & (GSS_C_FLAGS.GSS_C_REPLAY_FLAG | GSS_C_FLAGS.GSS_C_SEQUENCE_FLAG) 

5487 and struct.unpack(">I", seq)[0] != Context.RecvSeqNum 

5488 ): 

5489 raise ValueError("ERROR: Sequence numbers don't match") 

5490 # 3. Compute the 'Kcrypt' key 

5491 Klocal = strxor(Kss, len(Kss) * b"\xf0") 

5492 if Context.KrbSessionKey.etype == 24: # EXP 

5493 Kcrypt = Hmac_MD5(Klocal).digest(b"fortybits\x00" + b"\x00\x00\x00\x00") 

5494 Kcrypt = Kcrypt[:7] + b"\xab" * 9 

5495 else: 

5496 Kcrypt = Hmac_MD5(Klocal).digest(b"\x00\x00\x00\x00") 

5497 Kcrypt = Hmac_MD5(Kcrypt).digest(seq) 

5498 # 4. Decrypt 

5499 if confidentiality: 

5500 # 'encrypt' was requested 

5501 rc4 = Cipher(decrepit_algorithms.ARC4(Kcrypt), mode=None).encryptor() 

5502 Confounder = rc4.update(tok.root.CONFOUNDER) 

5503 Data = rc4.update(ToDecrypt) 

5504 # Split encrypted data 

5505 offset = 0 

5506 for msg in msgs: 

5507 msglen = len(msg.data) 

5508 if msg.conf_req_flag: 

5509 msg.data = Data[offset : offset + msglen] 

5510 offset += msglen 

5511 else: 

5512 # 'encrypt' was not requested 

5513 Confounder = tok.root.CONFOUNDER 

5514 # 5. Verify SGN_CKSUM 

5515 ToSign = _rfc1964pad(b"".join(x.data for x in msgs if x.sign)) 

5516 Context.KrbSessionKey.verify_checksum( 

5517 keyusage=13, # See errata 

5518 text=bytes(tok)[:8] + Confounder + ToSign, 

5519 cksum=tok.root.SGN_CKSUM, 

5520 ) 

5521 Context.RecvSeqNum += 1 

5522 return msgs 

5523 else: 

5524 raise NotImplementedError 

5525 

5526 def GSS_Init_sec_context( 

5527 self, 

5528 Context: CONTEXT, 

5529 input_token=None, 

5530 target_name: Optional[str] = None, 

5531 req_flags: Optional[GSS_C_FLAGS] = None, 

5532 chan_bindings: GssChannelBindings = GSS_C_NO_CHANNEL_BINDINGS, 

5533 ): 

5534 if Context is None: 

5535 # New context 

5536 Context = self.CONTEXT(IsAcceptor=False, req_flags=req_flags) 

5537 

5538 if self.IAKERB: 

5539 # IAKERB - We return asynchronously either packets from this 

5540 # GSS_Init_sec_context, or whatever packet are wrapped when talking to 

5541 # the server. 

5542 if Context.IAKerbSocket is None: 

5543 # Initial call: create a IAKerbSocket and a thread 

5544 _, crealm = _parse_upn(self.UPN) 

5545 Context.IAKERB = True 

5546 Context.IAKerbSocket = IAKerbSocket( 

5547 Context=Context, 

5548 realm=crealm, 

5549 ) 

5550 

5551 # Run in the background 

5552 Context.IAKerbSocket.run( 

5553 self.GSS_Init_sec_context, 

5554 Context=Context, 

5555 input_token=input_token, 

5556 target_name=target_name, 

5557 req_flags=req_flags, 

5558 chan_bindings=chan_bindings, 

5559 ) 

5560 

5561 return Context.IAKerbSocket.next() 

5562 elif input_token is not None: 

5563 # Intermediate token: let the thread handle it. 

5564 iakerb = Context.IAKerbSocket.unpack(input_token) 

5565 if iakerb: 

5566 # This is a IAKERB token 

5567 return Context.IAKerbSocket.next(iakerb) 

5568 

5569 # Else, continue. This is not an IAKERB token. 

5570 

5571 if Context.state == self.STATE.INIT and self.U2U: 

5572 # U2U - Get TGT 

5573 Context.state = self.STATE.CLI_SENT_TGTREQ 

5574 return ( 

5575 Context, 

5576 KRB_GSSAPI_Token( 

5577 MechType="1.2.840.113554.1.2.2.3", # U2U 

5578 innerToken=KRB_InnerToken( 

5579 TOK_ID=b"\x04\x00", 

5580 root=KRB_TGT_REQ(), 

5581 ), 

5582 ), 

5583 GSS_S_CONTINUE_NEEDED, 

5584 ) 

5585 

5586 if Context.state in [self.STATE.INIT, self.STATE.CLI_SENT_TGTREQ]: 

5587 if not self.UPN: 

5588 raise ValueError("Missing UPN attribute") 

5589 

5590 # Do we have a ST? 

5591 if self.ST is None: 

5592 # Client sends an AP-req 

5593 if not self.SPN and not target_name: 

5594 raise ValueError("Missing SPN/target_name attribute") 

5595 

5596 additional_tickets = [] 

5597 if self.U2U: 

5598 try: 

5599 # GSSAPI / Kerberos 

5600 tgt_rep = input_token.root.innerToken.root 

5601 except AttributeError: 

5602 try: 

5603 # Kerberos 

5604 tgt_rep = input_token.innerToken.root 

5605 except AttributeError: 

5606 return Context, None, GSS_S_DEFECTIVE_TOKEN 

5607 if not isinstance(tgt_rep, KRB_TGT_REP): 

5608 tgt_rep.show() 

5609 raise ValueError("KerberosSSP: Unexpected input_token !") 

5610 additional_tickets = [tgt_rep.ticket] 

5611 

5612 try: 

5613 if self.TGT is None: 

5614 # Get TGT. We were passed a kerberos key 

5615 res = krb_as_req( 

5616 upn=self.UPN, 

5617 ip=self.DC_IP, 

5618 key=self.KEY, 

5619 password=self.PASSWORD, 

5620 debug=self.debug, 

5621 verbose=bool(self.debug), 

5622 iakerb=self.IAKERB, 

5623 iakerb_socket=Context.IAKerbSocket, 

5624 ) 

5625 if res is None: 

5626 # Failed to retrieve the ticket 

5627 return Context, None, GSS_S_FAILURE 

5628 

5629 # Update UPN (could have been canonicalized) 

5630 self.UPN = res.upn 

5631 

5632 # Store TGT, 

5633 self.TGT = res.asrep.ticket 

5634 self.TGTSessionKey = res.sessionkey 

5635 elif self.TGTSessionKey is None: 

5636 # We have a TGT and were passed its key 

5637 self.TGTSessionKey = self.KEY 

5638 

5639 # Get ST 

5640 if not self.TGTSessionKey: 

5641 raise ValueError("Cannot use TGT without the KEY") 

5642 

5643 res = krb_tgs_req( 

5644 upn=self.UPN, 

5645 spn=self.SPN or target_name, 

5646 ip=self.DC_IP, 

5647 sessionkey=self.TGTSessionKey, 

5648 ticket=self.TGT, 

5649 additional_tickets=additional_tickets, 

5650 u2u=self.U2U, 

5651 debug=self.debug, 

5652 verbose=bool(self.debug), 

5653 iakerb=self.IAKERB, 

5654 iakerb_socket=Context.IAKerbSocket, 

5655 ) 

5656 if not res: 

5657 # Failed to retrieve the ticket 

5658 return Context, None, GSS_S_FAILURE 

5659 except TimeoutError: 

5660 # We couldn't reach the DC to get a ticket. Fail KerberosSSP. 

5661 return Context, None, GSS_S_BAD_MECH 

5662 

5663 # Store the service ticket and associated key 

5664 Context.ST, Context.STSessionKey = res.tgsrep.ticket, res.sessionkey 

5665 elif not self.KEY: 

5666 raise ValueError("Must provide KEY with ST") 

5667 else: 

5668 # We were passed a ST and its key 

5669 Context.ST = self.ST 

5670 Context.STSessionKey = self.KEY 

5671 

5672 target_spn = self.SPN or target_name 

5673 if target_spn and not _spn_are_equal(Context.ST.getSPN(), target_spn): 

5674 raise ValueError( 

5675 "SPN from ST doesn't match the passed SPN/target_name." 

5676 ) 

5677 

5678 if Context.flags & GSS_C_FLAGS.GSS_C_DELEG_FLAG: 

5679 raise ValueError( 

5680 "Cannot use GSS_C_DELEG_FLAG when passed a service ticket !" 

5681 ) 

5682 

5683 # Save ServerHostname 

5684 if len(Context.ST.sname.nameString) == 2: 

5685 Context.ServerHostname = Context.ST.sname.nameString[1].val.decode() 

5686 

5687 # Build the KRB-AP 

5688 apOptions = ASN1_BIT_STRING("000") 

5689 if Context.flags & GSS_C_FLAGS.GSS_C_MUTUAL_FLAG: 

5690 apOptions.set(2, "1") # mutual-required 

5691 if self.U2U: 

5692 apOptions.set(1, "1") # use-session-key 

5693 Context.U2U = True 

5694 ap_req = KRB_AP_REQ( 

5695 apOptions=apOptions, 

5696 ticket=Context.ST, 

5697 authenticator=EncryptedData(), 

5698 ) 

5699 

5700 # Get the current time 

5701 now_time = datetime.now(timezone.utc) 

5702 # Pick a random session key 

5703 Context.KrbSessionKey = Key.new_random_key( 

5704 self.SKEY_TYPE, 

5705 ) 

5706 

5707 # We use a random SendSeqNum 

5708 Context.SendSeqNum = RandNum(0, 0x7FFFFFFF)._fix() 

5709 

5710 # Get the realm of the client 

5711 _, crealm = _parse_upn(self.UPN) 

5712 

5713 # Build the RFC4121 authenticator checksum 

5714 authenticator_checksum = KRB_AuthenticatorChecksum( 

5715 # RFC 4121 sect 4.1.1.2 

5716 # "The Bnd field contains the MD5 hash of channel bindings" 

5717 Bnd=( 

5718 chan_bindings.digestMD5() 

5719 if chan_bindings != GSS_C_NO_CHANNEL_BINDINGS 

5720 else (b"\x00" * 16) 

5721 ), 

5722 Flags=int(Context.flags), 

5723 ) 

5724 

5725 if Context.flags & GSS_C_FLAGS.GSS_C_DELEG_FLAG: 

5726 # Delegate TGT 

5727 raise NotImplementedError("GSS_C_DELEG_FLAG is not implemented !") 

5728 # authenticator_checksum.Deleg = KRB_CRED( 

5729 # tickets=[self.TGT], 

5730 # encPart=EncryptedData() 

5731 # ) 

5732 # authenticator_checksum.encPart.encrypt( 

5733 # Context.STSessionKey, 

5734 # EncKrbCredPart( 

5735 # ticketInfo=KrbCredInfo( 

5736 # key=EncryptionKey.fromKey(self.TGTSessionKey), 

5737 # prealm=ASN1_GENERAL_STRING(crealm), 

5738 # pname=PrincipalName.fromUPN(self.UPN), 

5739 # # TODO: rework API to pass starttime... here. 

5740 # sreralm=self.TGT.realm, 

5741 # sname=self.TGT.sname, 

5742 # ) 

5743 # ) 

5744 # ) 

5745 

5746 # Build and encrypt the full KRB_Authenticator 

5747 ap_req.authenticator.encrypt( 

5748 Context.STSessionKey, 

5749 KRB_Authenticator( 

5750 crealm=crealm, 

5751 cname=PrincipalName.fromUPN(self.UPN), 

5752 cksum=Checksum( 

5753 cksumtype="KRB-AUTHENTICATOR", checksum=authenticator_checksum 

5754 ), 

5755 ctime=ASN1_GENERALIZED_TIME(now_time.replace(microsecond=0)), 

5756 cusec=ASN1_INTEGER(now_time.microsecond), 

5757 subkey=EncryptionKey.fromKey(Context.KrbSessionKey), 

5758 seqNumber=Context.SendSeqNum, 

5759 encAuthorizationData=AuthorizationData( 

5760 seq=[ 

5761 AuthorizationDataItem( 

5762 adType="AD-IF-RELEVANT", 

5763 adData=AuthorizationData( 

5764 seq=[ 

5765 AuthorizationDataItem( 

5766 adType="KERB-AUTH-DATA-TOKEN-RESTRICTIONS", 

5767 adData=KERB_AD_RESTRICTION_ENTRY( 

5768 restriction=LSAP_TOKEN_INFO_INTEGRITY( 

5769 MachineID=bytes(RandBin(32)), 

5770 CrossBootMachineID=bytes( 

5771 RandBin(32) 

5772 ), 

5773 ) 

5774 ), 

5775 ), 

5776 # This isn't documented, but sent on Windows :/ 

5777 AuthorizationDataItem( 

5778 adType="KERB-LOCAL", 

5779 adData=b"\x00" * 16, 

5780 ), 

5781 ] 

5782 + ( 

5783 # Channel bindings 

5784 [ 

5785 AuthorizationDataItem( 

5786 adType="AD-AUTH-DATA-AP-OPTIONS", 

5787 adData=KERB_AUTH_DATA_AP_OPTIONS( 

5788 apOptions="KERB_AP_OPTIONS_CBT" 

5789 ), 

5790 ) 

5791 ] 

5792 if chan_bindings != GSS_C_NO_CHANNEL_BINDINGS 

5793 else [] 

5794 ) 

5795 ), 

5796 ) 

5797 ] 

5798 ), 

5799 ), 

5800 ) 

5801 Context.state = self.STATE.CLI_SENT_APREQ 

5802 if Context.flags & GSS_C_FLAGS.GSS_C_DCE_STYLE: 

5803 # Raw kerberos DCE-STYLE 

5804 return Context, ap_req, GSS_S_CONTINUE_NEEDED 

5805 else: 

5806 # Kerberos wrapper 

5807 return ( 

5808 Context, 

5809 KRB_GSSAPI_Token( 

5810 innerToken=KRB_InnerToken( 

5811 root=ap_req, 

5812 ) 

5813 ), 

5814 GSS_S_CONTINUE_NEEDED, 

5815 ) 

5816 

5817 elif Context.state == self.STATE.CLI_SENT_APREQ: 

5818 if isinstance(input_token, KRB_AP_REP): 

5819 # Raw AP_REP was passed 

5820 ap_rep = input_token 

5821 else: 

5822 try: 

5823 # GSSAPI / Kerberos 

5824 ap_rep = input_token.root.innerToken.root 

5825 except AttributeError: 

5826 try: 

5827 # Kerberos 

5828 ap_rep = input_token.innerToken.root 

5829 except AttributeError: 

5830 try: 

5831 # Raw kerberos DCE-STYLE 

5832 ap_rep = input_token.root 

5833 except AttributeError: 

5834 return Context, None, GSS_S_DEFECTIVE_TOKEN 

5835 if not isinstance(ap_rep, KRB_AP_REP): 

5836 return Context, None, GSS_S_DEFECTIVE_TOKEN 

5837 

5838 # Retrieve SessionKey 

5839 repPart = ap_rep.encPart.decrypt(Context.STSessionKey) 

5840 # [RFC4120] sect 3.2.5: initial sequence number for server messages. 

5841 Context.RecvSeqNum = repPart.seqNumber.val if repPart.seqNumber else 0 

5842 if repPart.subkey is not None: 

5843 Context.SessionKey = repPart.subkey.keyvalue.val 

5844 Context.KrbSessionKey = repPart.subkey.toKey() 

5845 

5846 # OK ! 

5847 Context.state = self.STATE.CLI_RCVD_APREP 

5848 if Context.flags & GSS_C_FLAGS.GSS_C_DCE_STYLE: 

5849 # [MS-KILE] sect 3.4.5.1 

5850 # The client MUST generate an additional AP exchange reply message 

5851 # exactly as the server would as the final message to send to the 

5852 # server. 

5853 now_time = datetime.now(timezone.utc) 

5854 cli_ap_rep = KRB_AP_REP(encPart=EncryptedData()) 

5855 cli_ap_rep.encPart.encrypt( 

5856 Context.STSessionKey, 

5857 EncAPRepPart( 

5858 ctime=ASN1_GENERALIZED_TIME(now_time.replace(microsecond=0)), 

5859 cusec=ASN1_INTEGER(now_time.microsecond), 

5860 seqNumber=repPart.seqNumber, 

5861 subkey=None, 

5862 ), 

5863 ) 

5864 return Context, cli_ap_rep, GSS_S_COMPLETE 

5865 return Context, None, GSS_S_COMPLETE 

5866 elif ( 

5867 Context.state == self.STATE.CLI_RCVD_APREP 

5868 and Context.flags & GSS_C_FLAGS.GSS_C_DCE_STYLE 

5869 ): 

5870 # DCE_STYLE with SPNEGOSSP 

5871 return Context, None, GSS_S_COMPLETE 

5872 else: 

5873 raise ValueError("KerberosSSP: Unknown state") 

5874 

5875 def GSS_Accept_sec_context( 

5876 self, 

5877 Context: CONTEXT, 

5878 input_token=None, 

5879 req_flags: Optional[GSS_S_FLAGS] = GSS_S_FLAGS.GSS_S_ALLOW_MISSING_BINDINGS, 

5880 chan_bindings: GssChannelBindings = GSS_C_NO_CHANNEL_BINDINGS, 

5881 ): 

5882 if Context is None: 

5883 # New context 

5884 Context = self.CONTEXT(IsAcceptor=True, req_flags=req_flags) 

5885 

5886 import scapy.layers.msrpce.mspac # noqa: F401 

5887 

5888 if Context.state == self.STATE.INIT: 

5889 if self.UPN and self.SPN: 

5890 raise ValueError("Cannot use SPN and UPN at the same time !") 

5891 if self.SPN and self.TGT: 

5892 raise ValueError("Cannot use TGT with SPN.") 

5893 if self.UPN and not self.TGT: 

5894 # UPN is provided: use U2U 

5895 res = krb_as_req( 

5896 self.UPN, 

5897 self.DC_IP, 

5898 key=self.KEY, 

5899 password=self.PASSWORD, 

5900 ) 

5901 self.TGT, self.TGTSessionKey = res.asrep.ticket, res.sessionkey 

5902 

5903 # Server receives AP-req, sends AP-rep 

5904 if isinstance(input_token, KRB_AP_REQ): 

5905 # Raw AP_REQ was passed 

5906 ap_req = input_token 

5907 else: 

5908 try: 

5909 # GSSAPI/Kerberos 

5910 ap_req = input_token.root.innerToken.root 

5911 except AttributeError: 

5912 try: 

5913 # Kerberos 

5914 ap_req = input_token.innerToken.root 

5915 except AttributeError: 

5916 try: 

5917 # Raw kerberos 

5918 ap_req = input_token.root 

5919 except AttributeError: 

5920 return Context, None, GSS_S_DEFECTIVE_TOKEN 

5921 

5922 if isinstance(ap_req, KRB_TGT_REQ): 

5923 # Special U2U case 

5924 Context.U2U = True 

5925 return ( 

5926 None, 

5927 KRB_GSSAPI_Token( 

5928 MechType="1.2.840.113554.1.2.2.3", # U2U 

5929 innerToken=KRB_InnerToken( 

5930 TOK_ID=b"\x04\x01", 

5931 root=KRB_TGT_REP( 

5932 ticket=self.TGT, 

5933 ), 

5934 ), 

5935 ), 

5936 GSS_S_CONTINUE_NEEDED, 

5937 ) 

5938 elif not isinstance(ap_req, KRB_AP_REQ): 

5939 ap_req.show() 

5940 raise ValueError("Unexpected type in KerberosSSP") 

5941 if not self.KEY: 

5942 raise ValueError("Missing KEY attribute") 

5943 

5944 now_time = datetime.now(timezone.utc) 

5945 

5946 # If using a UPN, require U2U 

5947 if self.UPN and ap_req.apOptions.val[1] != "1": # use-session-key 

5948 # Required but not provided. Return an error 

5949 Context.U2U = True 

5950 err = KRB_GSSAPI_Token( 

5951 innerToken=KRB_InnerToken( 

5952 TOK_ID=b"\x03\x00", 

5953 root=KRB_ERROR( 

5954 errorCode="KRB_AP_ERR_USER_TO_USER_REQUIRED", 

5955 stime=ASN1_GENERALIZED_TIME( 

5956 now_time.replace(microsecond=0) 

5957 ), 

5958 susec=ASN1_INTEGER(now_time.microsecond), 

5959 realm=ap_req.ticket.realm, 

5960 sname=ap_req.ticket.sname, 

5961 eData=KRB_TGT_REP( 

5962 ticket=self.TGT, 

5963 ), 

5964 ), 

5965 ) 

5966 ) 

5967 return Context, err, GSS_S_CONTINUE_NEEDED 

5968 

5969 # Validate the 'serverName' of the ticket. 

5970 sname = ap_req.ticket.getSPN() 

5971 our_sname = self.SPN or self.UPN 

5972 if not _spn_are_equal(our_sname, sname): 

5973 warning("KerberosSSP: bad server name: %s != %s" % (sname, our_sname)) 

5974 err = KRB_GSSAPI_Token( 

5975 innerToken=KRB_InnerToken( 

5976 TOK_ID=b"\x03\x00", 

5977 root=KRB_ERROR( 

5978 errorCode="KRB_AP_ERR_BADMATCH", 

5979 stime=ASN1_GENERALIZED_TIME(now_time), 

5980 susec=ASN1_INTEGER(now_time.microsecond), 

5981 realm=ap_req.ticket.realm, 

5982 sname=ap_req.ticket.sname, 

5983 eData=None, 

5984 ), 

5985 ) 

5986 ) 

5987 return Context, err, GSS_S_BAD_MECH 

5988 

5989 # Decrypt the ticket 

5990 try: 

5991 tkt = ap_req.ticket.encPart.decrypt(self.KEY) 

5992 except ValueError as ex: 

5993 warning("KerberosSSP: %s (bad KEY?)" % ex) 

5994 err = KRB_GSSAPI_Token( 

5995 innerToken=KRB_InnerToken( 

5996 TOK_ID=b"\x03\x00", 

5997 root=KRB_ERROR( 

5998 errorCode="KRB_AP_ERR_MODIFIED", 

5999 stime=ASN1_GENERALIZED_TIME(now_time), 

6000 susec=ASN1_INTEGER(now_time.microsecond), 

6001 realm=ap_req.ticket.realm, 

6002 sname=ap_req.ticket.sname, 

6003 eData=None, 

6004 ), 

6005 ) 

6006 ) 

6007 return Context, err, GSS_S_DEFECTIVE_CREDENTIAL 

6008 

6009 # Store information about the user in the Context 

6010 if tkt.authorizationData and tkt.authorizationData.seq: 

6011 # Get AD-IF-RELEVANT 

6012 adIfRelevant = tkt.authorizationData.getAuthData(0x1) 

6013 if adIfRelevant: 

6014 # Get AD-WIN2K-PAC 

6015 Context.PAC = adIfRelevant.getAuthData(0x80) 

6016 

6017 # Get AP-REQ session key 

6018 Context.STSessionKey = tkt.key.toKey() 

6019 authenticator = ap_req.authenticator.decrypt(Context.STSessionKey) 

6020 

6021 # Eventually process the "checksum" 

6022 if authenticator.cksum and authenticator.cksum.cksumtype == 0x8003: 

6023 # KRB-Authenticator 

6024 authcksum = authenticator.cksum.checksum 

6025 Context.flags = authcksum.Flags 

6026 # Check channel bindings 

6027 if ( 

6028 chan_bindings != GSS_C_NO_CHANNEL_BINDINGS 

6029 and chan_bindings.digestMD5() != authcksum.Bnd 

6030 and not ( 

6031 GSS_S_FLAGS.GSS_S_ALLOW_MISSING_BINDINGS in req_flags 

6032 and authcksum.Bnd == GSS_C_NO_CHANNEL_BINDINGS 

6033 ) 

6034 ): 

6035 # Channel binding checks failed. 

6036 return Context, None, GSS_S_BAD_BINDINGS 

6037 elif ( 

6038 chan_bindings != GSS_C_NO_CHANNEL_BINDINGS 

6039 and GSS_S_FLAGS.GSS_S_ALLOW_MISSING_BINDINGS not in req_flags 

6040 ): 

6041 # Uhoh, we required channel bindings 

6042 return Context, None, GSS_S_BAD_BINDINGS 

6043 

6044 # [RFC4120] sect 3.2.3: initial sequence number for client messages. 

6045 Context.RecvSeqNum = ( 

6046 authenticator.seqNumber.val if authenticator.seqNumber else 0 

6047 ) 

6048 

6049 # Check the ticket validity period, the authenticator timestamp and 

6050 # prevent against replays. 

6051 # [RFC4120] sect 3.2.3 

6052 if not Context.passive: 

6053 starttime = (tkt.starttime or tkt.authtime).datetime 

6054 endtime = tkt.endtime.datetime 

6055 ctime = authenticator.getClientTime() 

6056 replay_key = (authenticator.getUPN(), ctime) 

6057 errorCode = None 

6058 gssErrorCode = GSS_S_DEFECTIVE_CREDENTIAL 

6059 if not starttime or starttime - now_time > KRB_MaxClockSkew: 

6060 errorCode = "KRB_AP_ERR_TKT_NYV" 

6061 elif not endtime or now_time - endtime > KRB_MaxClockSkew: 

6062 errorCode = "KRB_AP_ERR_TKT_EXPIRED" 

6063 gssErrorCode = GSS_S_CREDENTIALS_EXPIRED 

6064 elif not ctime or abs(ctime - now_time) > KRB_MaxClockSkew: 

6065 errorCode = "KRB_AP_ERR_SKEW" 

6066 elif replay_key in self.ReplayCache: 

6067 errorCode = "KRB_AP_ERR_REPEAT" 

6068 gssErrorCode = GSS_S_DUPLICATE_TOKEN 

6069 

6070 if errorCode: 

6071 warning("KerberosSSP: %s" % errorCode) 

6072 err = KRB_GSSAPI_Token( 

6073 innerToken=KRB_InnerToken( 

6074 TOK_ID=b"\x03\x00", 

6075 root=KRB_ERROR( 

6076 errorCode=errorCode, 

6077 stime=ASN1_GENERALIZED_TIME(now_time), 

6078 susec=ASN1_INTEGER(now_time.microsecond), 

6079 realm=ap_req.ticket.realm, 

6080 sname=ap_req.ticket.sname, 

6081 eData=None, 

6082 ), 

6083 ) 

6084 ) 

6085 return Context, err, gssErrorCode 

6086 

6087 # Store the time for future detections 

6088 self.ReplayCache[replay_key] = ctime + KRB_MaxClockSkew 

6089 

6090 # We take that opportunity to cleanup any expired items 

6091 for key, expiry in list(self.ReplayCache.items()): 

6092 if expiry < now_time: 

6093 self.ReplayCache.pop(key, None) 

6094 

6095 # Compute an application session key ([MS-KILE] sect 3.1.1.2) 

6096 subkey = None 

6097 if ap_req.apOptions.val[2] == "1": # mutual-required 

6098 appkey = Key.new_random_key( 

6099 self.SKEY_TYPE, 

6100 ) 

6101 Context.KrbSessionKey = appkey 

6102 Context.SessionKey = appkey.key 

6103 subkey = EncryptionKey.fromKey(appkey) 

6104 else: 

6105 Context.KrbSessionKey = self.KEY 

6106 Context.SessionKey = self.KEY.key 

6107 

6108 # Build response (RFC4120 sect 3.2.4) 

6109 ap_rep = KRB_AP_REP(encPart=EncryptedData()) 

6110 ap_rep.encPart.encrypt( 

6111 Context.STSessionKey, 

6112 EncAPRepPart( 

6113 ctime=authenticator.ctime, 

6114 cusec=authenticator.cusec, 

6115 seqNumber=None, 

6116 subkey=subkey, 

6117 ), 

6118 ) 

6119 Context.state = self.STATE.SRV_SENT_APREP 

6120 if Context.flags & GSS_C_FLAGS.GSS_C_DCE_STYLE: 

6121 # [MS-KILE] sect 3.4.5.1 

6122 return Context, ap_rep, GSS_S_CONTINUE_NEEDED 

6123 return Context, ap_rep, GSS_S_COMPLETE # success 

6124 elif ( 

6125 Context.state == self.STATE.SRV_SENT_APREP 

6126 and Context.flags & GSS_C_FLAGS.GSS_C_DCE_STYLE 

6127 ): 

6128 # [MS-KILE] sect 3.4.5.1 

6129 # The server MUST receive the additional AP exchange reply message and 

6130 # verify that the message is constructed correctly. 

6131 if not input_token: 

6132 return Context, None, GSS_S_DEFECTIVE_TOKEN 

6133 # Server receives AP-req, sends AP-rep 

6134 if isinstance(input_token, KRB_AP_REP): 

6135 # Raw AP_REP was passed 

6136 ap_rep = input_token 

6137 else: 

6138 try: 

6139 # GSSAPI/Kerberos 

6140 ap_rep = input_token.root.innerToken.root 

6141 except AttributeError: 

6142 try: 

6143 # Raw Kerberos 

6144 ap_rep = input_token.root 

6145 except AttributeError: 

6146 return Context, None, GSS_S_DEFECTIVE_TOKEN 

6147 # Decrypt the AP-REP 

6148 try: 

6149 ap_rep.encPart.decrypt(Context.STSessionKey) 

6150 except ValueError as ex: 

6151 warning("KerberosSSP: %s (bad KEY?)" % ex) 

6152 return Context, None, GSS_S_DEFECTIVE_TOKEN 

6153 return Context, None, GSS_S_COMPLETE # success 

6154 else: 

6155 raise ValueError("KerberosSSP: Unknown state %s" % repr(Context.state)) 

6156 

6157 def GSS_Passive( 

6158 self, 

6159 Context: CONTEXT, 

6160 input_token=None, 

6161 req_flags: Optional[GSS_S_FLAGS] = GSS_S_FLAGS.GSS_S_ALLOW_MISSING_BINDINGS, 

6162 ): 

6163 if Context is None: 

6164 Context = self.CONTEXT(True) 

6165 Context.passive = True 

6166 

6167 if Context.state == self.STATE.INIT or ( 

6168 # In DCE/RPC, there's an extra AP-REP sent from the client. 

6169 Context.state == self.STATE.SRV_SENT_APREP 

6170 and req_flags & GSS_C_FLAGS.GSS_C_DCE_STYLE 

6171 ): 

6172 Context, _, status = self.GSS_Accept_sec_context( 

6173 Context, 

6174 input_token=input_token, 

6175 req_flags=req_flags, 

6176 ) 

6177 if status in [GSS_S_CONTINUE_NEEDED, GSS_S_COMPLETE]: 

6178 Context.state = self.STATE.CLI_SENT_APREQ 

6179 else: 

6180 Context.state = self.STATE.FAILED 

6181 elif Context.state == self.STATE.CLI_SENT_APREQ: 

6182 Context, _, status = self.GSS_Init_sec_context( 

6183 Context, 

6184 input_token=input_token, 

6185 req_flags=req_flags, 

6186 ) 

6187 if status == GSS_S_COMPLETE: 

6188 if req_flags & GSS_C_FLAGS.GSS_C_DCE_STYLE: 

6189 status = GSS_S_CONTINUE_NEEDED 

6190 Context.state = self.STATE.SRV_SENT_APREP 

6191 else: 

6192 Context.state == self.STATE.FAILED 

6193 else: 

6194 # Unknown state. Don't crash though. 

6195 status = GSS_S_FAILURE 

6196 

6197 return Context, status 

6198 

6199 def GSS_Passive_set_Direction(self, Context: CONTEXT, IsAcceptor=False): 

6200 if Context.IsAcceptor is not IsAcceptor: 

6201 return 

6202 # Swap everything 

6203 Context.SendSeqNum, Context.RecvSeqNum = Context.RecvSeqNum, Context.SendSeqNum 

6204 Context.SendSealKeyUsage, Context.RecvSealKeyUsage = ( 

6205 Context.RecvSealKeyUsage, 

6206 Context.SendSealKeyUsage, 

6207 ) 

6208 Context.SendSignKeyUsage, Context.RecvSignKeyUsage = ( 

6209 Context.RecvSignKeyUsage, 

6210 Context.SendSignKeyUsage, 

6211 ) 

6212 Context.IsAcceptor = not Context.IsAcceptor 

6213 

6214 def LegsAmount(self, Context: CONTEXT): 

6215 if Context.flags & GSS_C_FLAGS.GSS_C_DCE_STYLE: 

6216 return 4 

6217 else: 

6218 return 2 

6219 

6220 def MaximumSignatureLength(self, Context: CONTEXT): 

6221 if Context.flags & GSS_C_FLAGS.GSS_C_CONF_FLAG: 

6222 # TODO: support DES 

6223 if Context.KrbSessionKey.etype in [17, 18]: # AES 

6224 return 76 

6225 elif Context.KrbSessionKey.etype in [23, 24]: # RC4_HMAC 

6226 return 45 

6227 else: 

6228 raise NotImplementedError 

6229 else: 

6230 return 28