CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
rapid7

Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.

GitHub Repository: rapid7/metasploit-framework
Path: blob/master/lib/rex/proto/ntlm/message.rb
Views: 11704
1
# -*- coding: binary -*-
2
#
3
# An NTLM Authentication Library for Ruby
4
#
5
# This code is a derivative of "dbf2.rb" written by yrock
6
# and Minero Aoki. You can find original code here:
7
# http://jp.rubyist.net/magazine/?0013-CodeReview
8
# -------------------------------------------------------------
9
# Copyright (c) 2005,2006 yrock
10
#
11
# This program is free software.
12
# You can distribute/modify this program under the terms of the
13
# Ruby License.
14
#
15
# 2011-02-23 refactored by Alexandre Maloteaux for Metasploit Project
16
# -------------------------------------------------------------
17
#
18
# 2006-02-11 refactored by Minero Aoki
19
# -------------------------------------------------------------
20
#
21
# All protocol information used to write this code stems from
22
# "The NTLM Authentication Protocol" by Eric Glass. The author
23
# would thank to him for this tremendous work and making it
24
# available on the net.
25
# http://davenport.sourceforge.net/ntlm.html
26
# -------------------------------------------------------------
27
# Copyright (c) 2003 Eric Glass
28
#
29
# Permission to use, copy, modify, and distribute this document
30
# for any purpose and without any fee is hereby granted,
31
# provided that the above copyright notice and this list of
32
# conditions appear in all copies.
33
# -------------------------------------------------------------
34
#
35
# The author also looked Mozilla-Firefox-1.0.7 source code,
36
# namely, security/manager/ssl/src/nsNTLMAuthModule.cpp and
37
# Jonathan Bastien-Filiatrault's libntlm-ruby.
38
# "http://x2a.org/websvn/filedetails.php?
39
# repname=libntlm-ruby&path=%2Ftrunk%2Fntlm.rb&sc=1"
40
# The latter has a minor bug in its separate_keys function.
41
# The third key has to begin from the 14th character of the
42
# input string instead of 13th:)
43
44
#this module defines the message class , useful for easily handling type 1/2/3 ntlm messages
45
46
47
48
module Rex
49
module Proto
50
module NTLM
51
class Message < Rex::Proto::NTLM::Base::FieldSet
52
53
BASE = Rex::Proto::NTLM::Base
54
CONST = Rex::Proto::NTLM::Constants
55
CRYPT = Rex::Proto::NTLM::Crypt
56
57
58
class << Message
59
def parse(str)
60
m = Type0.new
61
m.parse(str)
62
case m.type
63
when 1
64
t = Type1.parse(str)
65
when 2
66
t = Type2.parse(str)
67
when 3
68
t = Type3.parse(str)
69
else
70
raise ArgumentError, "unknown type: #{m.type}"
71
end
72
t
73
end
74
75
def decode64(str)
76
parse(Rex::Text::decode_base64(str))
77
end
78
end#self
79
80
def has_flag?(flag)
81
(self[:flag].value & CONST::FLAGS[flag]) == CONST::FLAGS[flag]
82
end
83
84
def set_flag(flag)
85
self[:flag].value |= CONST::FLAGS[flag]
86
end
87
88
def dump_flags
89
CONST::FLAG_KEYS.each{ |k| print(k, "=", flag?(k), "\n") }
90
end
91
92
def serialize
93
deflag
94
super + security_buffers.map{|n, f| f.value}.join
95
end
96
97
def encode64
98
Rex::Text::encode_base64(serialize)
99
end
100
101
def decode64(str)
102
parse(Rex::Text::decode_base64(str))
103
end
104
105
alias head_size size
106
107
def data_size
108
security_buffers.inject(0){|sum, a| sum += a[1].data_size}
109
end
110
111
def size
112
head_size + data_size
113
end
114
115
private
116
117
def security_buffers
118
@alist.find_all{|n, f| f.instance_of?(BASE::SecurityBuffer)}
119
end
120
121
def deflag
122
security_buffers.inject(head_size){|cur, a|
123
a[1].offset = cur
124
cur += a[1].data_size
125
}
126
end
127
128
def data_edge
129
security_buffers.map{ |n, f| f.active ? f.offset : size}.min
130
end
131
132
# sub class definitions
133
134
Type0 = Message.define {
135
string :sign, {:size => 8, :value => CONST::SSP_SIGN}
136
int32LE :type, {:value => 0}
137
}
138
139
Type1 = Message.define {
140
string :sign, {:size => 8, :value => CONST::SSP_SIGN}
141
int32LE :type, {:value => 1}
142
int32LE :flag, {:value => CONST::DEFAULT_FLAGS[:TYPE1] }
143
security_buffer :domain, {:value => "", :active => false}
144
security_buffer :workstation, {:value => "", :active => false}
145
string :padding, {:size => 0, :value => "", :active => false }
146
}
147
148
class Type1
149
class << Type1
150
def parse(str)
151
t = new
152
t.parse(str)
153
t
154
end
155
end
156
157
def parse(str)
158
super(str)
159
enable(:domain) if has_flag?(:DOMAIN_SUPPLIED)
160
enable(:workstation) if has_flag?(:WORKSTATION_SUPPLIED)
161
super(str)
162
if ( (len = data_edge - head_size) > 0)
163
self.padding = "\0" * len
164
super(str)
165
end
166
end
167
end
168
169
Type2 = Message.define{
170
string :sign, {:size => 8, :value => CONST::SSP_SIGN}
171
int32LE :type, {:value => 2}
172
security_buffer :target_name, {:size => 0, :value => ""}
173
int32LE :flag, {:value => CONST::DEFAULT_FLAGS[:TYPE2]}
174
int64LE :challenge, {:value => 0}
175
int64LE :context, {:value => 0, :active => false}
176
security_buffer :target_info, {:value => "", :active => false}
177
string :padding, {:size => 0, :value => "", :active => false }
178
}
179
180
class Type2
181
class << Type2
182
def parse(str)
183
t = new
184
t.parse(str)
185
t
186
end
187
end
188
189
def parse(str)
190
super(str)
191
if has_flag?(:TARGET_INFO)
192
enable(:context)
193
enable(:target_info)
194
super(str)
195
end
196
if ( (len = data_edge - head_size) > 0)
197
self.padding = "\0" * len
198
super(str)
199
end
200
end
201
#create a type 3 response base on a type2
202
# This method is not compatible with windows 7 / 2008 r2
203
# to make it compatible avpair Time and SPN must be handle as in utils
204
def response(arg, opt = {})
205
usr = arg[:user]
206
pwd = arg[:password]
207
if usr.nil? or pwd.nil?
208
raise ArgumentError, "user and password have to be supplied"
209
end
210
211
if opt[:workstation]
212
ws = opt[:workstation]
213
else
214
ws = ""
215
end
216
217
if opt[:client_challenge]
218
cc = opt[:client_challenge]
219
else
220
cc = rand(CONST::MAX64)
221
end
222
cc = Rex::Text::pack_int64le(cc) if cc.is_a?(Integer)
223
opt[:client_challenge] = cc
224
225
if has_flag?(:OEM) and opt[:unicode]
226
usr = Rex::Text::to_ascii(usr,'utf-16le')
227
pwd = Rex::Text::to_ascii(pwd,'utf-16le')
228
ws = Rex::Text::to_ascii(ws,'utf-16le')
229
opt[:unicode] = false
230
end
231
232
if has_flag?(:UNICODE) and !opt[:unicode]
233
usr = Rex::Text::to_unicode(usr,'utf-16le')
234
pwd = Rex::Text::to_unicode(pwd,'utf-16le')
235
ws = Rex::Text::to_unicode(ws,'utf-16le')
236
opt[:unicode] = true
237
end
238
239
tgt = self.target_name
240
ti = self.target_info
241
242
chal = self[:challenge].serialize
243
244
if opt[:ntlmv2]
245
ar = { :ntlmv2_hash => CRYPT::ntlmv2_hash(usr, pwd, tgt, opt),
246
:challenge => chal, :target_info => ti}
247
lm_res = CRYPT::lmv2_response(ar, opt)
248
ntlm_res = CRYPT::ntlmv2_response(ar, opt)
249
elsif has_flag?(:NTLM2_KEY)
250
ar = {:ntlm_hash => CRYPT::ntlm_hash(pwd, opt), :challenge => chal}
251
lm_res, ntlm_res = CRYPT::ntlm2_session(ar, opt)
252
else
253
lm_res = CRYPT::lm_response(pwd, chal)
254
ntlm_res = CRYPT::ntlm_response(pwd, chal)
255
end
256
257
Type3.create({
258
:lm_response => lm_res,
259
:ntlm_response => ntlm_res,
260
:domain => tgt,
261
:user => usr,
262
:workstation => ws,
263
:flag => self.flag
264
})
265
end
266
end
267
268
269
Type3 = Message.define{
270
string :sign, {:size => 8, :value => CONST::SSP_SIGN}
271
int32LE :type, {:value => 3}
272
security_buffer :lm_response, {:value => ""}
273
security_buffer :ntlm_response, {:value => ""}
274
security_buffer :domain, {:value => ""}
275
security_buffer :user, {:value => ""}
276
security_buffer :workstation, {:value => ""}
277
security_buffer :session_key, {:value => "", :active => false }
278
int64LE :flag, {:value => 0, :active => false }
279
}
280
281
class Type3
282
class << Type3
283
def parse(str)
284
t = new
285
t.parse(str)
286
t
287
end
288
289
def create(arg, opt ={})
290
t = new
291
t.lm_response = arg[:lm_response]
292
t.ntlm_response = arg[:ntlm_response]
293
t.domain = arg[:domain]
294
t.user = arg[:user]
295
t.workstation = arg[:workstation]
296
297
if arg[:session_key]
298
t.enable(:session_key)
299
t.session_key = arg[session_key]
300
end
301
if arg[:flag]
302
t.enable(:session_key)
303
t.enable(:flag)
304
t.flag = arg[:flag]
305
end
306
t
307
end
308
end#self
309
end
310
311
public
312
#those class method have been merged from lib/rex/smb/utils
313
314
#
315
# Process Type 3 NTLM Message (in Base64)
316
#
317
# from http://www.innovation.ch/personal/ronald/ntlm.html
318
#
319
# struct {
320
# byte protocol[8]; // 'N', 'T', 'L', 'M', 'S', 'S', 'P', '\0'
321
# byte type; // 0x03
322
# byte zero[3];
323
#
324
# short lm_resp_len; // LanManager response length (always 0x18)
325
# short lm_resp_len; // LanManager response length (always 0x18)
326
# short lm_resp_off; // LanManager response offset
327
# byte zero[2];
328
#
329
# short nt_resp_len; // NT response length (always 0x18)
330
# short nt_resp_len; // NT response length (always 0x18)
331
# short nt_resp_off; // NT response offset
332
# byte zero[2];
333
#
334
# short dom_len; // domain string length
335
# short dom_len; // domain string length
336
# short dom_off; // domain string offset (always 0x40)
337
# byte zero[2];
338
#
339
# short user_len; // username string length
340
# short user_len; // username string length
341
# short user_off; // username string offset
342
# byte zero[2];
343
#
344
# short host_len; // host string length
345
# short host_len; // host string length
346
# short host_off; // host string offset
347
# byte zero[6];
348
#
349
# short msg_len; // message length
350
# byte zero[2];
351
#
352
# short flags; // 0x8201
353
# byte zero[2];
354
#
355
# byte dom[*]; // domain string (unicode UTF-16LE)
356
# byte user[*]; // username string (unicode UTF-16LE)
357
# byte host[*]; // host string (unicode UTF-16LE)
358
# byte lm_resp[*]; // LanManager response
359
# byte nt_resp[*]; // NT response
360
# } type_3_message
361
#
362
def self.process_type3_message(message)
363
decode = Rex::Text.decode_base64(message.strip)
364
type = decode[8,1].unpack("C").first
365
if (type == 3)
366
lm_len = decode[12,2].unpack("v").first
367
lm_offset = decode[16,2].unpack("v").first
368
lm = decode[lm_offset, lm_len].unpack("H*").first
369
370
nt_len = decode[20,2].unpack("v").first
371
nt_offset = decode[24,2].unpack("v").first
372
nt = decode[nt_offset, nt_len].unpack("H*").first
373
374
dom_len = decode[28,2].unpack("v").first
375
dom_offset = decode[32,2].unpack("v").first
376
domain = decode[dom_offset, dom_len]
377
378
user_len = decode[36,2].unpack("v").first
379
user_offset = decode[40,2].unpack("v").first
380
user = decode[user_offset, user_len]
381
382
host_len = decode[44,2].unpack("v").first
383
host_offset = decode[48,2].unpack("v").first
384
host = decode[host_offset, host_len]
385
386
return domain, user, host, lm, nt
387
else
388
return "", "", "", "", ""
389
end
390
end
391
392
393
394
#
395
# Process Type 1 NTLM Messages, return a Base64 Type 2 Message
396
#
397
def self.process_type1_message(message, nonce = "\x11\x22\x33\x44\x55\x66\x77\x88", win_domain = 'DOMAIN',
398
win_name = 'SERVER', dns_name = 'server', dns_domain = 'example.com', downgrade = true)
399
400
dns_name = Rex::Text.to_unicode(dns_name + "." + dns_domain)
401
win_domain = Rex::Text.to_unicode(win_domain)
402
dns_domain = Rex::Text.to_unicode(dns_domain)
403
win_name = Rex::Text.to_unicode(win_name)
404
decode = Rex::Text.decode_base64(message.strip)
405
406
type = decode[8,1].unpack("C").first
407
408
if (type == 1)
409
# A type 1 message has been received, lets build a type 2 message response
410
411
reqflags = decode[12,4]
412
reqflags = reqflags.unpack("V").first
413
414
if (reqflags & CONST::REQUEST_TARGET) == CONST::REQUEST_TARGET
415
416
if (downgrade)
417
# At this time NTLMv2 and signing requirements are not supported
418
if (reqflags & CONST::NEGOTIATE_NTLM2_KEY) == CONST::NEGOTIATE_NTLM2_KEY
419
reqflags = reqflags - CONST::NEGOTIATE_NTLM2_KEY
420
end
421
if (reqflags & CONST::NEGOTIATE_ALWAYS_SIGN) == CONST::NEGOTIATE_ALWAYS_SIGN
422
reqflags = reqflags - CONST::NEGOTIATE_ALWAYS_SIGN
423
end
424
end
425
426
flags = reqflags + CONST::TARGET_TYPE_DOMAIN + CONST::TARGET_TYPE_SERVER
427
tid = true
428
429
tidoffset = 48 + win_domain.length
430
tidbuff =
431
[2].pack('v') + # tid type, win domain
432
[win_domain.length].pack('v') +
433
win_domain +
434
[1].pack('v') + # tid type, server name
435
[win_name.length].pack('v') +
436
win_name +
437
[4].pack('v') + # tid type, domain name
438
[dns_domain.length].pack('v') +
439
dns_domain +
440
[3].pack('v') + # tid type, dns_name
441
[dns_name.length].pack('v') +
442
dns_name
443
else
444
flags = CONST::NEGOTIATE_UNICODE + CONST::NEGOTIATE_NTLM
445
tid = false
446
end
447
448
type2msg = "NTLMSSP\0" + # protocol, 8 bytes
449
"\x02\x00\x00\x00" # type, 4 bytes
450
451
if (tid)
452
type2msg += # Target security info, 8 bytes. Filled if REQUEST_TARGET
453
[win_domain.length].pack('v') + # Length, 2 bytes
454
[win_domain.length].pack('v') # Allocated space, 2 bytes
455
end
456
457
type2msg +="\x30\x00\x00\x00" + # Offset, 4 bytes
458
[flags].pack('V') + # flags, 4 bytes
459
nonce + # the nonce, 8 bytes
460
"\x00" * 8 # Context (all 0s), 8 bytes
461
462
if (tid)
463
type2msg += # Target information security buffer. Filled if REQUEST_TARGET
464
[tidbuff.length].pack('v') + # Length, 2 bytes
465
[tidbuff.length].pack('v') + # Allocated space, 2 bytes
466
[tidoffset].pack('V') + # Offset, 4 bytes (usually \x48 + length of win_domain)
467
win_domain + # Target name data (domain in unicode if REQUEST_UNICODE)
468
# Target information data
469
tidbuff + # Type, 2 bytes
470
# Length, 2 bytes
471
# Data (in unicode if REQUEST_UNICODE)
472
"\x00\x00\x00\x00" # Terminator, 4 bytes, all \x00
473
end
474
475
type2msg = Rex::Text.encode_base64(type2msg).delete("\n") # base64 encode and remove the returns
476
else
477
# This is not a Type2 message
478
type2msg = ""
479
end
480
481
return type2msg
482
end
483
484
#
485
# Downgrading Type messages to LMv1/NTLMv1 and removing signing
486
#
487
def self.downgrade_type_message(message)
488
decode = Rex::Text.decode_base64(message.strip)
489
490
type = decode[8,1].unpack("C").first
491
492
if (type > 0 and type < 4)
493
reqflags = decode[12..15] if (type == 1 or type == 3)
494
reqflags = decode[20..23] if (type == 2)
495
reqflags = reqflags.unpack("V")
496
497
# Remove NEGOTIATE_NTLMV2_KEY and NEGOTIATE_ALWAYS_SIGN, this lowers the negotiation
498
# down to LMv1/NTLMv1.
499
if (reqflags & CONST::NEGOTIATE_NTLM2_KEY) == CONST::NEGOTIATE_NTLM2_KEY
500
reqflags = reqflags - CONST::NEGOTIATE_NTLM2_KEY
501
end
502
if (reqflags & CONST::NEGOTIATE_ALWAYS_SIGN) == CONST::NEGOTIATE_ALWAYS_SIGN
503
reqflags = reqflags - CONST::NEGOTIATE_ALWAYS_SIGN
504
end
505
506
# Return the flags back to the decode so we can base64 it again
507
flags = reqflags.to_s(16)
508
0.upto(8) do |idx|
509
if (idx > flags.length)
510
flags.insert(0, "0")
511
end
512
end
513
514
idx = 0
515
0.upto(3) do |cnt|
516
if (type == 2)
517
decode[23-cnt] = [flags[idx,1]].pack("C")
518
else
519
decode[15-cnt] = [flags[idx,1]].pack("C")
520
end
521
idx += 2
522
end
523
524
end
525
return Rex::Text.encode_base64(decode).delete("\n") # base64 encode and remove the returns
526
end
527
528
end
529
end
530
end
531
end
532
533