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