s3: Fix some valgrind errors
[abartlet/samba.git/.git] / source3 / libsmb / ntlmssp.c
1 /*
2    Unix SMB/Netbios implementation.
3    Version 3.0
4    handle NLTMSSP, server side
5
6    Copyright (C) Andrew Tridgell      2001
7    Copyright (C) Andrew Bartlett 2001-2003
8    Copyright (C) Andrew Bartlett 2005 (Updated from gensec).
9
10    This program is free software; you can redistribute it and/or modify
11    it under the terms of the GNU General Public License as published by
12    the Free Software Foundation; either version 3 of the License, or
13    (at your option) any later version.
14
15    This program is distributed in the hope that it will be useful,
16    but WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18    GNU General Public License for more details.
19
20    You should have received a copy of the GNU General Public License
21    along with this program.  If not, see <http://www.gnu.org/licenses/>.
22 */
23
24 #include "includes.h"
25 #include "../libcli/auth/ntlmssp.h"
26 #include "../libcli/auth/ntlmssp_private.h"
27 #include "../libcli/auth/libcli_auth.h"
28 #include "../librpc/gen_ndr/ndr_ntlmssp.h"
29 #include "../libcli/auth/ntlmssp_ndr.h"
30 #include "../lib/crypto/md5.h"
31 #include "../lib/crypto/arcfour.h"
32 #include "../lib/crypto/hmacmd5.h"
33
34 static NTSTATUS ntlmssp_client_initial(struct ntlmssp_state *ntlmssp_state,
35                                        DATA_BLOB reply, DATA_BLOB *next_request);
36 static NTSTATUS ntlmssp_server_negotiate(struct ntlmssp_state *ntlmssp_state,
37                                          const DATA_BLOB in, DATA_BLOB *out);
38 static NTSTATUS ntlmssp_client_challenge(struct ntlmssp_state *ntlmssp_state,
39                                          const DATA_BLOB reply, DATA_BLOB *next_request);
40 static NTSTATUS ntlmssp_server_auth(struct ntlmssp_state *ntlmssp_state,
41                                     const DATA_BLOB request, DATA_BLOB *reply);
42
43 /**
44  * Callbacks for NTLMSSP - for both client and server operating modes
45  *
46  */
47
48 static const struct ntlmssp_callbacks {
49         enum ntlmssp_role role;
50         enum ntlmssp_message_type ntlmssp_command;
51         NTSTATUS (*fn)(struct ntlmssp_state *ntlmssp_state,
52                        DATA_BLOB in, DATA_BLOB *out);
53 } ntlmssp_callbacks[] = {
54         {NTLMSSP_CLIENT, NTLMSSP_INITIAL, ntlmssp_client_initial},
55         {NTLMSSP_SERVER, NTLMSSP_NEGOTIATE, ntlmssp_server_negotiate},
56         {NTLMSSP_CLIENT, NTLMSSP_CHALLENGE, ntlmssp_client_challenge},
57         {NTLMSSP_SERVER, NTLMSSP_AUTH, ntlmssp_server_auth},
58         {NTLMSSP_CLIENT, NTLMSSP_UNKNOWN, NULL},
59         {NTLMSSP_SERVER, NTLMSSP_UNKNOWN, NULL}
60 };
61
62
63 /**
64  * Default challenge generation code.
65  *
66  */
67
68 static NTSTATUS get_challenge(const struct ntlmssp_state *ntlmssp_state,
69                               uint8_t chal[8])
70 {
71         generate_random_buffer(chal, 8);
72         return NT_STATUS_OK;
73 }
74
75 /**
76  * Default 'we can set the challenge to anything we like' implementation
77  *
78  */
79
80 static bool may_set_challenge(const struct ntlmssp_state *ntlmssp_state)
81 {
82         return True;
83 }
84
85 /**
86  * Default 'we can set the challenge to anything we like' implementation
87  *
88  * Does not actually do anything, as the value is always in the structure anyway.
89  *
90  */
91
92 static NTSTATUS set_challenge(struct ntlmssp_state *ntlmssp_state, DATA_BLOB *challenge)
93 {
94         SMB_ASSERT(challenge->length == 8);
95         return NT_STATUS_OK;
96 }
97
98 /**
99  * Set a username on an NTLMSSP context - ensures it is talloc()ed
100  *
101  */
102
103 NTSTATUS ntlmssp_set_username(struct ntlmssp_state *ntlmssp_state, const char *user)
104 {
105         ntlmssp_state->user = talloc_strdup(ntlmssp_state, user ? user : "" );
106         if (!ntlmssp_state->user) {
107                 return NT_STATUS_NO_MEMORY;
108         }
109         return NT_STATUS_OK;
110 }
111
112 /**
113  * Store NT and LM hashes on an NTLMSSP context - ensures they are talloc()ed
114  *
115  */
116 NTSTATUS ntlmssp_set_hashes(struct ntlmssp_state *ntlmssp_state,
117                             const uint8_t lm_hash[16],
118                             const uint8_t nt_hash[16])
119 {
120         ntlmssp_state->lm_hash = (uint8_t *)
121                 TALLOC_MEMDUP(ntlmssp_state, lm_hash, 16);
122         ntlmssp_state->nt_hash = (uint8_t *)
123                 TALLOC_MEMDUP(ntlmssp_state, nt_hash, 16);
124         if (!ntlmssp_state->lm_hash || !ntlmssp_state->nt_hash) {
125                 TALLOC_FREE(ntlmssp_state->lm_hash);
126                 TALLOC_FREE(ntlmssp_state->nt_hash);
127                 return NT_STATUS_NO_MEMORY;
128         }
129         return NT_STATUS_OK;
130 }
131
132 /**
133  * Converts a password to the hashes on an NTLMSSP context.
134  *
135  */
136 NTSTATUS ntlmssp_set_password(struct ntlmssp_state *ntlmssp_state, const char *password)
137 {
138         if (!password) {
139                 ntlmssp_state->lm_hash = NULL;
140                 ntlmssp_state->nt_hash = NULL;
141         } else {
142                 uint8_t lm_hash[16];
143                 uint8_t nt_hash[16];
144
145                 E_deshash(password, lm_hash);
146                 E_md4hash(password, nt_hash);
147                 return ntlmssp_set_hashes(ntlmssp_state, lm_hash, nt_hash);
148         }
149         return NT_STATUS_OK;
150 }
151
152 /**
153  * Set a domain on an NTLMSSP context - ensures it is talloc()ed
154  *
155  */
156 NTSTATUS ntlmssp_set_domain(struct ntlmssp_state *ntlmssp_state, const char *domain)
157 {
158         ntlmssp_state->domain = talloc_strdup(ntlmssp_state,
159                                               domain ? domain : "" );
160         if (!ntlmssp_state->domain) {
161                 return NT_STATUS_NO_MEMORY;
162         }
163         return NT_STATUS_OK;
164 }
165
166 /**
167  * Request features for the NTLMSSP negotiation
168  *
169  * @param ntlmssp_state NTLMSSP state
170  * @param feature_list List of space seperated features requested from NTLMSSP.
171  */
172 void ntlmssp_want_feature_list(struct ntlmssp_state *ntlmssp_state, char *feature_list)
173 {
174         /*
175          * We need to set this to allow a later SetPassword
176          * via the SAMR pipe to succeed. Strange.... We could
177          * also add  NTLMSSP_NEGOTIATE_SEAL here. JRA.
178          */
179         if (in_list("NTLMSSP_FEATURE_SESSION_KEY", feature_list, True)) {
180                 ntlmssp_state->neg_flags |= NTLMSSP_NEGOTIATE_SIGN;
181         }
182         if (in_list("NTLMSSP_FEATURE_SIGN", feature_list, True)) {
183                 ntlmssp_state->neg_flags |= NTLMSSP_NEGOTIATE_SIGN;
184         }
185         if(in_list("NTLMSSP_FEATURE_SEAL", feature_list, True)) {
186                 ntlmssp_state->neg_flags |= NTLMSSP_NEGOTIATE_SEAL;
187         }
188         if (in_list("NTLMSSP_FEATURE_CCACHE", feature_list, true)) {
189                 ntlmssp_state->use_ccache = true;
190         }
191 }
192
193 /**
194  * Request a feature for the NTLMSSP negotiation
195  *
196  * @param ntlmssp_state NTLMSSP state
197  * @param feature Bit flag specifying the requested feature
198  */
199 void ntlmssp_want_feature(struct ntlmssp_state *ntlmssp_state, uint32_t feature)
200 {
201         /* As per JRA's comment above */
202         if (feature & NTLMSSP_FEATURE_SESSION_KEY) {
203                 ntlmssp_state->neg_flags |= NTLMSSP_NEGOTIATE_SIGN;
204         }
205         if (feature & NTLMSSP_FEATURE_SIGN) {
206                 ntlmssp_state->neg_flags |= NTLMSSP_NEGOTIATE_SIGN;
207         }
208         if (feature & NTLMSSP_FEATURE_SEAL) {
209                 ntlmssp_state->neg_flags |= NTLMSSP_NEGOTIATE_SEAL;
210         }
211         if (feature & NTLMSSP_FEATURE_CCACHE) {
212                 ntlmssp_state->use_ccache = true;
213         }
214 }
215
216 /**
217  * Next state function for the NTLMSSP state machine
218  *
219  * @param ntlmssp_state NTLMSSP State
220  * @param in The packet in from the NTLMSSP partner, as a DATA_BLOB
221  * @param out The reply, as an allocated DATA_BLOB, caller to free.
222  * @return Errors, NT_STATUS_MORE_PROCESSING_REQUIRED or NT_STATUS_OK.
223  */
224
225 NTSTATUS ntlmssp_update(struct ntlmssp_state *ntlmssp_state,
226                         const DATA_BLOB input, DATA_BLOB *out)
227 {
228         uint32_t ntlmssp_command;
229         int i;
230
231         if (ntlmssp_state->expected_state == NTLMSSP_DONE) {
232                 /* Called update after negotiations finished. */
233                 DEBUG(1, ("Called NTLMSSP after state machine was 'done'\n"));
234                 return NT_STATUS_INVALID_PARAMETER;
235         }
236
237         *out = data_blob_null;
238
239         if (!input.length) {
240                 switch (ntlmssp_state->role) {
241                 case NTLMSSP_CLIENT:
242                         ntlmssp_command = NTLMSSP_INITIAL;
243                         break;
244                 case NTLMSSP_SERVER:
245                         /* 'datagram' mode - no neg packet */
246                         ntlmssp_command = NTLMSSP_NEGOTIATE;
247                         break;
248                 }
249         } else {
250                 if (!msrpc_parse(ntlmssp_state, &input, "Cd",
251                                  "NTLMSSP",
252                                  &ntlmssp_command)) {
253                         DEBUG(1, ("Failed to parse NTLMSSP packet, could not extract NTLMSSP command\n"));
254                         dump_data(2, input.data, input.length);
255                         return NT_STATUS_INVALID_PARAMETER;
256                 }
257         }
258
259         if (ntlmssp_command != ntlmssp_state->expected_state) {
260                 DEBUG(1, ("got NTLMSSP command %u, expected %u\n", ntlmssp_command, ntlmssp_state->expected_state));
261                 return NT_STATUS_INVALID_PARAMETER;
262         }
263
264         for (i=0; ntlmssp_callbacks[i].fn; i++) {
265                 if (ntlmssp_callbacks[i].role == ntlmssp_state->role
266                     && ntlmssp_callbacks[i].ntlmssp_command == ntlmssp_command) {
267                         return ntlmssp_callbacks[i].fn(ntlmssp_state, input, out);
268                 }
269         }
270
271         DEBUG(1, ("failed to find NTLMSSP callback for NTLMSSP mode %u, command %u\n",
272                   ntlmssp_state->role, ntlmssp_command));
273
274         return NT_STATUS_INVALID_PARAMETER;
275 }
276
277 /**
278  * End an NTLMSSP state machine
279  *
280  * @param ntlmssp_state NTLMSSP State, free()ed by this function
281  */
282
283 void ntlmssp_end(struct ntlmssp_state **ntlmssp_state)
284 {
285         data_blob_free(&(*ntlmssp_state)->chal);
286         data_blob_free(&(*ntlmssp_state)->lm_resp);
287         data_blob_free(&(*ntlmssp_state)->nt_resp);
288         TALLOC_FREE(*ntlmssp_state);
289
290         *ntlmssp_state = NULL;
291         return;
292 }
293
294 /**
295  * Determine correct target name flags for reply, given server role
296  * and negotiated flags
297  *
298  * @param ntlmssp_state NTLMSSP State
299  * @param neg_flags The flags from the packet
300  * @param chal_flags The flags to be set in the reply packet
301  * @return The 'target name' string.
302  */
303
304 static const char *ntlmssp_target_name(struct ntlmssp_state *ntlmssp_state,
305                                        uint32_t neg_flags, uint32_t *chal_flags)
306 {
307         if (neg_flags & NTLMSSP_REQUEST_TARGET) {
308                 *chal_flags |= NTLMSSP_NEGOTIATE_TARGET_INFO;
309                 *chal_flags |= NTLMSSP_REQUEST_TARGET;
310                 if (ntlmssp_state->server.is_standalone) {
311                         *chal_flags |= NTLMSSP_TARGET_TYPE_SERVER;
312                         return ntlmssp_state->server.netbios_name;
313                 } else {
314                         *chal_flags |= NTLMSSP_TARGET_TYPE_DOMAIN;
315                         return ntlmssp_state->server.netbios_domain;
316                 };
317         } else {
318                 return "";
319         }
320 }
321
322 static void ntlmssp_handle_neg_flags(struct ntlmssp_state *ntlmssp_state,
323                                      uint32_t neg_flags, bool allow_lm) {
324         if (neg_flags & NTLMSSP_NEGOTIATE_UNICODE) {
325                 ntlmssp_state->neg_flags |= NTLMSSP_NEGOTIATE_UNICODE;
326                 ntlmssp_state->neg_flags &= ~NTLMSSP_NEGOTIATE_OEM;
327                 ntlmssp_state->unicode = True;
328         } else {
329                 ntlmssp_state->neg_flags &= ~NTLMSSP_NEGOTIATE_UNICODE;
330                 ntlmssp_state->neg_flags |= NTLMSSP_NEGOTIATE_OEM;
331                 ntlmssp_state->unicode = False;
332         }
333
334         if ((neg_flags & NTLMSSP_NEGOTIATE_LM_KEY) && allow_lm) {
335                 /* other end forcing us to use LM */
336                 ntlmssp_state->neg_flags |= NTLMSSP_NEGOTIATE_LM_KEY;
337                 ntlmssp_state->use_ntlmv2 = False;
338         } else {
339                 ntlmssp_state->neg_flags &= ~NTLMSSP_NEGOTIATE_LM_KEY;
340         }
341
342         if (!(neg_flags & NTLMSSP_NEGOTIATE_ALWAYS_SIGN)) {
343                 ntlmssp_state->neg_flags &= ~NTLMSSP_NEGOTIATE_ALWAYS_SIGN;
344         }
345
346         if (!(neg_flags & NTLMSSP_NEGOTIATE_NTLM2)) {
347                 ntlmssp_state->neg_flags &= ~NTLMSSP_NEGOTIATE_NTLM2;
348         }
349
350         if (!(neg_flags & NTLMSSP_NEGOTIATE_128)) {
351                 ntlmssp_state->neg_flags &= ~NTLMSSP_NEGOTIATE_128;
352         }
353
354         if (!(neg_flags & NTLMSSP_NEGOTIATE_56)) {
355                 ntlmssp_state->neg_flags &= ~NTLMSSP_NEGOTIATE_56;
356         }
357
358         if (!(neg_flags & NTLMSSP_NEGOTIATE_KEY_EXCH)) {
359                 ntlmssp_state->neg_flags &= ~NTLMSSP_NEGOTIATE_KEY_EXCH;
360         }
361
362         if (!(neg_flags & NTLMSSP_NEGOTIATE_SIGN)) {
363                 ntlmssp_state->neg_flags &= ~NTLMSSP_NEGOTIATE_SIGN;
364         }
365
366         if (!(neg_flags & NTLMSSP_NEGOTIATE_SEAL)) {
367                 ntlmssp_state->neg_flags &= ~NTLMSSP_NEGOTIATE_SEAL;
368         }
369
370         /* Woop Woop - unknown flag for Windows compatibility...
371            What does this really do ? JRA. */
372         if (!(neg_flags & NTLMSSP_NEGOTIATE_VERSION)) {
373                 ntlmssp_state->neg_flags &= ~NTLMSSP_NEGOTIATE_VERSION;
374         }
375
376         if ((neg_flags & NTLMSSP_REQUEST_TARGET)) {
377                 ntlmssp_state->neg_flags |= NTLMSSP_REQUEST_TARGET;
378         }
379 }
380
381 /**
382  * Next state function for the Negotiate packet
383  *
384  * @param ntlmssp_state NTLMSSP State
385  * @param request The request, as a DATA_BLOB
386  * @param request The reply, as an allocated DATA_BLOB, caller to free.
387  * @return Errors or MORE_PROCESSING_REQUIRED if a reply is sent.
388  */
389
390 static NTSTATUS ntlmssp_server_negotiate(struct ntlmssp_state *ntlmssp_state,
391                                          const DATA_BLOB request, DATA_BLOB *reply)
392 {
393         DATA_BLOB struct_blob;
394         uint32_t neg_flags = 0;
395         uint32_t ntlmssp_command, chal_flags;
396         uint8_t cryptkey[8];
397         const char *target_name;
398         NTSTATUS status;
399
400         /* parse the NTLMSSP packet */
401 #if 0
402         file_save("ntlmssp_negotiate.dat", request.data, request.length);
403 #endif
404
405         if (request.length) {
406                 if ((request.length < 16) || !msrpc_parse(ntlmssp_state, &request, "Cdd",
407                                                           "NTLMSSP",
408                                                           &ntlmssp_command,
409                                                           &neg_flags)) {
410                         DEBUG(1, ("ntlmssp_server_negotiate: failed to parse NTLMSSP Negotiate of length %u\n",
411                                 (unsigned int)request.length));
412                         dump_data(2, request.data, request.length);
413                         return NT_STATUS_INVALID_PARAMETER;
414                 }
415                 debug_ntlmssp_flags(neg_flags);
416
417                 if (DEBUGLEVEL >= 10) {
418                         struct NEGOTIATE_MESSAGE *negotiate = talloc(
419                                 talloc_tos(), struct NEGOTIATE_MESSAGE);
420                         if (negotiate != NULL) {
421                                 status = ntlmssp_pull_NEGOTIATE_MESSAGE(
422                                         &request, negotiate, negotiate);
423                                 if (NT_STATUS_IS_OK(status)) {
424                                         NDR_PRINT_DEBUG(NEGOTIATE_MESSAGE,
425                                                         negotiate);
426                                 }
427                                 TALLOC_FREE(negotiate);
428                         }
429                 }
430         }
431
432         ntlmssp_handle_neg_flags(ntlmssp_state, neg_flags, lp_lanman_auth());
433
434         /* Ask our caller what challenge they would like in the packet */
435         status = ntlmssp_state->get_challenge(ntlmssp_state, cryptkey);
436         if (!NT_STATUS_IS_OK(status)) {
437                 return status;
438         }
439
440         /* Check if we may set the challenge */
441         if (!ntlmssp_state->may_set_challenge(ntlmssp_state)) {
442                 ntlmssp_state->neg_flags &= ~NTLMSSP_NEGOTIATE_NTLM2;
443         }
444
445         /* The flags we send back are not just the negotiated flags,
446          * they are also 'what is in this packet'.  Therfore, we
447          * operate on 'chal_flags' from here on
448          */
449
450         chal_flags = ntlmssp_state->neg_flags;
451
452         /* get the right name to fill in as 'target' */
453         target_name = ntlmssp_target_name(ntlmssp_state,
454                                           neg_flags, &chal_flags);
455         if (target_name == NULL)
456                 return NT_STATUS_INVALID_PARAMETER;
457
458         ntlmssp_state->chal = data_blob_talloc(ntlmssp_state, cryptkey, 8);
459         ntlmssp_state->internal_chal = data_blob_talloc(ntlmssp_state,
460                                                         cryptkey, 8);
461
462         /* This creates the 'blob' of names that appears at the end of the packet */
463         if (chal_flags & NTLMSSP_NEGOTIATE_TARGET_INFO)
464         {
465                 msrpc_gen(ntlmssp_state, &struct_blob, "aaaaa",
466                           MsvAvNbDomainName, target_name,
467                           MsvAvNbComputerName, ntlmssp_state->server.netbios_name,
468                           MsvAvDnsDomainName, ntlmssp_state->server.dns_domain,
469                           MsvAvDnsComputerName, ntlmssp_state->server.dns_name,
470                           MsvAvEOL, "");
471         } else {
472                 struct_blob = data_blob_null;
473         }
474
475         {
476                 /* Marshal the packet in the right format, be it unicode or ASCII */
477                 const char *gen_string;
478                 DATA_BLOB version_blob = data_blob_null;
479
480                 if (chal_flags & NTLMSSP_NEGOTIATE_VERSION) {
481                         enum ndr_err_code err;
482                         struct VERSION vers;
483
484                         /* "What Windows returns" as a version number. */
485                         ZERO_STRUCT(vers);
486                         vers.ProductMajorVersion = NTLMSSP_WINDOWS_MAJOR_VERSION_6;
487                         vers.ProductMinorVersion = NTLMSSP_WINDOWS_MINOR_VERSION_1;
488                         vers.ProductBuild = 0;
489                         vers.NTLMRevisionCurrent = NTLMSSP_REVISION_W2K3;
490
491                         err = ndr_push_struct_blob(&version_blob,
492                                                 ntlmssp_state,
493                                                 &vers,
494                                                 (ndr_push_flags_fn_t)ndr_push_VERSION);
495
496                         if (!NDR_ERR_CODE_IS_SUCCESS(err)) {
497                                 return NT_STATUS_NO_MEMORY;
498                         }
499                 }
500
501                 if (ntlmssp_state->unicode) {
502                         gen_string = "CdUdbddBb";
503                 } else {
504                         gen_string = "CdAdbddBb";
505                 }
506
507                 msrpc_gen(ntlmssp_state, reply, gen_string,
508                         "NTLMSSP",
509                         NTLMSSP_CHALLENGE,
510                         target_name,
511                         chal_flags,
512                         cryptkey, 8,
513                         0, 0,
514                         struct_blob.data, struct_blob.length,
515                         version_blob.data, version_blob.length);
516
517                 data_blob_free(&version_blob);
518
519                 if (DEBUGLEVEL >= 10) {
520                         struct CHALLENGE_MESSAGE *challenge = talloc(
521                                 talloc_tos(), struct CHALLENGE_MESSAGE);
522                         if (challenge != NULL) {
523                                 challenge->NegotiateFlags = chal_flags;
524                                 status = ntlmssp_pull_CHALLENGE_MESSAGE(
525                                         reply, challenge, challenge);
526                                 if (NT_STATUS_IS_OK(status)) {
527                                         NDR_PRINT_DEBUG(CHALLENGE_MESSAGE,
528                                                         challenge);
529                                 }
530                                 TALLOC_FREE(challenge);
531                         }
532                 }
533         }
534
535         data_blob_free(&struct_blob);
536
537         ntlmssp_state->expected_state = NTLMSSP_AUTH;
538
539         return NT_STATUS_MORE_PROCESSING_REQUIRED;
540 }
541
542 /**
543  * Next state function for the Authenticate packet
544  *
545  * @param ntlmssp_state NTLMSSP State
546  * @param request The request, as a DATA_BLOB
547  * @param request The reply, as an allocated DATA_BLOB, caller to free.
548  * @return Errors or NT_STATUS_OK.
549  */
550
551 static NTSTATUS ntlmssp_server_auth(struct ntlmssp_state *ntlmssp_state,
552                                     const DATA_BLOB request, DATA_BLOB *reply)
553 {
554         DATA_BLOB encrypted_session_key = data_blob_null;
555         DATA_BLOB user_session_key = data_blob_null;
556         DATA_BLOB lm_session_key = data_blob_null;
557         DATA_BLOB session_key = data_blob_null;
558         uint32_t ntlmssp_command, auth_flags;
559         NTSTATUS nt_status = NT_STATUS_OK;
560
561         /* used by NTLM2 */
562         bool doing_ntlm2 = False;
563
564         uint8_t session_nonce[16];
565         uint8_t session_nonce_hash[16];
566
567         const char *parse_string;
568
569         /* parse the NTLMSSP packet */
570         *reply = data_blob_null;
571
572 #if 0
573         file_save("ntlmssp_auth.dat", request.data, request.length);
574 #endif
575
576         if (ntlmssp_state->unicode) {
577                 parse_string = "CdBBUUUBd";
578         } else {
579                 parse_string = "CdBBAAABd";
580         }
581
582         data_blob_free(&ntlmssp_state->lm_resp);
583         data_blob_free(&ntlmssp_state->nt_resp);
584
585         ntlmssp_state->user = NULL;
586         ntlmssp_state->domain = NULL;
587
588         /* now the NTLMSSP encoded auth hashes */
589         if (!msrpc_parse(ntlmssp_state, &request, parse_string,
590                          "NTLMSSP",
591                          &ntlmssp_command,
592                          &ntlmssp_state->lm_resp,
593                          &ntlmssp_state->nt_resp,
594                          &ntlmssp_state->domain,
595                          &ntlmssp_state->user,
596                          &ntlmssp_state->client.netbios_name,
597                          &encrypted_session_key,
598                          &auth_flags)) {
599                 auth_flags = 0;
600
601                 /* Try again with a shorter string (Win9X truncates this packet) */
602                 if (ntlmssp_state->unicode) {
603                         parse_string = "CdBBUUU";
604                 } else {
605                         parse_string = "CdBBAAA";
606                 }
607
608                 /* now the NTLMSSP encoded auth hashes */
609                 if (!msrpc_parse(ntlmssp_state, &request, parse_string,
610                                  "NTLMSSP",
611                                  &ntlmssp_command,
612                                  &ntlmssp_state->lm_resp,
613                                  &ntlmssp_state->nt_resp,
614                                  &ntlmssp_state->domain,
615                                  &ntlmssp_state->user,
616                                  &ntlmssp_state->client.netbios_name)) {
617                         DEBUG(1, ("ntlmssp_server_auth: failed to parse NTLMSSP (tried both formats):\n"));
618                         dump_data(2, request.data, request.length);
619
620                         return NT_STATUS_INVALID_PARAMETER;
621                 }
622         }
623
624         if (auth_flags)
625                 ntlmssp_handle_neg_flags(ntlmssp_state, auth_flags, lp_lanman_auth());
626
627         if (DEBUGLEVEL >= 10) {
628                 struct AUTHENTICATE_MESSAGE *authenticate = talloc(
629                         talloc_tos(), struct AUTHENTICATE_MESSAGE);
630                 if (authenticate != NULL) {
631                         NTSTATUS status;
632                         authenticate->NegotiateFlags = auth_flags;
633                         status = ntlmssp_pull_AUTHENTICATE_MESSAGE(
634                                 &request, authenticate, authenticate);
635                         if (NT_STATUS_IS_OK(status)) {
636                                 NDR_PRINT_DEBUG(AUTHENTICATE_MESSAGE,
637                                                 authenticate);
638                         }
639                         TALLOC_FREE(authenticate);
640                 }
641         }
642
643         DEBUG(3,("Got user=[%s] domain=[%s] workstation=[%s] len1=%lu len2=%lu\n",
644                  ntlmssp_state->user, ntlmssp_state->domain,
645                  ntlmssp_state->client.netbios_name,
646                  (unsigned long)ntlmssp_state->lm_resp.length,
647                  (unsigned long)ntlmssp_state->nt_resp.length));
648
649 #if 0
650         file_save("nthash1.dat",  &ntlmssp_state->nt_resp.data,  &ntlmssp_state->nt_resp.length);
651         file_save("lmhash1.dat",  &ntlmssp_state->lm_resp.data,  &ntlmssp_state->lm_resp.length);
652 #endif
653
654         /* NTLM2 uses a 'challenge' that is made of up both the server challenge, and a
655            client challenge
656
657            However, the NTLM2 flag may still be set for the real NTLMv2 logins, be careful.
658         */
659         if (ntlmssp_state->neg_flags & NTLMSSP_NEGOTIATE_NTLM2) {
660                 if (ntlmssp_state->nt_resp.length == 24 && ntlmssp_state->lm_resp.length == 24) {
661                         struct MD5Context md5_session_nonce_ctx;
662                         SMB_ASSERT(ntlmssp_state->internal_chal.data && ntlmssp_state->internal_chal.length == 8);
663
664                         doing_ntlm2 = True;
665
666                         memcpy(session_nonce, ntlmssp_state->internal_chal.data, 8);
667                         memcpy(&session_nonce[8], ntlmssp_state->lm_resp.data, 8);
668
669                         MD5Init(&md5_session_nonce_ctx);
670                         MD5Update(&md5_session_nonce_ctx, session_nonce, 16);
671                         MD5Final(session_nonce_hash, &md5_session_nonce_ctx);
672
673                         ntlmssp_state->chal = data_blob_talloc(
674                                 ntlmssp_state, session_nonce_hash, 8);
675
676                         /* LM response is no longer useful */
677                         data_blob_free(&ntlmssp_state->lm_resp);
678
679                         /* We changed the effective challenge - set it */
680                         if (!NT_STATUS_IS_OK(nt_status = ntlmssp_state->set_challenge(ntlmssp_state, &ntlmssp_state->chal))) {
681                                 data_blob_free(&encrypted_session_key);
682                                 return nt_status;
683                         }
684
685                         /* LM Key is incompatible. */
686                         ntlmssp_state->neg_flags &= ~NTLMSSP_NEGOTIATE_LM_KEY;
687                 }
688         }
689
690         /*
691          * Note we don't check here for NTLMv2 auth settings. If NTLMv2 auth
692          * is required (by "ntlm auth = no" and "lm auth = no" being set in the
693          * smb.conf file) and no NTLMv2 response was sent then the password check
694          * will fail here. JRA.
695          */
696
697         /* Finally, actually ask if the password is OK */
698
699         if (!NT_STATUS_IS_OK(nt_status = ntlmssp_state->check_password(ntlmssp_state,
700                                                                        &user_session_key, &lm_session_key))) {
701                 data_blob_free(&encrypted_session_key);
702                 return nt_status;
703         }
704
705         dump_data_pw("NT session key:\n", user_session_key.data, user_session_key.length);
706         dump_data_pw("LM first-8:\n", lm_session_key.data, lm_session_key.length);
707
708         /* Handle the different session key derivation for NTLM2 */
709         if (doing_ntlm2) {
710                 if (user_session_key.data && user_session_key.length == 16) {
711                         session_key = data_blob_talloc(ntlmssp_state,
712                                                        NULL, 16);
713                         hmac_md5(user_session_key.data, session_nonce,
714                                  sizeof(session_nonce), session_key.data);
715                         DEBUG(10,("ntlmssp_server_auth: Created NTLM2 session key.\n"));
716                         dump_data_pw("NTLM2 session key:\n", session_key.data, session_key.length);
717
718                 } else {
719                         DEBUG(10,("ntlmssp_server_auth: Failed to create NTLM2 session key.\n"));
720                         session_key = data_blob_null;
721                 }
722         } else if (ntlmssp_state->neg_flags & NTLMSSP_NEGOTIATE_LM_KEY) {
723                 if (lm_session_key.data && lm_session_key.length >= 8) {
724                         if (ntlmssp_state->lm_resp.data && ntlmssp_state->lm_resp.length == 24) {
725                                 session_key = data_blob_talloc(ntlmssp_state,
726                                                                NULL, 16);
727                                 if (session_key.data == NULL) {
728                                         return NT_STATUS_NO_MEMORY;
729                                 }
730                                 SMBsesskeygen_lm_sess_key(lm_session_key.data, ntlmssp_state->lm_resp.data,
731                                                           session_key.data);
732                                 DEBUG(10,("ntlmssp_server_auth: Created NTLM session key.\n"));
733                         } else {
734                                 static const uint8_t zeros[24] = {0, };
735                                 session_key = data_blob_talloc(
736                                         ntlmssp_state, NULL, 16);
737                                 if (session_key.data == NULL) {
738                                         return NT_STATUS_NO_MEMORY;
739                                 }
740                                 SMBsesskeygen_lm_sess_key(
741                                         lm_session_key.data, zeros,
742                                         session_key.data);
743                         }
744                         dump_data_pw("LM session key:\n", session_key.data,
745                                      session_key.length);
746                 } else {
747                         DEBUG(10,("ntlmssp_server_auth: Failed to create NTLM session key.\n"));
748                         session_key = data_blob_null;
749                 }
750         } else if (user_session_key.data) {
751                 session_key = user_session_key;
752                 DEBUG(10,("ntlmssp_server_auth: Using unmodified nt session key.\n"));
753                 dump_data_pw("unmodified session key:\n", session_key.data, session_key.length);
754         } else if (lm_session_key.data) {
755                 session_key = lm_session_key;
756                 DEBUG(10,("ntlmssp_server_auth: Using unmodified lm session key.\n"));
757                 dump_data_pw("unmodified session key:\n", session_key.data, session_key.length);
758         } else {
759                 DEBUG(10,("ntlmssp_server_auth: Failed to create unmodified session key.\n"));
760                 session_key = data_blob_null;
761         }
762
763         /* With KEY_EXCH, the client supplies the proposed session key,
764            but encrypts it with the long-term key */
765         if (ntlmssp_state->neg_flags & NTLMSSP_NEGOTIATE_KEY_EXCH) {
766                 if (!encrypted_session_key.data || encrypted_session_key.length != 16) {
767                         data_blob_free(&encrypted_session_key);
768                         DEBUG(1, ("Client-supplied KEY_EXCH session key was of invalid length (%u)!\n",
769                                   (unsigned int)encrypted_session_key.length));
770                         return NT_STATUS_INVALID_PARAMETER;
771                 } else if (!session_key.data || session_key.length != 16) {
772                         DEBUG(5, ("server session key is invalid (len == %u), cannot do KEY_EXCH!\n",
773                                   (unsigned int)session_key.length));
774                         ntlmssp_state->session_key = session_key;
775                 } else {
776                         dump_data_pw("KEY_EXCH session key (enc):\n", encrypted_session_key.data, encrypted_session_key.length);
777                         arcfour_crypt_blob(encrypted_session_key.data,
778                                            encrypted_session_key.length,
779                                            &session_key);
780                         ntlmssp_state->session_key = data_blob_talloc(
781                                 ntlmssp_state, encrypted_session_key.data,
782                                 encrypted_session_key.length);
783                         dump_data_pw("KEY_EXCH session key:\n", encrypted_session_key.data,
784                                      encrypted_session_key.length);
785                 }
786         } else {
787                 ntlmssp_state->session_key = session_key;
788         }
789
790         if (!NT_STATUS_IS_OK(nt_status)) {
791                 ntlmssp_state->session_key = data_blob_null;
792         } else if (ntlmssp_state->session_key.length) {
793                 nt_status = ntlmssp_sign_init(ntlmssp_state);
794         }
795
796         data_blob_free(&encrypted_session_key);
797
798         /* Only one authentication allowed per server state. */
799         ntlmssp_state->expected_state = NTLMSSP_DONE;
800
801         return nt_status;
802 }
803
804 /**
805  * Create an NTLMSSP state machine
806  *
807  * @param ntlmssp_state NTLMSSP State, allocated by this function
808  */
809
810 NTSTATUS ntlmssp_server_start(TALLOC_CTX *mem_ctx,
811                               bool is_standalone,
812                               const char *netbios_name,
813                               const char *netbios_domain,
814                               const char *dns_name,
815                               const char *dns_domain,
816                               struct ntlmssp_state **_ntlmssp_state)
817 {
818         struct ntlmssp_state *ntlmssp_state;
819
820         if (!netbios_name) {
821                 netbios_name = "";
822         }
823
824         if (!netbios_domain) {
825                 netbios_domain = "";
826         }
827
828         if (!dns_domain) {
829                 dns_domain = "";
830         }
831
832         if (!dns_name) {
833                 dns_name = "";
834         }
835
836         ntlmssp_state = talloc_zero(mem_ctx, struct ntlmssp_state);
837         if (!ntlmssp_state) {
838                 return NT_STATUS_NO_MEMORY;
839         }
840
841         ntlmssp_state->role = NTLMSSP_SERVER;
842
843         ntlmssp_state->get_challenge = get_challenge;
844         ntlmssp_state->set_challenge = set_challenge;
845         ntlmssp_state->may_set_challenge = may_set_challenge;
846
847         ntlmssp_state->server.is_standalone = is_standalone;
848
849         ntlmssp_state->expected_state = NTLMSSP_NEGOTIATE;
850
851         ntlmssp_state->neg_flags =
852                 NTLMSSP_NEGOTIATE_128 |
853                 NTLMSSP_NEGOTIATE_56 |
854                 NTLMSSP_NEGOTIATE_VERSION |
855                 NTLMSSP_NEGOTIATE_ALWAYS_SIGN |
856                 NTLMSSP_NEGOTIATE_NTLM |
857                 NTLMSSP_NEGOTIATE_NTLM2 |
858                 NTLMSSP_NEGOTIATE_KEY_EXCH |
859                 NTLMSSP_NEGOTIATE_SIGN |
860                 NTLMSSP_NEGOTIATE_SEAL;
861
862         ntlmssp_state->server.netbios_name = talloc_strdup(ntlmssp_state, netbios_name);
863         if (!ntlmssp_state->server.netbios_name) {
864                 talloc_free(ntlmssp_state);
865                 return NT_STATUS_NO_MEMORY;
866         }
867         ntlmssp_state->server.netbios_domain = talloc_strdup(ntlmssp_state, netbios_domain);
868         if (!ntlmssp_state->server.netbios_domain) {
869                 talloc_free(ntlmssp_state);
870                 return NT_STATUS_NO_MEMORY;
871         }
872         ntlmssp_state->server.dns_name = talloc_strdup(ntlmssp_state, dns_name);
873         if (!ntlmssp_state->server.dns_name) {
874                 talloc_free(ntlmssp_state);
875                 return NT_STATUS_NO_MEMORY;
876         }
877         ntlmssp_state->server.dns_domain = talloc_strdup(ntlmssp_state, dns_domain);
878         if (!ntlmssp_state->server.dns_domain) {
879                 talloc_free(ntlmssp_state);
880                 return NT_STATUS_NO_MEMORY;
881         }
882
883         *_ntlmssp_state = ntlmssp_state;
884         return NT_STATUS_OK;
885 }
886
887 /*********************************************************************
888  Client side NTLMSSP
889 *********************************************************************/
890
891 /**
892  * Next state function for the Initial packet
893  *
894  * @param ntlmssp_state NTLMSSP State
895  * @param request The request, as a DATA_BLOB.  reply.data must be NULL
896  * @param request The reply, as an allocated DATA_BLOB, caller to free.
897  * @return Errors or NT_STATUS_OK.
898  */
899
900 static NTSTATUS ntlmssp_client_initial(struct ntlmssp_state *ntlmssp_state,
901                                   DATA_BLOB reply, DATA_BLOB *next_request)
902 {
903         if (ntlmssp_state->unicode) {
904                 ntlmssp_state->neg_flags |= NTLMSSP_NEGOTIATE_UNICODE;
905         } else {
906                 ntlmssp_state->neg_flags |= NTLMSSP_NEGOTIATE_OEM;
907         }
908
909         if (ntlmssp_state->use_ntlmv2) {
910                 ntlmssp_state->neg_flags |= NTLMSSP_NEGOTIATE_NTLM2;
911         }
912
913         /* generate the ntlmssp negotiate packet */
914         msrpc_gen(ntlmssp_state, next_request, "CddAA",
915                   "NTLMSSP",
916                   NTLMSSP_NEGOTIATE,
917                   ntlmssp_state->neg_flags,
918                   ntlmssp_state->client.netbios_domain,
919                   ntlmssp_state->client.netbios_name);
920
921         if (DEBUGLEVEL >= 10) {
922                 struct NEGOTIATE_MESSAGE *negotiate = talloc(
923                         talloc_tos(), struct NEGOTIATE_MESSAGE);
924                 if (negotiate != NULL) {
925                         NTSTATUS status;
926                         status = ntlmssp_pull_NEGOTIATE_MESSAGE(
927                                 next_request, negotiate, negotiate);
928                         if (NT_STATUS_IS_OK(status)) {
929                                 NDR_PRINT_DEBUG(NEGOTIATE_MESSAGE,
930                                                 negotiate);
931                         }
932                         TALLOC_FREE(negotiate);
933                 }
934         }
935
936         ntlmssp_state->expected_state = NTLMSSP_CHALLENGE;
937
938         return NT_STATUS_MORE_PROCESSING_REQUIRED;
939 }
940
941 /**
942  * Next state function for the Challenge Packet.  Generate an auth packet.
943  *
944  * @param ntlmssp_state NTLMSSP State
945  * @param request The request, as a DATA_BLOB.  reply.data must be NULL
946  * @param request The reply, as an allocated DATA_BLOB, caller to free.
947  * @return Errors or NT_STATUS_OK.
948  */
949
950 static NTSTATUS ntlmssp_client_challenge(struct ntlmssp_state *ntlmssp_state,
951                                          const DATA_BLOB reply, DATA_BLOB *next_request)
952 {
953         uint32_t chal_flags, ntlmssp_command, unkn1, unkn2;
954         DATA_BLOB server_domain_blob;
955         DATA_BLOB challenge_blob;
956         DATA_BLOB struct_blob = data_blob_null;
957         char *server_domain;
958         const char *chal_parse_string;
959         const char *auth_gen_string;
960         DATA_BLOB lm_response = data_blob_null;
961         DATA_BLOB nt_response = data_blob_null;
962         DATA_BLOB session_key = data_blob_null;
963         DATA_BLOB encrypted_session_key = data_blob_null;
964         NTSTATUS nt_status = NT_STATUS_OK;
965
966         if (ntlmssp_state->use_ccache) {
967                 struct wbcCredentialCacheParams params;
968                 struct wbcCredentialCacheInfo *info = NULL;
969                 struct wbcAuthErrorInfo *error = NULL;
970                 struct wbcNamedBlob auth_blob;
971                 struct wbcBlob *wbc_next = NULL;
972                 struct wbcBlob *wbc_session_key = NULL;
973                 wbcErr wbc_status;
974                 int i;
975
976                 params.account_name = ntlmssp_state->user;
977                 params.domain_name = ntlmssp_state->domain;
978                 params.level = WBC_CREDENTIAL_CACHE_LEVEL_NTLMSSP;
979
980                 auth_blob.name = "challenge_blob";
981                 auth_blob.flags = 0;
982                 auth_blob.blob.data = reply.data;
983                 auth_blob.blob.length = reply.length;
984                 params.num_blobs = 1;
985                 params.blobs = &auth_blob;
986
987                 wbc_status = wbcCredentialCache(&params, &info, &error);
988                 if (error != NULL) {
989                         wbcFreeMemory(error);
990                 }
991                 if (!WBC_ERROR_IS_OK(wbc_status)) {
992                         goto noccache;
993                 }
994
995                 for (i=0; i<info->num_blobs; i++) {
996                         if (strequal(info->blobs[i].name, "auth_blob")) {
997                                 wbc_next = &info->blobs[i].blob;
998                         }
999                         if (strequal(info->blobs[i].name, "session_key")) {
1000                                 wbc_session_key = &info->blobs[i].blob;
1001                         }
1002                 }
1003                 if ((wbc_next == NULL) || (wbc_session_key == NULL)) {
1004                         wbcFreeMemory(info);
1005                         goto noccache;
1006                 }
1007
1008                 *next_request = data_blob(wbc_next->data, wbc_next->length);
1009                 ntlmssp_state->session_key = data_blob(
1010                         wbc_session_key->data, wbc_session_key->length);
1011
1012                 wbcFreeMemory(info);
1013                 goto done;
1014         }
1015
1016 noccache:
1017
1018         if (!msrpc_parse(ntlmssp_state, &reply, "CdBd",
1019                          "NTLMSSP",
1020                          &ntlmssp_command,
1021                          &server_domain_blob,
1022                          &chal_flags)) {
1023                 DEBUG(1, ("Failed to parse the NTLMSSP Challenge: (#1)\n"));
1024                 dump_data(2, reply.data, reply.length);
1025
1026                 return NT_STATUS_INVALID_PARAMETER;
1027         }
1028
1029         if (DEBUGLEVEL >= 10) {
1030                 struct CHALLENGE_MESSAGE *challenge = talloc(
1031                         talloc_tos(), struct CHALLENGE_MESSAGE);
1032                 if (challenge != NULL) {
1033                         NTSTATUS status;
1034                         challenge->NegotiateFlags = chal_flags;
1035                         status = ntlmssp_pull_CHALLENGE_MESSAGE(
1036                                 &reply, challenge, challenge);
1037                         if (NT_STATUS_IS_OK(status)) {
1038                                 NDR_PRINT_DEBUG(CHALLENGE_MESSAGE,
1039                                                 challenge);
1040                         }
1041                         TALLOC_FREE(challenge);
1042                 }
1043         }
1044
1045         data_blob_free(&server_domain_blob);
1046
1047         DEBUG(3, ("Got challenge flags:\n"));
1048         debug_ntlmssp_flags(chal_flags);
1049
1050         ntlmssp_handle_neg_flags(ntlmssp_state, chal_flags, lp_client_lanman_auth());
1051
1052         if (ntlmssp_state->unicode) {
1053                 if (chal_flags & NTLMSSP_NEGOTIATE_TARGET_INFO) {
1054                         chal_parse_string = "CdUdbddB";
1055                 } else {
1056                         chal_parse_string = "CdUdbdd";
1057                 }
1058                 auth_gen_string = "CdBBUUUBd";
1059         } else {
1060                 if (chal_flags & NTLMSSP_NEGOTIATE_TARGET_INFO) {
1061                         chal_parse_string = "CdAdbddB";
1062                 } else {
1063                         chal_parse_string = "CdAdbdd";
1064                 }
1065
1066                 auth_gen_string = "CdBBAAABd";
1067         }
1068
1069         DEBUG(3, ("NTLMSSP: Set final flags:\n"));
1070         debug_ntlmssp_flags(ntlmssp_state->neg_flags);
1071
1072         if (!msrpc_parse(ntlmssp_state, &reply, chal_parse_string,
1073                          "NTLMSSP",
1074                          &ntlmssp_command,
1075                          &server_domain,
1076                          &chal_flags,
1077                          &challenge_blob, 8,
1078                          &unkn1, &unkn2,
1079                          &struct_blob)) {
1080                 DEBUG(1, ("Failed to parse the NTLMSSP Challenge: (#2)\n"));
1081                 dump_data(2, reply.data, reply.length);
1082                 return NT_STATUS_INVALID_PARAMETER;
1083         }
1084
1085         if (chal_flags & NTLMSSP_TARGET_TYPE_SERVER) {
1086                 ntlmssp_state->server.is_standalone = true;
1087         } else {
1088                 ntlmssp_state->server.is_standalone = false;
1089         }
1090         /* TODO: parse struct_blob and fill in the rest */
1091         ntlmssp_state->server.netbios_name = "";
1092         ntlmssp_state->server.netbios_domain = server_domain;
1093         ntlmssp_state->server.dns_name = "";
1094         ntlmssp_state->server.dns_domain = "";
1095
1096         if (challenge_blob.length != 8) {
1097                 data_blob_free(&struct_blob);
1098                 return NT_STATUS_INVALID_PARAMETER;
1099         }
1100
1101         if (!ntlmssp_state->nt_hash || !ntlmssp_state->lm_hash) {
1102                 static const uint8_t zeros[16] = {0, };
1103                 /* do nothing - blobs are zero length */
1104
1105                 /* session key is all zeros */
1106                 session_key = data_blob_talloc(ntlmssp_state, zeros, 16);
1107
1108                 /* not doing NLTM2 without a password */
1109                 ntlmssp_state->neg_flags &= ~NTLMSSP_NEGOTIATE_NTLM2;
1110         } else if (ntlmssp_state->use_ntlmv2) {
1111                 if (!struct_blob.length) {
1112                         /* be lazy, match win2k - we can't do NTLMv2 without it */
1113                         DEBUG(1, ("Server did not provide 'target information', required for NTLMv2\n"));
1114                         return NT_STATUS_INVALID_PARAMETER;
1115                 }
1116
1117                 /* TODO: if the remote server is standalone, then we should replace 'domain'
1118                    with the server name as supplied above */
1119
1120                 if (!SMBNTLMv2encrypt_hash(ntlmssp_state,
1121                                            ntlmssp_state->user,
1122                                            ntlmssp_state->domain,
1123                                            ntlmssp_state->nt_hash, &challenge_blob,
1124                                            &struct_blob,
1125                                            &lm_response, &nt_response, NULL,
1126                                            &session_key)) {
1127                         data_blob_free(&challenge_blob);
1128                         data_blob_free(&struct_blob);
1129                         return NT_STATUS_NO_MEMORY;
1130                 }
1131         } else if (ntlmssp_state->neg_flags & NTLMSSP_NEGOTIATE_NTLM2) {
1132                 struct MD5Context md5_session_nonce_ctx;
1133                 uint8_t session_nonce[16];
1134                 uint8_t session_nonce_hash[16];
1135                 uint8_t user_session_key[16];
1136
1137                 lm_response = data_blob_talloc(ntlmssp_state, NULL, 24);
1138                 generate_random_buffer(lm_response.data, 8);
1139                 memset(lm_response.data+8, 0, 16);
1140
1141                 memcpy(session_nonce, challenge_blob.data, 8);
1142                 memcpy(&session_nonce[8], lm_response.data, 8);
1143
1144                 MD5Init(&md5_session_nonce_ctx);
1145                 MD5Update(&md5_session_nonce_ctx, challenge_blob.data, 8);
1146                 MD5Update(&md5_session_nonce_ctx, lm_response.data, 8);
1147                 MD5Final(session_nonce_hash, &md5_session_nonce_ctx);
1148
1149                 DEBUG(5, ("NTLMSSP challenge set by NTLM2\n"));
1150                 DEBUG(5, ("challenge is: \n"));
1151                 dump_data(5, session_nonce_hash, 8);
1152
1153                 nt_response = data_blob_talloc(ntlmssp_state, NULL, 24);
1154                 SMBNTencrypt_hash(ntlmssp_state->nt_hash,
1155                                   session_nonce_hash,
1156                                   nt_response.data);
1157
1158                 session_key = data_blob_talloc(ntlmssp_state, NULL, 16);
1159
1160                 SMBsesskeygen_ntv1(ntlmssp_state->nt_hash, user_session_key);
1161                 hmac_md5(user_session_key, session_nonce, sizeof(session_nonce), session_key.data);
1162                 dump_data_pw("NTLM2 session key:\n", session_key.data, session_key.length);
1163         } else {
1164                 /* lanman auth is insecure, it may be disabled */
1165                 if (lp_client_lanman_auth()) {
1166                         lm_response = data_blob_talloc(ntlmssp_state,
1167                                                        NULL, 24);
1168                         SMBencrypt_hash(ntlmssp_state->lm_hash,challenge_blob.data,
1169                                    lm_response.data);
1170                 }
1171
1172                 nt_response = data_blob_talloc(ntlmssp_state, NULL, 24);
1173                 SMBNTencrypt_hash(ntlmssp_state->nt_hash,challenge_blob.data,
1174                              nt_response.data);
1175
1176                 session_key = data_blob_talloc(ntlmssp_state, NULL, 16);
1177                 if ((ntlmssp_state->neg_flags & NTLMSSP_NEGOTIATE_LM_KEY)
1178                     && lp_client_lanman_auth()) {
1179                         SMBsesskeygen_lm_sess_key(ntlmssp_state->lm_hash, lm_response.data,
1180                                         session_key.data);
1181                         dump_data_pw("LM session key\n", session_key.data, session_key.length);
1182                 } else {
1183                         SMBsesskeygen_ntv1(ntlmssp_state->nt_hash, session_key.data);
1184                         dump_data_pw("NT session key:\n", session_key.data, session_key.length);
1185                 }
1186         }
1187         data_blob_free(&struct_blob);
1188
1189         /* Key exchange encryptes a new client-generated session key with
1190            the password-derived key */
1191         if (ntlmssp_state->neg_flags & NTLMSSP_NEGOTIATE_KEY_EXCH) {
1192                 /* Make up a new session key */
1193                 uint8_t client_session_key[16];
1194                 generate_random_buffer(client_session_key, sizeof(client_session_key));
1195
1196                 /* Encrypt the new session key with the old one */
1197                 encrypted_session_key = data_blob(client_session_key, sizeof(client_session_key));
1198                 dump_data_pw("KEY_EXCH session key:\n", encrypted_session_key.data, encrypted_session_key.length);
1199                 arcfour_crypt_blob(encrypted_session_key.data, encrypted_session_key.length, &session_key);
1200                 dump_data_pw("KEY_EXCH session key (enc):\n", encrypted_session_key.data, encrypted_session_key.length);
1201
1202                 /* Mark the new session key as the 'real' session key */
1203                 data_blob_free(&session_key);
1204                 session_key = data_blob_talloc(ntlmssp_state,
1205                                                client_session_key,
1206                                                sizeof(client_session_key));
1207         }
1208
1209         /* this generates the actual auth packet */
1210         if (!msrpc_gen(ntlmssp_state, next_request, auth_gen_string,
1211                        "NTLMSSP",
1212                        NTLMSSP_AUTH,
1213                        lm_response.data, lm_response.length,
1214                        nt_response.data, nt_response.length,
1215                        ntlmssp_state->domain,
1216                        ntlmssp_state->user,
1217                        ntlmssp_state->client.netbios_name,
1218                        encrypted_session_key.data, encrypted_session_key.length,
1219                        ntlmssp_state->neg_flags)) {
1220
1221                 return NT_STATUS_NO_MEMORY;
1222         }
1223
1224         if (DEBUGLEVEL >= 10) {
1225                 struct AUTHENTICATE_MESSAGE *authenticate = talloc(
1226                         talloc_tos(), struct AUTHENTICATE_MESSAGE);
1227                 if (authenticate != NULL) {
1228                         NTSTATUS status;
1229                         authenticate->NegotiateFlags =
1230                                 ntlmssp_state->neg_flags;
1231                         status = ntlmssp_pull_AUTHENTICATE_MESSAGE(
1232                                 next_request, authenticate, authenticate);
1233                         if (NT_STATUS_IS_OK(status)) {
1234                                 NDR_PRINT_DEBUG(AUTHENTICATE_MESSAGE,
1235                                                 authenticate);
1236                         }
1237                         TALLOC_FREE(authenticate);
1238                 }
1239         }
1240
1241         data_blob_free(&encrypted_session_key);
1242
1243         data_blob_free(&ntlmssp_state->chal);
1244
1245         ntlmssp_state->session_key = session_key;
1246
1247         ntlmssp_state->chal = challenge_blob;
1248         ntlmssp_state->lm_resp = lm_response;
1249         ntlmssp_state->nt_resp = nt_response;
1250
1251 done:
1252
1253         ntlmssp_state->expected_state = NTLMSSP_DONE;
1254
1255         if (!NT_STATUS_IS_OK(nt_status = ntlmssp_sign_init(ntlmssp_state))) {
1256                 DEBUG(1, ("Could not setup NTLMSSP signing/sealing system (error was: %s)\n", nt_errstr(nt_status)));
1257         }
1258
1259         return nt_status;
1260 }
1261
1262 NTSTATUS ntlmssp_client_start(TALLOC_CTX *mem_ctx,
1263                               const char *netbios_name,
1264                               const char *netbios_domain,
1265                               bool use_ntlmv2,
1266                               struct ntlmssp_state **_ntlmssp_state)
1267 {
1268         struct ntlmssp_state *ntlmssp_state;
1269
1270         if (!netbios_name) {
1271                 netbios_name = "";
1272         }
1273
1274         if (!netbios_domain) {
1275                 netbios_domain = "";
1276         }
1277
1278         ntlmssp_state = talloc_zero(mem_ctx, struct ntlmssp_state);
1279         if (!ntlmssp_state) {
1280                 return NT_STATUS_NO_MEMORY;
1281         }
1282
1283         ntlmssp_state->role = NTLMSSP_CLIENT;
1284
1285         ntlmssp_state->unicode = True;
1286
1287         ntlmssp_state->use_ntlmv2 = use_ntlmv2;
1288
1289         ntlmssp_state->expected_state = NTLMSSP_INITIAL;
1290
1291         ntlmssp_state->neg_flags =
1292                 NTLMSSP_NEGOTIATE_128 |
1293                 NTLMSSP_NEGOTIATE_ALWAYS_SIGN |
1294                 NTLMSSP_NEGOTIATE_NTLM |
1295                 NTLMSSP_NEGOTIATE_NTLM2 |
1296                 NTLMSSP_NEGOTIATE_KEY_EXCH |
1297                 NTLMSSP_REQUEST_TARGET;
1298
1299         ntlmssp_state->client.netbios_name = talloc_strdup(ntlmssp_state, netbios_name);
1300         if (!ntlmssp_state->client.netbios_name) {
1301                 talloc_free(ntlmssp_state);
1302                 return NT_STATUS_NO_MEMORY;
1303         }
1304         ntlmssp_state->client.netbios_domain = talloc_strdup(ntlmssp_state, netbios_domain);
1305         if (!ntlmssp_state->client.netbios_domain) {
1306                 talloc_free(ntlmssp_state);
1307                 return NT_STATUS_NO_MEMORY;
1308         }
1309
1310         *_ntlmssp_state = ntlmssp_state;
1311         return NT_STATUS_OK;
1312 }