-
Notifications
You must be signed in to change notification settings - Fork 2
/
authentifier.go
482 lines (399 loc) · 13 KB
/
authentifier.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
package ntlm
import (
"bytes"
"context"
"fmt"
"hash"
"github.com/oiweiwei/go-msrpc/ssp/crypto"
)
// The NTLM Authentifier.
type Authentifier struct {
// The authentifier configuration.
Config *Config
// The list of messages for MIC computation.
mic bytes.Buffer
// The cryptographic state of the NTLM.
state *SecurityService
// The negotiated session parameters.
session *SecurityParameters
}
func (a *Authentifier) SessionKey() []byte {
if a.state != nil {
return a.state.ExportedSessionKey
}
return nil
}
func (a *Authentifier) TargetName() string {
if a.session != nil {
if a.session.DomainName != "" {
return a.session.DomainName
} else if a.session.ServerName != "" {
return a.session.ServerName
}
}
return ""
}
func (a *Authentifier) Reset() {
a.state, a.session = nil, nil
if a.mic.Reset(); a.Config == nil {
a.Config = &Config{}
}
}
// The authentifier state structure represents the negotiated
// authentication state.
type SecurityService struct {
// The exported session key.
ExportedSessionKey []byte
// The client signing key.
ClientSignKey []byte
// The client sealing key.
ClientSealKey []byte
// The server signing key.
ServerSignKey []byte
// The server sealing key.
ServerSealKey []byte
// The client cipher.
OutboundCipher *Cipher
// The server cipher.
InboundCipher *Cipher
// The sequence number to send.
OutboundSequenceNumber uint32
// The sequence number to receive.
InboundSequenceNumber uint32
}
// Negotiate function returns the initial token.
func (a *Authentifier) Negotiate(ctx context.Context) ([]byte, error) {
a.Reset()
nm := &NegotiateMessage{
Negotiate: a.Config.Negotiate(),
Version: a.Config.Version,
}
if a.Config.Credential != nil {
nm.DomainName = a.Config.Credential.DomainName()
nm.Workstation = a.Config.Credential.Workstation()
}
if nm.Negotiate.IsSet(NegotiateVersion) {
if nm.Version.IsZero() {
nm.Version = DefaultVersion
}
// clear domain/workstation if version is set.
nm.DomainName = ""
nm.Workstation = ""
}
if nm.DomainName != "" {
nm.Negotiate = nm.Negotiate.Set(NegotiateOEMDomainSupplied)
}
if nm.Workstation != "" {
nm.Negotiate = nm.Negotiate.Set(NegotiateOEMWorkstationSupplied)
}
b, err := nm.Marshal(ctx)
if err != nil {
return nil, fmt.Errorf("ntlm: init: negotiate: %w", err)
}
a.mic.Write(b)
return b, nil
}
// Authenticate function accepts the token containing the ChallengeMessage and returns
// the AuthenticateMessage token.
func (a *Authentifier) Authenticate(ctx context.Context, b []byte) ([]byte, error) {
cm := &ChallengeMessage{}
// unmarshal challenge message.
if err := cm.Unmarshal(ctx, b); err != nil {
return nil, fmt.Errorf("ntlm: init: authenticate: unmarshal challenge message: %w", err)
}
// check negotiated parameters.
if err := a.Config.Verify(cm.Negotiate); err != nil {
return nil, fmt.Errorf("ntlm: init: authenticate: %w", err)
}
// set session parameters.
a.makeSecurityParameters(ctx, cm)
ntlm := a.Config.NewNTLMVersion(ctx, a.Config, a.session)
// generate nonce.
clientChallenge, err := crypto.Nonce(8)
if err != nil {
return nil, fmt.Errorf("ntlm: init: authenticate: generate nonce: %w", err)
}
// compute challenge response.
resp, err := ntlm.ChallengeResponse(ctx, a.Config.Credential, cm, clientChallenge)
if err != nil {
return nil, fmt.Errorf("ntlm: init: authenticate: compute challenge response: %w", err)
}
// compute key-exchange-key.
if resp.KeyExchangeKey, err = ntlm.KeyExchangeKey(ctx, cm, resp); err != nil {
return nil, fmt.Errorf("ntlm: init: authenticate: compute key-exchange-key: %w", err)
}
// append challenge message to buffer.
a.mic.Write(b)
am := &AuthenticateMessage{
Negotiate: cm.Negotiate,
LMChallengeResponse: resp.LM,
NTChallengeResponse: resp.NT,
DomainName: a.Config.Credential.DomainName(),
UserName: a.Config.Credential.UserName(),
Workstation: a.Config.Credential.Workstation(),
MIC: make([]byte, 16),
}
var exportedKey []byte
if a.session.KeyExchange {
if exportedKey, err = crypto.Nonce(16); err != nil {
return nil, fmt.Errorf("ntlm: init: authenticate: compute exported session key: %w", err)
}
if am.EncryptedRandomSessionKey, err = RC4K(ctx, resp.KeyExchangeKey, exportedKey); err != nil {
return nil, fmt.Errorf("ntlm: init: authenticate: compute encrypted random session key: %w", err)
}
} else {
exportedKey = resp.KeyExchangeKey
}
// initialize sealing and signing.
if err = a.makeSecurityService(ctx, exportedKey); err != nil {
return nil, fmt.Errorf("ntlm: init: authenticate: initialize authenticator state: %w", err)
}
b, err = am.Marshal(ctx)
if err != nil {
return nil, fmt.Errorf("ntlm: init: authenticate: marshal response: %w", err)
}
// append message to the buffer.
a.mic.Write(b)
if resp.RequestMIC {
// calculate mic.
if am.MIC, err = crypto.HMAC_MD5(exportedKey, a.mic.Bytes()); err != nil {
return nil, fmt.Errorf("ntlm: init: authenticate: compute mic: %w", err)
}
// copy mic value.
copy(b[micidx:], am.MIC)
// reset the mic buffer.
a.mic.Reset()
}
return b, nil
}
// The MIC index in the output buffer.
const micidx = 72
var (
// client-to-server seal.
magicSealC2S = []byte("session key to client-to-server sealing key magic constant\x00")
// server-to-client seal.
magicSealS2C = []byte("session key to server-to-client sealing key magic constant\x00")
// client-to-server sign.
magicSignC2S = []byte("session key to client-to-server signing key magic constant\x00")
// server-to-client sign.
magicSignS2C = []byte("session key to server-to-client signing key magic constant\x00")
)
func (a *Authentifier) ResetSecurityService(ctx context.Context) error {
if err := a.makeSecurityService(ctx, a.state.ExportedSessionKey); err != nil {
return err
}
return nil
}
// makeSecurityService function initializes the signing and sealing data structures.
func (a *Authentifier) makeSecurityService(ctx context.Context, key []byte) error {
var err error
if a.state == nil {
a.state = &SecurityService{ExportedSessionKey: key}
}
// client signing key.
if a.state.ClientSignKey, err = a.makeSignKey(ctx, key, magicSignC2S); err != nil {
return err
}
// server signing key.
if a.state.ServerSignKey, err = a.makeSignKey(ctx, key, magicSignS2C); err != nil {
return err
}
// client seal key.
if a.state.ClientSealKey, err = a.makeSealKey(ctx, key, magicSealC2S); err != nil {
return err
}
// server seal key.
if a.state.ServerSealKey, err = a.makeSealKey(ctx, key, magicSealS2C); err != nil {
return err
}
// client hmac-md5/crc32 checksum function.
clientHash := a.makeHashFunc(ctx, a.state.ClientSignKey)
// client rc4 cipher.
clientCipher, err := NewCipher(ctx, a.state.ClientSealKey, clientHash)
if err != nil {
return err
}
// server hmac-md5/crc32 checksum function.
serverHash := a.makeHashFunc(ctx, a.state.ServerSignKey)
// server rc4 cipher.
serverCipher, err := NewCipher(ctx, a.state.ServerSealKey, serverHash)
if err != nil {
return err
}
// assign proper inbound/outbound ciphers.
if !a.Config.IsServer {
a.state.OutboundCipher, a.state.InboundCipher = clientCipher, serverCipher
} else {
a.state.OutboundCipher, a.state.InboundCipher = serverCipher, clientCipher
}
return nil
}
// makeSignKey creates the key for the signature.
func (a *Authentifier) makeSignKey(ctx context.Context, key []byte, magic []byte) ([]byte, error) {
if !a.session.ExtendedSessionSecurity {
return nil, nil
}
return crypto.MD5(key, magic)
}
type SecurityParameters struct {
ExtendedSessionSecurity bool
UseLMKey bool
NonNTSessionKey bool
Datagram bool
KeyExchange bool
KeySize int
ServerName string
DomainName string
}
// makeHashFunc creates the hash function.
func (a *Authentifier) makeHashFunc(ctx context.Context, key []byte) func(uint32) hash.Hash {
if a.session.ExtendedSessionSecurity {
return HMACMD5(key)
}
return CRC32(key)
}
// makeSealKey creates the key for the encryption.
func (a *Authentifier) makeSealKey(ctx context.Context, key []byte, magic []byte) ([]byte, error) {
if a.session.ExtendedSessionSecurity {
switch a.session.KeySize {
case 128:
// no-op.
case 56:
key = key[:7]
default:
key = key[:5]
}
return crypto.MD5(key, magic)
}
if a.session.UseLMKey || a.session.Datagram {
if a.session.KeySize == 56 {
return append(key[:7], 0xa0), nil
}
return append(key[:5], 0xe5, 0x38, 0xb0), nil
}
return key, nil
}
const (
// The signature version.
SignatureVersion = 0x01
)
func (a *Authentifier) makeSecurityParameters(ctx context.Context, cm *ChallengeMessage) {
a.session = &SecurityParameters{
ExtendedSessionSecurity: cm.Negotiate.IsSet(NegotiateExtendedSessionSecurity),
UseLMKey: cm.Negotiate.IsSet(NegotiateLMKey),
NonNTSessionKey: cm.Negotiate.IsSet(RequestNonNTSessionKey),
KeyExchange: cm.Negotiate.IsSet(NegotiateKeyExchange),
Datagram: cm.Negotiate.IsSet(NegotiateDatagram),
KeySize: 40,
}
if cm.Negotiate.IsSet(TargetTypeDomain) {
a.session.DomainName = cm.TargetName
} else if cm.Negotiate.IsSet(TargetTypeServer) {
a.session.ServerName = cm.TargetName
}
if cm.Negotiate.IsSet(Negotiate128) {
a.session.KeySize = 128
} else if cm.Negotiate.IsSet(Negotiate56) {
a.session.KeySize = 56
}
}
func (a *Authentifier) ApplyInboundCipher(ctx context.Context, b []byte) error {
if err := a.state.InboundCipher.XORKeyStream(b); err != nil {
return fmt.Errorf("ntlm: apply inbound cipher: %w", err)
}
return nil
}
func (a *Authentifier) ApplyOutboundCipher(ctx context.Context, b []byte) error {
if err := a.state.OutboundCipher.XORKeyStream(b); err != nil {
return fmt.Errorf("ntlm: apply outbound cipher: %w", err)
}
return nil
}
func (a *Authentifier) MakeInboundSignature(ctx context.Context, checksum []byte) ([]byte, error) {
sgn, err := a.makeSignature(ctx, a.state.InboundCipher, checksum, &a.state.InboundSequenceNumber)
if err != nil {
return nil, fmt.Errorf("ntlm: make inbound signature: %w", err)
}
return sgn, nil
}
func (a *Authentifier) MakeOutboundSignature(ctx context.Context, checksum []byte) ([]byte, error) {
sgn, err := a.makeSignature(ctx, a.state.OutboundCipher, checksum, &a.state.OutboundSequenceNumber)
if err != nil {
return nil, fmt.Errorf("ntlm: make outbound signature: %w", err)
}
return sgn, nil
}
func (a *Authentifier) MakeInboundChecksum(ctx context.Context, b [][]byte) ([]byte, error) {
chk, err := a.makeChecksum(ctx, a.state.InboundCipher, a.state.InboundSequenceNumber, b...)
if err != nil {
return nil, fmt.Errorf("ntlm: make inbound checksum: %w", err)
}
return chk, nil
}
func (a *Authentifier) MakeOutboundChecksum(ctx context.Context, b [][]byte) ([]byte, error) {
chk, err := a.makeChecksum(ctx, a.state.OutboundCipher, a.state.OutboundSequenceNumber, b...)
if err != nil {
return nil, fmt.Errorf("ntlm: make outbound checksum: %w", err)
}
return chk, nil
}
func (a *Authentifier) makeChecksum(ctx context.Context, cipher *Cipher, seqNum uint32, b ...[]byte) ([]byte, error) {
if !a.Config.Integrity {
return nil, nil
}
return cipher.Checksum(seqNum, b...)
}
// makeSignature function creates the NTLM signature.
func (a *Authentifier) makeSignature(ctx context.Context, cipher *Cipher, checksum []byte, seqNum *uint32) ([]byte, error) {
var err error
if !a.Config.Integrity {
// signing is not negotiated.
return (&Signature{Version: SignatureVersion}).Marshal(ctx)
}
if !a.session.ExtendedSessionSecurity {
// extended session security is not negotiated.
// basically this should not work because, a:
//
// https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-nlmp/524cdccb-563e-4793-92b0-7bc321fce096:
// If extended session security is not negotiated (section 2.2.2.5),
// then no signing keys are available and message signing is not supported.
//
// but at the same time, there is an algorithm to produce a signature:
// (possibly this is applicable for NTLMv1).
//
// https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-nlmp/0b1fb6a6-7224-4d5b-af35-fdd45c0791e5
s := &Signature{
Version: SignatureVersion,
Checksum: checksum,
SeqNum: *seqNum,
}
// random_pad + checksum.
if err = cipher.XORKeyStream(s.Checksum); err != nil {
return nil, fmt.Errorf("random_pad: xor_key_stream: %w", err)
}
if err = cipher.XORKeyStream(&s.SeqNum); err != nil {
return nil, fmt.Errorf("seq_num: xor_key_stream: %w", err)
}
// clear random pad.
copy(s.Checksum[:4], make([]byte, 4))
if !a.Config.Datagram {
*seqNum++
}
return s.Marshal(ctx)
}
s := Signature{
Version: SignatureVersion,
Checksum: checksum,
SeqNum: *seqNum,
}
if a.session.KeyExchange {
// key-exchange negotiated.
if err = cipher.XORKeyStream(s.Checksum); err != nil {
return nil, fmt.Errorf("checksum: key_exchange: xor_key_stream: %w", err)
}
}
if !a.Config.Datagram {
*seqNum++
}
return s.Marshal(ctx)
}