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