lib: Make callers of base64_encode_data_blob check for success
[samba.git] / source4 / utils / ntlm_auth.c
1 /* 
2    Unix SMB/CIFS implementation.
3
4    Winbind status program.
5
6    Copyright (C) Tim Potter      2000-2003
7    Copyright (C) Andrew Bartlett <abartlet@samba.org> 2003-2004
8    Copyright (C) Francesco Chemolli <kinkie@kame.usr.dsi.unimi.it> 2000 
9
10    This program is free software; you can redistribute it and/or modify
11    it under the terms of the GNU General Public License as published by
12    the Free Software Foundation; either version 3 of the License, or
13    (at your option) any later version.
14    
15    This program is distributed in the hope that it will be useful,
16    but WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18    GNU General Public License for more details.
19    
20    You should have received a copy of the GNU General Public License
21    along with this program.  If not, see <http://www.gnu.org/licenses/>.
22 */
23
24 #include "includes.h"
25 #include "system/filesys.h"
26 #include "lib/cmdline/popt_common.h"
27 #include <ldb.h>
28 #include "auth/credentials/credentials.h"
29 #include "auth/gensec/gensec.h"
30 #include "auth/gensec/gensec_internal.h" /* TODO: remove this */
31 #include "auth/auth.h"
32 #include "librpc/gen_ndr/ndr_netlogon.h"
33 #include "auth/auth_sam.h"
34 #include "libcli/auth/libcli_auth.h"
35 #include "libcli/security/security.h"
36 #include "lib/events/events.h"
37 #include "lib/messaging/messaging.h"
38 #include "lib/messaging/irpc.h"
39 #include "auth/ntlmssp/ntlmssp.h"
40 #include "param/param.h"
41
42 #define INITIAL_BUFFER_SIZE 300
43 #define MAX_BUFFER_SIZE 63000
44
45 enum stdio_helper_mode {
46         SQUID_2_4_BASIC,
47         SQUID_2_5_BASIC,
48         SQUID_2_5_NTLMSSP,
49         NTLMSSP_CLIENT_1,
50         GSS_SPNEGO_CLIENT,
51         GSS_SPNEGO_SERVER,
52         NTLM_SERVER_1,
53         NUM_HELPER_MODES
54 };
55
56 #define NTLM_AUTH_FLAG_USER_SESSION_KEY     0x0004
57 #define NTLM_AUTH_FLAG_LMKEY                0x0008
58
59
60 typedef void (*stdio_helper_function)(enum stdio_helper_mode stdio_helper_mode, 
61                                       struct loadparm_context *lp_ctx,
62                                       char *buf, int length, void **private1,
63                                       unsigned int mux_id, void **private2);
64
65 static void manage_squid_basic_request (enum stdio_helper_mode stdio_helper_mode, 
66                                         struct loadparm_context *lp_ctx,
67                                         char *buf, int length, void **private1,
68                                         unsigned int mux_id, void **private2);
69
70 static void manage_gensec_request (enum stdio_helper_mode stdio_helper_mode, 
71                                    struct loadparm_context *lp_ctx,
72                                    char *buf, int length, void **private1,
73                                    unsigned int mux_id, void **private2);
74
75 static void manage_ntlm_server_1_request (enum stdio_helper_mode stdio_helper_mode, 
76                                           struct loadparm_context *lp_ctx,
77                                           char *buf, int length, void **private1,
78                                           unsigned int mux_id, void **private2);
79
80 static void manage_squid_request(struct loadparm_context *lp_ctx,
81                                  enum stdio_helper_mode helper_mode, 
82                                  stdio_helper_function fn, void **private2);
83
84 static const struct {
85         enum stdio_helper_mode mode;
86         const char *name;
87         stdio_helper_function fn;
88 } stdio_helper_protocols[] = {
89         { SQUID_2_4_BASIC, "squid-2.4-basic", manage_squid_basic_request},
90         { SQUID_2_5_BASIC, "squid-2.5-basic", manage_squid_basic_request},
91         { SQUID_2_5_NTLMSSP, "squid-2.5-ntlmssp", manage_gensec_request},
92         { GSS_SPNEGO_CLIENT, "gss-spnego-client", manage_gensec_request},
93         { GSS_SPNEGO_SERVER, "gss-spnego", manage_gensec_request},
94         { NTLMSSP_CLIENT_1, "ntlmssp-client-1", manage_gensec_request},
95         { NTLM_SERVER_1, "ntlm-server-1", manage_ntlm_server_1_request},
96         { NUM_HELPER_MODES, NULL, NULL}
97 };
98
99 extern int winbindd_fd;
100
101 static const char *opt_username;
102 static const char *opt_domain;
103 static const char *opt_workstation;
104 static const char *opt_password;
105 static int opt_multiplex;
106 static int use_cached_creds;
107 static int opt_allow_mschapv2;
108
109
110 static void mux_printf(unsigned int mux_id, const char *format, ...) PRINTF_ATTRIBUTE(2, 3);
111
112 static void mux_printf(unsigned int mux_id, const char *format, ...)
113 {
114         va_list ap;
115
116         if (opt_multiplex) {
117                 x_fprintf(x_stdout, "%d ", mux_id);
118         }
119
120         va_start(ap, format);
121         x_vfprintf(x_stdout, format, ap);
122         va_end(ap);
123 }
124
125
126
127 /* Copy of parse_domain_user from winbindd_util.c.  Parse a string of the
128    form DOMAIN/user into a domain and a user */
129
130 static bool parse_ntlm_auth_domain_user(const char *domuser, char **domain, 
131                                                                                 char **user, char winbind_separator)
132 {
133
134         char *p = strchr(domuser, winbind_separator);
135
136         if (!p) {
137                 return false;
138         }
139         
140         *user = smb_xstrdup(p+1);
141         *domain = smb_xstrdup(domuser);
142         (*domain)[PTR_DIFF(p, domuser)] = 0;
143
144         return true;
145 }
146
147
148 /* Authenticate a user with a plaintext password */
149
150 static bool check_plaintext_auth(const char *user, const char *pass, 
151                                  bool stdout_diagnostics)
152 {
153         return (strcmp(pass, opt_password) == 0);
154 }
155
156 /* authenticate a user with an encrypted username/password */
157
158 static NTSTATUS local_pw_check_specified(struct loadparm_context *lp_ctx,
159                                          const char *username, 
160                                          const char *domain, 
161                                          const char *workstation,
162                                          const DATA_BLOB *challenge, 
163                                          const DATA_BLOB *lm_response, 
164                                          const DATA_BLOB *nt_response, 
165                                          uint32_t flags, 
166                                          DATA_BLOB *lm_session_key, 
167                                          DATA_BLOB *user_session_key, 
168                                          char **error_string, 
169                                          char **unix_name) 
170 {
171         NTSTATUS nt_status;
172         struct samr_Password lm_pw, nt_pw;
173         struct samr_Password *lm_pwd, *nt_pwd;
174         TALLOC_CTX *mem_ctx = talloc_init("local_pw_check_specified");
175         if (!mem_ctx) {
176                 nt_status = NT_STATUS_NO_MEMORY;
177         } else {
178                 uint32_t logon_parameters = 0;
179                 
180                 E_md4hash(opt_password, nt_pw.hash);
181                 if (E_deshash(opt_password, lm_pw.hash)) {
182                         lm_pwd = &lm_pw;
183                 } else {
184                         lm_pwd = NULL;
185                 }
186                 nt_pwd = &nt_pw;
187                 
188                 if (opt_allow_mschapv2) {
189                         logon_parameters |= MSV1_0_ALLOW_MSVCHAPV2;
190                 }
191                 
192                 nt_status = ntlm_password_check(mem_ctx, 
193                                                 lpcfg_lanman_auth(lp_ctx),
194                                                 lpcfg_ntlm_auth(lp_ctx),
195                                                 logon_parameters |
196                                                 MSV1_0_ALLOW_SERVER_TRUST_ACCOUNT |
197                                                 MSV1_0_ALLOW_WORKSTATION_TRUST_ACCOUNT,
198                                                 challenge,
199                                                 lm_response,
200                                                 nt_response,
201                                                 username,
202                                                 username,
203                                                 domain,
204                                                 lm_pwd, nt_pwd, user_session_key, lm_session_key);
205                 
206                 if (NT_STATUS_IS_OK(nt_status)) {
207                         if (unix_name) {
208                                 if (asprintf(unix_name, "%s%c%s", domain,
209                                              *lpcfg_winbind_separator(lp_ctx),
210                                              username) < 0) {
211                                         nt_status = NT_STATUS_NO_MEMORY;
212                                 }
213                         }
214                 } else {
215                         DEBUG(3, ("Login for user [%s]\\[%s]@[%s] failed due to [%s]\n", 
216                                   domain, username, workstation, 
217                                   nt_errstr(nt_status)));
218                 }
219                 talloc_free(mem_ctx);
220         }
221         if (error_string) {
222                 *error_string = strdup(nt_errstr(nt_status));
223         }
224         return nt_status;
225         
226         
227 }
228
229 static void manage_squid_basic_request(enum stdio_helper_mode stdio_helper_mode, 
230                                        struct loadparm_context *lp_ctx,
231                                        char *buf, int length, void **private1,
232                                        unsigned int mux_id, void **private2) 
233 {
234         char *user, *pass;      
235         user=buf;
236         
237         pass = memchr(buf, ' ', length);
238         if (!pass) {
239                 DEBUG(2, ("Password not found. Denying access\n"));
240                 mux_printf(mux_id, "ERR\n");
241                 return;
242         }
243         *pass='\0';
244         pass++;
245         
246         if (stdio_helper_mode == SQUID_2_5_BASIC) {
247                 rfc1738_unescape(user);
248                 rfc1738_unescape(pass);
249         }
250         
251         if (check_plaintext_auth(user, pass, false)) {
252                 mux_printf(mux_id, "OK\n");
253         } else {
254                 mux_printf(mux_id, "ERR\n");
255         }
256 }
257
258 /* This is a bit hairy, but the basic idea is to do a password callback
259    to the calling application.  The callback comes from within gensec */
260
261 static void manage_gensec_get_pw_request(enum stdio_helper_mode stdio_helper_mode, 
262                                          struct loadparm_context *lp_ctx,
263                                          char *buf, int length, void **private1,
264                                          unsigned int mux_id, void **password)  
265 {
266         DATA_BLOB in;
267         if (strlen(buf) < 2) {
268                 DEBUG(1, ("query [%s] invalid", buf));
269                 mux_printf(mux_id, "BH Query invalid\n");
270                 return;
271         }
272
273         if (strlen(buf) > 3) {
274                 in = base64_decode_data_blob(buf + 3);
275         } else {
276                 in = data_blob(NULL, 0);
277         }
278
279         if (strncmp(buf, "PW ", 3) == 0) {
280
281                 *password = talloc_strndup(*private1 /* hopefully the right gensec context, useful to use for talloc */,
282                                            (const char *)in.data, in.length);
283                 
284                 if (*password == NULL) {
285                         DEBUG(1, ("Out of memory\n"));
286                         mux_printf(mux_id, "BH Out of memory\n");
287                         data_blob_free(&in);
288                         return;
289                 }
290
291                 mux_printf(mux_id, "OK\n");
292                 data_blob_free(&in);
293                 return;
294         }
295         DEBUG(1, ("Asked for (and expected) a password\n"));
296         mux_printf(mux_id, "BH Expected a password\n");
297         data_blob_free(&in);
298 }
299
300 /** 
301  * Callback for password credentials.  This is not async, and when
302  * GENSEC and the credentials code is made async, it will look rather
303  * different.
304  */
305
306 static const char *get_password(struct cli_credentials *credentials) 
307 {
308         char *password = NULL;
309         void *cb = cli_credentials_callback_data_void(credentials);
310
311         /* Ask for a password */
312         mux_printf((unsigned int)(uintptr_t)cb, "PW\n");
313         cli_credentials_set_callback_data(credentials, NULL);
314
315         manage_squid_request(cmdline_lp_ctx, NUM_HELPER_MODES /* bogus */, manage_gensec_get_pw_request, (void **)&password);
316         return password;
317 }
318
319 /**
320  Check if a string is part of a list.
321 **/
322 static bool in_list(const char *s, const char *list, bool casesensitive)
323 {
324         char *tok;
325         size_t tok_len = 1024;
326         const char *p=list;
327
328         if (!list)
329                 return false;
330
331         tok = (char *)malloc(tok_len);
332         if (!tok) {
333                 return false;
334         }
335
336         while (next_token(&p, tok, LIST_SEP, tok_len)) {
337                 if ((casesensitive?strcmp:strcasecmp_m)(tok,s) == 0) {
338                         free(tok);
339                         return true;
340                 }
341         }
342         free(tok);
343         return false;
344 }
345
346 static void gensec_want_feature_list(struct gensec_security *state, char* feature_list)
347 {
348         if (in_list("NTLMSSP_FEATURE_SESSION_KEY", feature_list, true)) {
349                 DEBUG(10, ("want GENSEC_FEATURE_SESSION_KEY\n"));
350                 gensec_want_feature(state, GENSEC_FEATURE_SESSION_KEY);
351         }
352         if (in_list("NTLMSSP_FEATURE_SIGN", feature_list, true)) {
353                 DEBUG(10, ("want GENSEC_FEATURE_SIGN\n"));
354                 gensec_want_feature(state, GENSEC_FEATURE_SIGN);
355         }
356         if (in_list("NTLMSSP_FEATURE_SEAL", feature_list, true)) {
357                 DEBUG(10, ("want GENSEC_FEATURE_SEAL\n"));
358                 gensec_want_feature(state, GENSEC_FEATURE_SEAL);
359         }
360 }
361
362 static void manage_gensec_request(enum stdio_helper_mode stdio_helper_mode, 
363                                   struct loadparm_context *lp_ctx,
364                                   char *buf, int length, void **private1,
365                                   unsigned int mux_id, void **private2) 
366 {
367         DATA_BLOB in;
368         DATA_BLOB out = data_blob(NULL, 0);
369         char *out_base64 = NULL;
370         const char *reply_arg = NULL;
371         struct gensec_ntlm_state {
372                 struct gensec_security *gensec_state;
373                 const char *set_password;
374         };
375         struct gensec_ntlm_state *state;
376         struct tevent_context *ev;
377         struct imessaging_context *msg;
378
379         NTSTATUS nt_status;
380         bool first = false;
381         const char *reply_code;
382         struct cli_credentials *creds;
383
384         static char *want_feature_list = NULL;
385         static DATA_BLOB session_key;
386
387         TALLOC_CTX *mem_ctx;
388
389         if (*private1) {
390                 state = (struct gensec_ntlm_state *)*private1;
391         } else {
392                 state = talloc_zero(NULL, struct gensec_ntlm_state);
393                 if (!state) {
394                         mux_printf(mux_id, "BH No Memory\n");
395                         exit(1);
396                 }
397                 *private1 = state;
398                 if (opt_password) {
399                         state->set_password = opt_password;
400                 }
401         }
402         
403         if (strlen(buf) < 2) {
404                 DEBUG(1, ("query [%s] invalid", buf));
405                 mux_printf(mux_id, "BH Query invalid\n");
406                 return;
407         }
408
409         if (strlen(buf) > 3) {
410                 if(strncmp(buf, "SF ", 3) == 0) {
411                         DEBUG(10, ("Setting flags to negotiate\n"));
412                         talloc_free(want_feature_list);
413                         want_feature_list = talloc_strndup(state, buf+3, strlen(buf)-3);
414                         mux_printf(mux_id, "OK\n");
415                         return;
416                 }
417                 in = base64_decode_data_blob(buf + 3);
418         } else {
419                 in = data_blob(NULL, 0);
420         }
421
422         if (strncmp(buf, "YR", 2) == 0) {
423                 if (state->gensec_state) {
424                         talloc_free(state->gensec_state);
425                         state->gensec_state = NULL;
426                 }
427         } else if ( (strncmp(buf, "OK", 2) == 0)) {
428                 /* Just return BH, like ntlm_auth from Samba 3 does. */
429                 mux_printf(mux_id, "BH Command expected\n");
430                 data_blob_free(&in);
431                 return;
432         } else if ( (strncmp(buf, "TT ", 3) != 0) &&
433                     (strncmp(buf, "KK ", 3) != 0) &&
434                     (strncmp(buf, "AF ", 3) != 0) &&
435                     (strncmp(buf, "NA ", 3) != 0) && 
436                     (strncmp(buf, "UG", 2) != 0) && 
437                     (strncmp(buf, "PW ", 3) != 0) &&
438                     (strncmp(buf, "GK", 2) != 0) &&
439                     (strncmp(buf, "GF", 2) != 0)) {
440                 DEBUG(1, ("SPNEGO request [%s] invalid\n", buf));
441                 mux_printf(mux_id, "BH SPNEGO request invalid\n");
442                 data_blob_free(&in);
443                 return;
444         }
445
446         ev = s4_event_context_init(state);
447         if (!ev) {
448                 exit(1);
449         }
450
451         mem_ctx = talloc_named(NULL, 0, "manage_gensec_request internal mem_ctx");
452
453         /* setup gensec */
454         if (!(state->gensec_state)) {
455                 switch (stdio_helper_mode) {
456                 case GSS_SPNEGO_CLIENT:
457                 case NTLMSSP_CLIENT_1:
458                         /* setup the client side */
459
460                         nt_status = gensec_client_start(NULL, &state->gensec_state,
461                                                         lpcfg_gensec_settings(NULL, lp_ctx));
462                         if (!NT_STATUS_IS_OK(nt_status)) {
463                                 talloc_free(mem_ctx);
464                                 exit(1);
465                         }
466
467                         break;
468                 case GSS_SPNEGO_SERVER:
469                 case SQUID_2_5_NTLMSSP:
470                 {
471                         const char *winbind_method[] = { "winbind", NULL };
472                         struct auth4_context *auth_context;
473
474                         msg = imessaging_client_init(state, lp_ctx, ev);
475                         if (!msg) {
476                                 talloc_free(mem_ctx);
477                                 exit(1);
478                         }
479                         nt_status = auth_context_create_methods(mem_ctx, 
480                                                                 winbind_method,
481                                                                 ev, 
482                                                                 msg, 
483                                                                 lp_ctx,
484                                                                 NULL,
485                                                                 &auth_context);
486         
487                         if (!NT_STATUS_IS_OK(nt_status)) {
488                                 talloc_free(mem_ctx);
489                                 exit(1);
490                         }
491                         
492                         if (!NT_STATUS_IS_OK(gensec_server_start(state,
493                                                                  lpcfg_gensec_settings(state, lp_ctx),
494                                                                  auth_context, &state->gensec_state))) {
495                                 talloc_free(mem_ctx);
496                                 exit(1);
497                         }
498                         break;
499                 }
500                 default:
501                         talloc_free(mem_ctx);
502                         abort();
503                 }
504
505                 creds = cli_credentials_init(state->gensec_state);
506                 cli_credentials_set_conf(creds, lp_ctx);
507                 if (opt_username) {
508                         cli_credentials_set_username(creds, opt_username, CRED_SPECIFIED);
509                 }
510                 if (opt_domain) {
511                         cli_credentials_set_domain(creds, opt_domain, CRED_SPECIFIED);
512                 }
513                 if (state->set_password) {
514                         cli_credentials_set_password(creds, state->set_password, CRED_SPECIFIED);
515                 } else {
516                         void *cb = (void*)(uintptr_t)mux_id;
517                         cli_credentials_set_callback_data(creds, cb);
518                         cli_credentials_set_password_callback(creds, get_password);
519                 }
520                 if (opt_workstation) {
521                         cli_credentials_set_workstation(creds, opt_workstation, CRED_SPECIFIED);
522                 }
523                 
524                 switch (stdio_helper_mode) {
525                 case GSS_SPNEGO_SERVER:
526                 case SQUID_2_5_NTLMSSP:
527                         cli_credentials_set_machine_account(creds, lp_ctx);
528                         break;
529                 default:
530                         break;
531                 }
532
533                 gensec_set_credentials(state->gensec_state, creds);
534                 gensec_want_feature_list(state->gensec_state, want_feature_list);
535
536                 switch (stdio_helper_mode) {
537                 case GSS_SPNEGO_CLIENT:
538                 case GSS_SPNEGO_SERVER:
539                         nt_status = gensec_start_mech_by_oid(state->gensec_state, GENSEC_OID_SPNEGO);
540                         if (!in.length) {
541                                 first = true;
542                         }
543                         break;
544                 case NTLMSSP_CLIENT_1:
545                         if (!in.length) {
546                                 first = true;
547                         }
548                         /* fall through */
549                 case SQUID_2_5_NTLMSSP:
550                         nt_status = gensec_start_mech_by_oid(state->gensec_state, GENSEC_OID_NTLMSSP);
551                         break;
552                 default:
553                         talloc_free(mem_ctx);
554                         abort();
555                 }
556
557                 if (!NT_STATUS_IS_OK(nt_status)) {
558                         DEBUG(1, ("GENSEC mech failed to start: %s\n", nt_errstr(nt_status)));
559                         mux_printf(mux_id, "BH GENSEC mech failed to start\n");
560                         talloc_free(mem_ctx);
561                         return;
562                 }
563
564         }
565
566         /* update */
567
568         if (strncmp(buf, "PW ", 3) == 0) {
569                 state->set_password = talloc_strndup(state,
570                                                      (const char *)in.data, 
571                                                      in.length);
572                 
573                 cli_credentials_set_password(gensec_get_credentials(state->gensec_state),
574                                              state->set_password,
575                                              CRED_SPECIFIED);
576                 mux_printf(mux_id, "OK\n");
577                 data_blob_free(&in);
578                 talloc_free(mem_ctx);
579                 return;
580         }
581
582         if (strncmp(buf, "UG", 2) == 0) {
583                 int i;
584                 char *grouplist = NULL;
585                 struct auth_session_info *session_info;
586
587                 nt_status = gensec_session_info(state->gensec_state, mem_ctx, &session_info);
588                 if (!NT_STATUS_IS_OK(nt_status)) {
589                         DEBUG(1, ("gensec_session_info failed: %s\n", nt_errstr(nt_status)));
590                         mux_printf(mux_id, "BH %s\n", nt_errstr(nt_status));
591                         data_blob_free(&in);
592                         talloc_free(mem_ctx);
593                         return;
594                 }
595                 
596                 /* get the string onto the context */
597                 grouplist = talloc_strdup(mem_ctx, "");
598                 
599                 for (i=0; i<session_info->security_token->num_sids; i++) {
600                         struct security_token *token = session_info->security_token; 
601                         const char *sidstr = dom_sid_string(session_info, 
602                                                             &token->sids[i]);
603                         grouplist = talloc_asprintf_append_buffer(grouplist, "%s,", sidstr);
604                 }
605
606                 mux_printf(mux_id, "GL %s\n", grouplist);
607                 talloc_free(session_info);
608                 data_blob_free(&in);
609                 talloc_free(mem_ctx);
610                 return;
611         }
612
613         if (strncmp(buf, "GK", 2) == 0) {
614                 char *base64_key;
615                 DEBUG(10, ("Requested session key\n"));
616                 nt_status = gensec_session_key(state->gensec_state, mem_ctx, &session_key);
617                 if(!NT_STATUS_IS_OK(nt_status)) {
618                         DEBUG(1, ("gensec_session_key failed: %s\n", nt_errstr(nt_status)));
619                         mux_printf(mux_id, "BH No session key\n");
620                         talloc_free(mem_ctx);
621                         return;
622                 } else {
623                         base64_key = base64_encode_data_blob(state, session_key);
624                         SMB_ASSERT(base64_key != NULL);
625                         mux_printf(mux_id, "GK %s\n", base64_key);
626                         talloc_free(base64_key);
627                 }
628                 talloc_free(mem_ctx);
629                 return;
630         }
631
632         if (strncmp(buf, "GF", 2) == 0) {
633                 struct ntlmssp_state *ntlmssp_state;
634                 uint32_t neg_flags;
635
636                 ntlmssp_state = talloc_get_type(state->gensec_state->private_data,
637                                 struct ntlmssp_state);
638                 neg_flags = ntlmssp_state->neg_flags;
639
640                 DEBUG(10, ("Requested negotiated feature flags\n"));
641                 mux_printf(mux_id, "GF 0x%08x\n", neg_flags);
642                 return;
643         }
644
645         nt_status = gensec_update_ev(state->gensec_state, mem_ctx, ev, in, &out);
646         
647         /* don't leak 'bad password'/'no such user' info to the network client */
648         nt_status = nt_status_squash(nt_status);
649
650         if (out.length) {
651                 out_base64 = base64_encode_data_blob(mem_ctx, out);
652                 SMB_ASSERT(out_base64 != NULL);
653         } else {
654                 out_base64 = NULL;
655         }
656
657         if (NT_STATUS_EQUAL(nt_status, NT_STATUS_MORE_PROCESSING_REQUIRED)) {
658                 reply_arg = "*";
659                 if (first) {
660                         reply_code = "YR";
661                 } else if (state->gensec_state->gensec_role == GENSEC_CLIENT) { 
662                         reply_code = "KK";
663                 } else if (state->gensec_state->gensec_role == GENSEC_SERVER) { 
664                         reply_code = "TT";
665                 } else {
666                         abort();
667                 }
668
669
670         } else if (NT_STATUS_EQUAL(nt_status, NT_STATUS_ACCESS_DENIED)) {
671                 reply_code = "BH NT_STATUS_ACCESS_DENIED";
672                 reply_arg = nt_errstr(nt_status);
673                 DEBUG(1, ("GENSEC login failed: %s\n", nt_errstr(nt_status)));
674         } else if (NT_STATUS_EQUAL(nt_status, NT_STATUS_UNSUCCESSFUL)) {
675                 reply_code = "BH NT_STATUS_UNSUCCESSFUL";
676                 reply_arg = nt_errstr(nt_status);
677                 DEBUG(1, ("GENSEC login failed: %s\n", nt_errstr(nt_status)));
678         } else if (!NT_STATUS_IS_OK(nt_status)) {
679                 reply_code = "NA";
680                 reply_arg = nt_errstr(nt_status);
681                 DEBUG(1, ("GENSEC login failed: %s\n", nt_errstr(nt_status)));
682         } else if /* OK */ (state->gensec_state->gensec_role == GENSEC_SERVER) {
683                 struct auth_session_info *session_info;
684
685                 nt_status = gensec_session_info(state->gensec_state, mem_ctx, &session_info);
686                 if (!NT_STATUS_IS_OK(nt_status)) {
687                         reply_code = "BH Failed to retrive session info";
688                         reply_arg = nt_errstr(nt_status);
689                         DEBUG(1, ("GENSEC failed to retrieve the session info: %s\n", nt_errstr(nt_status)));
690                 } else {
691
692                         reply_code = "AF";
693                         reply_arg = talloc_asprintf(state->gensec_state, 
694                                                     "%s%s%s", session_info->info->domain_name,
695                                                     lpcfg_winbind_separator(lp_ctx), session_info->info->account_name);
696                         talloc_free(session_info);
697                 }
698         } else if (state->gensec_state->gensec_role == GENSEC_CLIENT) {
699                 reply_code = "AF";
700                 reply_arg = out_base64;
701         } else {
702                 abort();
703         }
704
705         switch (stdio_helper_mode) {
706         case GSS_SPNEGO_SERVER:
707                 mux_printf(mux_id, "%s %s %s\n", reply_code, 
708                           out_base64 ? out_base64 : "*", 
709                           reply_arg ? reply_arg : "*");
710                 break;
711         default:
712                 if (out_base64) {
713                         mux_printf(mux_id, "%s %s\n", reply_code, out_base64);
714                 } else if (reply_arg) {
715                         mux_printf(mux_id, "%s %s\n", reply_code, reply_arg);
716                 } else {
717                         mux_printf(mux_id, "%s\n", reply_code);
718                 }
719         }
720
721         talloc_free(mem_ctx);
722         return;
723 }
724
725 static void manage_ntlm_server_1_request(enum stdio_helper_mode stdio_helper_mode, 
726                                          struct loadparm_context *lp_ctx,
727                                          char *buf, int length, void **private1,
728                                          unsigned int mux_id, void **private2) 
729 {
730         char *request, *parameter;      
731         static DATA_BLOB challenge;
732         static DATA_BLOB lm_response;
733         static DATA_BLOB nt_response;
734         static char *full_username;
735         static char *username;
736         static char *domain;
737         static char *plaintext_password;
738         static bool ntlm_server_1_user_session_key;
739         static bool ntlm_server_1_lm_session_key;
740         
741         if (strequal(buf, ".")) {
742                 if (!full_username && !username) {      
743                         mux_printf(mux_id, "Error: No username supplied!\n");
744                 } else if (plaintext_password) {
745                         /* handle this request as plaintext */
746                         if (!full_username) {
747                                 if (asprintf(&full_username, "%s%c%s", domain, *lpcfg_winbind_separator(lp_ctx), username) < 0) {
748                                         mux_printf(mux_id, "Error: Out of memory in asprintf!\n.\n");
749                                         return;
750                                 }
751                         }
752                         if (check_plaintext_auth(full_username, plaintext_password, false)) {
753                                 mux_printf(mux_id, "Authenticated: Yes\n");
754                         } else {
755                                 mux_printf(mux_id, "Authenticated: No\n");
756                         }
757                 } else if (!lm_response.data && !nt_response.data) {
758                         mux_printf(mux_id, "Error: No password supplied!\n");
759                 } else if (!challenge.data) {   
760                         mux_printf(mux_id, "Error: No lanman-challenge supplied!\n");
761                 } else {
762                         char *error_string = NULL;
763                         DATA_BLOB lm_key;
764                         DATA_BLOB user_session_key;
765                         uint32_t flags = 0;
766
767                         if (full_username && !username) {
768                                 SAFE_FREE(username);
769                                 SAFE_FREE(domain);
770                                 if (!parse_ntlm_auth_domain_user(full_username, &username, 
771                                                                                                  &domain, 
772                                                                                                  *lpcfg_winbind_separator(lp_ctx))) {
773                                         /* username might be 'tainted', don't print into our new-line deleimianted stream */
774                                         mux_printf(mux_id, "Error: Could not parse into domain and username\n");
775                                 }
776                         }
777
778                         if (!domain) {
779                                 domain = smb_xstrdup(lpcfg_workgroup(lp_ctx));
780                         }
781
782                         if (ntlm_server_1_lm_session_key) 
783                                 flags |= NTLM_AUTH_FLAG_LMKEY;
784                         
785                         if (ntlm_server_1_user_session_key) 
786                                 flags |= NTLM_AUTH_FLAG_USER_SESSION_KEY;
787
788                         if (!NT_STATUS_IS_OK(
789                                     local_pw_check_specified(lp_ctx,
790                                                              username, 
791                                                               domain, 
792                                                               lpcfg_netbios_name(lp_ctx),
793                                                               &challenge, 
794                                                               &lm_response, 
795                                                               &nt_response, 
796                                                               flags, 
797                                                               &lm_key, 
798                                                               &user_session_key,
799                                                               &error_string,
800                                                               NULL))) {
801
802                                 mux_printf(mux_id, "Authenticated: No\n");
803                                 mux_printf(mux_id, "Authentication-Error: %s\n.\n", error_string);
804                                 SAFE_FREE(error_string);
805                         } else {
806                                 static char zeros[16];
807
808                                 mux_printf(mux_id, "Authenticated: Yes\n");
809
810                                 if (ntlm_server_1_lm_session_key 
811                                     && lm_key.length 
812                                     && (memcmp(zeros, lm_key.data, 
813                                                                 lm_key.length) != 0)) {
814                                         char hex_lm_key[lm_key.length*2+1];
815                                         hex_encode_buf(hex_lm_key, lm_key.data,
816                                                        lm_key.length);
817                                         mux_printf(mux_id, "LANMAN-Session-Key: %s\n", hex_lm_key);
818                                 }
819
820                                 if (ntlm_server_1_user_session_key 
821                                     && user_session_key.length 
822                                     && (memcmp(zeros, user_session_key.data, 
823                                                user_session_key.length) != 0)) {
824                                         char hex_user_session_key[
825                                                 user_session_key.length*2+1];
826                                         hex_encode_buf(hex_user_session_key,
827                                                        user_session_key.data,
828                                                        user_session_key.length);
829                                         mux_printf(mux_id, "User-Session-Key: %s\n", hex_user_session_key);
830                                 }
831                         }
832                 }
833                 /* clear out the state */
834                 challenge = data_blob(NULL, 0);
835                 nt_response = data_blob(NULL, 0);
836                 lm_response = data_blob(NULL, 0);
837                 SAFE_FREE(full_username);
838                 SAFE_FREE(username);
839                 SAFE_FREE(domain);
840                 SAFE_FREE(plaintext_password);
841                 ntlm_server_1_user_session_key = false;
842                 ntlm_server_1_lm_session_key = false;
843                 mux_printf(mux_id, ".\n");
844
845                 return;
846         }
847
848         request = buf;
849
850         /* Indicates a base64 encoded structure */
851         parameter = strstr(request, ":: ");
852         if (!parameter) {
853                 parameter = strstr(request, ": ");
854                 
855                 if (!parameter) {
856                         DEBUG(0, ("Parameter not found!\n"));
857                         mux_printf(mux_id, "Error: Parameter not found!\n.\n");
858                         return;
859                 }
860                 
861                 parameter[0] ='\0';
862                 parameter++;
863                 parameter[0] ='\0';
864                 parameter++;
865
866         } else {
867                 parameter[0] ='\0';
868                 parameter++;
869                 parameter[0] ='\0';
870                 parameter++;
871                 parameter[0] ='\0';
872                 parameter++;
873
874                 base64_decode_inplace(parameter);
875         }
876
877         if (strequal(request, "LANMAN-Challenge")) {
878                 challenge = strhex_to_data_blob(NULL, parameter);
879                 if (challenge.length != 8) {
880                         mux_printf(mux_id, "Error: hex decode of %s failed! (got %d bytes, expected 8)\n.\n", 
881                                   parameter,
882                                   (int)challenge.length);
883                         challenge = data_blob(NULL, 0);
884                 }
885         } else if (strequal(request, "NT-Response")) {
886                 nt_response = strhex_to_data_blob(NULL, parameter);
887                 if (nt_response.length < 24) {
888                         mux_printf(mux_id, "Error: hex decode of %s failed! (only got %d bytes, needed at least 24)\n.\n", 
889                                   parameter,
890                                   (int)nt_response.length);
891                         nt_response = data_blob(NULL, 0);
892                 }
893         } else if (strequal(request, "LANMAN-Response")) {
894                 lm_response = strhex_to_data_blob(NULL, parameter);
895                 if (lm_response.length != 24) {
896                         mux_printf(mux_id, "Error: hex decode of %s failed! (got %d bytes, expected 24)\n.\n", 
897                                   parameter,
898                                   (int)lm_response.length);
899                         lm_response = data_blob(NULL, 0);
900                 }
901         } else if (strequal(request, "Password")) {
902                 plaintext_password = smb_xstrdup(parameter);
903         } else if (strequal(request, "NT-Domain")) {
904                 domain = smb_xstrdup(parameter);
905         } else if (strequal(request, "Username")) {
906                 username = smb_xstrdup(parameter);
907         } else if (strequal(request, "Full-Username")) {
908                 full_username = smb_xstrdup(parameter);
909         } else if (strequal(request, "Request-User-Session-Key")) {
910                 ntlm_server_1_user_session_key = strequal(parameter, "Yes");
911         } else if (strequal(request, "Request-LanMan-Session-Key")) {
912                 ntlm_server_1_lm_session_key = strequal(parameter, "Yes");
913         } else {
914                 mux_printf(mux_id, "Error: Unknown request %s\n.\n", request);
915         }
916 }
917
918 static void manage_squid_request(struct loadparm_context *lp_ctx, enum stdio_helper_mode helper_mode,
919                                  stdio_helper_function fn, void **private2) 
920 {
921         char *buf;
922         char tmp[INITIAL_BUFFER_SIZE+1];
923         unsigned int mux_id = 0;
924         int length, buf_size = 0;
925         char *c;
926         struct mux_private {
927                 unsigned int max_mux;
928                 void **private_pointers;
929         };
930
931         static struct mux_private *mux_private;
932         static void *normal_private;
933         void **private1;
934
935         buf = talloc_strdup(NULL, "");
936
937         if (buf == NULL) {
938                 DEBUG(0, ("Failed to allocate memory for reading the input "
939                           "buffer.\n"));
940                 x_fprintf(x_stdout, "ERR\n");
941                 return;
942         }
943
944         do {
945                 /* this is not a typo - x_fgets doesn't work too well under
946                  * squid */
947                 if (fgets(tmp, INITIAL_BUFFER_SIZE, stdin) == NULL) {
948                         if (ferror(stdin)) {
949                                 DEBUG(1, ("fgets() failed! dying..... errno=%d "
950                                           "(%s)\n", ferror(stdin),
951                                           strerror(ferror(stdin))));
952
953                                 exit(1);    /* BIIG buffer */
954                         }
955                         exit(0);
956                 }
957
958                 buf = talloc_strdup_append_buffer(buf, tmp);
959                 buf_size += INITIAL_BUFFER_SIZE;
960
961                 if (buf_size > MAX_BUFFER_SIZE) {
962                         DEBUG(0, ("Invalid Request (too large)\n"));
963                         x_fprintf(x_stdout, "ERR\n");
964                         talloc_free(buf);
965                         return;
966                 }
967
968                 c = strchr(buf, '\n');
969         } while (c == NULL);
970
971         *c = '\0';
972         length = c-buf;
973
974         DEBUG(10, ("Got '%s' from squid (length: %d).\n",buf,length));
975
976         if (buf[0] == '\0') {
977                 DEBUG(0, ("Invalid Request (empty)\n"));
978                 x_fprintf(x_stdout, "ERR\n");
979                 talloc_free(buf);
980                 return;
981         }
982
983         if (opt_multiplex) {
984                 if (sscanf(buf, "%u ", &mux_id) != 1) {
985                         DEBUG(0, ("Invalid Request - no multiplex id\n"));
986                         x_fprintf(x_stdout, "ERR\n");
987                         talloc_free(buf);
988                         return;
989                 }
990                 if (!mux_private) {
991                         mux_private = talloc(NULL, struct mux_private);
992                         mux_private->max_mux = 0;
993                         mux_private->private_pointers = NULL;
994                 }
995                 
996                 c=strchr(buf,' ');
997                 if (!c) {
998                         DEBUG(0, ("Invalid Request - no data after multiplex id\n"));
999                         x_fprintf(x_stdout, "ERR\n");
1000                         talloc_free(buf);
1001                         return;
1002                 }
1003                 c++;
1004                 if (mux_id >= mux_private->max_mux) {
1005                         unsigned int prev_max = mux_private->max_mux;
1006                         mux_private->max_mux = mux_id + 1;
1007                         mux_private->private_pointers
1008                                 = talloc_realloc(mux_private, 
1009                                                    mux_private->private_pointers, 
1010                                                    void *, mux_private->max_mux);
1011                         memset(&mux_private->private_pointers[prev_max], '\0',  
1012                                (sizeof(*mux_private->private_pointers) * (mux_private->max_mux - prev_max))); 
1013                 };
1014
1015                 private1 = &mux_private->private_pointers[mux_id];
1016         } else {
1017                 c = buf;
1018                 private1 = &normal_private;
1019         }
1020
1021         fn(helper_mode, lp_ctx, c, length, private1, mux_id, private2);
1022         talloc_free(buf);
1023 }
1024
1025 static void squid_stream(struct loadparm_context *lp_ctx,
1026                          enum stdio_helper_mode stdio_mode, 
1027                          stdio_helper_function fn) {
1028         /* initialize FDescs */
1029         x_setbuf(x_stdout, NULL);
1030         x_setbuf(x_stderr, NULL);
1031         while(1) {
1032                 manage_squid_request(lp_ctx, stdio_mode, fn, NULL);
1033         }
1034 }
1035
1036
1037 /* Main program */
1038
1039 enum {
1040         OPT_USERNAME = 1000,
1041         OPT_DOMAIN,
1042         OPT_WORKSTATION,
1043         OPT_CHALLENGE,
1044         OPT_RESPONSE,
1045         OPT_LM,
1046         OPT_NT,
1047         OPT_PASSWORD,
1048         OPT_LM_KEY,
1049         OPT_USER_SESSION_KEY,
1050         OPT_DIAGNOSTICS,
1051         OPT_REQUIRE_MEMBERSHIP,
1052         OPT_MULTIPLEX,
1053         OPT_USE_CACHED_CREDS,
1054         OPT_ALLOW_MSCHAPV2,
1055 };
1056
1057 int main(int argc, const char **argv)
1058 {
1059         static const char *helper_protocol;
1060         int opt;
1061
1062         poptContext pc;
1063
1064         /* NOTE: DO NOT change this interface without considering the implications!
1065            This is an external interface, which other programs will use to interact 
1066            with this helper.
1067         */
1068
1069         /* We do not use single-letter command abbreviations, because they harm future 
1070            interface stability. */
1071
1072         struct poptOption long_options[] = {
1073                 POPT_AUTOHELP
1074                 { "helper-protocol", 0, POPT_ARG_STRING, &helper_protocol, OPT_DOMAIN, "operate as a stdio-based helper", "helper protocol to use"},
1075                 { "domain", 0, POPT_ARG_STRING, &opt_domain, OPT_DOMAIN, "domain name"},
1076                 { "workstation", 0, POPT_ARG_STRING, &opt_workstation, OPT_WORKSTATION, "workstation"},
1077                 { "username", 0, POPT_ARG_STRING, &opt_username, OPT_PASSWORD, "Username"},             
1078                 { "password", 0, POPT_ARG_STRING, &opt_password, OPT_PASSWORD, "User's plaintext password"},            
1079                 { "multiplex", 0, POPT_ARG_NONE, &opt_multiplex, OPT_MULTIPLEX, "Multiplex Mode"},
1080                 { "use-cached-creds", 0, POPT_ARG_NONE, &use_cached_creds, OPT_USE_CACHED_CREDS, "silently ignored for compatibility reasons"},
1081                 { "allow-mschapv2", 0, POPT_ARG_NONE, &opt_allow_mschapv2, OPT_ALLOW_MSCHAPV2, "Explicitly allow MSCHAPv2" },
1082                 POPT_COMMON_SAMBA
1083                 POPT_COMMON_VERSION
1084                 { NULL }
1085         };
1086
1087         /* Samba client initialisation */
1088
1089         setup_logging(NULL, DEBUG_STDERR);
1090
1091         /* Parse options */
1092
1093         pc = poptGetContext("ntlm_auth", argc, argv, long_options, 0);
1094
1095         /* Parse command line options */
1096
1097         if (argc == 1) {
1098                 poptPrintHelp(pc, stderr, 0);
1099                 return 1;
1100         }
1101
1102         pc = poptGetContext(NULL, argc, (const char **)argv, long_options, 
1103                             POPT_CONTEXT_KEEP_FIRST);
1104
1105         while((opt = poptGetNextOpt(pc)) != -1) {
1106                 if (opt < -1) {
1107                         break;
1108                 }
1109         }
1110         if (opt < -1) {
1111                 fprintf(stderr, "%s: %s\n",
1112                         poptBadOption(pc, POPT_BADOPTION_NOALIAS),
1113                         poptStrerror(opt));
1114                 return 1;
1115         }
1116
1117         gensec_init();
1118
1119         if (opt_domain == NULL) {
1120                 opt_domain = lpcfg_workgroup(cmdline_lp_ctx);
1121         }
1122
1123         if (helper_protocol) {
1124                 int i;
1125                 for (i=0; i<NUM_HELPER_MODES; i++) {
1126                         if (strcmp(helper_protocol, stdio_helper_protocols[i].name) == 0) {
1127                                 squid_stream(cmdline_lp_ctx, stdio_helper_protocols[i].mode, stdio_helper_protocols[i].fn);
1128                                 exit(0);
1129                         }
1130                 }
1131                 x_fprintf(x_stderr, "unknown helper protocol [%s]\n\nValid helper protools:\n\n", helper_protocol);
1132
1133                 for (i=0; i<NUM_HELPER_MODES; i++) {
1134                         x_fprintf(x_stderr, "%s\n", stdio_helper_protocols[i].name);
1135                 }
1136
1137                 exit(1);
1138         }
1139
1140         if (!opt_username) {
1141                 x_fprintf(x_stderr, "username must be specified!\n\n");
1142                 poptPrintHelp(pc, stderr, 0);
1143                 exit(1);
1144         }
1145
1146         if (opt_workstation == NULL) {
1147                 opt_workstation = lpcfg_netbios_name(cmdline_lp_ctx);
1148         }
1149
1150         if (!opt_password) {
1151                 char pwd[256] = {0};
1152                 int rc;
1153
1154                 rc = samba_getpass("Password: ", pwd, sizeof(pwd), false, false);
1155                 if (rc == 0) {
1156                         opt_password = smb_xstrdup(pwd);
1157                 }
1158         }
1159
1160         {
1161                 char *user;
1162
1163                 if (asprintf(&user, "%s%c%s", opt_domain,
1164                              *lpcfg_winbind_separator(cmdline_lp_ctx),
1165                              opt_username) < 0) {
1166                         return 1;
1167                 }
1168                 if (!check_plaintext_auth(user, opt_password, true)) {
1169                         return 1;
1170                 }
1171         }
1172
1173         /* Exit code */
1174
1175         poptFreeContext(pc);
1176         return 0;
1177 }