Release still reachable memory if the smbclient context is freed.
[ira/wip.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->mem_ctx, 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->mem_ctx, lm_hash, 16);
168         ntlmssp_state->nt_hash = (unsigned char *)
169                 TALLOC_MEMDUP(ntlmssp_state->mem_ctx, 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->mem_ctx, domain ? domain : "" );
205         if (!ntlmssp_state->domain) {
206                 return NT_STATUS_NO_MEMORY;
207         }
208         return NT_STATUS_OK;
209 }
210
211 /** 
212  * Set a workstation on an NTLMSSP context - ensures it is talloc()ed 
213  *
214  */
215 NTSTATUS ntlmssp_set_workstation(NTLMSSP_STATE *ntlmssp_state, const char *workstation) 
216 {
217         ntlmssp_state->workstation = talloc_strdup(ntlmssp_state->mem_ctx, workstation);
218         if (!ntlmssp_state->workstation) {
219                 return NT_STATUS_NO_MEMORY;
220         }
221         return NT_STATUS_OK;
222 }
223
224 /**
225  *  Store a DATA_BLOB containing an NTLMSSP response, for use later.
226  *  This copies the data blob
227  */
228
229 NTSTATUS ntlmssp_store_response(NTLMSSP_STATE *ntlmssp_state,
230                                 DATA_BLOB response) 
231 {
232         ntlmssp_state->stored_response = data_blob_talloc(ntlmssp_state->mem_ctx, 
233                                                           response.data, response.length);
234         return NT_STATUS_OK;
235 }
236
237 /**
238  * Request features for the NTLMSSP negotiation
239  *
240  * @param ntlmssp_state NTLMSSP state
241  * @param feature_list List of space seperated features requested from NTLMSSP.
242  */
243 void ntlmssp_want_feature_list(NTLMSSP_STATE *ntlmssp_state, char *feature_list)
244 {
245         /*
246          * We need to set this to allow a later SetPassword
247          * via the SAMR pipe to succeed. Strange.... We could
248          * also add  NTLMSSP_NEGOTIATE_SEAL here. JRA.
249          */
250         if (in_list("NTLMSSP_FEATURE_SESSION_KEY", feature_list, True)) {
251                 ntlmssp_state->neg_flags |= NTLMSSP_NEGOTIATE_SIGN;
252         }
253         if (in_list("NTLMSSP_FEATURE_SIGN", feature_list, True)) {
254                 ntlmssp_state->neg_flags |= NTLMSSP_NEGOTIATE_SIGN;
255         }
256         if(in_list("NTLMSSP_FEATURE_SEAL", feature_list, True)) {
257                 ntlmssp_state->neg_flags |= NTLMSSP_NEGOTIATE_SEAL;
258         }
259 }
260
261 /**
262  * Request a feature for the NTLMSSP negotiation
263  *
264  * @param ntlmssp_state NTLMSSP state
265  * @param feature Bit flag specifying the requested feature
266  */
267 void ntlmssp_want_feature(NTLMSSP_STATE *ntlmssp_state, uint32 feature)
268 {
269         /* As per JRA's comment above */
270         if (feature & NTLMSSP_FEATURE_SESSION_KEY) {
271                 ntlmssp_state->neg_flags |= NTLMSSP_NEGOTIATE_SIGN;
272         }
273         if (feature & NTLMSSP_FEATURE_SIGN) {
274                 ntlmssp_state->neg_flags |= NTLMSSP_NEGOTIATE_SIGN;
275         }
276         if (feature & NTLMSSP_FEATURE_SEAL) {
277                 ntlmssp_state->neg_flags |= NTLMSSP_NEGOTIATE_SEAL;
278         }
279 }
280  
281 /**
282  * Next state function for the NTLMSSP state machine
283  * 
284  * @param ntlmssp_state NTLMSSP State
285  * @param in The packet in from the NTLMSSP partner, as a DATA_BLOB
286  * @param out The reply, as an allocated DATA_BLOB, caller to free.
287  * @return Errors, NT_STATUS_MORE_PROCESSING_REQUIRED or NT_STATUS_OK. 
288  */
289
290 NTSTATUS ntlmssp_update(NTLMSSP_STATE *ntlmssp_state, 
291                         const DATA_BLOB in, DATA_BLOB *out) 
292 {
293         DATA_BLOB input;
294         uint32 ntlmssp_command;
295         int i;
296
297         if (ntlmssp_state->expected_state == NTLMSSP_DONE) {
298                 /* Called update after negotiations finished. */
299                 DEBUG(1, ("Called NTLMSSP after state machine was 'done'\n"));
300                 return NT_STATUS_INVALID_PARAMETER;
301         }
302
303         *out = data_blob_null;
304
305         if (!in.length && ntlmssp_state->stored_response.length) {
306                 input = ntlmssp_state->stored_response;
307                 
308                 /* we only want to read the stored response once - overwrite it */
309                 ntlmssp_state->stored_response = data_blob_null;
310         } else {
311                 input = in;
312         }
313
314         if (!input.length) {
315                 switch (ntlmssp_state->role) {
316                 case NTLMSSP_CLIENT:
317                         ntlmssp_command = NTLMSSP_INITIAL;
318                         break;
319                 case NTLMSSP_SERVER:
320                         /* 'datagram' mode - no neg packet */
321                         ntlmssp_command = NTLMSSP_NEGOTIATE;
322                         break;
323                 }
324         } else {
325                 if (!msrpc_parse(&input, "Cd",
326                                  "NTLMSSP",
327                                  &ntlmssp_command)) {
328                         DEBUG(1, ("Failed to parse NTLMSSP packet, could not extract NTLMSSP command\n"));
329                         dump_data(2, input.data, input.length);
330                         return NT_STATUS_INVALID_PARAMETER;
331                 }
332         }
333
334         if (ntlmssp_command != ntlmssp_state->expected_state) {
335                 DEBUG(1, ("got NTLMSSP command %u, expected %u\n", ntlmssp_command, ntlmssp_state->expected_state));
336                 return NT_STATUS_INVALID_PARAMETER;
337         }
338
339         for (i=0; ntlmssp_callbacks[i].fn; i++) {
340                 if (ntlmssp_callbacks[i].role == ntlmssp_state->role 
341                     && ntlmssp_callbacks[i].ntlmssp_command == ntlmssp_command) {
342                         return ntlmssp_callbacks[i].fn(ntlmssp_state, input, out);
343                 }
344         }
345
346         DEBUG(1, ("failed to find NTLMSSP callback for NTLMSSP mode %u, command %u\n", 
347                   ntlmssp_state->role, ntlmssp_command)); 
348
349         return NT_STATUS_INVALID_PARAMETER;
350 }
351
352 /**
353  * End an NTLMSSP state machine
354  * 
355  * @param ntlmssp_state NTLMSSP State, free()ed by this function
356  */
357
358 void ntlmssp_end(NTLMSSP_STATE **ntlmssp_state)
359 {
360         TALLOC_CTX *mem_ctx = (*ntlmssp_state)->mem_ctx;
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
369                 talloc_destroy(mem_ctx);
370         }
371
372         *ntlmssp_state = NULL;
373         return;
374 }
375
376 /**
377  * Determine correct target name flags for reply, given server role 
378  * and negotiated flags
379  * 
380  * @param ntlmssp_state NTLMSSP State
381  * @param neg_flags The flags from the packet
382  * @param chal_flags The flags to be set in the reply packet
383  * @return The 'target name' string.
384  */
385
386 static const char *ntlmssp_target_name(struct ntlmssp_state *ntlmssp_state,
387                                        uint32 neg_flags, uint32 *chal_flags) 
388 {
389         if (neg_flags & NTLMSSP_REQUEST_TARGET) {
390                 *chal_flags |= NTLMSSP_CHAL_TARGET_INFO;
391                 *chal_flags |= NTLMSSP_REQUEST_TARGET;
392                 if (ntlmssp_state->server_role == ROLE_STANDALONE) {
393                         *chal_flags |= NTLMSSP_TARGET_TYPE_SERVER;
394                         return ntlmssp_state->get_global_myname();
395                 } else {
396                         *chal_flags |= NTLMSSP_TARGET_TYPE_DOMAIN;
397                         return ntlmssp_state->get_domain();
398                 };
399         } else {
400                 return "";
401         }
402 }
403
404 static void ntlmssp_handle_neg_flags(struct ntlmssp_state *ntlmssp_state,
405                                       uint32 neg_flags, bool allow_lm) {
406         if (neg_flags & NTLMSSP_NEGOTIATE_UNICODE) {
407                 ntlmssp_state->neg_flags |= NTLMSSP_NEGOTIATE_UNICODE;
408                 ntlmssp_state->neg_flags &= ~NTLMSSP_NEGOTIATE_OEM;
409                 ntlmssp_state->unicode = True;
410         } else {
411                 ntlmssp_state->neg_flags &= ~NTLMSSP_NEGOTIATE_UNICODE;
412                 ntlmssp_state->neg_flags |= NTLMSSP_NEGOTIATE_OEM;
413                 ntlmssp_state->unicode = False;
414         }
415
416         if ((neg_flags & NTLMSSP_NEGOTIATE_LM_KEY) && allow_lm) {
417                 /* other end forcing us to use LM */
418                 ntlmssp_state->neg_flags |= NTLMSSP_NEGOTIATE_LM_KEY;
419                 ntlmssp_state->use_ntlmv2 = False;
420         } else {
421                 ntlmssp_state->neg_flags &= ~NTLMSSP_NEGOTIATE_LM_KEY;
422         }
423
424         if (!(neg_flags & NTLMSSP_NEGOTIATE_ALWAYS_SIGN)) {
425                 ntlmssp_state->neg_flags &= ~NTLMSSP_NEGOTIATE_ALWAYS_SIGN;
426         }
427
428         if (!(neg_flags & NTLMSSP_NEGOTIATE_NTLM2)) {
429                 ntlmssp_state->neg_flags &= ~NTLMSSP_NEGOTIATE_NTLM2;
430         }
431
432         if (!(neg_flags & NTLMSSP_NEGOTIATE_128)) {
433                 ntlmssp_state->neg_flags &= ~NTLMSSP_NEGOTIATE_128;
434         }
435
436         if (!(neg_flags & NTLMSSP_NEGOTIATE_56)) {
437                 ntlmssp_state->neg_flags &= ~NTLMSSP_NEGOTIATE_56;
438         }
439
440         if (!(neg_flags & NTLMSSP_NEGOTIATE_KEY_EXCH)) {
441                 ntlmssp_state->neg_flags &= ~NTLMSSP_NEGOTIATE_KEY_EXCH;
442         }
443
444         if (!(neg_flags & NTLMSSP_NEGOTIATE_SIGN)) {
445                 ntlmssp_state->neg_flags &= ~NTLMSSP_NEGOTIATE_SIGN;
446         }
447
448         if (!(neg_flags & NTLMSSP_NEGOTIATE_SEAL)) {
449                 ntlmssp_state->neg_flags &= ~NTLMSSP_NEGOTIATE_SEAL;
450         }
451
452         /* Woop Woop - unknown flag for Windows compatibility...
453            What does this really do ? JRA. */
454         if (!(neg_flags & NTLMSSP_NEGOTIATE_VERSION)) {
455                 ntlmssp_state->neg_flags &= ~NTLMSSP_NEGOTIATE_VERSION;
456         }
457
458         if ((neg_flags & NTLMSSP_REQUEST_TARGET)) {
459                 ntlmssp_state->neg_flags |= NTLMSSP_REQUEST_TARGET;
460         }
461 }
462
463 /**
464  Weaken NTLMSSP keys to cope with down-level clients and servers.
465
466  We probably should have some parameters to control this, but as
467  it only occours for LM_KEY connections, and this is controlled
468  by the client lanman auth/lanman auth parameters, it isn't too bad.
469 */
470
471 DATA_BLOB ntlmssp_weaken_keys(NTLMSSP_STATE *ntlmssp_state, TALLOC_CTX *mem_ctx)
472 {
473         DATA_BLOB weakened_key = data_blob_talloc(mem_ctx,
474                                         ntlmssp_state->session_key.data,
475                                         ntlmssp_state->session_key.length);
476
477         /* Nothing to weaken.  We certainly don't want to 'extend' the length... */
478         if (weakened_key.length < 16) {
479                 /* perhaps there was no key? */
480                 return weakened_key;
481         }
482
483         /* Key weakening not performed on the master key for NTLM2
484            and does not occour for NTLM1.  Therefore we only need
485            to do this for the LM_KEY.
486         */
487
488         if (ntlmssp_state->neg_flags & NTLMSSP_NEGOTIATE_LM_KEY) {
489                 /* LM key doesn't support 128 bit crypto, so this is
490                  * the best we can do.  If you negotiate 128 bit, but
491                  * not 56, you end up with 40 bit... */
492                 if (ntlmssp_state->neg_flags & NTLMSSP_NEGOTIATE_56) {
493                         weakened_key.data[7] = 0xa0;
494                 } else { /* forty bits */
495                         weakened_key.data[5] = 0xe5;
496                         weakened_key.data[6] = 0x38;
497                         weakened_key.data[7] = 0xb0;
498                 }
499                 weakened_key.length = 8;
500         }
501         return weakened_key;
502 }
503
504 /**
505  * Next state function for the Negotiate packet
506  *
507  * @param ntlmssp_state NTLMSSP State
508  * @param request The request, as a DATA_BLOB
509  * @param request The reply, as an allocated DATA_BLOB, caller to free.
510  * @return Errors or MORE_PROCESSING_REQUIRED if a reply is sent.
511  */
512
513 static NTSTATUS ntlmssp_server_negotiate(struct ntlmssp_state *ntlmssp_state,
514                                          const DATA_BLOB request, DATA_BLOB *reply) 
515 {
516         DATA_BLOB struct_blob;
517         const char *dnsname;
518         char *dnsdomname = NULL;
519         uint32 neg_flags = 0;
520         uint32 ntlmssp_command, chal_flags;
521         const uint8 *cryptkey;
522         const char *target_name;
523
524         /* parse the NTLMSSP packet */
525 #if 0
526         file_save("ntlmssp_negotiate.dat", request.data, request.length);
527 #endif
528
529         if (request.length) {
530                 if ((request.length < 16) || !msrpc_parse(&request, "Cdd",
531                                                         "NTLMSSP",
532                                                         &ntlmssp_command,
533                                                         &neg_flags)) {
534                         DEBUG(1, ("ntlmssp_server_negotiate: failed to parse NTLMSSP Negotiate of length %u\n",
535                                 (unsigned int)request.length));
536                         dump_data(2, request.data, request.length);
537                         return NT_STATUS_INVALID_PARAMETER;
538                 }
539                 debug_ntlmssp_flags(neg_flags);
540         }
541
542         ntlmssp_handle_neg_flags(ntlmssp_state, neg_flags, lp_lanman_auth());
543
544         /* Ask our caller what challenge they would like in the packet */
545         cryptkey = ntlmssp_state->get_challenge(ntlmssp_state);
546
547         /* Check if we may set the challenge */
548         if (!ntlmssp_state->may_set_challenge(ntlmssp_state)) {
549                 ntlmssp_state->neg_flags &= ~NTLMSSP_NEGOTIATE_NTLM2;
550         }
551
552         /* The flags we send back are not just the negotiated flags,
553          * they are also 'what is in this packet'.  Therfore, we
554          * operate on 'chal_flags' from here on
555          */
556
557         chal_flags = ntlmssp_state->neg_flags;
558
559         /* get the right name to fill in as 'target' */
560         target_name = ntlmssp_target_name(ntlmssp_state,
561                                           neg_flags, &chal_flags);
562         if (target_name == NULL)
563                 return NT_STATUS_INVALID_PARAMETER;
564
565         ntlmssp_state->chal = data_blob_talloc(ntlmssp_state->mem_ctx, cryptkey, 8);
566         ntlmssp_state->internal_chal = data_blob_talloc(ntlmssp_state->mem_ctx, cryptkey, 8);
567
568         /* This should be a 'netbios domain -> DNS domain' mapping */
569         dnsdomname = get_mydnsdomname(ntlmssp_state->mem_ctx);
570         if (!dnsdomname) {
571                 dnsdomname = talloc_strdup(ntlmssp_state->mem_ctx, "");
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(ntlmssp_state->mem_ctx, session_nonce_hash, 8);
774
775                         /* LM response is no longer useful */
776                         data_blob_free(&ntlmssp_state->lm_resp);
777
778                         /* We changed the effective challenge - set it */
779                         if (!NT_STATUS_IS_OK(nt_status = ntlmssp_state->set_challenge(ntlmssp_state, &ntlmssp_state->chal))) {
780                                 data_blob_free(&encrypted_session_key);
781                                 return nt_status;
782                         }
783
784                         /* LM Key is incompatible. */
785                         ntlmssp_state->neg_flags &= ~NTLMSSP_NEGOTIATE_LM_KEY;
786                 }
787         }
788
789         /*
790          * Note we don't check here for NTLMv2 auth settings. If NTLMv2 auth
791          * is required (by "ntlm auth = no" and "lm auth = no" being set in the
792          * smb.conf file) and no NTLMv2 response was sent then the password check
793          * will fail here. JRA.
794          */
795
796         /* Finally, actually ask if the password is OK */
797
798         if (!NT_STATUS_IS_OK(nt_status = ntlmssp_state->check_password(ntlmssp_state, 
799                                                                        &user_session_key, &lm_session_key))) {
800                 data_blob_free(&encrypted_session_key);
801                 return nt_status;
802         }
803
804         dump_data_pw("NT session key:\n", user_session_key.data, user_session_key.length);
805         dump_data_pw("LM first-8:\n", lm_session_key.data, lm_session_key.length);
806
807         /* Handle the different session key derivation for NTLM2 */
808         if (doing_ntlm2) {
809                 if (user_session_key.data && user_session_key.length == 16) {
810                         session_key = data_blob_talloc(ntlmssp_state->mem_ctx, NULL, 16);
811                         hmac_md5(user_session_key.data, session_nonce, 
812                                  sizeof(session_nonce), session_key.data);
813                         DEBUG(10,("ntlmssp_server_auth: Created NTLM2 session key.\n"));
814                         dump_data_pw("NTLM2 session key:\n", session_key.data, session_key.length);
815                         
816                 } else {
817                         DEBUG(10,("ntlmssp_server_auth: Failed to create NTLM2 session key.\n"));
818                         session_key = data_blob_null;
819                 }
820         } else if (ntlmssp_state->neg_flags & NTLMSSP_NEGOTIATE_LM_KEY) {
821                 if (lm_session_key.data && lm_session_key.length >= 8) {
822                         if (ntlmssp_state->lm_resp.data && ntlmssp_state->lm_resp.length == 24) {
823                                 session_key = data_blob_talloc(ntlmssp_state->mem_ctx, NULL, 16);
824                                 if (session_key.data == NULL) {
825                                         return NT_STATUS_NO_MEMORY;
826                                 }
827                                 SMBsesskeygen_lm_sess_key(lm_session_key.data, ntlmssp_state->lm_resp.data, 
828                                                           session_key.data);
829                                 DEBUG(10,("ntlmssp_server_auth: Created NTLM session key.\n"));
830                         } else {
831                                 uint8 zeros[24];
832                                 ZERO_STRUCT(zeros);
833                                 session_key = data_blob_talloc(
834                                         ntlmssp_state->mem_ctx, NULL, 16);
835                                 if (session_key.data == NULL) {
836                                         return NT_STATUS_NO_MEMORY;
837                                 }
838                                 SMBsesskeygen_lm_sess_key(
839                                         lm_session_key.data, zeros,
840                                         session_key.data);
841                         }
842                         dump_data_pw("LM session key:\n", session_key.data,
843                                      session_key.length);
844                 } else {
845                         DEBUG(10,("ntlmssp_server_auth: Failed to create NTLM session key.\n"));
846                         session_key = data_blob_null;
847                 }
848         } else if (user_session_key.data) {
849                 session_key = user_session_key;
850                 DEBUG(10,("ntlmssp_server_auth: Using unmodified nt session key.\n"));
851                 dump_data_pw("unmodified session key:\n", session_key.data, session_key.length);
852         } else if (lm_session_key.data) {
853                 session_key = lm_session_key;
854                 DEBUG(10,("ntlmssp_server_auth: Using unmodified lm session key.\n"));
855                 dump_data_pw("unmodified session key:\n", session_key.data, session_key.length);
856         } else {
857                 DEBUG(10,("ntlmssp_server_auth: Failed to create unmodified session key.\n"));
858                 session_key = data_blob_null;
859         }
860
861         /* With KEY_EXCH, the client supplies the proposed session key, 
862            but encrypts it with the long-term key */
863         if (ntlmssp_state->neg_flags & NTLMSSP_NEGOTIATE_KEY_EXCH) {
864                 if (!encrypted_session_key.data || encrypted_session_key.length != 16) {
865                         data_blob_free(&encrypted_session_key);
866                         DEBUG(1, ("Client-supplied KEY_EXCH session key was of invalid length (%u)!\n", 
867                                   (unsigned int)encrypted_session_key.length));
868                         return NT_STATUS_INVALID_PARAMETER;
869                 } else if (!session_key.data || session_key.length != 16) {
870                         DEBUG(5, ("server session key is invalid (len == %u), cannot do KEY_EXCH!\n", 
871                                   (unsigned int)session_key.length));
872                         ntlmssp_state->session_key = session_key;
873                 } else {
874                         dump_data_pw("KEY_EXCH session key (enc):\n", encrypted_session_key.data, encrypted_session_key.length);
875                         SamOEMhash(encrypted_session_key.data, 
876                                    session_key.data, 
877                                    encrypted_session_key.length);
878                         ntlmssp_state->session_key = data_blob_talloc(ntlmssp_state->mem_ctx, 
879                                                                       encrypted_session_key.data, 
880                                                                       encrypted_session_key.length);
881                         dump_data_pw("KEY_EXCH session key:\n", encrypted_session_key.data, 
882                                      encrypted_session_key.length);
883                 }
884         } else {
885                 ntlmssp_state->session_key = session_key;
886         }
887
888         if (!NT_STATUS_IS_OK(nt_status)) {
889                 ntlmssp_state->session_key = data_blob_null;
890         } else if (ntlmssp_state->session_key.length) {
891                 nt_status = ntlmssp_sign_init(ntlmssp_state);
892         }
893
894         data_blob_free(&encrypted_session_key);
895         
896         /* Only one authentication allowed per server state. */
897         ntlmssp_state->expected_state = NTLMSSP_DONE;
898
899         return nt_status;
900 }
901
902 /**
903  * Create an NTLMSSP state machine
904  * 
905  * @param ntlmssp_state NTLMSSP State, allocated by this function
906  */
907
908 NTSTATUS ntlmssp_server_start(NTLMSSP_STATE **ntlmssp_state)
909 {
910         TALLOC_CTX *mem_ctx;
911
912         mem_ctx = talloc_init("NTLMSSP context");
913         
914         *ntlmssp_state = TALLOC_ZERO_P(mem_ctx, NTLMSSP_STATE);
915         if (!*ntlmssp_state) {
916                 DEBUG(0,("ntlmssp_server_start: talloc failed!\n"));
917                 talloc_destroy(mem_ctx);
918                 return NT_STATUS_NO_MEMORY;
919         }
920
921         (*ntlmssp_state)->role = NTLMSSP_SERVER;
922
923         (*ntlmssp_state)->mem_ctx = mem_ctx;
924         (*ntlmssp_state)->get_challenge = get_challenge;
925         (*ntlmssp_state)->set_challenge = set_challenge;
926         (*ntlmssp_state)->may_set_challenge = may_set_challenge;
927
928         (*ntlmssp_state)->get_global_myname = global_myname;
929         (*ntlmssp_state)->get_domain = lp_workgroup;
930         (*ntlmssp_state)->server_role = ROLE_DOMAIN_MEMBER; /* a good default */
931
932         (*ntlmssp_state)->expected_state = NTLMSSP_NEGOTIATE;
933
934         (*ntlmssp_state)->ref_count = 1;
935
936         (*ntlmssp_state)->neg_flags = 
937                 NTLMSSP_NEGOTIATE_128 |
938                 NTLMSSP_NEGOTIATE_56 |
939                 NTLMSSP_NEGOTIATE_VERSION |
940                 NTLMSSP_NEGOTIATE_ALWAYS_SIGN |
941                 NTLMSSP_NEGOTIATE_NTLM |
942                 NTLMSSP_NEGOTIATE_NTLM2 |
943                 NTLMSSP_NEGOTIATE_KEY_EXCH |
944                 NTLMSSP_NEGOTIATE_SIGN |
945                 NTLMSSP_NEGOTIATE_SEAL;
946
947         return NT_STATUS_OK;
948 }
949
950 /*********************************************************************
951  Client side NTLMSSP
952 *********************************************************************/
953
954 /**
955  * Next state function for the Initial packet
956  * 
957  * @param ntlmssp_state NTLMSSP State
958  * @param request The request, as a DATA_BLOB.  reply.data must be NULL
959  * @param request The reply, as an allocated DATA_BLOB, caller to free.
960  * @return Errors or NT_STATUS_OK. 
961  */
962
963 static NTSTATUS ntlmssp_client_initial(struct ntlmssp_state *ntlmssp_state, 
964                                   DATA_BLOB reply, DATA_BLOB *next_request) 
965 {
966         if (ntlmssp_state->unicode) {
967                 ntlmssp_state->neg_flags |= NTLMSSP_NEGOTIATE_UNICODE;
968         } else {
969                 ntlmssp_state->neg_flags |= NTLMSSP_NEGOTIATE_OEM;
970         }
971         
972         if (ntlmssp_state->use_ntlmv2) {
973                 ntlmssp_state->neg_flags |= NTLMSSP_NEGOTIATE_NTLM2;
974         }
975
976         /* generate the ntlmssp negotiate packet */
977         msrpc_gen(next_request, "CddAA",
978                   "NTLMSSP",
979                   NTLMSSP_NEGOTIATE,
980                   ntlmssp_state->neg_flags,
981                   ntlmssp_state->get_domain(), 
982                   ntlmssp_state->get_global_myname());
983
984         ntlmssp_state->expected_state = NTLMSSP_CHALLENGE;
985
986         return NT_STATUS_MORE_PROCESSING_REQUIRED;
987 }
988
989 /**
990  * Next state function for the Challenge Packet.  Generate an auth packet.
991  * 
992  * @param ntlmssp_state NTLMSSP State
993  * @param request The request, as a DATA_BLOB.  reply.data must be NULL
994  * @param request The reply, as an allocated DATA_BLOB, caller to free.
995  * @return Errors or NT_STATUS_OK. 
996  */
997
998 static NTSTATUS ntlmssp_client_challenge(struct ntlmssp_state *ntlmssp_state, 
999                                          const DATA_BLOB reply, DATA_BLOB *next_request) 
1000 {
1001         uint32 chal_flags, ntlmssp_command, unkn1, unkn2;
1002         DATA_BLOB server_domain_blob;
1003         DATA_BLOB challenge_blob;
1004         DATA_BLOB struct_blob = data_blob_null;
1005         char *server_domain;
1006         const char *chal_parse_string;
1007         const char *auth_gen_string;
1008         DATA_BLOB lm_response = data_blob_null;
1009         DATA_BLOB nt_response = data_blob_null;
1010         DATA_BLOB session_key = data_blob_null;
1011         DATA_BLOB encrypted_session_key = data_blob_null;
1012         NTSTATUS nt_status = NT_STATUS_OK;
1013
1014         if (!msrpc_parse(&reply, "CdBd",
1015                          "NTLMSSP",
1016                          &ntlmssp_command, 
1017                          &server_domain_blob,
1018                          &chal_flags)) {
1019                 DEBUG(1, ("Failed to parse the NTLMSSP Challenge: (#1)\n"));
1020                 dump_data(2, reply.data, reply.length);
1021
1022                 return NT_STATUS_INVALID_PARAMETER;
1023         }
1024         
1025         data_blob_free(&server_domain_blob);
1026
1027         DEBUG(3, ("Got challenge flags:\n"));
1028         debug_ntlmssp_flags(chal_flags);
1029
1030         ntlmssp_handle_neg_flags(ntlmssp_state, chal_flags, lp_client_lanman_auth());
1031
1032         if (ntlmssp_state->unicode) {
1033                 if (chal_flags & NTLMSSP_CHAL_TARGET_INFO) {
1034                         chal_parse_string = "CdUdbddB";
1035                 } else {
1036                         chal_parse_string = "CdUdbdd";
1037                 }
1038                 auth_gen_string = "CdBBUUUBd";
1039         } else {
1040                 if (chal_flags & NTLMSSP_CHAL_TARGET_INFO) {
1041                         chal_parse_string = "CdAdbddB";
1042                 } else {
1043                         chal_parse_string = "CdAdbdd";
1044                 }
1045
1046                 auth_gen_string = "CdBBAAABd";
1047         }
1048
1049         DEBUG(3, ("NTLMSSP: Set final flags:\n"));
1050         debug_ntlmssp_flags(ntlmssp_state->neg_flags);
1051
1052         if (!msrpc_parse(&reply, chal_parse_string,
1053                          "NTLMSSP",
1054                          &ntlmssp_command, 
1055                          &server_domain,
1056                          &chal_flags,
1057                          &challenge_blob, 8,
1058                          &unkn1, &unkn2,
1059                          &struct_blob)) {
1060                 DEBUG(1, ("Failed to parse the NTLMSSP Challenge: (#2)\n"));
1061                 dump_data(2, reply.data, reply.length);
1062                 return NT_STATUS_INVALID_PARAMETER;
1063         }
1064
1065         ntlmssp_state->server_domain = talloc_strdup(ntlmssp_state->mem_ctx,
1066                                                      server_domain);
1067
1068         SAFE_FREE(server_domain);
1069         if (challenge_blob.length != 8) {
1070                 data_blob_free(&struct_blob);
1071                 return NT_STATUS_INVALID_PARAMETER;
1072         }
1073
1074         if (!ntlmssp_state->nt_hash || !ntlmssp_state->lm_hash) {
1075                 uchar zeros[16];
1076                 /* do nothing - blobs are zero length */
1077
1078                 ZERO_STRUCT(zeros);
1079
1080                 /* session key is all zeros */
1081                 session_key = data_blob_talloc(ntlmssp_state->mem_ctx, zeros, 16);
1082                 
1083                 /* not doing NLTM2 without a password */
1084                 ntlmssp_state->neg_flags &= ~NTLMSSP_NEGOTIATE_NTLM2;
1085         } else if (ntlmssp_state->use_ntlmv2) {
1086
1087                 if (!struct_blob.length) {
1088                         /* be lazy, match win2k - we can't do NTLMv2 without it */
1089                         DEBUG(1, ("Server did not provide 'target information', required for NTLMv2\n"));
1090                         return NT_STATUS_INVALID_PARAMETER;
1091                 }
1092
1093                 /* TODO: if the remote server is standalone, then we should replace 'domain'
1094                    with the server name as supplied above */
1095                 
1096                 if (!SMBNTLMv2encrypt_hash(ntlmssp_state->user, 
1097                                       ntlmssp_state->domain, 
1098                                       ntlmssp_state->nt_hash, &challenge_blob, 
1099                                       &struct_blob, 
1100                                       &lm_response, &nt_response, &session_key)) {
1101                         data_blob_free(&challenge_blob);
1102                         data_blob_free(&struct_blob);
1103                         return NT_STATUS_NO_MEMORY;
1104                 }
1105         } else if (ntlmssp_state->neg_flags & NTLMSSP_NEGOTIATE_NTLM2) {
1106                 struct MD5Context md5_session_nonce_ctx;
1107                 uchar session_nonce[16];
1108                 uchar session_nonce_hash[16];
1109                 uchar user_session_key[16];
1110                 
1111                 lm_response = data_blob_talloc(ntlmssp_state->mem_ctx, NULL, 24);
1112                 generate_random_buffer(lm_response.data, 8);
1113                 memset(lm_response.data+8, 0, 16);
1114
1115                 memcpy(session_nonce, challenge_blob.data, 8);
1116                 memcpy(&session_nonce[8], lm_response.data, 8);
1117         
1118                 MD5Init(&md5_session_nonce_ctx);
1119                 MD5Update(&md5_session_nonce_ctx, challenge_blob.data, 8);
1120                 MD5Update(&md5_session_nonce_ctx, lm_response.data, 8);
1121                 MD5Final(session_nonce_hash, &md5_session_nonce_ctx);
1122
1123                 DEBUG(5, ("NTLMSSP challenge set by NTLM2\n"));
1124                 DEBUG(5, ("challenge is: \n"));
1125                 dump_data(5, session_nonce_hash, 8);
1126                 
1127                 nt_response = data_blob_talloc(ntlmssp_state->mem_ctx, NULL, 24);
1128                 SMBNTencrypt_hash(ntlmssp_state->nt_hash,
1129                              session_nonce_hash,
1130                              nt_response.data);
1131
1132                 session_key = data_blob_talloc(ntlmssp_state->mem_ctx, NULL, 16);
1133
1134                 SMBsesskeygen_ntv1(ntlmssp_state->nt_hash, NULL, user_session_key);
1135                 hmac_md5(user_session_key, session_nonce, sizeof(session_nonce), session_key.data);
1136                 dump_data_pw("NTLM2 session key:\n", session_key.data, session_key.length);
1137         } else {
1138                 /* lanman auth is insecure, it may be disabled */
1139                 if (lp_client_lanman_auth()) {
1140                         lm_response = data_blob_talloc(ntlmssp_state->mem_ctx, NULL, 24);
1141                         SMBencrypt_hash(ntlmssp_state->lm_hash,challenge_blob.data,
1142                                    lm_response.data);
1143                 }
1144                 
1145                 nt_response = data_blob_talloc(ntlmssp_state->mem_ctx, NULL, 24);
1146                 SMBNTencrypt_hash(ntlmssp_state->nt_hash,challenge_blob.data,
1147                              nt_response.data);
1148                 
1149                 session_key = data_blob_talloc(ntlmssp_state->mem_ctx, NULL, 16);
1150                 if ((ntlmssp_state->neg_flags & NTLMSSP_NEGOTIATE_LM_KEY) 
1151                     && lp_client_lanman_auth()) {
1152                         SMBsesskeygen_lm_sess_key(ntlmssp_state->lm_hash, lm_response.data,
1153                                         session_key.data);
1154                         dump_data_pw("LM session key\n", session_key.data, session_key.length);
1155                 } else {
1156                         SMBsesskeygen_ntv1(ntlmssp_state->nt_hash, NULL, session_key.data);
1157                         dump_data_pw("NT session key:\n", session_key.data, session_key.length);
1158                 }
1159         }
1160         data_blob_free(&struct_blob);
1161
1162         /* Key exchange encryptes a new client-generated session key with
1163            the password-derived key */
1164         if (ntlmssp_state->neg_flags & NTLMSSP_NEGOTIATE_KEY_EXCH) {
1165                 /* Make up a new session key */
1166                 uint8 client_session_key[16];
1167                 generate_random_buffer(client_session_key, sizeof(client_session_key));
1168
1169                 /* Encrypt the new session key with the old one */
1170                 encrypted_session_key = data_blob(client_session_key, sizeof(client_session_key));
1171                 dump_data_pw("KEY_EXCH session key:\n", encrypted_session_key.data, encrypted_session_key.length);
1172                 SamOEMhash(encrypted_session_key.data, session_key.data, encrypted_session_key.length);
1173                 dump_data_pw("KEY_EXCH session key (enc):\n", encrypted_session_key.data, encrypted_session_key.length);
1174
1175                 /* Mark the new session key as the 'real' session key */
1176                 data_blob_free(&session_key);
1177                 session_key = data_blob_talloc(ntlmssp_state->mem_ctx, client_session_key, sizeof(client_session_key));
1178         }
1179
1180         /* this generates the actual auth packet */
1181         if (!msrpc_gen(next_request, auth_gen_string, 
1182                        "NTLMSSP", 
1183                        NTLMSSP_AUTH, 
1184                        lm_response.data, lm_response.length,
1185                        nt_response.data, nt_response.length,
1186                        ntlmssp_state->domain, 
1187                        ntlmssp_state->user, 
1188                        ntlmssp_state->get_global_myname(), 
1189                        encrypted_session_key.data, encrypted_session_key.length,
1190                        ntlmssp_state->neg_flags)) {
1191                 
1192                 return NT_STATUS_NO_MEMORY;
1193         }
1194
1195         data_blob_free(&encrypted_session_key);
1196
1197         data_blob_free(&ntlmssp_state->chal);
1198
1199         ntlmssp_state->session_key = session_key;
1200
1201         ntlmssp_state->chal = challenge_blob;
1202         ntlmssp_state->lm_resp = lm_response;
1203         ntlmssp_state->nt_resp = nt_response;
1204
1205         ntlmssp_state->expected_state = NTLMSSP_DONE;
1206
1207         if (!NT_STATUS_IS_OK(nt_status = ntlmssp_sign_init(ntlmssp_state))) {
1208                 DEBUG(1, ("Could not setup NTLMSSP signing/sealing system (error was: %s)\n", nt_errstr(nt_status)));
1209         }
1210
1211         return nt_status;
1212 }
1213
1214 NTSTATUS ntlmssp_client_start(NTLMSSP_STATE **ntlmssp_state)
1215 {
1216         TALLOC_CTX *mem_ctx;
1217
1218         mem_ctx = talloc_init("NTLMSSP Client context");
1219         
1220         *ntlmssp_state = TALLOC_ZERO_P(mem_ctx, NTLMSSP_STATE);
1221         if (!*ntlmssp_state) {
1222                 DEBUG(0,("ntlmssp_client_start: talloc failed!\n"));
1223                 talloc_destroy(mem_ctx);
1224                 return NT_STATUS_NO_MEMORY;
1225         }
1226
1227         (*ntlmssp_state)->role = NTLMSSP_CLIENT;
1228
1229         (*ntlmssp_state)->mem_ctx = mem_ctx;
1230
1231         (*ntlmssp_state)->get_global_myname = global_myname;
1232         (*ntlmssp_state)->get_domain = lp_workgroup;
1233
1234         (*ntlmssp_state)->unicode = True;
1235
1236         (*ntlmssp_state)->use_ntlmv2 = lp_client_ntlmv2_auth();
1237
1238         (*ntlmssp_state)->expected_state = NTLMSSP_INITIAL;
1239
1240         (*ntlmssp_state)->ref_count = 1;
1241
1242         (*ntlmssp_state)->neg_flags = 
1243                 NTLMSSP_NEGOTIATE_128 |
1244                 NTLMSSP_NEGOTIATE_ALWAYS_SIGN |
1245                 NTLMSSP_NEGOTIATE_NTLM |
1246                 NTLMSSP_NEGOTIATE_NTLM2 |
1247                 NTLMSSP_NEGOTIATE_KEY_EXCH |
1248                 NTLMSSP_REQUEST_TARGET;
1249
1250         return NT_STATUS_OK;
1251 }