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