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