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