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