ntlm.py 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971
  1. # Copyright (c) 2003-2016 CORE Security Technologies:
  2. #
  3. # This software is provided under under a slightly modified version
  4. # of the Apache Software License. See the accompanying LICENSE file
  5. # for more information.
  6. #
  7. import base64
  8. import struct
  9. import calendar
  10. import time
  11. import hashlib
  12. import random
  13. import string
  14. import binascii
  15. from impacket.structure import Structure
  16. from impacket import LOG
  17. # This is important. NTLMv2 is not negotiated by the client or server.
  18. # It is used if set locally on both sides. Change this item if you don't want to use
  19. # NTLMv2 by default and fall back to NTLMv1 (with EXTENDED_SESSION_SECURITY or not)
  20. # Check the following links:
  21. # http://davenport.sourceforge.net/ntlm.html
  22. # http://blogs.msdn.com/b/openspecification/archive/2010/04/20/ntlm-keys-and-sundry-stuff.aspx
  23. # http://social.msdn.microsoft.com/Forums/en-US/os_interopscenarios/thread/c8f488ed-1b96-4e06-bd65-390aa41138d1/
  24. # So I'm setting a global variable to control this, this can also be set programmatically
  25. USE_NTLMv2 = True # if false will fall back to NTLMv1 (or NTLMv1 with ESS a.k.a NTLM2)
  26. def computeResponse(flags, serverChallenge, clientChallenge, serverName, domain, user, password, lmhash='', nthash='',
  27. use_ntlmv2=USE_NTLMv2):
  28. if use_ntlmv2:
  29. return computeResponseNTLMv2(flags, serverChallenge, clientChallenge, serverName, domain, user, password,
  30. lmhash, nthash, use_ntlmv2=use_ntlmv2)
  31. else:
  32. return computeResponseNTLMv1(flags, serverChallenge, clientChallenge, serverName, domain, user, password,
  33. lmhash, nthash, use_ntlmv2=use_ntlmv2)
  34. try:
  35. POW = None
  36. from Crypto.Cipher import ARC4
  37. from Crypto.Cipher import DES
  38. from Crypto.Hash import MD4
  39. except Exception:
  40. try:
  41. import POW
  42. except Exception:
  43. LOG.critical("Warning: You don't have any crypto installed. You need PyCrypto")
  44. LOG.critical("See http://www.pycrypto.org/")
  45. NTLM_AUTH_NONE = 1
  46. NTLM_AUTH_CONNECT = 2
  47. NTLM_AUTH_CALL = 3
  48. NTLM_AUTH_PKT = 4
  49. NTLM_AUTH_PKT_INTEGRITY = 5
  50. NTLM_AUTH_PKT_PRIVACY = 6
  51. # If set, requests 56-bit encryption. If the client sends NTLMSSP_NEGOTIATE_SEAL or NTLMSSP_NEGOTIATE_SIGN
  52. # with NTLMSSP_NEGOTIATE_56 to the server in the NEGOTIATE_MESSAGE, the server MUST return NTLMSSP_NEGOTIATE_56 to
  53. # the client in the CHALLENGE_MESSAGE. Otherwise it is ignored. If both NTLMSSP_NEGOTIATE_56 and NTLMSSP_NEGOTIATE_128
  54. # are requested and supported by the client and server, NTLMSSP_NEGOTIATE_56 and NTLMSSP_NEGOTIATE_128 will both be
  55. # returned to the client. Clients and servers that set NTLMSSP_NEGOTIATE_SEAL SHOULD set NTLMSSP_NEGOTIATE_56 if it is
  56. # supported. An alternate name for this field is NTLMSSP_NEGOTIATE_56.
  57. NTLMSSP_NEGOTIATE_56 = 0x80000000
  58. # If set, requests an explicit key exchange. This capability SHOULD be used because it improves security for message
  59. # integrity or confidentiality. See sections 3.2.5.1.2, 3.2.5.2.1, and 3.2.5.2.2 for details. An alternate name for
  60. # this field is NTLMSSP_NEGOTIATE_KEY_EXCH.
  61. NTLMSSP_NEGOTIATE_KEY_EXCH = 0x40000000
  62. # If set, requests 128-bit session key negotiation. An alternate name for this field is NTLMSSP_NEGOTIATE_128.
  63. # If the client sends NTLMSSP_NEGOTIATE_128 to the server in the NEGOTIATE_MESSAGE, the server MUST return
  64. # NTLMSSP_NEGOTIATE_128 to the client in the CHALLENGE_MESSAGE only if the client sets NTLMSSP_NEGOTIATE_SEAL or
  65. # NTLMSSP_NEGOTIATE_SIGN. Otherwise it is ignored. If both NTLMSSP_NEGOTIATE_56 and NTLMSSP_NEGOTIATE_128 are
  66. # requested and supported by the client and server, NTLMSSP_NEGOTIATE_56 and NTLMSSP_NEGOTIATE_128 will both be
  67. # returned to the client. Clients and servers that set NTLMSSP_NEGOTIATE_SEAL SHOULD set NTLMSSP_NEGOTIATE_128 if it
  68. # is supported. An alternate name for this field is NTLMSSP_NEGOTIATE_128
  69. NTLMSSP_NEGOTIATE_128 = 0x20000000
  70. NTLMSSP_RESERVED_1 = 0x10000000
  71. NTLMSSP_RESERVED_2 = 0x08000000
  72. NTLMSSP_RESERVED_3 = 0x04000000
  73. # If set, requests the protocol version number. The data corresponding to this flag is provided in the Version field
  74. # of the NEGOTIATE_MESSAGE, the CHALLENGE_MESSAGE, and the AUTHENTICATE_MESSAGE.<22> An alternate name for this field
  75. # is NTLMSSP_NEGOTIATE_VERSION
  76. NTLMSSP_NEGOTIATE_VERSION = 0x02000000
  77. NTLMSSP_RESERVED_4 = 0x01000000
  78. # If set, indicates that the TargetInfo fields in the CHALLENGE_MESSAGE (section 2.2.1.2) are populated.
  79. # An alternate name for this field is NTLMSSP_NEGOTIATE_TARGET_INFO.
  80. NTLMSSP_NEGOTIATE_TARGET_INFO = 0x00800000
  81. # If set, requests the usage of the LMOWF (section 3.3). An alternate name for this field is
  82. # NTLMSSP_REQUEST_NON_NT_SESSION_KEY.
  83. NTLMSSP_REQUEST_NON_NT_SESSION_KEY = 0x00400000
  84. NTLMSSP_RESERVED_5 = 0x00200000
  85. # If set, requests an identify level token. An alternate name for this field is NTLMSSP_NEGOTIATE_IDENTIFY
  86. NTLMSSP_NEGOTIATE_IDENTIFY = 0x00100000
  87. # If set, requests usage of the NTLM v2 session security. NTLM v2 session security is a misnomer because it is not
  88. # NTLM v2. It is NTLM v1 using the extended session security that is also in NTLM v2. NTLMSSP_NEGOTIATE_LM_KEY and
  89. # NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY are mutually exclusive. If both NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY
  90. # and NTLMSSP_NEGOTIATE_LM_KEY are requested, NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY alone MUST be returned to the
  91. # client. NTLM v2 authentication session key generation MUST be supported by both the client and the DC in order to be
  92. # used, and extended session security signing and sealing requires support from the client and the server in order to
  93. # be used.<23> An alternate name for this field is NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY
  94. NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY = 0x00080000
  95. NTLMSSP_NEGOTIATE_NTLM2 = 0x00080000
  96. NTLMSSP_TARGET_TYPE_SHARE = 0x00040000
  97. # If set, TargetName MUST be a server name. The data corresponding to this flag is provided by the server in the
  98. # TargetName field of the CHALLENGE_MESSAGE. If this bit is set, then NTLMSSP_TARGET_TYPE_DOMAIN MUST NOT be set.
  99. # This flag MUST be ignored in the NEGOTIATE_MESSAGE and the AUTHENTICATE_MESSAGE. An alternate name for this field
  100. # is NTLMSSP_TARGET_TYPE_SERVER
  101. NTLMSSP_TARGET_TYPE_SERVER = 0x00020000
  102. # If set, TargetName MUST be a domain name. The data corresponding to this flag is provided by the server in the
  103. # TargetName field of the CHALLENGE_MESSAGE. If set, then NTLMSSP_TARGET_TYPE_SERVER MUST NOT be set. This flag MUST
  104. # be ignored in the NEGOTIATE_MESSAGE and the AUTHENTICATE_MESSAGE. An alternate name for this field is
  105. # NTLMSSP_TARGET_TYPE_DOMAIN.
  106. NTLMSSP_TARGET_TYPE_DOMAIN = 0x00010000
  107. # If set, requests the presence of a signature block on all messages. NTLMSSP_NEGOTIATE_ALWAYS_SIGN MUST be set in the
  108. # NEGOTIATE_MESSAGE to the server and the CHALLENGE_MESSAGE to the client. NTLMSSP_NEGOTIATE_ALWAYS_SIGN is overridden
  109. # by NTLMSSP_NEGOTIATE_SIGN and NTLMSSP_NEGOTIATE_SEAL, if they are supported. An alternate name for this field is
  110. # NTLMSSP_NEGOTIATE_ALWAYS_SIGN.
  111. NTLMSSP_NEGOTIATE_ALWAYS_SIGN = 0x00008000 # forces the other end to sign packets
  112. NTLMSSP_RESERVED_6 = 0x00004000
  113. # This flag indicates whether the Workstation field is present. If this flag is not set, the Workstation field MUST be
  114. # ignored. If this flag is set, the length field of the Workstation field specifies whether the workstation name is
  115. # nonempty or not.<24> An alternate name for this field is NTLMSSP_NEGOTIATE_OEM_WORKSTATION_SUPPLIED.
  116. NTLMSSP_NEGOTIATE_OEM_WORKSTATION_SUPPLIED = 0x00002000
  117. # If set, the domain name is provided (section 2.2.1.1).<25> An alternate name for this field is
  118. # NTLMSSP_NEGOTIATE_OEM_DOMAIN_SUPPLIED
  119. NTLMSSP_NEGOTIATE_OEM_DOMAIN_SUPPLIED = 0x00001000
  120. NTLMSSP_RESERVED_7 = 0x00000800
  121. # If set, LM authentication is not allowed and only NT authentication is used.
  122. NTLMSSP_NEGOTIATE_NT_ONLY = 0x00000400
  123. # If set, requests usage of the NTLM v1 session security protocol. NTLMSSP_NEGOTIATE_NTLM MUST be set in the
  124. # NEGOTIATE_MESSAGE to the server and the CHALLENGE_MESSAGE to the client. An alternate name for this field is
  125. # NTLMSSP_NEGOTIATE_NTLM
  126. NTLMSSP_NEGOTIATE_NTLM = 0x00000200
  127. NTLMSSP_RESERVED_8 = 0x00000100
  128. # If set, requests LAN Manager (LM) session key computation. NTLMSSP_NEGOTIATE_LM_KEY and
  129. # NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY are mutually exclusive. If both NTLMSSP_NEGOTIATE_LM_KEY and
  130. # NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY are requested, NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY alone MUST be
  131. # returned to the client. NTLM v2 authentication session key generation MUST be supported by both the client and the
  132. # DC in order to be used, and extended session security signing and sealing requires support from the client and the
  133. # server to be used. An alternate name for this field is NTLMSSP_NEGOTIATE_LM_KEY.
  134. NTLMSSP_NEGOTIATE_LM_KEY = 0x00000080
  135. # If set, requests connectionless authentication. If NTLMSSP_NEGOTIATE_DATAGRAM is set, then NTLMSSP_NEGOTIATE_KEY_EXCH
  136. # MUST always be set in the AUTHENTICATE_MESSAGE to the server and the CHALLENGE_MESSAGE to the client. An alternate
  137. # name for this field is NTLMSSP_NEGOTIATE_DATAGRAM.
  138. NTLMSSP_NEGOTIATE_DATAGRAM = 0x00000040
  139. # If set, requests session key negotiation for message confidentiality. If the client sends NTLMSSP_NEGOTIATE_SEAL to
  140. # the server in the NEGOTIATE_MESSAGE, the server MUST return NTLMSSP_NEGOTIATE_SEAL to the client in the
  141. # CHALLENGE_MESSAGE. Clients and servers that set NTLMSSP_NEGOTIATE_SEAL SHOULD always set NTLMSSP_NEGOTIATE_56 and
  142. # NTLMSSP_NEGOTIATE_128, if they are supported. An alternate name for this field is NTLMSSP_NEGOTIATE_SEAL.
  143. NTLMSSP_NEGOTIATE_SEAL = 0x00000020
  144. # If set, requests session key negotiation for message signatures. If the client sends NTLMSSP_NEGOTIATE_SIGN to the
  145. # server in the NEGOTIATE_MESSAGE, the server MUST return NTLMSSP_NEGOTIATE_SIGN to the client in the CHALLENGE_MESSAGE.
  146. # An alternate name for this field is NTLMSSP_NEGOTIATE_SIGN.
  147. NTLMSSP_NEGOTIATE_SIGN = 0x00000010 # means packet is signed, if verifier is wrong it fails
  148. NTLMSSP_RESERVED_9 = 0x00000008
  149. # If set, a TargetName field of the CHALLENGE_MESSAGE (section 2.2.1.2) MUST be supplied. An alternate name for this
  150. # field is NTLMSSP_REQUEST_TARGET.
  151. NTLMSSP_REQUEST_TARGET = 0x00000004
  152. # If set, requests OEM character set encoding. An alternate name for this field is NTLM_NEGOTIATE_OEM. See bit A for
  153. # details.
  154. NTLM_NEGOTIATE_OEM = 0x00000002
  155. # If set, requests Unicode character set encoding. An alternate name for this field is NTLMSSP_NEGOTIATE_UNICODE.
  156. NTLMSSP_NEGOTIATE_UNICODE = 0x00000001
  157. # AV_PAIR constants
  158. NTLMSSP_AV_EOL = 0x00
  159. NTLMSSP_AV_HOSTNAME = 0x01
  160. NTLMSSP_AV_DOMAINNAME = 0x02
  161. NTLMSSP_AV_DNS_HOSTNAME = 0x03
  162. NTLMSSP_AV_DNS_DOMAINNAME = 0x04
  163. NTLMSSP_AV_DNS_TREENAME = 0x05
  164. NTLMSSP_AV_FLAGS = 0x06
  165. NTLMSSP_AV_TIME = 0x07
  166. NTLMSSP_AV_RESTRICTIONS = 0x08
  167. NTLMSSP_AV_TARGET_NAME = 0x09
  168. NTLMSSP_AV_CHANNEL_BINDINGS = 0x0a
  169. class AV_PAIRS():
  170. def __init__(self, data = None):
  171. self.fields = {}
  172. if data is not None:
  173. self.fromString(data)
  174. def __setitem__(self,key,value):
  175. self.fields[key] = (len(value),value)
  176. def __getitem__(self, key):
  177. if self.fields.has_key(key):
  178. return self.fields[key]
  179. return None
  180. def __delitem__(self, key):
  181. del self.fields[key]
  182. def __len__(self):
  183. return len(self.getData())
  184. def __str__(self):
  185. return len(self.getData())
  186. def fromString(self, data):
  187. tInfo = data
  188. fType = 0xff
  189. while fType is not NTLMSSP_AV_EOL:
  190. fType = struct.unpack('<H',tInfo[:struct.calcsize('<H')])[0]
  191. tInfo = tInfo[struct.calcsize('<H'):]
  192. length = struct.unpack('<H',tInfo[:struct.calcsize('<H')])[0]
  193. tInfo = tInfo[struct.calcsize('<H'):]
  194. content = tInfo[:length]
  195. self.fields[fType]=(length,content)
  196. tInfo = tInfo[length:]
  197. def dump(self):
  198. for i in self.fields.keys():
  199. print "%s: {%r}" % (i,self[i])
  200. def getData(self):
  201. if self.fields.has_key(NTLMSSP_AV_EOL):
  202. del self.fields[NTLMSSP_AV_EOL]
  203. ans = ''
  204. for i in self.fields.keys():
  205. ans+= struct.pack('<HH', i, self[i][0])
  206. ans+= self[i][1]
  207. # end with a NTLMSSP_AV_EOL
  208. ans += struct.pack('<HH', NTLMSSP_AV_EOL, 0)
  209. return ans
  210. class NTLMAuthMixin:
  211. def get_os_version(self):
  212. if self['os_version'] == '':
  213. return None
  214. else:
  215. mayor_v = struct.unpack('B',self['os_version'][0])[0]
  216. minor_v = struct.unpack('B',self['os_version'][1])[0]
  217. build_v = struct.unpack('H',self['os_version'][2:4])
  218. return (mayor_v,minor_v,build_v)
  219. class NTLMAuthNegotiate(Structure, NTLMAuthMixin):
  220. structure = (
  221. ('','"NTLMSSP\x00'),
  222. ('message_type','<L=1'),
  223. ('flags','<L'),
  224. ('domain_len','<H-domain_name'),
  225. ('domain_max_len','<H-domain_name'),
  226. ('domain_offset','<L=0'),
  227. ('host_len','<H-host_name'),
  228. ('host_maxlen','<H-host_name'),
  229. ('host_offset','<L=0'),
  230. ('os_version',':'),
  231. ('host_name',':'),
  232. ('domain_name',':'))
  233. def __init__(self):
  234. Structure.__init__(self)
  235. self['flags']= (
  236. NTLMSSP_NEGOTIATE_128 |
  237. NTLMSSP_NEGOTIATE_KEY_EXCH|
  238. # NTLMSSP_LM_KEY |
  239. NTLMSSP_NEGOTIATE_NTLM |
  240. NTLMSSP_NEGOTIATE_UNICODE |
  241. # NTLMSSP_ALWAYS_SIGN |
  242. NTLMSSP_NEGOTIATE_SIGN |
  243. NTLMSSP_NEGOTIATE_SEAL |
  244. # NTLMSSP_TARGET |
  245. 0)
  246. self['host_name']=''
  247. self['domain_name']=''
  248. self['os_version']=''
  249. def getData(self):
  250. if len(self.fields['host_name']) > 0:
  251. self['flags'] |= NTLMSSP_NEGOTIATE_OEM_WORKSTATION_SUPPLIED
  252. if len(self.fields['domain_name']) > 0:
  253. self['flags'] |= NTLMSSP_NEGOTIATE_OEM_DOMAIN_SUPPLIED
  254. if len(self.fields['os_version']) > 0:
  255. self['flags'] |= NTLMSSP_NEGOTIATE_VERSION
  256. if (self['flags'] & NTLMSSP_NEGOTIATE_VERSION) == NTLMSSP_NEGOTIATE_VERSION:
  257. version_len = 8
  258. else:
  259. version_len = 0
  260. if (self['flags'] & NTLMSSP_NEGOTIATE_OEM_WORKSTATION_SUPPLIED) == NTLMSSP_NEGOTIATE_OEM_WORKSTATION_SUPPLIED:
  261. self['host_offset']=32 + version_len
  262. if (self['flags'] & NTLMSSP_NEGOTIATE_OEM_DOMAIN_SUPPLIED) == NTLMSSP_NEGOTIATE_OEM_DOMAIN_SUPPLIED:
  263. self['domain_offset']=32+len(self['host_name']) + version_len
  264. return Structure.getData(self)
  265. def fromString(self,data):
  266. Structure.fromString(self,data)
  267. domain_offset = self['domain_offset']
  268. domain_end = self['domain_len'] + domain_offset
  269. self['domain_name'] = data[ domain_offset : domain_end ]
  270. host_offset = self['host_offset']
  271. host_end = self['host_len'] + host_offset
  272. self['host_name'] = data[ host_offset : host_end ]
  273. hasOsInfo = self['flags'] & NTLMSSP_NEGOTIATE_VERSION
  274. if len(data) >= 36 and hasOsInfo:
  275. self['os_version'] = data[32:40]
  276. else:
  277. self['os_version'] = ''
  278. class NTLMAuthChallenge(Structure):
  279. structure = (
  280. ('','"NTLMSSP\x00'),
  281. ('message_type','<L=2'),
  282. ('domain_len','<H-domain_name'),
  283. ('domain_max_len','<H-domain_name'),
  284. ('domain_offset','<L=40'),
  285. ('flags','<L=0'),
  286. ('challenge','8s'),
  287. ('reserved','8s=""'),
  288. ('TargetInfoFields_len','<H-TargetInfoFields'),
  289. ('TargetInfoFields_max_len','<H-TargetInfoFields'),
  290. ('TargetInfoFields_offset','<L'),
  291. ('VersionLen','_-Version','self.checkVersion(self["flags"])'),
  292. ('Version',':'),
  293. ('domain_name',':'),
  294. ('TargetInfoFields',':'))
  295. def checkVersion(self, flags):
  296. if flags is not None:
  297. if flags & NTLMSSP_NEGOTIATE_VERSION == 0:
  298. return 0
  299. return 8
  300. def getData(self):
  301. if self['TargetInfoFields'] is not None and type(self['TargetInfoFields']) is not str:
  302. raw_av_fields = self['TargetInfoFields'].getData()
  303. self['TargetInfoFields'] = raw_av_fields
  304. return Structure.getData(self)
  305. def fromString(self,data):
  306. Structure.fromString(self,data)
  307. # Just in case there's more data after the TargetInfoFields
  308. self['TargetInfoFields'] = self['TargetInfoFields'][:self['TargetInfoFields_len']]
  309. # We gotta process the TargetInfoFields
  310. #if self['TargetInfoFields_len'] > 0:
  311. # av_pairs = AV_PAIRS(self['TargetInfoFields'][:self['TargetInfoFields_len']])
  312. # self['TargetInfoFields'] = av_pairs
  313. return self
  314. class NTLMAuthChallengeResponse(Structure, NTLMAuthMixin):
  315. structure = (
  316. ('','"NTLMSSP\x00'),
  317. ('message_type','<L=3'),
  318. ('lanman_len','<H-lanman'),
  319. ('lanman_max_len','<H-lanman'),
  320. ('lanman_offset','<L'),
  321. ('ntlm_len','<H-ntlm'),
  322. ('ntlm_max_len','<H-ntlm'),
  323. ('ntlm_offset','<L'),
  324. ('domain_len','<H-domain_name'),
  325. ('domain_max_len','<H-domain_name'),
  326. ('domain_offset','<L'),
  327. ('user_len','<H-user_name'),
  328. ('user_max_len','<H-user_name'),
  329. ('user_offset','<L'),
  330. ('host_len','<H-host_name'),
  331. ('host_max_len','<H-host_name'),
  332. ('host_offset','<L'),
  333. ('session_key_len','<H-session_key'),
  334. ('session_key_max_len','<H-session_key'),
  335. ('session_key_offset','<L'),
  336. ('flags','<L'),
  337. ('VersionLen','_-Version','self.checkVersion(self["flags"])'),
  338. ('Version',':=""'),
  339. ('MICLen','_-MIC','self.checkMIC(self["flags"])'),
  340. ('MIC',':=""'),
  341. ('domain_name',':'),
  342. ('user_name',':'),
  343. ('host_name',':'),
  344. ('lanman',':'),
  345. ('ntlm',':'),
  346. ('session_key',':'))
  347. def __init__(self, username = '', password = '', challenge = '', lmhash = '', nthash = '', flags = 0):
  348. Structure.__init__(self)
  349. self['session_key']=''
  350. self['user_name']=username.encode('utf-16le')
  351. self['domain_name']='' #"CLON".encode('utf-16le')
  352. self['host_name']='' #"BETS".encode('utf-16le')
  353. self['flags'] = ( #authResp['flags']
  354. # we think (beto & gera) that his flags force a memory conten leakage when a windows 2000 answers using uninitializaed verifiers
  355. NTLMSSP_NEGOTIATE_128 |
  356. NTLMSSP_NEGOTIATE_KEY_EXCH|
  357. # NTLMSSP_LM_KEY |
  358. NTLMSSP_NEGOTIATE_NTLM |
  359. NTLMSSP_NEGOTIATE_UNICODE |
  360. # NTLMSSP_ALWAYS_SIGN |
  361. NTLMSSP_NEGOTIATE_SIGN |
  362. NTLMSSP_NEGOTIATE_SEAL |
  363. # NTLMSSP_TARGET |
  364. 0)
  365. # Here we do the stuff
  366. if username and ( lmhash != '' or nthash != ''):
  367. self['lanman'] = get_ntlmv1_response(lmhash, challenge)
  368. self['ntlm'] = get_ntlmv1_response(nthash, challenge)
  369. elif (username and password):
  370. lmhash = compute_lmhash(password)
  371. nthash = compute_nthash(password)
  372. self['lanman']=get_ntlmv1_response(lmhash, challenge)
  373. self['ntlm']=get_ntlmv1_response(nthash, challenge) # This is not used for LM_KEY nor NTLM_KEY
  374. else:
  375. self['lanman'] = ''
  376. self['ntlm'] = ''
  377. if not self['host_name']:
  378. self['host_name'] = 'NULL'.encode('utf-16le') # for NULL session there must be a hostname
  379. def checkVersion(self, flags):
  380. if flags is not None:
  381. if flags & NTLMSSP_NEGOTIATE_VERSION == 0:
  382. return 0
  383. return 8
  384. def checkMIC(self, flags):
  385. # TODO: Find a proper way to check the MIC is in there
  386. if flags is not None:
  387. if flags & NTLMSSP_NEGOTIATE_VERSION == 0:
  388. return 0
  389. return 16
  390. def getData(self):
  391. self['domain_offset']=64+self.checkMIC(self["flags"])+self.checkVersion(self["flags"])
  392. self['user_offset']=64+self.checkMIC(self["flags"])+self.checkVersion(self["flags"])+len(self['domain_name'])
  393. self['host_offset']=self['user_offset']+len(self['user_name'])
  394. self['lanman_offset']=self['host_offset']+len(self['host_name'])
  395. self['ntlm_offset']=self['lanman_offset']+len(self['lanman'])
  396. self['session_key_offset']=self['ntlm_offset']+len(self['ntlm'])
  397. return Structure.getData(self)
  398. def fromString(self,data):
  399. Structure.fromString(self,data)
  400. # [MS-NLMP] page 27
  401. # Payload data can be present in any order within the Payload field,
  402. # with variable-length padding before or after the data
  403. domain_offset = self['domain_offset']
  404. domain_end = self['domain_len'] + domain_offset
  405. self['domain_name'] = data[ domain_offset : domain_end ]
  406. host_offset = self['host_offset']
  407. host_end = self['host_len'] + host_offset
  408. self['host_name'] = data[ host_offset: host_end ]
  409. user_offset = self['user_offset']
  410. user_end = self['user_len'] + user_offset
  411. self['user_name'] = data[ user_offset: user_end ]
  412. ntlm_offset = self['ntlm_offset']
  413. ntlm_end = self['ntlm_len'] + ntlm_offset
  414. self['ntlm'] = data[ ntlm_offset : ntlm_end ]
  415. lanman_offset = self['lanman_offset']
  416. lanman_end = self['lanman_len'] + lanman_offset
  417. self['lanman'] = data[ lanman_offset : lanman_end]
  418. #if len(data) >= 36:
  419. # self['os_version'] = data[32:36]
  420. #else:
  421. # self['os_version'] = ''
  422. class ImpacketStructure(Structure):
  423. def set_parent(self, other):
  424. self.parent = other
  425. def get_packet(self):
  426. return str(self)
  427. def get_size(self):
  428. return len(self)
  429. class ExtendedOrNotMessageSignature(Structure):
  430. def __init__(self, flags = 0, **kargs):
  431. if flags & NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY:
  432. self.structure = self.extendedMessageSignature
  433. else:
  434. self.structure = self.MessageSignature
  435. return Structure.__init__(self, **kargs)
  436. class NTLMMessageSignature(ExtendedOrNotMessageSignature):
  437. extendedMessageSignature = (
  438. ('Version','<L=1'),
  439. ('Checksum','<q'),
  440. ('SeqNum','<i'),
  441. )
  442. MessageSignature = (
  443. ('Version','<L=1'),
  444. ('RandomPad','<i=0'),
  445. ('Checksum','<i'),
  446. ('SeqNum','<i'),
  447. )
  448. KNOWN_DES_INPUT = "KGS!@#$%"
  449. def __expand_DES_key( key):
  450. # Expand the key from a 7-byte password key into a 8-byte DES key
  451. key = key[:7]
  452. key += '\x00'*(7-len(key))
  453. s = chr(((ord(key[0]) >> 1) & 0x7f) << 1)
  454. s = s + chr(((ord(key[0]) & 0x01) << 6 | ((ord(key[1]) >> 2) & 0x3f)) << 1)
  455. s = s + chr(((ord(key[1]) & 0x03) << 5 | ((ord(key[2]) >> 3) & 0x1f)) << 1)
  456. s = s + chr(((ord(key[2]) & 0x07) << 4 | ((ord(key[3]) >> 4) & 0x0f)) << 1)
  457. s = s + chr(((ord(key[3]) & 0x0f) << 3 | ((ord(key[4]) >> 5) & 0x07)) << 1)
  458. s = s + chr(((ord(key[4]) & 0x1f) << 2 | ((ord(key[5]) >> 6) & 0x03)) << 1)
  459. s = s + chr(((ord(key[5]) & 0x3f) << 1 | ((ord(key[6]) >> 7) & 0x01)) << 1)
  460. s = s + chr((ord(key[6]) & 0x7f) << 1)
  461. return s
  462. def __DES_block(key, msg):
  463. if POW:
  464. cipher = POW.Symmetric(POW.DES_ECB)
  465. cipher.encryptInit(__expand_DES_key(key))
  466. return cipher.update(msg)
  467. else:
  468. cipher = DES.new(__expand_DES_key(key),DES.MODE_ECB)
  469. return cipher.encrypt(msg)
  470. def ntlmssp_DES_encrypt(key, challenge):
  471. answer = __DES_block(key[:7], challenge)
  472. answer += __DES_block(key[7:14], challenge)
  473. answer += __DES_block(key[14:], challenge)
  474. return answer
  475. # High level functions to use NTLMSSP
  476. def getNTLMSSPType1(workstation='', domain='', signingRequired = False, use_ntlmv2 = USE_NTLMv2):
  477. # Let's do some encoding checks before moving on. Kind of dirty, but found effective when dealing with
  478. # international characters.
  479. import sys
  480. encoding = sys.getfilesystemencoding()
  481. if encoding is not None:
  482. try:
  483. workstation.encode('utf-16le')
  484. except:
  485. workstation = workstation.decode(encoding)
  486. try:
  487. domain.encode('utf-16le')
  488. except:
  489. domain = domain.decode(encoding)
  490. # Let's prepare a Type 1 NTLMSSP Message
  491. auth = NTLMAuthNegotiate()
  492. auth['flags']=0
  493. if signingRequired:
  494. auth['flags'] = NTLMSSP_NEGOTIATE_KEY_EXCH | NTLMSSP_NEGOTIATE_SIGN | NTLMSSP_NEGOTIATE_ALWAYS_SIGN | NTLMSSP_NEGOTIATE_SEAL
  495. if use_ntlmv2:
  496. auth['flags'] |= NTLMSSP_NEGOTIATE_TARGET_INFO
  497. auth['flags'] |= NTLMSSP_NEGOTIATE_NTLM | NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY | NTLMSSP_NEGOTIATE_UNICODE | NTLMSSP_REQUEST_TARGET | NTLMSSP_NEGOTIATE_128 | NTLMSSP_NEGOTIATE_56
  498. auth['domain_name'] = domain.encode('utf-16le')
  499. return auth
  500. def getNTLMSSPType3(type1, type2, user, password, domain, lmhash = '', nthash = '', use_ntlmv2 = USE_NTLMv2):
  501. # Let's do some encoding checks before moving on. Kind of dirty, but found effective when dealing with
  502. # international characters.
  503. import sys
  504. encoding = sys.getfilesystemencoding()
  505. if encoding is not None:
  506. try:
  507. user.encode('utf-16le')
  508. except:
  509. user = user.decode(encoding)
  510. try:
  511. password.encode('utf-16le')
  512. except:
  513. password = password.decode(encoding)
  514. try:
  515. domain.encode('utf-16le')
  516. except:
  517. domain = user.decode(encoding)
  518. ntlmChallenge = NTLMAuthChallenge(type2)
  519. # Let's start with the original flags sent in the type1 message
  520. responseFlags = type1['flags']
  521. # Token received and parsed. Depending on the authentication
  522. # method we will create a valid ChallengeResponse
  523. ntlmChallengeResponse = NTLMAuthChallengeResponse(user, password, ntlmChallenge['challenge'])
  524. clientChallenge = "".join([random.choice(string.digits+string.letters) for i in xrange(8)])
  525. serverName = ntlmChallenge['TargetInfoFields']
  526. ntResponse, lmResponse, sessionBaseKey = computeResponse(ntlmChallenge['flags'], ntlmChallenge['challenge'], clientChallenge, serverName, domain, user, password, lmhash, nthash, use_ntlmv2 )
  527. # Let's check the return flags
  528. if (ntlmChallenge['flags'] & NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY) == 0:
  529. # No extended session security, taking it out
  530. responseFlags &= 0xffffffff ^ NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY
  531. if (ntlmChallenge['flags'] & NTLMSSP_NEGOTIATE_128 ) == 0:
  532. # No support for 128 key len, taking it out
  533. responseFlags &= 0xffffffff ^ NTLMSSP_NEGOTIATE_128
  534. if (ntlmChallenge['flags'] & NTLMSSP_NEGOTIATE_KEY_EXCH) == 0:
  535. # No key exchange supported, taking it out
  536. responseFlags &= 0xffffffff ^ NTLMSSP_NEGOTIATE_KEY_EXCH
  537. if (ntlmChallenge['flags'] & NTLMSSP_NEGOTIATE_SEAL) == 0:
  538. # No sign available, taking it out
  539. responseFlags &= 0xffffffff ^ NTLMSSP_NEGOTIATE_SEAL
  540. if (ntlmChallenge['flags'] & NTLMSSP_NEGOTIATE_SIGN) == 0:
  541. # No sign available, taking it out
  542. responseFlags &= 0xffffffff ^ NTLMSSP_NEGOTIATE_SIGN
  543. if (ntlmChallenge['flags'] & NTLMSSP_NEGOTIATE_ALWAYS_SIGN) == 0:
  544. # No sign available, taking it out
  545. responseFlags &= 0xffffffff ^ NTLMSSP_NEGOTIATE_ALWAYS_SIGN
  546. keyExchangeKey = KXKEY(ntlmChallenge['flags'],sessionBaseKey, lmResponse, ntlmChallenge['challenge'], password, lmhash, nthash,use_ntlmv2)
  547. # Special case for anonymous login
  548. if user == '' and password == '' and lmhash == '' and nthash == '':
  549. keyExchangeKey = '\x00'*16
  550. # If we set up key exchange, let's fill the right variables
  551. if ntlmChallenge['flags'] & NTLMSSP_NEGOTIATE_KEY_EXCH:
  552. # not exactly what I call random tho :\
  553. # exportedSessionKey = this is the key we should use to sign
  554. exportedSessionKey = "".join([random.choice(string.digits+string.letters) for i in xrange(16)])
  555. #exportedSessionKey = "A"*16
  556. #print "keyExchangeKey %r" % keyExchangeKey
  557. # Let's generate the right session key based on the challenge flags
  558. #if responseFlags & NTLMSSP_NTLM2_KEY:
  559. # Extended session security enabled
  560. # if responseFlags & NTLMSSP_KEY_128:
  561. # Full key
  562. # exportedSessionKey = exportedSessionKey
  563. # elif responseFlags & NTLMSSP_KEY_56:
  564. # Only 56-bit key
  565. # exportedSessionKey = exportedSessionKey[:7]
  566. # else:
  567. # exportedSessionKey = exportedSessionKey[:5]
  568. #elif responseFlags & NTLMSSP_KEY_56:
  569. # No extended session security, just 56 bits key
  570. # exportedSessionKey = exportedSessionKey[:7] + '\xa0'
  571. #else:
  572. # exportedSessionKey = exportedSessionKey[:5] + '\xe5\x38\xb0'
  573. encryptedRandomSessionKey = generateEncryptedSessionKey(keyExchangeKey, exportedSessionKey)
  574. else:
  575. encryptedRandomSessionKey = None
  576. # [MS-NLMP] page 46
  577. exportedSessionKey = keyExchangeKey
  578. ntlmChallengeResponse['flags'] = responseFlags
  579. ntlmChallengeResponse['domain_name'] = domain.encode('utf-16le')
  580. ntlmChallengeResponse['lanman'] = lmResponse
  581. ntlmChallengeResponse['ntlm'] = ntResponse
  582. if encryptedRandomSessionKey is not None:
  583. ntlmChallengeResponse['session_key'] = encryptedRandomSessionKey
  584. return ntlmChallengeResponse, exportedSessionKey
  585. # NTLMv1 Algorithm
  586. def generateSessionKeyV1(password, lmhash, nthash):
  587. if POW:
  588. hash = POW.Digest(POW.MD4_DIGEST)
  589. else:
  590. hash = MD4.new()
  591. hash.update(NTOWFv1(password, lmhash, nthash))
  592. return hash.digest()
  593. def computeResponseNTLMv1(flags, serverChallenge, clientChallenge, serverName, domain, user, password, lmhash='', nthash='', use_ntlmv2 = USE_NTLMv2):
  594. if (user == '' and password == ''):
  595. # Special case for anonymous authentication
  596. lmResponse = ''
  597. ntResponse = ''
  598. else:
  599. lmhash = LMOWFv1(password, lmhash, nthash)
  600. nthash = NTOWFv1(password, lmhash, nthash)
  601. if flags & NTLMSSP_NEGOTIATE_LM_KEY:
  602. ntResponse = ''
  603. lmResponse = get_ntlmv1_response(lmhash, serverChallenge)
  604. elif flags & NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY:
  605. md5 = hashlib.new('md5')
  606. chall = (serverChallenge + clientChallenge)
  607. md5.update(chall)
  608. ntResponse = ntlmssp_DES_encrypt(nthash, md5.digest()[:8])
  609. lmResponse = clientChallenge + '\x00'*16
  610. else:
  611. ntResponse = get_ntlmv1_response(nthash,serverChallenge)
  612. lmResponse = get_ntlmv1_response(lmhash, serverChallenge)
  613. sessionBaseKey = generateSessionKeyV1(password, lmhash, nthash)
  614. return ntResponse, lmResponse, sessionBaseKey
  615. def compute_lmhash(password):
  616. # This is done according to Samba's encryption specification (docs/html/ENCRYPTION.html)
  617. password = password.upper()
  618. lmhash = __DES_block(password[:7], KNOWN_DES_INPUT)
  619. lmhash += __DES_block(password[7:14], KNOWN_DES_INPUT)
  620. return lmhash
  621. def NTOWFv1(password, lmhash = '', nthash=''):
  622. if nthash != '':
  623. return nthash
  624. return compute_nthash(password)
  625. def LMOWFv1(password, lmhash = '', nthash=''):
  626. if lmhash != '':
  627. return lmhash
  628. return compute_lmhash(password)
  629. def compute_nthash(password):
  630. # This is done according to Samba's encryption specification (docs/html/ENCRYPTION.html)
  631. try:
  632. password = unicode(password).encode('utf_16le')
  633. except UnicodeDecodeError:
  634. import sys
  635. password = password.decode(sys.getfilesystemencoding()).encode('utf_16le')
  636. if POW:
  637. hash = POW.Digest(POW.MD4_DIGEST)
  638. else:
  639. hash = MD4.new()
  640. hash.update(password)
  641. return hash.digest()
  642. def get_ntlmv1_response(key, challenge):
  643. return ntlmssp_DES_encrypt(key, challenge)
  644. # NTLMv2 Algorithm - as described in MS-NLMP Section 3.3.2
  645. # Crypto Stuff
  646. def MAC(flags, handle, signingKey, seqNum, message):
  647. # [MS-NLMP] Section 3.4.4
  648. # Returns the right messageSignature depending on the flags
  649. messageSignature = NTLMMessageSignature(flags)
  650. if flags & NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY:
  651. if flags & NTLMSSP_NEGOTIATE_KEY_EXCH:
  652. messageSignature['Version'] = 1
  653. messageSignature['Checksum'] = struct.unpack('<q',handle(hmac_md5(signingKey, struct.pack('<i',seqNum)+message)[:8]))[0]
  654. messageSignature['SeqNum'] = seqNum
  655. seqNum += 1
  656. else:
  657. messageSignature['Version'] = 1
  658. messageSignature['Checksum'] = struct.unpack('<q',hmac_md5(signingKey, struct.pack('<i',seqNum)+message)[:8])[0]
  659. messageSignature['SeqNum'] = seqNum
  660. seqNum += 1
  661. else:
  662. messageSignature['Version'] = 1
  663. messageSignature['Checksum'] = struct.pack('<i',binascii.crc32(message))
  664. messageSignature['RandomPad'] = 0
  665. messageSignature['RandomPad'] = handle(struct.pack('<i',messageSignature['RandomPad']))
  666. messageSignature['Checksum'] = struct.unpack('<i',handle(messageSignature['Checksum']))[0]
  667. messageSignature['SeqNum'] = handle('\x00\x00\x00\x00')
  668. messageSignature['SeqNum'] = struct.unpack('<i',messageSignature['SeqNum'])[0] ^ seqNum
  669. messageSignature['RandomPad'] = 0
  670. return messageSignature
  671. def SEAL(flags, signingKey, sealingKey, messageToSign, messageToEncrypt, seqNum, handle):
  672. sealedMessage = handle(messageToEncrypt)
  673. signature = MAC(flags, handle, signingKey, seqNum, messageToSign)
  674. return sealedMessage, signature
  675. def SIGN(flags, signingKey, message, seqNum, handle):
  676. return MAC(flags, handle, signingKey, seqNum, message)
  677. def SIGNKEY(flags, randomSessionKey, mode = 'Client'):
  678. if flags & NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY:
  679. if mode == 'Client':
  680. md5 = hashlib.new('md5')
  681. md5.update(randomSessionKey + "session key to client-to-server signing key magic constant\x00")
  682. signKey = md5.digest()
  683. else:
  684. md5 = hashlib.new('md5')
  685. md5.update(randomSessionKey + "session key to server-to-client signing key magic constant\x00")
  686. signKey = md5.digest()
  687. else:
  688. signKey = None
  689. return signKey
  690. def SEALKEY(flags, randomSessionKey, mode = 'Client'):
  691. if flags & NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY:
  692. if flags & NTLMSSP_NEGOTIATE_128:
  693. sealKey = randomSessionKey
  694. elif flags & NTLMSSP_NEGOTIATE_56:
  695. sealKey = randomSessionKey[:7]
  696. else:
  697. sealKey = randomSessionKey[:5]
  698. if mode == 'Client':
  699. md5 = hashlib.new('md5')
  700. md5.update(sealKey + 'session key to client-to-server sealing key magic constant\x00')
  701. sealKey = md5.digest()
  702. else:
  703. md5 = hashlib.new('md5')
  704. md5.update(sealKey + 'session key to server-to-client sealing key magic constant\x00')
  705. sealKey = md5.digest()
  706. elif flags & NTLMSSP_NEGOTIATE_56:
  707. sealKey = randomSessionKey[:7] + '\xa0'
  708. else:
  709. sealKey = randomSessionKey[:5] + '\xe5\x38\xb0'
  710. return sealKey
  711. def generateEncryptedSessionKey(keyExchangeKey, exportedSessionKey):
  712. if POW:
  713. cipher = POW.Symmetric(POW.RC4)
  714. cipher.encryptInit(keyExchangeKey)
  715. cipher_encrypt = cipher.update
  716. else:
  717. cipher = ARC4.new(keyExchangeKey)
  718. cipher_encrypt = cipher.encrypt
  719. sessionKey = cipher_encrypt(exportedSessionKey)
  720. return sessionKey
  721. def KXKEY(flags, sessionBaseKey, lmChallengeResponse, serverChallenge, password, lmhash, nthash, use_ntlmv2 = USE_NTLMv2):
  722. if use_ntlmv2:
  723. return sessionBaseKey
  724. if flags & NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY:
  725. if flags & NTLMSSP_NEGOTIATE_NTLM:
  726. keyExchangeKey = hmac_md5(sessionBaseKey, serverChallenge + lmChallengeResponse[:8])
  727. else:
  728. keyExchangeKey = sessionBaseKey
  729. elif flags & NTLMSSP_NEGOTIATE_NTLM:
  730. if flags & NTLMSSP_NEGOTIATE_LM_KEY:
  731. keyExchangeKey = __DES_block(LMOWFv1(password,lmhash)[:7], lmChallengeResponse[:8]) + __DES_block(LMOWFv1(password,lmhash)[7] + '\xBD\xBD\xBD\xBD\xBD\xBD', lmChallengeResponse[:8])
  732. elif flags & NTLMSSP_REQUEST_NON_NT_SESSION_KEY:
  733. keyExchangeKey = LMOWFv1(password,lmhash)[:8] + '\x00'*8
  734. else:
  735. keyExchangeKey = sessionBaseKey
  736. else:
  737. raise "Can't create a valid KXKEY!"
  738. return keyExchangeKey
  739. def hmac_md5(key, data):
  740. if POW:
  741. h = POW.Hmac(POW.MD5_DIGEST, key)
  742. h.update(data)
  743. result = h.mac()
  744. else:
  745. import hmac
  746. h = hmac.new(key)
  747. h.update(data)
  748. result = h.digest()
  749. return result
  750. def NTOWFv2( user, password, domain, hash = ''):
  751. if hash != '':
  752. theHash = hash
  753. else:
  754. theHash = compute_nthash(password)
  755. return hmac_md5(theHash, user.upper().encode('utf-16le') + domain.encode('utf-16le'))
  756. def LMOWFv2( user, password, domain, lmhash = ''):
  757. return NTOWFv2( user, password, domain, lmhash)
  758. def computeResponseNTLMv2(flags, serverChallenge, clientChallenge, serverName, domain, user, password, lmhash = '', nthash = '', use_ntlmv2 = USE_NTLMv2):
  759. responseServerVersion = '\x01'
  760. hiResponseServerVersion = '\x01'
  761. responseKeyNT = NTOWFv2(user, password, domain, nthash)
  762. responseKeyLM = LMOWFv2(user, password, domain, lmhash)
  763. # If you're running test-ntlm, comment the following lines and uncoment the ones that are commented. Don't forget to turn it back after the tests!
  764. ######################
  765. av_pairs = AV_PAIRS(serverName)
  766. # In order to support SPN target name validation, we have to add this to the serverName av_pairs. Otherwise we will get access denied
  767. # This is set at Local Security Policy -> Local Policies -> Security Options -> Server SPN target name validation level
  768. av_pairs[NTLMSSP_AV_TARGET_NAME] = 'cifs/'.encode('utf-16le') + av_pairs[NTLMSSP_AV_HOSTNAME][1]
  769. if av_pairs[NTLMSSP_AV_TIME] is not None:
  770. aTime = av_pairs[NTLMSSP_AV_TIME][1]
  771. else:
  772. aTime = struct.pack('<q', (116444736000000000 + calendar.timegm(time.gmtime()) * 10000000) )
  773. #aTime = '\x00'*8
  774. av_pairs[NTLMSSP_AV_TIME] = aTime
  775. serverName = av_pairs.getData()
  776. ######################
  777. #aTime = '\x00'*8
  778. ######################
  779. temp = responseServerVersion + hiResponseServerVersion + '\x00' * 6 + aTime + clientChallenge + '\x00' * 4 + serverName + '\x00' * 4
  780. ntProofStr = hmac_md5(responseKeyNT, serverChallenge + temp)
  781. ntChallengeResponse = ntProofStr + temp
  782. lmChallengeResponse = hmac_md5(responseKeyNT, serverChallenge + clientChallenge) + clientChallenge
  783. sessionBaseKey = hmac_md5(responseKeyNT, ntProofStr)
  784. if (user == '' and password == ''):
  785. # Special case for anonymous authentication
  786. ntChallengeResponse = ''
  787. lmChallengeResponse = ''
  788. return ntChallengeResponse, lmChallengeResponse, sessionBaseKey
  789. class NTLM_HTTP(object):
  790. '''Parent class for NTLM HTTP classes.'''
  791. MSG_TYPE = None
  792. @classmethod
  793. def get_instace(cls,msg_64):
  794. msg = None
  795. msg_type = 0
  796. if msg_64 != '':
  797. msg = base64.b64decode(msg_64[5:]) # Remove the 'NTLM '
  798. msg_type = ord(msg[8])
  799. for _cls in NTLM_HTTP.__subclasses__():
  800. if msg_type == _cls.MSG_TYPE:
  801. instance = _cls()
  802. instance.fromString(msg)
  803. return instance
  804. class NTLM_HTTP_AuthRequired(NTLM_HTTP):
  805. commonHdr = ()
  806. # Message 0 means the first HTTP request e.g. 'GET /bla.png'
  807. MSG_TYPE = 0
  808. def fromString(self,data):
  809. pass
  810. class NTLM_HTTP_AuthNegotiate(NTLM_HTTP, NTLMAuthNegotiate):
  811. commonHdr = ()
  812. MSG_TYPE = 1
  813. def __init__(self):
  814. NTLMAuthNegotiate.__init__(self)
  815. class NTLM_HTTP_AuthChallengeResponse(NTLM_HTTP, NTLMAuthChallengeResponse):
  816. commonHdr = ()
  817. MSG_TYPE = 3
  818. def __init__(self):
  819. NTLMAuthChallengeResponse.__init__(self)