auth/common: add support for auth4_ctx->check_ntlm_password_send/recv()
[metze/samba/wip.git] / auth / ntlmssp / ntlmssp_server.c
1 /*
2    Unix SMB/Netbios implementation.
3    Version 3.0
4    handle NTLMSSP, server side
5
6    Copyright (C) Andrew Tridgell      2001
7    Copyright (C) Andrew Bartlett 2001-2010
8
9    This program is free software; you can redistribute it and/or modify
10    it under the terms of the GNU General Public License as published by
11    the Free Software Foundation; either version 3 of the License, or
12    (at your option) any later version.
13
14    This program is distributed in the hope that it will be useful,
15    but WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17    GNU General Public License for more details.
18
19    You should have received a copy of the GNU General Public License
20    along with this program.  If not, see <http://www.gnu.org/licenses/>.
21 */
22
23 #include "includes.h"
24 #include <tevent.h>
25 #include "lib/util/tevent_ntstatus.h"
26 #include "lib/util/time_basic.h"
27 #include "auth/ntlmssp/ntlmssp.h"
28 #include "auth/ntlmssp/ntlmssp_private.h"
29 #include "../librpc/gen_ndr/ndr_ntlmssp.h"
30 #include "auth/ntlmssp/ntlmssp_ndr.h"
31 #include "../libcli/auth/libcli_auth.h"
32 #include "../lib/crypto/crypto.h"
33 #include "auth/gensec/gensec.h"
34 #include "auth/gensec/gensec_internal.h"
35 #include "auth/common_auth.h"
36 #include "param/param.h"
37 #include "param/loadparm.h"
38 #include "libcli/security/session.h"
39
40 /**
41  * Determine correct target name flags for reply, given server role
42  * and negotiated flags
43  *
44  * @param ntlmssp_state NTLMSSP State
45  * @param neg_flags The flags from the packet
46  * @param chal_flags The flags to be set in the reply packet
47  * @return The 'target name' string.
48  */
49
50 const char *ntlmssp_target_name(struct ntlmssp_state *ntlmssp_state,
51                                 uint32_t neg_flags, uint32_t *chal_flags)
52 {
53         if (neg_flags & NTLMSSP_REQUEST_TARGET) {
54                 *chal_flags |= NTLMSSP_NEGOTIATE_TARGET_INFO;
55                 *chal_flags |= NTLMSSP_REQUEST_TARGET;
56                 if (ntlmssp_state->server.is_standalone) {
57                         *chal_flags |= NTLMSSP_TARGET_TYPE_SERVER;
58                         return ntlmssp_state->server.netbios_name;
59                 } else {
60                         *chal_flags |= NTLMSSP_TARGET_TYPE_DOMAIN;
61                         return ntlmssp_state->server.netbios_domain;
62                 };
63         } else {
64                 return "";
65         }
66 }
67
68 /**
69  * Next state function for the NTLMSSP Negotiate packet
70  *
71  * @param gensec_security GENSEC state
72  * @param out_mem_ctx Memory context for *out
73  * @param in The request, as a DATA_BLOB.  reply.data must be NULL
74  * @param out The reply, as an allocated DATA_BLOB, caller to free.
75  * @return Errors or MORE_PROCESSING_REQUIRED if (normal) a reply is required.
76  */
77
78 NTSTATUS gensec_ntlmssp_server_negotiate(struct gensec_security *gensec_security,
79                                          TALLOC_CTX *out_mem_ctx,
80                                          const DATA_BLOB request, DATA_BLOB *reply)
81 {
82         struct gensec_ntlmssp_context *gensec_ntlmssp =
83                 talloc_get_type_abort(gensec_security->private_data,
84                                       struct gensec_ntlmssp_context);
85         struct ntlmssp_state *ntlmssp_state = gensec_ntlmssp->ntlmssp_state;
86         struct auth4_context *auth_context = gensec_security->auth_context;
87         DATA_BLOB struct_blob;
88         uint32_t neg_flags = 0;
89         uint32_t ntlmssp_command, chal_flags;
90         uint8_t cryptkey[8];
91         const char *target_name;
92         NTSTATUS status;
93         struct timeval tv_now = timeval_current();
94         /*
95          * See [MS-NLMP]
96          *
97          * Windows NT 4.0, windows_2000: use 30 minutes,
98          * Windows XP, Windows Server 2003, Windows Vista,
99          * Windows Server 2008, Windows 7, and Windows Server 2008 R2
100          * use 36 hours.
101          *
102          * Newer systems doesn't check this, likely because the
103          * connectionless NTLMSSP is no longer supported.
104          *
105          * As we expect the AUTHENTICATION_MESSAGE to arrive
106          * directly after the NEGOTIATE_MESSAGE (typically less than
107          * as 1 second later). We use a hard timeout of 30 Minutes.
108          *
109          * We don't look at AUTHENTICATE_MESSAGE.NtChallengeResponse.TimeStamp
110          * instead we just remember our own time.
111          */
112         uint32_t max_lifetime = 30 * 60;
113         struct timeval tv_end = timeval_add(&tv_now, max_lifetime, 0);
114
115         /* parse the NTLMSSP packet */
116 #if 0
117         file_save("ntlmssp_negotiate.dat", request.data, request.length);
118 #endif
119
120         if (request.length) {
121                 if (request.length > UINT16_MAX) {
122                         DEBUG(1, ("ntlmssp_server_negotiate: reject large request of length %u\n",
123                                 (unsigned int)request.length));
124                         return NT_STATUS_INVALID_PARAMETER;
125                 }
126
127                 if ((request.length < 16) || !msrpc_parse(ntlmssp_state, &request, "Cdd",
128                                                           "NTLMSSP",
129                                                           &ntlmssp_command,
130                                                           &neg_flags)) {
131                         DEBUG(1, ("ntlmssp_server_negotiate: failed to parse NTLMSSP Negotiate of length %u\n",
132                                 (unsigned int)request.length));
133                         dump_data(2, request.data, request.length);
134                         return NT_STATUS_INVALID_PARAMETER;
135                 }
136                 debug_ntlmssp_flags(neg_flags);
137
138                 if (DEBUGLEVEL >= 10) {
139                         struct NEGOTIATE_MESSAGE *negotiate = talloc(
140                                 ntlmssp_state, struct NEGOTIATE_MESSAGE);
141                         if (negotiate != NULL) {
142                                 status = ntlmssp_pull_NEGOTIATE_MESSAGE(
143                                         &request, negotiate, negotiate);
144                                 if (NT_STATUS_IS_OK(status)) {
145                                         NDR_PRINT_DEBUG(NEGOTIATE_MESSAGE,
146                                                         negotiate);
147                                 }
148                                 TALLOC_FREE(negotiate);
149                         }
150                 }
151         }
152
153         status = ntlmssp_handle_neg_flags(ntlmssp_state, neg_flags, "negotiate");
154         if (!NT_STATUS_IS_OK(status)){
155                 return status;
156         }
157
158         /* Ask our caller what challenge they would like in the packet */
159         if (auth_context->get_ntlm_challenge) {
160                 status = auth_context->get_ntlm_challenge(auth_context, cryptkey);
161                 if (!NT_STATUS_IS_OK(status)) {
162                         DEBUG(1, ("gensec_ntlmssp_server_negotiate: failed to get challenge: %s\n",
163                                   nt_errstr(status)));
164                         return status;
165                 }
166         } else {
167                 DEBUG(1, ("gensec_ntlmssp_server_negotiate: backend doesn't give a challenge\n"));
168                 return NT_STATUS_NOT_IMPLEMENTED;
169         }
170
171         /* The flags we send back are not just the negotiated flags,
172          * they are also 'what is in this packet'.  Therfore, we
173          * operate on 'chal_flags' from here on
174          */
175
176         chal_flags = ntlmssp_state->neg_flags;
177         ntlmssp_state->server.challenge_endtime = timeval_to_nttime(&tv_end);
178
179         /* get the right name to fill in as 'target' */
180         target_name = ntlmssp_target_name(ntlmssp_state,
181                                           neg_flags, &chal_flags);
182         if (target_name == NULL)
183                 return NT_STATUS_INVALID_PARAMETER;
184
185         ntlmssp_state->chal = data_blob_talloc(ntlmssp_state, cryptkey, 8);
186         ntlmssp_state->internal_chal = data_blob_talloc(ntlmssp_state,
187                                                         cryptkey, 8);
188
189         /* This creates the 'blob' of names that appears at the end of the packet */
190         if (chal_flags & NTLMSSP_NEGOTIATE_TARGET_INFO) {
191                 enum ndr_err_code err;
192                 struct AV_PAIR *pairs = NULL;
193                 uint32_t count = 5;
194
195                 pairs = talloc_zero_array(ntlmssp_state, struct AV_PAIR, count + 1);
196                 if (pairs == NULL) {
197                         return NT_STATUS_NO_MEMORY;
198                 }
199
200                 pairs[0].AvId                   = MsvAvNbDomainName;
201                 pairs[0].Value.AvNbDomainName   = target_name;
202
203                 pairs[1].AvId                   = MsvAvNbComputerName;
204                 pairs[1].Value.AvNbComputerName = ntlmssp_state->server.netbios_name;
205
206                 pairs[2].AvId                   = MsvAvDnsDomainName;
207                 pairs[2].Value.AvDnsDomainName  = ntlmssp_state->server.dns_domain;
208
209                 pairs[3].AvId                   = MsvAvDnsComputerName;
210                 pairs[3].Value.AvDnsComputerName= ntlmssp_state->server.dns_name;
211
212                 if (!ntlmssp_state->force_old_spnego) {
213                         pairs[4].AvId                   = MsvAvTimestamp;
214                         pairs[4].Value.AvTimestamp      =
215                                                 timeval_to_nttime(&tv_now);
216                         count += 1;
217
218                         pairs[5].AvId                   = MsvAvEOL;
219                 } else {
220                         pairs[4].AvId                   = MsvAvEOL;
221                 }
222
223                 ntlmssp_state->server.av_pair_list.count = count;
224                 ntlmssp_state->server.av_pair_list.pair = pairs;
225
226                 err = ndr_push_struct_blob(&struct_blob,
227                                         ntlmssp_state,
228                                         &ntlmssp_state->server.av_pair_list,
229                                         (ndr_push_flags_fn_t)ndr_push_AV_PAIR_LIST);
230                 if (!NDR_ERR_CODE_IS_SUCCESS(err)) {
231                         return NT_STATUS_NO_MEMORY;
232                 }
233         } else {
234                 struct_blob = data_blob_null;
235         }
236
237         {
238                 /* Marshal the packet in the right format, be it unicode or ASCII */
239                 const char *gen_string;
240                 const DATA_BLOB version_blob = ntlmssp_version_blob();
241
242                 if (ntlmssp_state->unicode) {
243                         gen_string = "CdUdbddBb";
244                 } else {
245                         gen_string = "CdAdbddBb";
246                 }
247
248                 status = msrpc_gen(out_mem_ctx, reply, gen_string,
249                         "NTLMSSP",
250                         NTLMSSP_CHALLENGE,
251                         target_name,
252                         chal_flags,
253                         cryptkey, 8,
254                         0, 0,
255                         struct_blob.data, struct_blob.length,
256                         version_blob.data, version_blob.length);
257
258                 if (!NT_STATUS_IS_OK(status)) {
259                         data_blob_free(&struct_blob);
260                         return status;
261                 }
262
263                 if (DEBUGLEVEL >= 10) {
264                         struct CHALLENGE_MESSAGE *challenge = talloc(
265                                 ntlmssp_state, struct CHALLENGE_MESSAGE);
266                         if (challenge != NULL) {
267                                 challenge->NegotiateFlags = chal_flags;
268                                 status = ntlmssp_pull_CHALLENGE_MESSAGE(
269                                         reply, challenge, challenge);
270                                 if (NT_STATUS_IS_OK(status)) {
271                                         NDR_PRINT_DEBUG(CHALLENGE_MESSAGE,
272                                                         challenge);
273                                 }
274                                 TALLOC_FREE(challenge);
275                         }
276                 }
277         }
278
279         data_blob_free(&struct_blob);
280
281         ntlmssp_state->negotiate_blob = data_blob_dup_talloc(ntlmssp_state,
282                                                              request);
283         if (ntlmssp_state->negotiate_blob.length != request.length) {
284                 return NT_STATUS_NO_MEMORY;
285         }
286
287         ntlmssp_state->challenge_blob = data_blob_dup_talloc(ntlmssp_state,
288                                                              *reply);
289         if (ntlmssp_state->challenge_blob.length != reply->length) {
290                 return NT_STATUS_NO_MEMORY;
291         }
292
293         ntlmssp_state->expected_state = NTLMSSP_AUTH;
294
295         return NT_STATUS_MORE_PROCESSING_REQUIRED;
296 }
297
298 struct ntlmssp_server_auth_state {
299         struct gensec_security *gensec_security;
300         struct gensec_ntlmssp_context *gensec_ntlmssp;
301         DATA_BLOB in;
302         struct auth_usersupplied_info *user_info;
303         DATA_BLOB user_session_key;
304         DATA_BLOB lm_session_key;
305         /* internal variables used by KEY_EXCH (client-supplied user session key */
306         DATA_BLOB encrypted_session_key;
307         bool doing_ntlm2;
308         /* internal variables used by NTLM2 */
309         uint8_t session_nonce[16];
310 };
311
312 static NTSTATUS ntlmssp_server_preauth(struct gensec_security *gensec_security,
313                                        struct gensec_ntlmssp_context *gensec_ntlmssp,
314                                        struct ntlmssp_server_auth_state *state,
315                                        const DATA_BLOB request);
316 static void ntlmssp_server_auth_done(struct tevent_req *subreq);
317 static NTSTATUS ntlmssp_server_postauth(struct gensec_security *gensec_security,
318                                         struct gensec_ntlmssp_context *gensec_ntlmssp,
319                                         struct ntlmssp_server_auth_state *state,
320                                         DATA_BLOB request);
321
322 struct tevent_req *ntlmssp_server_auth_send(TALLOC_CTX *mem_ctx,
323                                             struct tevent_context *ev,
324                                             struct gensec_security *gensec_security,
325                                             const DATA_BLOB in)
326 {
327         struct gensec_ntlmssp_context *gensec_ntlmssp =
328                 talloc_get_type_abort(gensec_security->private_data,
329                                       struct gensec_ntlmssp_context);
330         struct auth4_context *auth_context = gensec_security->auth_context;
331         struct tevent_req *req = NULL;
332         struct ntlmssp_server_auth_state *state = NULL;
333         uint8_t authoritative = 0;
334         NTSTATUS status;
335
336         req = tevent_req_create(mem_ctx, &state,
337                                 struct ntlmssp_server_auth_state);
338         if (req == NULL) {
339                 return NULL;
340         }
341         state->gensec_security = gensec_security;
342         state->gensec_ntlmssp = gensec_ntlmssp;
343         state->in = in;
344
345         status = ntlmssp_server_preauth(gensec_security,
346                                         gensec_ntlmssp,
347                                         state, in);
348         if (tevent_req_nterror(req, status)) {
349                 return tevent_req_post(req, ev);
350         }
351
352         if (auth_context->check_ntlm_password_send != NULL) {
353                 struct tevent_req *subreq = NULL;
354
355                 subreq = auth_context->check_ntlm_password_send(state, ev,
356                                                 auth_context,
357                                                 state->user_info);
358                 if (tevent_req_nomem(subreq, req)) {
359                         return tevent_req_post(req, ev);
360                 }
361                 tevent_req_set_callback(subreq,
362                                         ntlmssp_server_auth_done,
363                                         req);
364                 return req;
365         }
366
367         if (auth_context->check_ntlm_password == NULL) {
368                 tevent_req_nterror(req, NT_STATUS_INTERNAL_ERROR);
369                 return tevent_req_post(req, ev);
370         }
371
372         status = auth_context->check_ntlm_password(auth_context,
373                                                    gensec_ntlmssp,
374                                                    state->user_info,
375                                                    &authoritative,
376                                                    &gensec_ntlmssp->server_returned_info,
377                                                    &state->user_session_key,
378                                                    &state->lm_session_key);
379         if (!NT_STATUS_IS_OK(status)) {
380                 DBG_INFO("Checking NTLMSSP password for %s\\%s failed: %s\n",
381                          state->user_info->client.domain_name,
382                          state->user_info->client.account_name,
383                          nt_errstr(status));
384         }
385         if (tevent_req_nterror(req, status)) {
386                 return tevent_req_post(req, ev);
387         }
388         talloc_steal(state, state->user_session_key.data);
389         talloc_steal(state, state->lm_session_key.data);
390
391         status = ntlmssp_server_postauth(gensec_security,
392                                          gensec_ntlmssp,
393                                          state, in);
394         if (tevent_req_nterror(req, status)) {
395                 return tevent_req_post(req, ev);
396         }
397
398         tevent_req_done(req);
399         return tevent_req_post(req, ev);
400 }
401
402 /**
403  * Next state function for the Authenticate packet
404  *
405  * @param ntlmssp_state NTLMSSP State
406  * @param request The request, as a DATA_BLOB
407  * @return Errors or NT_STATUS_OK.
408  */
409
410 static NTSTATUS ntlmssp_server_preauth(struct gensec_security *gensec_security,
411                                        struct gensec_ntlmssp_context *gensec_ntlmssp,
412                                        struct ntlmssp_server_auth_state *state,
413                                        const DATA_BLOB request)
414 {
415         struct ntlmssp_state *ntlmssp_state = gensec_ntlmssp->ntlmssp_state;
416         struct auth4_context *auth_context = gensec_security->auth_context;
417         struct auth_usersupplied_info *user_info = NULL;
418         uint32_t ntlmssp_command, auth_flags;
419         NTSTATUS nt_status;
420         const unsigned int version_len = 8;
421         DATA_BLOB version_blob = data_blob_null;
422         const unsigned int mic_len = NTLMSSP_MIC_SIZE;
423         DATA_BLOB mic_blob = data_blob_null;
424         uint8_t session_nonce_hash[16];
425         const char *parse_string;
426         bool ok;
427         struct timeval endtime;
428         bool expired = false;
429
430 #if 0
431         file_save("ntlmssp_auth.dat", request.data, request.length);
432 #endif
433
434         if (ntlmssp_state->unicode) {
435                 parse_string = "CdBBUUUBdbb";
436         } else {
437                 parse_string = "CdBBAAABdbb";
438         }
439
440         /* zero these out */
441         data_blob_free(&ntlmssp_state->session_key);
442         data_blob_free(&ntlmssp_state->lm_resp);
443         data_blob_free(&ntlmssp_state->nt_resp);
444
445         ntlmssp_state->user = NULL;
446         ntlmssp_state->domain = NULL;
447         ntlmssp_state->client.netbios_name = NULL;
448
449         /* now the NTLMSSP encoded auth hashes */
450         ok = msrpc_parse(ntlmssp_state, &request, parse_string,
451                          "NTLMSSP",
452                          &ntlmssp_command,
453                          &ntlmssp_state->lm_resp,
454                          &ntlmssp_state->nt_resp,
455                          &ntlmssp_state->domain,
456                          &ntlmssp_state->user,
457                          &ntlmssp_state->client.netbios_name,
458                          &state->encrypted_session_key,
459                          &auth_flags,
460                          &version_blob, version_len,
461                          &mic_blob, mic_len);
462         if (!ok) {
463                 DEBUG(10, ("ntlmssp_server_auth: failed to parse NTLMSSP (nonfatal):\n"));
464                 dump_data(10, request.data, request.length);
465
466                 data_blob_free(&version_blob);
467                 data_blob_free(&mic_blob);
468
469                 if (ntlmssp_state->unicode) {
470                         parse_string = "CdBBUUUBd";
471                 } else {
472                         parse_string = "CdBBAAABd";
473                 }
474
475                 ok = msrpc_parse(ntlmssp_state, &request, parse_string,
476                                  "NTLMSSP",
477                                  &ntlmssp_command,
478                                  &ntlmssp_state->lm_resp,
479                                  &ntlmssp_state->nt_resp,
480                                  &ntlmssp_state->domain,
481                                  &ntlmssp_state->user,
482                                  &ntlmssp_state->client.netbios_name,
483                                  &state->encrypted_session_key,
484                                  &auth_flags);
485         }
486
487         if (!ok) {
488                 DEBUG(10, ("ntlmssp_server_auth: failed to parse NTLMSSP (nonfatal):\n"));
489                 dump_data(10, request.data, request.length);
490
491                 /* zero this out */
492                 data_blob_free(&state->encrypted_session_key);
493                 auth_flags = 0;
494
495                 /* Try again with a shorter string (Win9X truncates this packet) */
496                 if (ntlmssp_state->unicode) {
497                         parse_string = "CdBBUUU";
498                 } else {
499                         parse_string = "CdBBAAA";
500                 }
501
502                 /* now the NTLMSSP encoded auth hashes */
503                 if (!msrpc_parse(ntlmssp_state, &request, parse_string,
504                                  "NTLMSSP",
505                                  &ntlmssp_command,
506                                  &ntlmssp_state->lm_resp,
507                                  &ntlmssp_state->nt_resp,
508                                  &ntlmssp_state->domain,
509                                  &ntlmssp_state->user,
510                                  &ntlmssp_state->client.netbios_name)) {
511                         DEBUG(1, ("ntlmssp_server_auth: failed to parse NTLMSSP (tried both formats):\n"));
512                         dump_data(2, request.data, request.length);
513
514                         return NT_STATUS_INVALID_PARAMETER;
515                 }
516         }
517
518         talloc_steal(state, state->encrypted_session_key.data);
519
520         if (auth_flags != 0) {
521                 nt_status = ntlmssp_handle_neg_flags(ntlmssp_state,
522                                                      auth_flags,
523                                                      "authenticate");
524                 if (!NT_STATUS_IS_OK(nt_status)){
525                         return nt_status;
526                 }
527         }
528
529         if (DEBUGLEVEL >= 10) {
530                 struct AUTHENTICATE_MESSAGE *authenticate = talloc(
531                         ntlmssp_state, struct AUTHENTICATE_MESSAGE);
532                 if (authenticate != NULL) {
533                         NTSTATUS status;
534                         authenticate->NegotiateFlags = auth_flags;
535                         status = ntlmssp_pull_AUTHENTICATE_MESSAGE(
536                                 &request, authenticate, authenticate);
537                         if (NT_STATUS_IS_OK(status)) {
538                                 NDR_PRINT_DEBUG(AUTHENTICATE_MESSAGE,
539                                                 authenticate);
540                         }
541                         TALLOC_FREE(authenticate);
542                 }
543         }
544
545         DEBUG(3,("Got user=[%s] domain=[%s] workstation=[%s] len1=%lu len2=%lu\n",
546                  ntlmssp_state->user, ntlmssp_state->domain,
547                  ntlmssp_state->client.netbios_name,
548                  (unsigned long)ntlmssp_state->lm_resp.length,
549                  (unsigned long)ntlmssp_state->nt_resp.length));
550
551 #if 0
552         file_save("nthash1.dat",  &ntlmssp_state->nt_resp.data,  &ntlmssp_state->nt_resp.length);
553         file_save("lmhash1.dat",  &ntlmssp_state->lm_resp.data,  &ntlmssp_state->lm_resp.length);
554 #endif
555
556         if (ntlmssp_state->nt_resp.length > 24) {
557                 struct NTLMv2_RESPONSE v2_resp;
558                 enum ndr_err_code err;
559                 uint32_t i = 0;
560                 uint32_t count = 0;
561                 const struct AV_PAIR *flags = NULL;
562                 const struct AV_PAIR *eol = NULL;
563                 uint32_t av_flags = 0;
564
565                 err = ndr_pull_struct_blob(&ntlmssp_state->nt_resp,
566                                         ntlmssp_state,
567                                         &v2_resp,
568                                         (ndr_pull_flags_fn_t)ndr_pull_NTLMv2_RESPONSE);
569                 if (!NDR_ERR_CODE_IS_SUCCESS(err)) {
570                         nt_status = ndr_map_error2ntstatus(err);
571                         DEBUG(1,("%s: failed to parse NTLMv2_RESPONSE of length %zu for "
572                                  "user=[%s] domain=[%s] workstation=[%s] - %s %s\n",
573                                  __func__, ntlmssp_state->nt_resp.length,
574                                  ntlmssp_state->user, ntlmssp_state->domain,
575                                  ntlmssp_state->client.netbios_name,
576                                  ndr_errstr(err), nt_errstr(nt_status)));
577                         return nt_status;
578                 }
579
580                 if (DEBUGLVL(10)) {
581                         NDR_PRINT_DEBUG(NTLMv2_RESPONSE, &v2_resp);
582                 }
583
584                 eol = ndr_ntlmssp_find_av(&v2_resp.Challenge.AvPairs,
585                                           MsvAvEOL);
586                 if (eol == NULL) {
587                         DEBUG(1,("%s: missing MsvAvEOL for "
588                                  "user=[%s] domain=[%s] workstation=[%s]\n",
589                                  __func__, ntlmssp_state->user, ntlmssp_state->domain,
590                                  ntlmssp_state->client.netbios_name));
591                         return NT_STATUS_INVALID_PARAMETER;
592                 }
593
594                 flags = ndr_ntlmssp_find_av(&v2_resp.Challenge.AvPairs,
595                                             MsvAvFlags);
596                 if (flags != NULL) {
597                         av_flags = flags->Value.AvFlags;
598                 }
599
600                 if (av_flags & NTLMSSP_AVFLAG_MIC_IN_AUTHENTICATE_MESSAGE) {
601                         if (mic_blob.length != NTLMSSP_MIC_SIZE) {
602                                 DEBUG(1,("%s: mic_blob.length[%u] for "
603                                          "user=[%s] domain=[%s] workstation=[%s]\n",
604                                          __func__,
605                                          (unsigned)mic_blob.length,
606                                          ntlmssp_state->user,
607                                          ntlmssp_state->domain,
608                                          ntlmssp_state->client.netbios_name));
609                                 return NT_STATUS_INVALID_PARAMETER;
610                         }
611
612                         if (request.length <
613                             (NTLMSSP_MIC_OFFSET + NTLMSSP_MIC_SIZE))
614                         {
615                                 DEBUG(1,("%s: missing MIC "
616                                          "request.length[%u] for "
617                                          "user=[%s] domain=[%s] workstation=[%s]\n",
618                                          __func__,
619                                          (unsigned)request.length,
620                                          ntlmssp_state->user,
621                                          ntlmssp_state->domain,
622                                          ntlmssp_state->client.netbios_name));
623                                 return NT_STATUS_INVALID_PARAMETER;
624                         }
625
626                         ntlmssp_state->new_spnego = true;
627                 }
628
629                 count = ntlmssp_state->server.av_pair_list.count;
630                 if (v2_resp.Challenge.AvPairs.count < count) {
631                         return NT_STATUS_INVALID_PARAMETER;
632                 }
633
634                 for (i = 0; i < count; i++) {
635                         const struct AV_PAIR *sp =
636                                 &ntlmssp_state->server.av_pair_list.pair[i];
637                         const struct AV_PAIR *cp = NULL;
638
639                         if (sp->AvId == MsvAvEOL) {
640                                 continue;
641                         }
642
643                         cp = ndr_ntlmssp_find_av(&v2_resp.Challenge.AvPairs,
644                                                  sp->AvId);
645                         if (cp == NULL) {
646                                 DEBUG(1,("%s: AvId 0x%x missing for"
647                                          "user=[%s] domain=[%s] "
648                                          "workstation=[%s]\n",
649                                          __func__,
650                                          (unsigned)sp->AvId,
651                                          ntlmssp_state->user,
652                                          ntlmssp_state->domain,
653                                          ntlmssp_state->client.netbios_name));
654                                 return NT_STATUS_INVALID_PARAMETER;
655                         }
656
657                         switch (cp->AvId) {
658 #define CASE_STRING(v) case Msv ## v: do { \
659         int cmp; \
660         if (sp->Value.v == NULL) { \
661                 return NT_STATUS_INTERNAL_ERROR; \
662         } \
663         if (cp->Value.v == NULL) { \
664                 DEBUG(1,("%s: invalid %s " \
665                          "got[%s] expect[%s] for " \
666                          "user=[%s] domain=[%s] workstation=[%s]\n", \
667                          __func__, #v, \
668                          cp->Value.v, \
669                          sp->Value.v, \
670                          ntlmssp_state->user, \
671                          ntlmssp_state->domain, \
672                          ntlmssp_state->client.netbios_name)); \
673                 return NT_STATUS_INVALID_PARAMETER; \
674         } \
675         cmp = strcmp(cp->Value.v, sp->Value.v); \
676         if (cmp != 0) { \
677                 DEBUG(1,("%s: invalid %s " \
678                          "got[%s] expect[%s] for " \
679                          "user=[%s] domain=[%s] workstation=[%s]\n", \
680                          __func__, #v, \
681                          cp->Value.v, \
682                          sp->Value.v, \
683                          ntlmssp_state->user, \
684                          ntlmssp_state->domain, \
685                          ntlmssp_state->client.netbios_name)); \
686                 return NT_STATUS_INVALID_PARAMETER; \
687         } \
688 } while(0); break
689                         CASE_STRING(AvNbComputerName);
690                         CASE_STRING(AvNbDomainName);
691                         CASE_STRING(AvDnsComputerName);
692                         CASE_STRING(AvDnsDomainName);
693                         CASE_STRING(AvDnsTreeName);
694                         case MsvAvTimestamp:
695                                 if (cp->Value.AvTimestamp != sp->Value.AvTimestamp) {
696                                         struct timeval ct;
697                                         struct timeval st;
698                                         struct timeval_buf tmp1;
699                                         struct timeval_buf tmp2;
700
701                                         nttime_to_timeval(&ct,
702                                                           cp->Value.AvTimestamp);
703                                         nttime_to_timeval(&st,
704                                                           sp->Value.AvTimestamp);
705
706                                         DEBUG(1,("%s: invalid AvTimestamp "
707                                                  "got[%s] expect[%s] for "
708                                                  "user=[%s] domain=[%s] "
709                                                  "workstation=[%s]\n",
710                                                  __func__,
711                                                  timeval_str_buf(&ct, false,
712                                                                  true, &tmp1),
713                                                  timeval_str_buf(&st, false,
714                                                                  true, &tmp2),
715                                                  ntlmssp_state->user,
716                                                  ntlmssp_state->domain,
717                                                  ntlmssp_state->client.netbios_name));
718                                         return NT_STATUS_INVALID_PARAMETER;
719                                 }
720                                 break;
721                         default:
722                                 /*
723                                  * This can't happen as we control
724                                  * ntlmssp_state->server.av_pair_list
725                                  */
726                                 return NT_STATUS_INTERNAL_ERROR;
727                         }
728                 }
729         }
730
731         nttime_to_timeval(&endtime, ntlmssp_state->server.challenge_endtime);
732         expired = timeval_expired(&endtime);
733         if (expired) {
734                 struct timeval_buf tmp;
735                 DEBUG(1,("%s: challenge invalid (expired %s) for "
736                          "user=[%s] domain=[%s] workstation=[%s]\n",
737                          __func__,
738                          timeval_str_buf(&endtime, false, true, &tmp),
739                          ntlmssp_state->user, ntlmssp_state->domain,
740                          ntlmssp_state->client.netbios_name));
741                 return NT_STATUS_INVALID_PARAMETER;
742         }
743
744         /* NTLM2 uses a 'challenge' that is made of up both the server challenge, and a
745            client challenge
746
747            However, the NTLM2 flag may still be set for the real NTLMv2 logins, be careful.
748         */
749         if (ntlmssp_state->neg_flags & NTLMSSP_NEGOTIATE_NTLM2) {
750                 if (ntlmssp_state->nt_resp.length == 24 && ntlmssp_state->lm_resp.length == 24) {
751                         MD5_CTX md5_session_nonce_ctx;
752                         state->doing_ntlm2 = true;
753
754                         memcpy(state->session_nonce, ntlmssp_state->internal_chal.data, 8);
755                         memcpy(&state->session_nonce[8], ntlmssp_state->lm_resp.data, 8);
756
757                         SMB_ASSERT(ntlmssp_state->internal_chal.data && ntlmssp_state->internal_chal.length == 8);
758
759                         MD5Init(&md5_session_nonce_ctx);
760                         MD5Update(&md5_session_nonce_ctx, state->session_nonce, 16);
761                         MD5Final(session_nonce_hash, &md5_session_nonce_ctx);
762
763                         /* LM response is no longer useful */
764                         data_blob_free(&ntlmssp_state->lm_resp);
765
766                         /* We changed the effective challenge - set it */
767                         if (auth_context->set_ntlm_challenge) {
768                                 nt_status = auth_context->set_ntlm_challenge(auth_context,
769                                                                              session_nonce_hash,
770                                                                              "NTLMSSP callback (NTLM2)");
771                                 if (!NT_STATUS_IS_OK(nt_status)) {
772                                         DEBUG(1, ("gensec_ntlmssp_server_negotiate: failed to get challenge: %s\n",
773                                                   nt_errstr(nt_status)));
774                                         return nt_status;
775                                 }
776                         } else {
777                                 DEBUG(1, ("gensec_ntlmssp_server_negotiate: backend doesn't have facility for challenge to be set\n"));
778
779                                 return NT_STATUS_NOT_IMPLEMENTED;
780                         }
781
782                         /* LM Key is incompatible. */
783                         ntlmssp_state->neg_flags &= ~NTLMSSP_NEGOTIATE_LM_KEY;
784                 }
785         }
786
787         user_info = talloc_zero(state, struct auth_usersupplied_info);
788         if (!user_info) {
789                 return NT_STATUS_NO_MEMORY;
790         }
791
792         user_info->logon_parameters = MSV1_0_ALLOW_SERVER_TRUST_ACCOUNT | MSV1_0_ALLOW_WORKSTATION_TRUST_ACCOUNT;
793         user_info->flags = 0;
794         user_info->mapped_state = false;
795         user_info->client.account_name = ntlmssp_state->user;
796         user_info->client.domain_name = ntlmssp_state->domain;
797         user_info->workstation_name = ntlmssp_state->client.netbios_name;
798         user_info->remote_host = gensec_get_remote_address(gensec_security);
799         user_info->local_host = gensec_get_local_address(gensec_security);
800         user_info->service_description
801                 = gensec_get_target_service_description(gensec_security);
802
803         /*
804          * This will just be the string "NTLMSSP" from
805          * gensec_ntlmssp_final_auth_type, but ensures it stays in sync
806          * with the same use in the authorization logging triggered by
807          * gensec_session_info() later
808          */
809         user_info->auth_description = gensec_final_auth_type(gensec_security);
810
811         user_info->password_state = AUTH_PASSWORD_RESPONSE;
812         user_info->password.response.lanman = ntlmssp_state->lm_resp;
813         user_info->password.response.nt = ntlmssp_state->nt_resp;
814
815         state->user_info = user_info;
816         return NT_STATUS_OK;
817 }
818
819 static void ntlmssp_server_auth_done(struct tevent_req *subreq)
820 {
821         struct tevent_req *req =
822                 tevent_req_callback_data(subreq,
823                 struct tevent_req);
824         struct ntlmssp_server_auth_state *state =
825                 tevent_req_data(req,
826                 struct ntlmssp_server_auth_state);
827         struct gensec_security *gensec_security = state->gensec_security;
828         struct gensec_ntlmssp_context *gensec_ntlmssp = state->gensec_ntlmssp;
829         struct auth4_context *auth_context = gensec_security->auth_context;
830         uint8_t authoritative = 0;
831         NTSTATUS status;
832
833         status = auth_context->check_ntlm_password_recv(subreq,
834                                                 gensec_ntlmssp,
835                                                 &authoritative,
836                                                 &gensec_ntlmssp->server_returned_info,
837                                                 &state->user_session_key,
838                                                 &state->lm_session_key);
839         TALLOC_FREE(subreq);
840         if (!NT_STATUS_IS_OK(status)) {
841                 DBG_INFO("Checking NTLMSSP password for %s\\%s failed: %s\n",
842                          state->user_info->client.domain_name,
843                          state->user_info->client.account_name,
844                          nt_errstr(status));
845         }
846         if (tevent_req_nterror(req, status)) {
847                 return;
848         }
849         talloc_steal(state, state->user_session_key.data);
850         talloc_steal(state, state->lm_session_key.data);
851
852         status = ntlmssp_server_postauth(state->gensec_security,
853                                          state->gensec_ntlmssp,
854                                          state, state->in);
855         if (tevent_req_nterror(req, status)) {
856                 return;
857         }
858
859         tevent_req_done(req);
860 }
861
862 /**
863  * Next state function for the Authenticate packet
864  * (after authentication - figures out the session keys etc)
865  *
866  * @param ntlmssp_state NTLMSSP State
867  * @return Errors or NT_STATUS_OK.
868  */
869
870 static NTSTATUS ntlmssp_server_postauth(struct gensec_security *gensec_security,
871                                         struct gensec_ntlmssp_context *gensec_ntlmssp,
872                                         struct ntlmssp_server_auth_state *state,
873                                         DATA_BLOB request)
874 {
875         struct ntlmssp_state *ntlmssp_state = gensec_ntlmssp->ntlmssp_state;
876         struct auth4_context *auth_context = gensec_security->auth_context;
877         DATA_BLOB user_session_key = state->user_session_key;
878         DATA_BLOB lm_session_key = state->lm_session_key;
879         NTSTATUS nt_status = NT_STATUS_OK;
880         DATA_BLOB session_key = data_blob(NULL, 0);
881         struct auth_session_info *session_info = NULL;
882
883         TALLOC_FREE(state->user_info);
884
885         if (lpcfg_map_to_guest(gensec_security->settings->lp_ctx) != NEVER_MAP_TO_GUEST
886             && auth_context->generate_session_info != NULL)
887         {
888                 NTSTATUS tmp_status;
889
890                 /*
891                  * We need to check if the auth is anonymous or mapped to guest
892                  */
893                 tmp_status = auth_context->generate_session_info(auth_context, state,
894                                                                  gensec_ntlmssp->server_returned_info,
895                                                                  gensec_ntlmssp->ntlmssp_state->user,
896                                                                  AUTH_SESSION_INFO_SIMPLE_PRIVILEGES,
897                                                                  &session_info);
898                 if (!NT_STATUS_IS_OK(tmp_status)) {
899                         /*
900                          * We don't care about failures,
901                          * the worst result is that we try MIC checking
902                          * for a map to guest authentication.
903                          */
904                         TALLOC_FREE(session_info);
905                 }
906         }
907
908         if (session_info != NULL) {
909                 if (security_session_user_level(session_info, NULL) < SECURITY_USER) {
910                         /*
911                          * Anonymous and GUEST are not secure anyway.
912                          * avoid new_spnego and MIC checking.
913                          */
914                         ntlmssp_state->new_spnego = false;
915                         ntlmssp_state->neg_flags &= ~NTLMSSP_NEGOTIATE_SIGN;
916                         ntlmssp_state->neg_flags &= ~NTLMSSP_NEGOTIATE_SEAL;
917                 }
918                 TALLOC_FREE(session_info);
919         }
920
921         dump_data_pw("NT session key:\n", user_session_key.data, user_session_key.length);
922         dump_data_pw("LM first-8:\n", lm_session_key.data, lm_session_key.length);
923
924         /* Handle the different session key derivation for NTLM2 */
925         if (state->doing_ntlm2) {
926                 if (user_session_key.data && user_session_key.length == 16) {
927                         session_key = data_blob_talloc(ntlmssp_state,
928                                                        NULL, 16);
929                         hmac_md5(user_session_key.data, state->session_nonce,
930                                  sizeof(state->session_nonce), session_key.data);
931                         DEBUG(10,("ntlmssp_server_auth: Created NTLM2 session key.\n"));
932                         dump_data_pw("NTLM2 session key:\n", session_key.data, session_key.length);
933
934                 } else {
935                         DEBUG(10,("ntlmssp_server_auth: Failed to create NTLM2 session key.\n"));
936                         session_key = data_blob_null;
937                 }
938         } else if ((ntlmssp_state->neg_flags & NTLMSSP_NEGOTIATE_LM_KEY)
939                 /* Ensure we can never get here on NTLMv2 */
940                 && (ntlmssp_state->nt_resp.length == 0 || ntlmssp_state->nt_resp.length == 24)) {
941
942                 if (lm_session_key.data && lm_session_key.length >= 8) {
943                         if (ntlmssp_state->lm_resp.data && ntlmssp_state->lm_resp.length == 24) {
944                                 session_key = data_blob_talloc(ntlmssp_state,
945                                                                NULL, 16);
946                                 if (session_key.data == NULL) {
947                                         return NT_STATUS_NO_MEMORY;
948                                 }
949                                 SMBsesskeygen_lm_sess_key(lm_session_key.data, ntlmssp_state->lm_resp.data,
950                                                           session_key.data);
951                                 DEBUG(10,("ntlmssp_server_auth: Created NTLM session key.\n"));
952                         } else {
953                                 static const uint8_t zeros[24] = {0, };
954                                 session_key = data_blob_talloc(
955                                         ntlmssp_state, NULL, 16);
956                                 if (session_key.data == NULL) {
957                                         return NT_STATUS_NO_MEMORY;
958                                 }
959                                 SMBsesskeygen_lm_sess_key(zeros, zeros,
960                                                           session_key.data);
961                                 DEBUG(10,("ntlmssp_server_auth: Created NTLM session key.\n"));
962                         }
963                         dump_data_pw("LM session key:\n", session_key.data,
964                                      session_key.length);
965                 } else {
966                         /* LM Key not selected */
967                         ntlmssp_state->neg_flags &= ~NTLMSSP_NEGOTIATE_LM_KEY;
968
969                         DEBUG(10,("ntlmssp_server_auth: Failed to create NTLM session key.\n"));
970                         session_key = data_blob_null;
971                 }
972
973         } else if (user_session_key.data) {
974                 session_key = user_session_key;
975                 DEBUG(10,("ntlmssp_server_auth: Using unmodified nt session key.\n"));
976                 dump_data_pw("unmodified session key:\n", session_key.data, session_key.length);
977
978                 /* LM Key not selected */
979                 ntlmssp_state->neg_flags &= ~NTLMSSP_NEGOTIATE_LM_KEY;
980
981         } else if (lm_session_key.data) {
982                 /* Very weird to have LM key, but no user session key, but anyway.. */
983                 session_key = lm_session_key;
984                 DEBUG(10,("ntlmssp_server_auth: Using unmodified lm session key.\n"));
985                 dump_data_pw("unmodified session key:\n", session_key.data, session_key.length);
986
987                 /* LM Key not selected */
988                 ntlmssp_state->neg_flags &= ~NTLMSSP_NEGOTIATE_LM_KEY;
989
990         } else {
991                 DEBUG(10,("ntlmssp_server_auth: Failed to create unmodified session key.\n"));
992                 session_key = data_blob_null;
993
994                 /* LM Key not selected */
995                 ntlmssp_state->neg_flags &= ~NTLMSSP_NEGOTIATE_LM_KEY;
996         }
997
998         /* With KEY_EXCH, the client supplies the proposed session key,
999            but encrypts it with the long-term key */
1000         if (ntlmssp_state->neg_flags & NTLMSSP_NEGOTIATE_KEY_EXCH) {
1001                 if (!state->encrypted_session_key.data
1002                     || state->encrypted_session_key.length != 16) {
1003                         DEBUG(1, ("Client-supplied KEY_EXCH session key was of invalid length (%u)!\n",
1004                                   (unsigned)state->encrypted_session_key.length));
1005                         return NT_STATUS_INVALID_PARAMETER;
1006                 } else if (!session_key.data || session_key.length != 16) {
1007                         DEBUG(5, ("server session key is invalid (len == %u), cannot do KEY_EXCH!\n",
1008                                   (unsigned int)session_key.length));
1009                         ntlmssp_state->session_key = session_key;
1010                         talloc_steal(ntlmssp_state, session_key.data);
1011                 } else {
1012                         dump_data_pw("KEY_EXCH session key (enc):\n",
1013                                      state->encrypted_session_key.data,
1014                                      state->encrypted_session_key.length);
1015                         arcfour_crypt(state->encrypted_session_key.data,
1016                                       session_key.data,
1017                                       state->encrypted_session_key.length);
1018                         ntlmssp_state->session_key = data_blob_talloc(ntlmssp_state,
1019                                                                       state->encrypted_session_key.data,
1020                                                                       state->encrypted_session_key.length);
1021                         dump_data_pw("KEY_EXCH session key:\n",
1022                                      state->encrypted_session_key.data,
1023                                      state->encrypted_session_key.length);
1024                 }
1025         } else {
1026                 ntlmssp_state->session_key = session_key;
1027                 talloc_steal(ntlmssp_state, session_key.data);
1028         }
1029
1030         if (ntlmssp_state->new_spnego) {
1031                 HMACMD5Context ctx;
1032                 uint8_t mic_buffer[NTLMSSP_MIC_SIZE] = { 0, };
1033                 int cmp;
1034
1035                 hmac_md5_init_limK_to_64(ntlmssp_state->session_key.data,
1036                                          ntlmssp_state->session_key.length,
1037                                          &ctx);
1038
1039                 hmac_md5_update(ntlmssp_state->negotiate_blob.data,
1040                                 ntlmssp_state->negotiate_blob.length,
1041                                 &ctx);
1042                 hmac_md5_update(ntlmssp_state->challenge_blob.data,
1043                                 ntlmssp_state->challenge_blob.length,
1044                                 &ctx);
1045
1046                 /* checked were we set ntlmssp_state->new_spnego */
1047                 SMB_ASSERT(request.length >
1048                            (NTLMSSP_MIC_OFFSET + NTLMSSP_MIC_SIZE));
1049
1050                 hmac_md5_update(request.data, NTLMSSP_MIC_OFFSET, &ctx);
1051                 hmac_md5_update(mic_buffer, NTLMSSP_MIC_SIZE, &ctx);
1052                 hmac_md5_update(request.data +
1053                                 (NTLMSSP_MIC_OFFSET + NTLMSSP_MIC_SIZE),
1054                                 request.length -
1055                                 (NTLMSSP_MIC_OFFSET + NTLMSSP_MIC_SIZE),
1056                                 &ctx);
1057                 hmac_md5_final(mic_buffer, &ctx);
1058
1059                 cmp = memcmp(request.data + NTLMSSP_MIC_OFFSET,
1060                              mic_buffer, NTLMSSP_MIC_SIZE);
1061                 if (cmp != 0) {
1062                         DEBUG(1,("%s: invalid NTLMSSP_MIC for "
1063                                  "user=[%s] domain=[%s] workstation=[%s]\n",
1064                                  __func__,
1065                                  ntlmssp_state->user,
1066                                  ntlmssp_state->domain,
1067                                  ntlmssp_state->client.netbios_name));
1068                         dump_data(1, request.data + NTLMSSP_MIC_OFFSET,
1069                                   NTLMSSP_MIC_SIZE);
1070                         dump_data(1, mic_buffer,
1071                                   NTLMSSP_MIC_SIZE);
1072                         return NT_STATUS_INVALID_PARAMETER;
1073                 }
1074         }
1075
1076         data_blob_free(&ntlmssp_state->negotiate_blob);
1077         data_blob_free(&ntlmssp_state->challenge_blob);
1078
1079         if (gensec_ntlmssp_have_feature(gensec_security, GENSEC_FEATURE_SIGN)) {
1080                 nt_status = ntlmssp_sign_init(ntlmssp_state);
1081         }
1082
1083         data_blob_clear_free(&ntlmssp_state->internal_chal);
1084         data_blob_clear_free(&ntlmssp_state->chal);
1085         data_blob_clear_free(&ntlmssp_state->lm_resp);
1086         data_blob_clear_free(&ntlmssp_state->nt_resp);
1087
1088         ntlmssp_state->expected_state = NTLMSSP_DONE;
1089
1090         return nt_status;
1091 }
1092
1093 NTSTATUS ntlmssp_server_auth_recv(struct tevent_req *req,
1094                                   TALLOC_CTX *out_mem_ctx,
1095                                   DATA_BLOB *out)
1096 {
1097         NTSTATUS status;
1098
1099         *out = data_blob_null;
1100
1101         if (tevent_req_is_nterror(req, &status)) {
1102                 tevent_req_received(req);
1103                 return status;
1104         }
1105
1106         tevent_req_received(req);
1107         return NT_STATUS_OK;
1108 }