08160247745cb4d6417d46c4fa97d063b3f890eb
[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                         mux_printf(mux_id, "GK %s\n", base64_key);
625                         talloc_free(base64_key);
626                 }
627                 talloc_free(mem_ctx);
628                 return;
629         }
630
631         if (strncmp(buf, "GF", 2) == 0) {
632                 struct ntlmssp_state *ntlmssp_state;
633                 uint32_t neg_flags;
634
635                 ntlmssp_state = talloc_get_type(state->gensec_state->private_data,
636                                 struct ntlmssp_state);
637                 neg_flags = ntlmssp_state->neg_flags;
638
639                 DEBUG(10, ("Requested negotiated feature flags\n"));
640                 mux_printf(mux_id, "GF 0x%08x\n", neg_flags);
641                 return;
642         }
643
644         nt_status = gensec_update_ev(state->gensec_state, mem_ctx, ev, in, &out);
645         
646         /* don't leak 'bad password'/'no such user' info to the network client */
647         nt_status = nt_status_squash(nt_status);
648
649         if (out.length) {
650                 out_base64 = base64_encode_data_blob(mem_ctx, out);
651         } else {
652                 out_base64 = NULL;
653         }
654
655         if (NT_STATUS_EQUAL(nt_status, NT_STATUS_MORE_PROCESSING_REQUIRED)) {
656                 reply_arg = "*";
657                 if (first) {
658                         reply_code = "YR";
659                 } else if (state->gensec_state->gensec_role == GENSEC_CLIENT) { 
660                         reply_code = "KK";
661                 } else if (state->gensec_state->gensec_role == GENSEC_SERVER) { 
662                         reply_code = "TT";
663                 } else {
664                         abort();
665                 }
666
667
668         } else if (NT_STATUS_EQUAL(nt_status, NT_STATUS_ACCESS_DENIED)) {
669                 reply_code = "BH NT_STATUS_ACCESS_DENIED";
670                 reply_arg = nt_errstr(nt_status);
671                 DEBUG(1, ("GENSEC login failed: %s\n", nt_errstr(nt_status)));
672         } else if (NT_STATUS_EQUAL(nt_status, NT_STATUS_UNSUCCESSFUL)) {
673                 reply_code = "BH NT_STATUS_UNSUCCESSFUL";
674                 reply_arg = nt_errstr(nt_status);
675                 DEBUG(1, ("GENSEC login failed: %s\n", nt_errstr(nt_status)));
676         } else if (!NT_STATUS_IS_OK(nt_status)) {
677                 reply_code = "NA";
678                 reply_arg = nt_errstr(nt_status);
679                 DEBUG(1, ("GENSEC login failed: %s\n", nt_errstr(nt_status)));
680         } else if /* OK */ (state->gensec_state->gensec_role == GENSEC_SERVER) {
681                 struct auth_session_info *session_info;
682
683                 nt_status = gensec_session_info(state->gensec_state, mem_ctx, &session_info);
684                 if (!NT_STATUS_IS_OK(nt_status)) {
685                         reply_code = "BH Failed to retrive session info";
686                         reply_arg = nt_errstr(nt_status);
687                         DEBUG(1, ("GENSEC failed to retrieve the session info: %s\n", nt_errstr(nt_status)));
688                 } else {
689
690                         reply_code = "AF";
691                         reply_arg = talloc_asprintf(state->gensec_state, 
692                                                     "%s%s%s", session_info->info->domain_name,
693                                                     lpcfg_winbind_separator(lp_ctx), session_info->info->account_name);
694                         talloc_free(session_info);
695                 }
696         } else if (state->gensec_state->gensec_role == GENSEC_CLIENT) {
697                 reply_code = "AF";
698                 reply_arg = out_base64;
699         } else {
700                 abort();
701         }
702
703         switch (stdio_helper_mode) {
704         case GSS_SPNEGO_SERVER:
705                 mux_printf(mux_id, "%s %s %s\n", reply_code, 
706                           out_base64 ? out_base64 : "*", 
707                           reply_arg ? reply_arg : "*");
708                 break;
709         default:
710                 if (out_base64) {
711                         mux_printf(mux_id, "%s %s\n", reply_code, out_base64);
712                 } else if (reply_arg) {
713                         mux_printf(mux_id, "%s %s\n", reply_code, reply_arg);
714                 } else {
715                         mux_printf(mux_id, "%s\n", reply_code);
716                 }
717         }
718
719         talloc_free(mem_ctx);
720         return;
721 }
722
723 static void manage_ntlm_server_1_request(enum stdio_helper_mode stdio_helper_mode, 
724                                          struct loadparm_context *lp_ctx,
725                                          char *buf, int length, void **private1,
726                                          unsigned int mux_id, void **private2) 
727 {
728         char *request, *parameter;      
729         static DATA_BLOB challenge;
730         static DATA_BLOB lm_response;
731         static DATA_BLOB nt_response;
732         static char *full_username;
733         static char *username;
734         static char *domain;
735         static char *plaintext_password;
736         static bool ntlm_server_1_user_session_key;
737         static bool ntlm_server_1_lm_session_key;
738         
739         if (strequal(buf, ".")) {
740                 if (!full_username && !username) {      
741                         mux_printf(mux_id, "Error: No username supplied!\n");
742                 } else if (plaintext_password) {
743                         /* handle this request as plaintext */
744                         if (!full_username) {
745                                 if (asprintf(&full_username, "%s%c%s", domain, *lpcfg_winbind_separator(lp_ctx), username) < 0) {
746                                         mux_printf(mux_id, "Error: Out of memory in asprintf!\n.\n");
747                                         return;
748                                 }
749                         }
750                         if (check_plaintext_auth(full_username, plaintext_password, false)) {
751                                 mux_printf(mux_id, "Authenticated: Yes\n");
752                         } else {
753                                 mux_printf(mux_id, "Authenticated: No\n");
754                         }
755                 } else if (!lm_response.data && !nt_response.data) {
756                         mux_printf(mux_id, "Error: No password supplied!\n");
757                 } else if (!challenge.data) {   
758                         mux_printf(mux_id, "Error: No lanman-challenge supplied!\n");
759                 } else {
760                         char *error_string = NULL;
761                         DATA_BLOB lm_key;
762                         DATA_BLOB user_session_key;
763                         uint32_t flags = 0;
764
765                         if (full_username && !username) {
766                                 SAFE_FREE(username);
767                                 SAFE_FREE(domain);
768                                 if (!parse_ntlm_auth_domain_user(full_username, &username, 
769                                                                                                  &domain, 
770                                                                                                  *lpcfg_winbind_separator(lp_ctx))) {
771                                         /* username might be 'tainted', don't print into our new-line deleimianted stream */
772                                         mux_printf(mux_id, "Error: Could not parse into domain and username\n");
773                                 }
774                         }
775
776                         if (!domain) {
777                                 domain = smb_xstrdup(lpcfg_workgroup(lp_ctx));
778                         }
779
780                         if (ntlm_server_1_lm_session_key) 
781                                 flags |= NTLM_AUTH_FLAG_LMKEY;
782                         
783                         if (ntlm_server_1_user_session_key) 
784                                 flags |= NTLM_AUTH_FLAG_USER_SESSION_KEY;
785
786                         if (!NT_STATUS_IS_OK(
787                                     local_pw_check_specified(lp_ctx,
788                                                              username, 
789                                                               domain, 
790                                                               lpcfg_netbios_name(lp_ctx),
791                                                               &challenge, 
792                                                               &lm_response, 
793                                                               &nt_response, 
794                                                               flags, 
795                                                               &lm_key, 
796                                                               &user_session_key,
797                                                               &error_string,
798                                                               NULL))) {
799
800                                 mux_printf(mux_id, "Authenticated: No\n");
801                                 mux_printf(mux_id, "Authentication-Error: %s\n.\n", error_string);
802                                 SAFE_FREE(error_string);
803                         } else {
804                                 static char zeros[16];
805
806                                 mux_printf(mux_id, "Authenticated: Yes\n");
807
808                                 if (ntlm_server_1_lm_session_key 
809                                     && lm_key.length 
810                                     && (memcmp(zeros, lm_key.data, 
811                                                                 lm_key.length) != 0)) {
812                                         char hex_lm_key[lm_key.length*2+1];
813                                         hex_encode_buf(hex_lm_key, lm_key.data,
814                                                        lm_key.length);
815                                         mux_printf(mux_id, "LANMAN-Session-Key: %s\n", hex_lm_key);
816                                 }
817
818                                 if (ntlm_server_1_user_session_key 
819                                     && user_session_key.length 
820                                     && (memcmp(zeros, user_session_key.data, 
821                                                user_session_key.length) != 0)) {
822                                         char hex_user_session_key[
823                                                 user_session_key.length*2+1];
824                                         hex_encode_buf(hex_user_session_key,
825                                                        user_session_key.data,
826                                                        user_session_key.length);
827                                         mux_printf(mux_id, "User-Session-Key: %s\n", hex_user_session_key);
828                                 }
829                         }
830                 }
831                 /* clear out the state */
832                 challenge = data_blob(NULL, 0);
833                 nt_response = data_blob(NULL, 0);
834                 lm_response = data_blob(NULL, 0);
835                 SAFE_FREE(full_username);
836                 SAFE_FREE(username);
837                 SAFE_FREE(domain);
838                 SAFE_FREE(plaintext_password);
839                 ntlm_server_1_user_session_key = false;
840                 ntlm_server_1_lm_session_key = false;
841                 mux_printf(mux_id, ".\n");
842
843                 return;
844         }
845
846         request = buf;
847
848         /* Indicates a base64 encoded structure */
849         parameter = strstr(request, ":: ");
850         if (!parameter) {
851                 parameter = strstr(request, ": ");
852                 
853                 if (!parameter) {
854                         DEBUG(0, ("Parameter not found!\n"));
855                         mux_printf(mux_id, "Error: Parameter not found!\n.\n");
856                         return;
857                 }
858                 
859                 parameter[0] ='\0';
860                 parameter++;
861                 parameter[0] ='\0';
862                 parameter++;
863
864         } else {
865                 parameter[0] ='\0';
866                 parameter++;
867                 parameter[0] ='\0';
868                 parameter++;
869                 parameter[0] ='\0';
870                 parameter++;
871
872                 base64_decode_inplace(parameter);
873         }
874
875         if (strequal(request, "LANMAN-Challenge")) {
876                 challenge = strhex_to_data_blob(NULL, parameter);
877                 if (challenge.length != 8) {
878                         mux_printf(mux_id, "Error: hex decode of %s failed! (got %d bytes, expected 8)\n.\n", 
879                                   parameter,
880                                   (int)challenge.length);
881                         challenge = data_blob(NULL, 0);
882                 }
883         } else if (strequal(request, "NT-Response")) {
884                 nt_response = strhex_to_data_blob(NULL, parameter);
885                 if (nt_response.length < 24) {
886                         mux_printf(mux_id, "Error: hex decode of %s failed! (only got %d bytes, needed at least 24)\n.\n", 
887                                   parameter,
888                                   (int)nt_response.length);
889                         nt_response = data_blob(NULL, 0);
890                 }
891         } else if (strequal(request, "LANMAN-Response")) {
892                 lm_response = strhex_to_data_blob(NULL, parameter);
893                 if (lm_response.length != 24) {
894                         mux_printf(mux_id, "Error: hex decode of %s failed! (got %d bytes, expected 24)\n.\n", 
895                                   parameter,
896                                   (int)lm_response.length);
897                         lm_response = data_blob(NULL, 0);
898                 }
899         } else if (strequal(request, "Password")) {
900                 plaintext_password = smb_xstrdup(parameter);
901         } else if (strequal(request, "NT-Domain")) {
902                 domain = smb_xstrdup(parameter);
903         } else if (strequal(request, "Username")) {
904                 username = smb_xstrdup(parameter);
905         } else if (strequal(request, "Full-Username")) {
906                 full_username = smb_xstrdup(parameter);
907         } else if (strequal(request, "Request-User-Session-Key")) {
908                 ntlm_server_1_user_session_key = strequal(parameter, "Yes");
909         } else if (strequal(request, "Request-LanMan-Session-Key")) {
910                 ntlm_server_1_lm_session_key = strequal(parameter, "Yes");
911         } else {
912                 mux_printf(mux_id, "Error: Unknown request %s\n.\n", request);
913         }
914 }
915
916 static void manage_squid_request(struct loadparm_context *lp_ctx, enum stdio_helper_mode helper_mode,
917                                  stdio_helper_function fn, void **private2) 
918 {
919         char *buf;
920         char tmp[INITIAL_BUFFER_SIZE+1];
921         unsigned int mux_id = 0;
922         int length, buf_size = 0;
923         char *c;
924         struct mux_private {
925                 unsigned int max_mux;
926                 void **private_pointers;
927         };
928
929         static struct mux_private *mux_private;
930         static void *normal_private;
931         void **private1;
932
933         buf = talloc_strdup(NULL, "");
934
935         if (buf == NULL) {
936                 DEBUG(0, ("Failed to allocate memory for reading the input "
937                           "buffer.\n"));
938                 x_fprintf(x_stdout, "ERR\n");
939                 return;
940         }
941
942         do {
943                 /* this is not a typo - x_fgets doesn't work too well under
944                  * squid */
945                 if (fgets(tmp, INITIAL_BUFFER_SIZE, stdin) == NULL) {
946                         if (ferror(stdin)) {
947                                 DEBUG(1, ("fgets() failed! dying..... errno=%d "
948                                           "(%s)\n", ferror(stdin),
949                                           strerror(ferror(stdin))));
950
951                                 exit(1);    /* BIIG buffer */
952                         }
953                         exit(0);
954                 }
955
956                 buf = talloc_strdup_append_buffer(buf, tmp);
957                 buf_size += INITIAL_BUFFER_SIZE;
958
959                 if (buf_size > MAX_BUFFER_SIZE) {
960                         DEBUG(0, ("Invalid Request (too large)\n"));
961                         x_fprintf(x_stdout, "ERR\n");
962                         talloc_free(buf);
963                         return;
964                 }
965
966                 c = strchr(buf, '\n');
967         } while (c == NULL);
968
969         *c = '\0';
970         length = c-buf;
971
972         DEBUG(10, ("Got '%s' from squid (length: %d).\n",buf,length));
973
974         if (buf[0] == '\0') {
975                 DEBUG(0, ("Invalid Request (empty)\n"));
976                 x_fprintf(x_stdout, "ERR\n");
977                 talloc_free(buf);
978                 return;
979         }
980
981         if (opt_multiplex) {
982                 if (sscanf(buf, "%u ", &mux_id) != 1) {
983                         DEBUG(0, ("Invalid Request - no multiplex id\n"));
984                         x_fprintf(x_stdout, "ERR\n");
985                         talloc_free(buf);
986                         return;
987                 }
988                 if (!mux_private) {
989                         mux_private = talloc(NULL, struct mux_private);
990                         mux_private->max_mux = 0;
991                         mux_private->private_pointers = NULL;
992                 }
993                 
994                 c=strchr(buf,' ');
995                 if (!c) {
996                         DEBUG(0, ("Invalid Request - no data after multiplex id\n"));
997                         x_fprintf(x_stdout, "ERR\n");
998                         talloc_free(buf);
999                         return;
1000                 }
1001                 c++;
1002                 if (mux_id >= mux_private->max_mux) {
1003                         unsigned int prev_max = mux_private->max_mux;
1004                         mux_private->max_mux = mux_id + 1;
1005                         mux_private->private_pointers
1006                                 = talloc_realloc(mux_private, 
1007                                                    mux_private->private_pointers, 
1008                                                    void *, mux_private->max_mux);
1009                         memset(&mux_private->private_pointers[prev_max], '\0',  
1010                                (sizeof(*mux_private->private_pointers) * (mux_private->max_mux - prev_max))); 
1011                 };
1012
1013                 private1 = &mux_private->private_pointers[mux_id];
1014         } else {
1015                 c = buf;
1016                 private1 = &normal_private;
1017         }
1018
1019         fn(helper_mode, lp_ctx, c, length, private1, mux_id, private2);
1020         talloc_free(buf);
1021 }
1022
1023 static void squid_stream(struct loadparm_context *lp_ctx,
1024                          enum stdio_helper_mode stdio_mode, 
1025                          stdio_helper_function fn) {
1026         /* initialize FDescs */
1027         x_setbuf(x_stdout, NULL);
1028         x_setbuf(x_stderr, NULL);
1029         while(1) {
1030                 manage_squid_request(lp_ctx, stdio_mode, fn, NULL);
1031         }
1032 }
1033
1034
1035 /* Main program */
1036
1037 enum {
1038         OPT_USERNAME = 1000,
1039         OPT_DOMAIN,
1040         OPT_WORKSTATION,
1041         OPT_CHALLENGE,
1042         OPT_RESPONSE,
1043         OPT_LM,
1044         OPT_NT,
1045         OPT_PASSWORD,
1046         OPT_LM_KEY,
1047         OPT_USER_SESSION_KEY,
1048         OPT_DIAGNOSTICS,
1049         OPT_REQUIRE_MEMBERSHIP,
1050         OPT_MULTIPLEX,
1051         OPT_USE_CACHED_CREDS,
1052         OPT_ALLOW_MSCHAPV2,
1053 };
1054
1055 int main(int argc, const char **argv)
1056 {
1057         static const char *helper_protocol;
1058         int opt;
1059
1060         poptContext pc;
1061
1062         /* NOTE: DO NOT change this interface without considering the implications!
1063            This is an external interface, which other programs will use to interact 
1064            with this helper.
1065         */
1066
1067         /* We do not use single-letter command abbreviations, because they harm future 
1068            interface stability. */
1069
1070         struct poptOption long_options[] = {
1071                 POPT_AUTOHELP
1072                 { "helper-protocol", 0, POPT_ARG_STRING, &helper_protocol, OPT_DOMAIN, "operate as a stdio-based helper", "helper protocol to use"},
1073                 { "domain", 0, POPT_ARG_STRING, &opt_domain, OPT_DOMAIN, "domain name"},
1074                 { "workstation", 0, POPT_ARG_STRING, &opt_workstation, OPT_WORKSTATION, "workstation"},
1075                 { "username", 0, POPT_ARG_STRING, &opt_username, OPT_PASSWORD, "Username"},             
1076                 { "password", 0, POPT_ARG_STRING, &opt_password, OPT_PASSWORD, "User's plaintext password"},            
1077                 { "multiplex", 0, POPT_ARG_NONE, &opt_multiplex, OPT_MULTIPLEX, "Multiplex Mode"},
1078                 { "use-cached-creds", 0, POPT_ARG_NONE, &use_cached_creds, OPT_USE_CACHED_CREDS, "silently ignored for compatibility reasons"},
1079                 { "allow-mschapv2", 0, POPT_ARG_NONE, &opt_allow_mschapv2, OPT_ALLOW_MSCHAPV2, "Explicitly allow MSCHAPv2" },
1080                 POPT_COMMON_SAMBA
1081                 POPT_COMMON_VERSION
1082                 { NULL }
1083         };
1084
1085         /* Samba client initialisation */
1086
1087         setup_logging(NULL, DEBUG_STDERR);
1088
1089         /* Parse options */
1090
1091         pc = poptGetContext("ntlm_auth", argc, argv, long_options, 0);
1092
1093         /* Parse command line options */
1094
1095         if (argc == 1) {
1096                 poptPrintHelp(pc, stderr, 0);
1097                 return 1;
1098         }
1099
1100         pc = poptGetContext(NULL, argc, (const char **)argv, long_options, 
1101                             POPT_CONTEXT_KEEP_FIRST);
1102
1103         while((opt = poptGetNextOpt(pc)) != -1) {
1104                 if (opt < -1) {
1105                         break;
1106                 }
1107         }
1108         if (opt < -1) {
1109                 fprintf(stderr, "%s: %s\n",
1110                         poptBadOption(pc, POPT_BADOPTION_NOALIAS),
1111                         poptStrerror(opt));
1112                 return 1;
1113         }
1114
1115         gensec_init();
1116
1117         if (opt_domain == NULL) {
1118                 opt_domain = lpcfg_workgroup(cmdline_lp_ctx);
1119         }
1120
1121         if (helper_protocol) {
1122                 int i;
1123                 for (i=0; i<NUM_HELPER_MODES; i++) {
1124                         if (strcmp(helper_protocol, stdio_helper_protocols[i].name) == 0) {
1125                                 squid_stream(cmdline_lp_ctx, stdio_helper_protocols[i].mode, stdio_helper_protocols[i].fn);
1126                                 exit(0);
1127                         }
1128                 }
1129                 x_fprintf(x_stderr, "unknown helper protocol [%s]\n\nValid helper protools:\n\n", helper_protocol);
1130
1131                 for (i=0; i<NUM_HELPER_MODES; i++) {
1132                         x_fprintf(x_stderr, "%s\n", stdio_helper_protocols[i].name);
1133                 }
1134
1135                 exit(1);
1136         }
1137
1138         if (!opt_username) {
1139                 x_fprintf(x_stderr, "username must be specified!\n\n");
1140                 poptPrintHelp(pc, stderr, 0);
1141                 exit(1);
1142         }
1143
1144         if (opt_workstation == NULL) {
1145                 opt_workstation = lpcfg_netbios_name(cmdline_lp_ctx);
1146         }
1147
1148         if (!opt_password) {
1149                 char pwd[256] = {0};
1150                 int rc;
1151
1152                 rc = samba_getpass("Password: ", pwd, sizeof(pwd), false, false);
1153                 if (rc == 0) {
1154                         opt_password = smb_xstrdup(pwd);
1155                 }
1156         }
1157
1158         {
1159                 char *user;
1160
1161                 if (asprintf(&user, "%s%c%s", opt_domain,
1162                              *lpcfg_winbind_separator(cmdline_lp_ctx),
1163                              opt_username) < 0) {
1164                         return 1;
1165                 }
1166                 if (!check_plaintext_auth(user, opt_password, true)) {
1167                         return 1;
1168                 }
1169         }
1170
1171         /* Exit code */
1172
1173         poptFreeContext(pc);
1174         return 0;
1175 }