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