PageRenderTime 51ms CodeModel.GetById 15ms RepoModel.GetById 1ms app.codeStats 0ms

/nselib/smbauth.lua

https://github.com/prakashgamit/nmap
Lua | 836 lines | 450 code | 118 blank | 268 comment | 75 complexity | 3e410ecde8f39407b315bb27243b8aa4 MD5 | raw file
Possible License(s): BSD-3-Clause, GPL-2.0, LGPL-2.0, LGPL-2.1
  1. ---
  2. -- This module takes care of the authentication used in SMB (LM, NTLM, LMv2, NTLMv2).
  3. --
  4. -- There is a lot to this functionality, so if you're interested in how it works, read
  5. -- on.
  6. -- In SMB authentication, there are two distinct concepts. Each will be dealt with
  7. -- separately. There are:
  8. -- * Stored hashes
  9. -- * Authentication
  10. --
  11. -- What's confusing is that the same names are used for each of those.
  12. --
  13. -- Stored Hashes:
  14. -- Windows stores two types of hashes: Lanman and NT Lanman (or NTLM). Vista and later
  15. -- store NTLM only. Lanman passwords are divided into two 7-character passwords and
  16. -- used as a key in DES, while NTLM is converted to unicode and MD4ed.
  17. --
  18. -- The stored hashes can be dumped in a variety of ways (pwdump6, fgdump, Metasploit's
  19. -- <code>priv</code> module, <code>smb-psexec.nse</code>, etc). Generally, two hashes are dumped together
  20. -- (generally, Lanman:NTLM). Sometimes, Lanman is empty and only NTLM is given. Lanman
  21. -- is never required.
  22. --
  23. -- The password hashes can be given instead of passwords when supplying credentials;
  24. -- this is done by using the <code>smbhash</code> argument. Either a pair of hashes
  25. -- can be passed, in the form of Lanman:NTLM, or a single hash, which is assumed to
  26. -- be NTLM.
  27. --
  28. -- Authentication:
  29. -- There are four types of authentication. Confusingly, these have the same names as
  30. -- stored hashes, but only slight relationships. The four types are Lanmanv1, NTLMv1,
  31. -- Lanmanv2, and NTLMv2. By default, Lanmanv1 and NTLMv1 are used together in most
  32. -- applications. These Nmap scripts default to NTLMv1 alone, except in special cases,
  33. -- but it can be overridden by the user.
  34. --
  35. -- Lanmanv1 and NTLMv1 both use DES for their response. The DES mixes a server challenge
  36. -- with the hash (Lanman hash for Lanmanv1 response and NTLMv1 hash for NTLM response).
  37. -- The way the challenge is DESed with the hashes is identical for Lanmanv1 and NTLMv1,
  38. -- the only difference is the starting hash (Lanman vs NTLM).
  39. --
  40. -- Lanmanv2 and NTLMv2 both use HMAC-MD5 for their response. The HMAC-MD5 mixes a
  41. -- server challenge and a client challenge with the NTLM hash, in both cases. The
  42. -- difference between Lanmanv2 and NTLMv2 is the length of the client challenge;
  43. -- Lanmanv2 has a maximum client challenge of 8 bytes, whereas NTLMv2 doesn't limit
  44. -- the length of the client challenge.
  45. --
  46. -- The primary advantage to the 'v2' protocols is the client challenge -- by
  47. -- incorporating a client challenge, a malicious server can't use a precomputation
  48. -- attack.
  49. --
  50. -- In addition to hashing the passwords, messages are also signed, by default, if a
  51. -- v1 protocol is being used (I (Ron Bowes) couldn't get signatures to work on v2
  52. -- protocols; if anybody knows how I'd love to implement it).
  53. --
  54. --@args smbusername The SMB username to log in with. The forms "DOMAIN\username" and "username@DOMAIN"
  55. -- are not understood. To set a domain, use the <code>smbdomain</code> argument.
  56. --@args smbdomain The domain to log in with. If you aren't in a domained environment, then anything
  57. -- will (should?) be accepted by the server.
  58. --@args smbpassword The password to connect with. Be cautious with this, since some servers will lock
  59. -- accounts if the incorrect password is given. Although it's rare that the
  60. -- Administrator account can be locked out, in the off chance that it can, you could
  61. -- get yourself in trouble. To use a blank password, leave this parameter off
  62. -- altogether.
  63. --@args smbhash A password hash to use when logging in. This is given as a single hex string (32
  64. -- characters) or a pair of hex strings (both 32 characters, optionally separated by a
  65. -- single character). These hashes are the LanMan or NTLM hash of the user's password,
  66. -- and are stored on disk or in memory. They can be retrieved from memory
  67. -- using the fgdump or pwdump tools.
  68. --@args smbtype The type of SMB authentication to use. These are the possible options:
  69. -- * <code>v1</code>: Sends LMv1 and NTLMv1.
  70. -- * <code>LMv1</code>: Sends LMv1 only.
  71. -- * <code>NTLMv1</code>: Sends NTLMv1 only (default).
  72. -- * <code>v2</code>: Sends LMv2 and NTLMv2.
  73. -- * <code>LMv2</code>: Sends LMv2 only.
  74. -- * <code>NTLMv2</code>: Doesn't exist; the protocol doesn't support NTLMv2 alone.
  75. -- The default, <code>NTLMv1</code>, is a pretty decent compromise between security and
  76. -- compatibility. If you are paranoid, you might want to use <code>v2</code> or
  77. -- <code>lmv2</code> for this. (Actually, if you're paranoid, you should be avoiding this
  78. -- protocol altogether!). If you're using an extremely old system, you might need to set
  79. -- this to <code>v1</code> or <code>lm</code>, which are less secure but more compatible.
  80. -- For information, see <code>smbauth.lua</code>.
  81. --@args smbnoguest Use to disable usage of the 'guest' account.
  82. local bin = require "bin"
  83. local nmap = require "nmap"
  84. local stdnse = require "stdnse"
  85. local string = require "string"
  86. local table = require "table"
  87. _ENV = stdnse.module("smbauth", stdnse.seeall)
  88. local have_ssl, openssl = pcall(require, "openssl")
  89. -- Constants
  90. local NTLMSSP_NEGOTIATE = 0x00000001
  91. local NTLMSSP_CHALLENGE = 0x00000002
  92. local NTLMSSP_AUTH = 0x00000003
  93. local session_key = string.rep(string.char(0x00), 16)
  94. -- Types of accounts (ordered by how useful they are
  95. local ACCOUNT_TYPES = {
  96. ANONYMOUS = 0,
  97. GUEST = 1,
  98. USER = 2,
  99. ADMIN = 3
  100. }
  101. local function account_exists(host, username, domain)
  102. if(host.registry['smbaccounts'] == nil) then
  103. return false
  104. end
  105. for i, j in pairs(host.registry['smbaccounts']) do
  106. if(j['username'] == username and j['domain'] == domain) then
  107. return true
  108. end
  109. end
  110. return false
  111. end
  112. function next_account(host, num)
  113. if(num == nil) then
  114. if(host.registry['smbindex'] == nil) then
  115. host.registry['smbindex'] = 1
  116. else
  117. host.registry['smbindex'] = host.registry['smbindex'] + 1
  118. end
  119. else
  120. host.registry['smbindex'] = num
  121. end
  122. end
  123. ---Writes the given account to the registry. There are several places where accounts are stored:
  124. -- * registry['usernames'][username] => true
  125. -- * registry['smbaccounts'][username] => password
  126. -- * registry[ip]['smbaccounts'] => array of table containing 'username', 'password', and 'is_admin'
  127. --
  128. -- The final place, 'smbaccount', is reserved for the "best" account. This is an administrator
  129. -- account, if one's found; otherwise, it's the first account discovered that isn't <code>guest</code>.
  130. --
  131. -- This has to be called while no SMB connections are made, since it potentially makes its own connection.
  132. --
  133. --@param host The host object.
  134. --@param username The username to add.
  135. --@param domain The domain to add.
  136. --@param password The password to add.
  137. --@param password_hash The password hash to add.
  138. --@param hash_type The hash type to use.
  139. --@param is_admin [optional] Set to 'true' the account is known to be an administrator.
  140. function add_account(host, username, domain, password, password_hash, hash_type, is_admin)
  141. -- Save the username in a global list -- TODO: restore this
  142. -- if(nmap.registry.usernames == nil) then
  143. -- nmap.registry.usernames = {}
  144. -- end
  145. -- nmap.registry.usernames[username] = true
  146. --
  147. -- -- Save the username/password pair in a global list
  148. -- if(nmap.registry.smbaccounts == nil) then
  149. -- nmap.registry.smbaccounts = {}
  150. -- end
  151. -- nmap.registry.smbaccounts[username] = password
  152. -- Check if we've already recorded this account
  153. if(account_exists(host, username, domain)) then
  154. return
  155. end
  156. if(host.registry['smbaccounts'] == nil) then
  157. host.registry['smbaccounts'] = {}
  158. end
  159. -- Determine the type of account, if it wasn't given
  160. local account_type = nil
  161. if(is_admin) then
  162. account_type = ACCOUNT_TYPES.ADMIN
  163. else
  164. if(username == '') then
  165. -- Anonymous account
  166. account_type = ACCOUNT_TYPES.ANONYMOUS
  167. elseif(string.lower(username) == 'guest') then
  168. -- Guest account
  169. account_type = ACCOUNT_TYPES.GUEST
  170. else
  171. -- We have to assume it's a user-level account (we just can't call any SMB functions from inside here)
  172. account_type = ACCOUNT_TYPES.USER
  173. end
  174. end
  175. -- Set some defaults
  176. if(hash_type == nil) then
  177. hash_type = 'ntlm'
  178. end
  179. -- Save the new account if this is our first one, or our other account isn't an admin
  180. local new_entry = {}
  181. new_entry['username'] = username
  182. new_entry['domain'] = domain
  183. new_entry['password'] = password
  184. new_entry['password_hash'] = password_hash
  185. new_entry['hash_type'] = string.lower(hash_type)
  186. new_entry['account_type'] = account_type
  187. -- Insert the new entry into the table
  188. table.insert(host.registry['smbaccounts'], new_entry)
  189. -- Sort the table based on the account type (we want anonymous at the end, administrator at the front)
  190. table.sort(host.registry['smbaccounts'], function(a,b) return a['account_type'] > b['account_type'] end)
  191. -- Print a debug message
  192. stdnse.print_debug(1, "SMB: Added account '%s' to account list", username)
  193. -- Reset the credentials
  194. next_account(host, 1)
  195. -- io.write("\n\n" .. nsedebug.tostr(host.registry['smbaccounts']) .. "\n\n")
  196. end
  197. ---Retrieve the current set of credentials set in the registry. If these fail, <code>next_credentials</code> should be
  198. -- called.
  199. --
  200. --@param host The host object.
  201. --@return (result, username, domain, password, password_hash, hash_type) If result is false, username is an error message. Otherwise, username and password are
  202. -- the current username and password that should be used.
  203. function get_account(host)
  204. if(host.registry['smbindex'] == nil) then
  205. host.registry['smbindex'] = 1
  206. end
  207. local index = host.registry['smbindex']
  208. local account = host.registry['smbaccounts'][index]
  209. if(account == nil) then
  210. return false, "No accounts left to try"
  211. end
  212. return true, account['username'], account['domain'], account['password'], account['password_hash'], account['hash_type']
  213. end
  214. ---Create the account table with the anonymous and guest users, as well as the user given in the script's
  215. -- arguments, if there is one.
  216. --
  217. --@param host The host object.
  218. function init_account(host)
  219. -- Don't run this more than once for each host
  220. if(host.registry['smbaccounts'] ~= nil) then
  221. return
  222. end
  223. -- Create the list
  224. host.registry['smbaccounts'] = {}
  225. -- Add the anonymous/guest accounts
  226. add_account(host, '', '', '', nil, 'none')
  227. if(not stdnse.get_script_args( "smbnoguest" )) then
  228. add_account(host, 'guest', '', '', nil, 'ntlm')
  229. end
  230. -- Add the account given on the commandline (TODO: allow more than one?)
  231. local args = nmap.registry.args
  232. local username = nil
  233. local domain = ''
  234. local password = nil
  235. local password_hash = nil
  236. local hash_type = 'ntlm'
  237. -- Do the username first
  238. if(args.smbusername ~= nil) then
  239. username = args.smbusername
  240. elseif(args.smbuser ~= nil) then
  241. username = args.smbuser
  242. end
  243. -- If the username exists, do everything else
  244. if(username ~= nil) then
  245. -- Domain
  246. if(args.smbdomain ~= nil) then
  247. domain = args.smbdomain
  248. end
  249. -- Type
  250. if(args.smbtype ~= nil) then
  251. hash_type = args.smbtype
  252. end
  253. -- Do the password
  254. if(args.smbpassword ~= nil) then
  255. password = args.smbpassword
  256. elseif(args.smbpass ~= nil) then
  257. password = args.smbpass
  258. end
  259. -- Only use the hash if there's no password
  260. if(password == nil) then
  261. password_hash = args.smbhash
  262. end
  263. -- Add the account, if we got a password
  264. if(password == nil and password_hash == nil) then
  265. stdnse.print_debug(1, "SMB: Either smbpass, smbpassword, or smbhash have to be passed as script arguments to use an account")
  266. else
  267. add_account(host, username, domain, password, password_hash, hash_type)
  268. end
  269. end
  270. end
  271. local function to_unicode(str)
  272. local unicode = ""
  273. for i = 1, #str, 1 do
  274. unicode = unicode .. bin.pack("<S", string.byte(str, i))
  275. end
  276. return unicode
  277. end
  278. local function from_unicode(unicode)
  279. local str = ""
  280. if ( unicode == nil ) then
  281. return nil
  282. end
  283. for char_itr = 1, unicode:len(), 2 do
  284. str = str .. unicode:sub(char_itr, char_itr)
  285. end
  286. return str
  287. end
  288. ---Generate the Lanman v1 hash (LMv1). The generated hash is incredibly easy to reverse, because the input
  289. -- is padded or truncated to 14 characters, then split into two 7-character strings. Each of these strings
  290. -- are used as a key to encrypt the string, "KGS!@#$%" in DES. Because the keys are no longer than
  291. -- 7-characters long, it's pretty trivial to bruteforce them.
  292. --
  293. --@param password the password to hash
  294. --@return (status, hash) If status is true, the hash is returned; otherwise, an error message is returned.
  295. local function lm_create_hash(password)
  296. if(have_ssl ~= true) then
  297. return false, "SMB: OpenSSL not present"
  298. end
  299. local str1, str2
  300. local key1, key2
  301. local result
  302. -- Convert the password to uppercase
  303. password = string.upper(password)
  304. -- If password is under 14 characters, pad it to 14
  305. if(#password < 14) then
  306. password = password .. string.rep(string.char(0), 14 - #password)
  307. end
  308. -- Take the first and second half of the password (note that if it's longer than 14 characters, it's truncated)
  309. str1 = string.sub(password, 1, 7)
  310. str2 = string.sub(password, 8, 14)
  311. -- Generate the keys
  312. key1 = openssl.DES_string_to_key(str1)
  313. key2 = openssl.DES_string_to_key(str2)
  314. -- Encrypt the string "KGS!@#$%" with each half, and concatenate it
  315. result = openssl.encrypt("DES", key1, nil, "KGS!@#$%") .. openssl.encrypt("DES", key2, nil, "KGS!@#$%")
  316. return true, result
  317. end
  318. ---Generate the NTLMv1 hash. This hash is quite a bit better than LMv1, and is far easier to generate. Basically,
  319. -- it's the MD4 of the Unicode password.
  320. --
  321. --@param password the password to hash
  322. --@return (status, hash) If status is true, the hash is returned; otherwise, an error message is returned.
  323. function ntlm_create_hash(password)
  324. if(have_ssl ~= true) then
  325. return false, "SMB: OpenSSL not present"
  326. end
  327. return true, openssl.md4(to_unicode(password))
  328. end
  329. ---Create the Lanman response to send back to the server. To do this, the Lanman password is padded to 21
  330. -- characters and split into three 7-character strings. Each of those strings is used as a key to encrypt
  331. -- the server challenge. The three encrypted strings are concatenated and returned.
  332. --
  333. --@param lanman The LMv1 hash
  334. --@param challenge The server's challenge.
  335. --@return (status, response) If status is true, the response is returned; otherwise, an error message is returned.
  336. function lm_create_response(lanman, challenge)
  337. if(have_ssl ~= true) then
  338. return false, "SMB: OpenSSL not present"
  339. end
  340. local str1, str2, str3
  341. local key1, key2, key3
  342. local result
  343. -- Pad the hash to 21 characters
  344. lanman = lanman .. string.rep(string.char(0), 21 - #lanman)
  345. -- Take the first and second half of the password (note that if it's longer than 14 characters, it's truncated)
  346. str1 = string.sub(lanman, 1, 7)
  347. str2 = string.sub(lanman, 8, 14)
  348. str3 = string.sub(lanman, 15, 21)
  349. -- Generate the keys
  350. key1 = openssl.DES_string_to_key(str1)
  351. key2 = openssl.DES_string_to_key(str2)
  352. key3 = openssl.DES_string_to_key(str3)
  353. -- Print a warning message if a blank challenge is received, and create a phony challenge. A blank challenge is
  354. -- invalid in the protocol, and causes some versions of OpenSSL to abort with no possible error handling.
  355. if(challenge == "") then
  356. stdnse.print_debug(1, "SMB: ERROR: Server returned invalid (blank) challenge value (should be 8 bytes); failing login to avoid OpenSSL crash.")
  357. challenge = "AAAAAAAA"
  358. end
  359. -- Encrypt the challenge with each key
  360. result = openssl.encrypt("DES", key1, nil, challenge) .. openssl.encrypt("DES", key2, nil, challenge) .. openssl.encrypt("DES", key3, nil, challenge)
  361. return true, result
  362. end
  363. ---Create the NTLM response to send back to the server. This is actually done the exact same way as the Lanman hash,
  364. -- so I call the <code>Lanman</code> function.
  365. --
  366. --@param ntlm The NTLMv1 hash
  367. --@param challenge The server's challenge.
  368. --@return (status, response) If status is true, the response is returned; otherwise, an error message is returned.
  369. function ntlm_create_response(ntlm, challenge)
  370. if(have_ssl ~= true) then
  371. return false, "SMB: OpenSSL not present"
  372. end
  373. return lm_create_response(ntlm, challenge)
  374. end
  375. ---Create the NTLM mac key, which is used for message signing. For basic authentication, this is the md4 of the
  376. -- NTLM hash, concatenated with the response hash; for extended authentication, this is just the md4 of the NTLM
  377. -- hash.
  378. --@param ntlm_hash The NTLM hash.
  379. --@param ntlm_response The NTLM response.
  380. --@param is_extended Should be set if extended security negotiations are being used.
  381. function ntlm_create_mac_key(ntlm_hash, ntlm_response, is_extended)
  382. if(have_ssl ~= true) then
  383. return false, "SMB: OpenSSL not present"
  384. end
  385. if(is_extended) then
  386. return openssl.md4(ntlm_hash)
  387. else
  388. return openssl.md4(ntlm_hash) .. ntlm_response
  389. end
  390. end
  391. ---Create the LM mac key, which is used for message signing. For basic authentication, it's the first 8 bytes
  392. -- of the lanman hash, followed by 8 null bytes, followed by the lanman response; for extended authentication,
  393. -- this is just the first 8 bytes of the lanman hash followed by 8 null bytes.
  394. --@param lm_hash The NTLM hash.
  395. --@param lm_response The NTLM response.
  396. --@param is_extended Should be set if extended security negotiations are being used.
  397. function lm_create_mac_key(lm_hash, lm_response, is_extended)
  398. if(have_ssl ~= true) then
  399. return false, "SMB: OpenSSL not present"
  400. end
  401. if(is_extended) then
  402. return string.sub(lm_hash, 1, 8) .. string.rep(string.char(0), 8)
  403. else
  404. return string.sub(lm_hash, 1, 8) .. string.rep(string.char(0), 8) .. lm_response
  405. end
  406. end
  407. ---Create the NTLMv2 hash, which is based on the NTLMv1 hash (for easy upgrading), the username, and the domain.
  408. -- Essentially, the NTLM hash is used as a HMAC-MD5 key, which is used to hash the unicode domain concatenated
  409. -- with the unicode username.
  410. --
  411. --@param ntlm The NTLMv1 hash.
  412. --@param username The username we're using.
  413. --@param domain The domain.
  414. --@return (status, response) If status is true, the response is returned; otherwise, an error message is returned.
  415. function ntlmv2_create_hash(ntlm, username, domain)
  416. if(have_ssl ~= true) then
  417. return false, "SMB: OpenSSL not present"
  418. end
  419. local unicode = ""
  420. username = to_unicode(string.upper(username))
  421. domain = to_unicode(string.upper(domain))
  422. return true, openssl.hmac("MD5", ntlm, username .. domain)
  423. end
  424. ---Create the LMv2 response, which can be sent back to the server. This is identical to the <code>NTLMv2</code> function,
  425. -- except that it uses an 8-byte client challenge.
  426. --
  427. -- The reason for LMv2 is a long and twisted story. Well, not really. The reason is basically that the v1 hashes
  428. -- are always 24-bytes, and some servers expect 24 bytes, but the NTLMv2 hash is more than 24 bytes. So, the only
  429. -- way to keep pass-through compatibility was to have a v2-hash that was guaranteed to be 24 bytes. So LMv1 was
  430. -- born -- it has a 16-byte hash followed by the 8-byte client challenge, for a total of 24 bytes. And now you've
  431. -- learned something
  432. --
  433. --@param ntlm The NVLMv1 hash.
  434. --@param username The username we're using.
  435. --@param domain The domain.
  436. --@param challenge The server challenge.
  437. --@return (status, response) If status is true, the response is returned; otherwise, an error message is returned.
  438. function lmv2_create_response(ntlm, username, domain, challenge)
  439. if(have_ssl ~= true) then
  440. return false, "SMB: OpenSSL not present"
  441. end
  442. return ntlmv2_create_response(ntlm, username, domain, challenge, 8)
  443. end
  444. ---Create the NTLMv2 response, which can be sent back to the server. This is done by using the HMAC-MD5 algorithm
  445. -- with the NTLMv2 hash as a key, and the server challenge concatenated with the client challenge for the data.
  446. -- The resulting hash is concatenated with the client challenge and returned.
  447. --
  448. -- The "proper" implementation for this uses a certain structure for the client challenge, involving the time
  449. -- and computer name and stuff (if you don't do this, Wireshark tells you it's a malformed packet). In my tests,
  450. -- however, I couldn't get Vista to recognize a client challenge longer than 24 bytes, and this structure was
  451. -- guaranteed to be much longer than 24 bytes. So, I just use a random string generated by OpenSSL. I've tested
  452. -- it on every Windows system from Windows 2000 to Windows Vista, and it has always worked.
  453. function ntlmv2_create_response(ntlm, username, domain, challenge, client_challenge_length)
  454. if(have_ssl ~= true) then
  455. return false, "SMB: OpenSSL not present"
  456. end
  457. local client_challenge = openssl.rand_bytes(client_challenge_length)
  458. local status, ntlmv2_hash = ntlmv2_create_hash(ntlm, username, domain)
  459. return true, openssl.hmac("MD5", ntlmv2_hash, challenge .. client_challenge) .. client_challenge
  460. end
  461. ---Generate the Lanman and NTLM password hashes. The password itself is taken from the function parameters,
  462. -- the nmap arguments, and the registry (in that order). If no password is set, then the password hash
  463. -- is used (which is read from all the usual places). If neither is set, then a blank password is used.
  464. --
  465. -- The output passwords are hashed based on the hash type.
  466. --
  467. --@param ip The ip address of the host, used for registry lookups.
  468. --@param username The username, which is used for v2 passwords.
  469. --@param domain The username, which is used for v2 passwords.
  470. --@param password [optional] The overriding password.
  471. --@param password_hash [optional] The overriding password hash. Shouldn't be set if password is set.
  472. --@param challenge The server challenge.
  473. --@param hash_type The way in which to hash the password.
  474. --@param is_extended Set to 'true' if extended security negotiations are being used (this has to be known for the
  475. -- message-signing key to be generated properly).
  476. --@return (lm_response, ntlm_response, mac_key) The two strings that can be sent directly back to the server,
  477. -- and the mac_key, which is used for message signing.
  478. function get_password_response(ip, username, domain, password, password_hash, hash_type, challenge, is_extended)
  479. local status
  480. local lm_hash = nil
  481. local ntlm_hash = nil
  482. local mac_key = nil
  483. local lm_response, ntlm_response
  484. -- Check for a blank password
  485. if(password == nil and password_hash == nil) then
  486. stdnse.print_debug(2, "SMB: Couldn't find password or hash to use (assuming blank)")
  487. password = ""
  488. end
  489. -- The anonymous user requires a single 0-byte instead of a LANMAN hash (don't ask me why, but it doesn't work without)
  490. if(hash_type == 'none') then
  491. return string.char(0), '', nil
  492. end
  493. -- If we got a password, hash it
  494. if(password ~= nil) then
  495. status, lm_hash = lm_create_hash(password)
  496. status, ntlm_hash = ntlm_create_hash(password)
  497. else
  498. if(password_hash ~= nil) then
  499. if(string.find(password_hash, "^" .. string.rep("%x%x", 16) .. "$")) then
  500. stdnse.print_debug(2, "SMB: Found a 16-byte hex string")
  501. lm_hash = bin.pack("H", password_hash:sub(1, 32))
  502. ntlm_hash = bin.pack("H", password_hash:sub(1, 32))
  503. elseif(string.find(password_hash, "^" .. string.rep("%x%x", 32) .. "$")) then
  504. stdnse.print_debug(2, "SMB: Found a 32-byte hex string")
  505. lm_hash = bin.pack("H", password_hash:sub(1, 32))
  506. ntlm_hash = bin.pack("H", password_hash:sub(33, 64))
  507. elseif(string.find(password_hash, "^" .. string.rep("%x%x", 16) .. "." .. string.rep("%x%x", 16) .. "$")) then
  508. stdnse.print_debug(2, "SMB: Found two 16-byte hex strings")
  509. lm_hash = bin.pack("H", password_hash:sub(1, 32))
  510. ntlm_hash = bin.pack("H", password_hash:sub(34, 65))
  511. else
  512. stdnse.print_debug(1, "SMB: ERROR: Hash(es) provided in an invalid format (should be 32, 64, or 65 hex characters)")
  513. lm_hash = nil
  514. ntlm_hash = nil
  515. end
  516. end
  517. end
  518. -- At this point, we should have a good lm_hash and ntlm_hash if we're getting one
  519. if(lm_hash == nil or ntlm_hash == nil) then
  520. stdnse.print_debug(2, "SMB: Couldn't determine which password to use, using a blank one")
  521. return "", ""
  522. end
  523. -- Output what we've got so far
  524. stdnse.print_debug(2, "SMB: Lanman hash: %s", stdnse.tohex(lm_hash))
  525. stdnse.print_debug(2, "SMB: NTLM hash: %s", stdnse.tohex(ntlm_hash))
  526. -- Hash the password the way the user wants
  527. if(hash_type == "v1") then
  528. -- LM and NTLM are hashed with their respective algorithms
  529. stdnse.print_debug(2, "SMB: Creating v1 response")
  530. status, lm_response = lm_create_response(lm_hash, challenge)
  531. status, ntlm_response = ntlm_create_response(ntlm_hash, challenge)
  532. mac_key = ntlm_create_mac_key(ntlm_hash, ntlm_response, is_extended)
  533. elseif(hash_type == "lm") then
  534. -- LM is hashed with its algorithm, NTLM is blank
  535. stdnse.print_debug(2, "SMB: Creating LMv1 response")
  536. status, lm_response = lm_create_response(lm_hash, challenge)
  537. ntlm_response = ""
  538. mac_key = lm_create_mac_key(lm_hash, lm_response, is_extended)
  539. elseif(hash_type == "ntlm") then
  540. -- LM and NTLM both use the NTLM algorithm
  541. stdnse.print_debug(2, "SMB: Creating NTLMv1 response")
  542. status, lm_response = ntlm_create_response(ntlm_hash, challenge)
  543. status, ntlm_response = ntlm_create_response(ntlm_hash, challenge)
  544. mac_key = ntlm_create_mac_key(ntlm_hash, ntlm_response, is_extended)
  545. elseif(hash_type == "v2") then
  546. -- LM and NTLM are hashed with their respective v2 algorithms
  547. stdnse.print_debug(2, "SMB: Creating v2 response")
  548. status, lm_response = lmv2_create_response(ntlm_hash, username, domain, challenge)
  549. status, ntlm_response = ntlmv2_create_response(ntlm_hash, username, domain, challenge, 24)
  550. elseif(hash_type == "lmv2") then
  551. -- LM is hashed with its v2 algorithm, NTLM is blank
  552. stdnse.print_debug(2, "SMB: Creating LMv2 response")
  553. status, lm_response = lmv2_create_response(ntlm_hash, username, domain, challenge)
  554. ntlm_response = ""
  555. else
  556. -- Default to NTLMv1
  557. if(hash_type ~= nil) then
  558. stdnse.print_debug(1, "SMB: Invalid login type specified ('%s'), using default (NTLM)", hash_type)
  559. else
  560. stdnse.print_debug(1, "SMB: No login type specified, using default (NTLM)")
  561. end
  562. status, lm_response = ntlm_create_response(ntlm_hash, challenge)
  563. status, ntlm_response = ntlm_create_response(ntlm_hash, challenge)
  564. end
  565. stdnse.print_debug(2, "SMB: Lanman response: %s", stdnse.tohex(lm_response))
  566. stdnse.print_debug(2, "SMB: NTLM response: %s", stdnse.tohex(ntlm_response))
  567. return lm_response, ntlm_response, mac_key
  568. end
  569. function get_security_blob(security_blob, ip, username, domain, password, password_hash, hash_type, flags)
  570. local pos = 1
  571. local new_blob
  572. local flags = flags or 0x00008215 -- (NEGOTIATE_SIGN_ALWAYS | NEGOTIATE_NTLM | NEGOTIATE_SIGN | REQUEST_TARGET | NEGOTIATE_UNICODE)
  573. if(security_blob == nil) then
  574. -- If security_blob is nil, this is the initial packet
  575. new_blob = bin.pack("<zIILL",
  576. "NTLMSSP", -- Identifier
  577. NTLMSSP_NEGOTIATE, -- Type
  578. flags, -- Flags
  579. 0, -- Calling workstation domain
  580. 0 -- Calling workstation name
  581. )
  582. return true, new_blob, "", ""
  583. else
  584. -- Parse the old security blob
  585. local pos, identifier, message_type, domain_length, domain_max, domain_offset, server_flags, challenge, reserved = bin.unpack("<LISSIIA8A8", security_blob, 1)
  586. local lanman, ntlm, mac_key = get_password_response(ip, username, domain, password, password_hash, hash_type, challenge, true)
  587. -- Convert the username and domain to unicode (TODO: Disable the unicode flag, evaluate if that'll work)
  588. local hostname = to_unicode("nmap")
  589. username = to_unicode(username)
  590. domain = (#username > 0 ) and to_unicode(domain) or ""
  591. ntlm = (#username > 0 ) and ntlm or ""
  592. lanman = (#username > 0 ) and lanman or string.char(0)
  593. local domain_offset = 0x40
  594. local username_offset = domain_offset + #domain
  595. local hostname_offset = username_offset + #username
  596. local lanman_offset = hostname_offset + #hostname
  597. local ntlm_offset = lanman_offset + #lanman
  598. local sessionkey_offset = ntlm_offset + #ntlm
  599. new_blob = bin.pack("<zISSISSISSISSISSISSIIAAAAAA",
  600. "NTLMSSP",
  601. NTLMSSP_AUTH,
  602. #lanman,
  603. #lanman,
  604. lanman_offset,
  605. ( #ntlm > 0 and #ntlm - 16 or 0 ),
  606. ( #ntlm > 0 and #ntlm - 16 or 0 ),
  607. ntlm_offset,
  608. #domain,
  609. #domain,
  610. domain_offset,
  611. #username,
  612. #username,
  613. username_offset,
  614. #hostname,
  615. #hostname,
  616. hostname_offset,
  617. #session_key,
  618. #session_key,
  619. sessionkey_offset,
  620. flags,
  621. domain,
  622. username,
  623. hostname,
  624. lanman,
  625. ntlm,
  626. session_key)
  627. return true, new_blob, mac_key
  628. end
  629. end
  630. function get_host_info_from_security_blob(security_blob)
  631. local ntlm_challenge = {}
  632. --local pos, identifier, message_type, domain_length, domain_max, domain_offset, server_flags, challenge, reserved, target_info_length, target_info_max, target_info_offset = bin.unpack("<A8ISSIILLSSI", security_blob)
  633. local pos, identifier, message_type, domain_length, domain_max, domain_offset, server_flags, challenge, reserved, target_info_length, target_info_max, target_info_offset = bin.unpack("<A8ISSIILLSSI", security_blob)
  634. -- Do some validation on the NTLMSSP message
  635. if ( identifier ~= "NTLMSSP\0" ) then
  636. stdnse.print_debug( 1, "SMB: Invalid NTLM challenge message: unexpected signature." )
  637. return false, "Invalid NTLM challenge message"
  638. -- Per MS-NLMP, this field must be 2 for an NTLM challenge message
  639. elseif ( message_type ~= 0x2 ) then
  640. stdnse.print_debug( 1, "SMB: Invalid NTLM challenge message: unexpected message type: %d.", message_type )
  641. return false, "Invalid message type in NTLM challenge message"
  642. end
  643. -- Parse the TargetName data (i.e. the server authentication realm)
  644. if ( domain_length > 0 ) then
  645. local length = domain_length
  646. local pos = domain_offset + 1 -- +1 to convert to Lua's 1-based indexes
  647. local target_realm
  648. pos, target_realm = bin.unpack( string.format( "A%d", length ), security_blob, pos )
  649. ntlm_challenge[ "target_realm" ] = from_unicode( target_realm )
  650. end
  651. -- Parse the TargetInfo data (Wireshark calls this the "Address List")
  652. if ( target_info_length > 0 ) then
  653. -- Definition of AvId values (IDs for AV_PAIR (attribute-value pair) structures),
  654. -- as definied by the NTLM Authentication Protocol specification [MS-NLMP].
  655. local NTLM_AV_ID_VALUES = {
  656. MsvAvEOL = 0x0,
  657. MsvAvNbComputerName = 0x1,
  658. MsvAvNbDomainName = 0x2,
  659. MsvAvDnsComputerName = 0x3,
  660. MsvAvDnsDomainName = 0x4,
  661. MsvAvDnsTreeName = 0x5,
  662. MsvAvFlags = 0x6,
  663. MsvAvTimestamp = 0x7,
  664. MsvAvRestrictions = 0x8,
  665. MsvAvTargetName = 0x9,
  666. MsvAvChannelBindings = 0xA,
  667. }
  668. -- Friendlier names for AvId values, to be used as keys in the results table
  669. -- e.g. ntlm_challenge[ "dns_computer_name" ] -> "host.test.local"
  670. local NTLM_AV_ID_NAMES = {
  671. [NTLM_AV_ID_VALUES.MsvAvNbComputerName] = "netbios_computer_name",
  672. [NTLM_AV_ID_VALUES.MsvAvNbDomainName] = "netbios_domain_name",
  673. [NTLM_AV_ID_VALUES.MsvAvDnsComputerName] = "fqdn",
  674. [NTLM_AV_ID_VALUES.MsvAvDnsDomainName] = "dns_domain_name",
  675. [NTLM_AV_ID_VALUES.MsvAvDnsTreeName] = "dns_forest_name",
  676. [NTLM_AV_ID_VALUES.MsvAvTimestamp] = "timestamp",
  677. }
  678. local length = target_info_length
  679. local pos = target_info_offset + 1 -- +1 to convert to Lua's 1-based indexes
  680. local target_info
  681. pos, target_info = bin.unpack( string.format( "A%d", length ), security_blob, pos )
  682. pos = 1 -- reset pos to 1, since we'll be working out of just the target_info
  683. repeat
  684. local value, av_id, av_len
  685. pos, av_id, av_len = bin.unpack( "<SS", target_info, pos )
  686. pos, value = bin.unpack( string.format( "A%d", av_len ), target_info, pos )
  687. local friendly_name = NTLM_AV_ID_NAMES[ av_id ]
  688. if ( av_id == NTLM_AV_ID_VALUES.MsvAvEOL ) then
  689. break
  690. elseif ( av_id == NTLM_AV_ID_VALUES.MsvAvTimestamp ) then
  691. -- this is a FILETIME value (see [MS-DTYP]), representing the time in 100-ns increments since 1/1/1601
  692. ntlm_challenge[ friendly_name ] = bin.unpack( "<L", value )
  693. elseif ( friendly_name ) then
  694. ntlm_challenge[ friendly_name ] = from_unicode( value )
  695. end
  696. until ( pos >= #target_info )
  697. end
  698. return ntlm_challenge
  699. end
  700. ---Create an 8-byte message signature that's sent with all SMB packets.
  701. --
  702. --@param mac_key The key used for authentication. It's the concatination of the session key and the
  703. -- response hash.
  704. --@param data The packet to generate the signature for. This should be the packet that's about to be
  705. -- sent, except with the signature slot replaced with the sequence number.
  706. --@return The 8-byte signature. The signature is equal to the first eight bytes of md5(mac_key .. smb_data)
  707. function calculate_signature(mac_key, data)
  708. if(have_ssl) then
  709. return string.sub(openssl.md5(mac_key .. data), 1, 8)
  710. else
  711. return string.rep(string.char(0), 8)
  712. end
  713. end
  714. return _ENV;