r14858: fix bugs noticed by the ibm code checker
[sfrench/samba-autobuild/.git] / source4 / utils / ntlm_auth.c
1 /* 
2    Unix SMB/CIFS implementation.
3
4    Winbind status program.
5
6    Copyright (C) Tim Potter      2000-2003
7    Copyright (C) Andrew Bartlett <abartlet@samba.org> 2003-2004
8    Copyright (C) Francesco Chemolli <kinkie@kame.usr.dsi.unimi.it> 2000 
9
10    This program is free software; you can redistribute it and/or modify
11    it under the terms of the GNU General Public License as published by
12    the Free Software Foundation; either version 2 of the License, or
13    (at your option) any later version.
14    
15    This program is distributed in the hope that it will be useful,
16    but WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18    GNU General Public License for more details.
19    
20    You should have received a copy of the GNU General Public License
21    along with this program; if not, write to the Free Software
22    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
23 */
24
25 #include "includes.h"
26 #include "system/filesys.h"
27 #include "lib/cmdline/popt_common.h"
28 #include "auth/auth.h"
29 #include "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                 nt_status = gensec_session_info(state->gensec_state, &session_info); 
459                 if (!NT_STATUS_IS_OK(nt_status)) {
460                         DEBUG(1, ("gensec_session_info failed: %s\n", nt_errstr(nt_status)));
461                         mux_printf(mux_id, "BH %s\n", nt_errstr(nt_status));
462                         data_blob_free(&in);
463                         talloc_free(mem_ctx);
464                         return;
465                 }
466                 
467                 /* get the string onto the context */
468                 grouplist = talloc_strdup(mem_ctx, "");
469                 
470                 for (i=0; i<session_info->security_token->num_sids; i++) {
471                         struct security_token *token = session_info->security_token; 
472                         const char *sidstr = dom_sid_string(session_info, 
473                                                             token->sids[i]);
474                         grouplist = talloc_asprintf_append(grouplist, "%s,", sidstr);
475                 }
476
477                 mux_printf(mux_id, "GL %s\n", grouplist);
478                 talloc_free(session_info);
479                 data_blob_free(&in);
480                 talloc_free(mem_ctx);
481                 return;
482         }
483
484         nt_status = gensec_update(state->gensec_state, mem_ctx, in, &out);
485         
486         /* don't leak 'bad password'/'no such user' info to the network client */
487         nt_status = auth_nt_status_squash(nt_status);
488
489         if (out.length) {
490                 out_base64 = base64_encode_data_blob(mem_ctx, out);
491         } else {
492                 out_base64 = NULL;
493         }
494
495         if (NT_STATUS_EQUAL(nt_status, NT_STATUS_MORE_PROCESSING_REQUIRED)) {
496                 reply_arg = "*";
497                 if (first) {
498                         reply_code = "YR";
499                 } else if (state->gensec_state->gensec_role == GENSEC_CLIENT) { 
500                         reply_code = "KK";
501                 } else if (state->gensec_state->gensec_role == GENSEC_SERVER) { 
502                         reply_code = "TT";
503                 } else {
504                         abort();
505                 }
506
507
508         } else if (NT_STATUS_EQUAL(nt_status, NT_STATUS_ACCESS_DENIED)) {
509                 reply_code = "BH";
510                 reply_arg = nt_errstr(nt_status);
511                 DEBUG(1, ("GENSEC login failed: %s\n", nt_errstr(nt_status)));
512         } else if (NT_STATUS_EQUAL(nt_status, NT_STATUS_UNSUCCESSFUL)) {
513                 reply_code = "BH";
514                 reply_arg = nt_errstr(nt_status);
515                 DEBUG(1, ("GENSEC login failed: %s\n", nt_errstr(nt_status)));
516         } else if (!NT_STATUS_IS_OK(nt_status)) {
517                 reply_code = "NA";
518                 reply_arg = nt_errstr(nt_status);
519                 DEBUG(1, ("GENSEC login failed: %s\n", nt_errstr(nt_status)));
520         } else if /* OK */ (state->gensec_state->gensec_role == GENSEC_SERVER) {
521                 struct auth_session_info *session_info;
522
523                 nt_status = gensec_session_info(state->gensec_state, &session_info);
524                 if (!NT_STATUS_IS_OK(nt_status)) {
525                         reply_code = "BH";
526                         reply_arg = nt_errstr(nt_status);
527                         DEBUG(1, ("GENSEC failed to retreive the session info: %s\n", nt_errstr(nt_status)));
528                 } else {
529
530                         reply_code = "AF";
531                         reply_arg = talloc_asprintf(state->gensec_state, 
532                                                     "%s%s%s", session_info->server_info->domain_name, 
533                                                     lp_winbind_separator(), session_info->server_info->account_name);
534                         talloc_free(session_info);
535                 }
536         } else if (state->gensec_state->gensec_role == GENSEC_CLIENT) {
537                 reply_code = "AF";
538                 reply_arg = out_base64;
539         } else {
540                 abort();
541         }
542
543         switch (stdio_helper_mode) {
544         case GSS_SPNEGO_SERVER:
545                 mux_printf(mux_id, "%s %s %s\n", reply_code, 
546                           out_base64 ? out_base64 : "*", 
547                           reply_arg ? reply_arg : "*");
548                 break;
549         default:
550                 if (out_base64) {
551                         mux_printf(mux_id, "%s %s\n", reply_code, out_base64);
552                 } else if (reply_arg) {
553                         mux_printf(mux_id, "%s %s\n", reply_code, reply_arg);
554                 } else {
555                         mux_printf(mux_id, "%s\n", reply_code);
556                 }
557         }
558
559         talloc_free(mem_ctx);
560         return;
561 }
562
563 static void manage_ntlm_server_1_request(enum stdio_helper_mode stdio_helper_mode, 
564                                          char *buf, int length, void **private,
565                                          unsigned int mux_id, void **private2) 
566 {
567         char *request, *parameter;      
568         static DATA_BLOB challenge;
569         static DATA_BLOB lm_response;
570         static DATA_BLOB nt_response;
571         static char *full_username;
572         static char *username;
573         static char *domain;
574         static char *plaintext_password;
575         static BOOL ntlm_server_1_user_session_key;
576         static BOOL ntlm_server_1_lm_session_key;
577         
578         if (strequal(buf, ".")) {
579                 if (!full_username && !username) {      
580                         mux_printf(mux_id, "Error: No username supplied!\n");
581                 } else if (plaintext_password) {
582                         /* handle this request as plaintext */
583                         if (!full_username) {
584                                 if (asprintf(&full_username, "%s%c%s", domain, *lp_winbind_separator(), username) == -1) {
585                                         mux_printf(mux_id, "Error: Out of memory in asprintf!\n.\n");
586                                         return;
587                                 }
588                         }
589                         if (check_plaintext_auth(full_username, plaintext_password, False)) {
590                                 mux_printf(mux_id, "Authenticated: Yes\n");
591                         } else {
592                                 mux_printf(mux_id, "Authenticated: No\n");
593                         }
594                 } else if (!lm_response.data && !nt_response.data) {
595                         mux_printf(mux_id, "Error: No password supplied!\n");
596                 } else if (!challenge.data) {   
597                         mux_printf(mux_id, "Error: No lanman-challenge supplied!\n");
598                 } else {
599                         char *error_string = NULL;
600                         DATA_BLOB lm_key;
601                         DATA_BLOB user_session_key;
602                         uint32_t flags = 0;
603
604                         if (full_username && !username) {
605                                 fstring fstr_user;
606                                 fstring fstr_domain;
607                                 
608                                 if (!parse_ntlm_auth_domain_user(full_username, fstr_user, fstr_domain)) {
609                                         /* username might be 'tainted', don't print into our new-line deleimianted stream */
610                                         mux_printf(mux_id, "Error: Could not parse into domain and username\n");
611                                 }
612                                 SAFE_FREE(username);
613                                 SAFE_FREE(domain);
614                                 username = smb_xstrdup(fstr_user);
615                                 domain = smb_xstrdup(fstr_domain);
616                         }
617
618                         if (!domain) {
619                                 domain = smb_xstrdup(lp_workgroup());
620                         }
621
622                         if (ntlm_server_1_lm_session_key) 
623                                 flags |= NTLM_AUTH_FLAG_LMKEY;
624                         
625                         if (ntlm_server_1_user_session_key) 
626                                 flags |= NTLM_AUTH_FLAG_USER_SESSION_KEY;
627
628                         if (!NT_STATUS_IS_OK(
629                                     local_pw_check_specified(username, 
630                                                               domain, 
631                                                               lp_netbios_name(),
632                                                               &challenge, 
633                                                               &lm_response, 
634                                                               &nt_response, 
635                                                               flags, 
636                                                               &lm_key, 
637                                                               &user_session_key,
638                                                               &error_string,
639                                                               NULL))) {
640
641                                 mux_printf(mux_id, "Authenticated: No\n");
642                                 mux_printf(mux_id, "Authentication-Error: %s\n.\n", error_string);
643                                 SAFE_FREE(error_string);
644                         } else {
645                                 static char zeros[16];
646                                 char *hex_lm_key;
647                                 char *hex_user_session_key;
648
649                                 mux_printf(mux_id, "Authenticated: Yes\n");
650
651                                 if (ntlm_server_1_lm_session_key 
652                                     && lm_key.length 
653                                     && (memcmp(zeros, lm_key.data, 
654                                                                 lm_key.length) != 0)) {
655                                         hex_encode(lm_key.data,
656                                                    lm_key.length,
657                                                    &hex_lm_key);
658                                         mux_printf(mux_id, "LANMAN-Session-Key: %s\n", hex_lm_key);
659                                         SAFE_FREE(hex_lm_key);
660                                 }
661
662                                 if (ntlm_server_1_user_session_key 
663                                     && user_session_key.length 
664                                     && (memcmp(zeros, user_session_key.data, 
665                                                user_session_key.length) != 0)) {
666                                         hex_encode(user_session_key.data, 
667                                                    user_session_key.length, 
668                                                    &hex_user_session_key);
669                                         mux_printf(mux_id, "User-Session-Key: %s\n", hex_user_session_key);
670                                         SAFE_FREE(hex_user_session_key);
671                                 }
672                         }
673                 }
674                 /* clear out the state */
675                 challenge = data_blob(NULL, 0);
676                 nt_response = data_blob(NULL, 0);
677                 lm_response = data_blob(NULL, 0);
678                 SAFE_FREE(full_username);
679                 SAFE_FREE(username);
680                 SAFE_FREE(domain);
681                 SAFE_FREE(plaintext_password);
682                 ntlm_server_1_user_session_key = False;
683                 ntlm_server_1_lm_session_key = False;
684                 mux_printf(mux_id, ".\n");
685
686                 return;
687         }
688
689         request = buf;
690
691         /* Indicates a base64 encoded structure */
692         parameter = strstr(request, ":: ");
693         if (!parameter) {
694                 parameter = strstr(request, ": ");
695                 
696                 if (!parameter) {
697                         DEBUG(0, ("Parameter not found!\n"));
698                         mux_printf(mux_id, "Error: Parameter not found!\n.\n");
699                         return;
700                 }
701                 
702                 parameter[0] ='\0';
703                 parameter++;
704                 parameter[0] ='\0';
705                 parameter++;
706
707         } else {
708                 parameter[0] ='\0';
709                 parameter++;
710                 parameter[0] ='\0';
711                 parameter++;
712                 parameter[0] ='\0';
713                 parameter++;
714
715                 base64_decode_inplace(parameter);
716         }
717
718         if (strequal(request, "LANMAN-Challenge")) {
719                 challenge = strhex_to_data_blob(parameter);
720                 if (challenge.length != 8) {
721                         mux_printf(mux_id, "Error: hex decode of %s failed! (got %d bytes, expected 8)\n.\n", 
722                                   parameter,
723                                   (int)challenge.length);
724                         challenge = data_blob(NULL, 0);
725                 }
726         } else if (strequal(request, "NT-Response")) {
727                 nt_response = strhex_to_data_blob(parameter);
728                 if (nt_response.length < 24) {
729                         mux_printf(mux_id, "Error: hex decode of %s failed! (only got %d bytes, needed at least 24)\n.\n", 
730                                   parameter,
731                                   (int)nt_response.length);
732                         nt_response = data_blob(NULL, 0);
733                 }
734         } else if (strequal(request, "LANMAN-Response")) {
735                 lm_response = strhex_to_data_blob(parameter);
736                 if (lm_response.length != 24) {
737                         mux_printf(mux_id, "Error: hex decode of %s failed! (got %d bytes, expected 24)\n.\n", 
738                                   parameter,
739                                   (int)lm_response.length);
740                         lm_response = data_blob(NULL, 0);
741                 }
742         } else if (strequal(request, "Password")) {
743                 plaintext_password = smb_xstrdup(parameter);
744         } else if (strequal(request, "NT-Domain")) {
745                 domain = smb_xstrdup(parameter);
746         } else if (strequal(request, "Username")) {
747                 username = smb_xstrdup(parameter);
748         } else if (strequal(request, "Full-Username")) {
749                 full_username = smb_xstrdup(parameter);
750         } else if (strequal(request, "Request-User-Session-Key")) {
751                 ntlm_server_1_user_session_key = strequal(parameter, "Yes");
752         } else if (strequal(request, "Request-LanMan-Session-Key")) {
753                 ntlm_server_1_lm_session_key = strequal(parameter, "Yes");
754         } else {
755                 mux_printf(mux_id, "Error: Unknown request %s\n.\n", request);
756         }
757 }
758
759 static void manage_squid_request(enum stdio_helper_mode helper_mode, 
760                                  stdio_helper_function fn, void **private2) 
761 {
762         char buf[SQUID_BUFFER_SIZE+1];
763         unsigned int mux_id = 0;
764         int length;
765         char *c;
766         static BOOL err;
767         struct mux_private {
768                 unsigned int max_mux;
769                 void **private_pointers;
770         };
771         
772         static struct mux_private *mux_private;
773         static void *normal_private;
774         void **private;
775
776         /* this is not a typo - x_fgets doesn't work too well under squid */
777         if (fgets(buf, sizeof(buf)-1, stdin) == NULL) {
778                 if (ferror(stdin)) {
779                         DEBUG(1, ("fgets() failed! dying..... errno=%d (%s)\n", ferror(stdin),
780                                   strerror(ferror(stdin))));
781                         
782                         exit(1);    /* BIIG buffer */
783                 }
784                 exit(0);
785         }
786     
787         c=memchr(buf,'\n',sizeof(buf)-1);
788         if (c) {
789                 *c = '\0';
790                 length = c-buf;
791         } else {
792                 err = 1;
793                 return;
794         }
795         if (err) {
796                 DEBUG(0, ("Oversized message\n"));
797                 x_fprintf(x_stdout, "ERR\n");
798                 err = 0;
799                 return;
800         }
801
802         DEBUG(10, ("Got '%s' from squid (length: %d).\n",buf,length));
803
804         if (buf[0] == '\0') {
805                 DEBUG(0, ("Invalid Request (empty)\n"));
806                 x_fprintf(x_stdout, "ERR\n");
807                 return;
808         }
809
810         if (opt_multiplex) {
811                 if (sscanf(buf, "%u ", &mux_id) != 1) {
812                         DEBUG(0, ("Invalid Request - no multiplex id\n"));
813                         x_fprintf(x_stdout, "ERR\n");
814                         return;
815                 }
816                 if (!mux_private) {
817                         mux_private = talloc(NULL, struct mux_private);
818                         mux_private->max_mux = 0;
819                         mux_private->private_pointers = NULL;
820                 }
821                 
822                 c=strchr(buf,' ');
823                 if (!c) {
824                         DEBUG(0, ("Invalid Request - no data after multiplex id\n"));
825                         x_fprintf(x_stdout, "ERR\n");
826                         return;
827                 }
828                 c++;
829                 if (mux_id >= mux_private->max_mux) {
830                         unsigned int prev_max = mux_private->max_mux;
831                         mux_private->max_mux = mux_id + 1;
832                         mux_private->private_pointers
833                                 = talloc_realloc(mux_private, 
834                                                    mux_private->private_pointers, 
835                                                    void *, mux_private->max_mux);
836                         memset(&mux_private->private_pointers[prev_max], '\0',  
837                                (sizeof(*mux_private->private_pointers) * (mux_private->max_mux - prev_max))); 
838                 };
839
840                 private = &mux_private->private_pointers[mux_id];
841         } else {
842                 c = buf;
843                 private = &normal_private;
844         }
845         
846         fn(helper_mode, c, length, private, mux_id, private2);
847 }
848
849 static void squid_stream(enum stdio_helper_mode stdio_mode, 
850                          stdio_helper_function fn) {
851         /* initialize FDescs */
852         x_setbuf(x_stdout, NULL);
853         x_setbuf(x_stderr, NULL);
854         while(1) {
855                 manage_squid_request(stdio_mode, fn, NULL);
856         }
857 }
858
859
860 /* Main program */
861
862 enum {
863         OPT_USERNAME = 1000,
864         OPT_DOMAIN,
865         OPT_WORKSTATION,
866         OPT_CHALLENGE,
867         OPT_RESPONSE,
868         OPT_LM,
869         OPT_NT,
870         OPT_PASSWORD,
871         OPT_LM_KEY,
872         OPT_USER_SESSION_KEY,
873         OPT_DIAGNOSTICS,
874         OPT_REQUIRE_MEMBERSHIP,
875         OPT_MULTIPLEX,
876 };
877
878 int main(int argc, const char **argv)
879 {
880         static const char *helper_protocol;
881         int opt;
882
883         poptContext pc;
884
885         /* NOTE: DO NOT change this interface without considering the implications!
886            This is an external interface, which other programs will use to interact 
887            with this helper.
888         */
889
890         /* We do not use single-letter command abbreviations, because they harm future 
891            interface stability. */
892
893         struct poptOption long_options[] = {
894                 POPT_AUTOHELP
895                 { "helper-protocol", 0, POPT_ARG_STRING, &helper_protocol, OPT_DOMAIN, "operate as a stdio-based helper", "helper protocol to use"},
896                 { "domain", 0, POPT_ARG_STRING, &opt_domain, OPT_DOMAIN, "domain name"},
897                 { "workstation", 0, POPT_ARG_STRING, &opt_workstation, OPT_WORKSTATION, "workstation"},
898                 { "username", 0, POPT_ARG_STRING, &opt_username, OPT_PASSWORD, "Username"},             
899                 { "password", 0, POPT_ARG_STRING, &opt_password, OPT_PASSWORD, "User's plaintext password"},            
900                 { "multiplex", 0, POPT_ARG_NONE, &opt_multiplex, OPT_MULTIPLEX, "Multiplex Mode"},
901                 POPT_COMMON_SAMBA
902                 POPT_COMMON_VERSION
903                 POPT_TABLEEND
904         };
905
906         /* Samba client initialisation */
907
908         setup_logging(NULL, DEBUG_STDERR);
909
910         /* Parse options */
911
912         pc = poptGetContext("ntlm_auth", argc, argv, long_options, 0);
913
914         /* Parse command line options */
915
916         if (argc == 1) {
917                 poptPrintHelp(pc, stderr, 0);
918                 return 1;
919         }
920
921         pc = poptGetContext(NULL, argc, (const char **)argv, long_options, 
922                             POPT_CONTEXT_KEEP_FIRST);
923
924         while((opt = poptGetNextOpt(pc)) != -1) {
925                 if (opt < -1) {
926                         break;
927                 }
928         }
929         if (opt < -1) {
930                 fprintf(stderr, "%s: %s\n",
931                         poptBadOption(pc, POPT_BADOPTION_NOALIAS),
932                         poptStrerror(opt));
933                 return 1;
934         }
935
936         gensec_init();
937
938         if (opt_domain == NULL) {
939                 opt_domain = lp_workgroup();
940         }
941
942         if (helper_protocol) {
943                 int i;
944                 for (i=0; i<NUM_HELPER_MODES; i++) {
945                         if (strcmp(helper_protocol, stdio_helper_protocols[i].name) == 0) {
946                                 squid_stream(stdio_helper_protocols[i].mode, stdio_helper_protocols[i].fn);
947                                 exit(0);
948                         }
949                 }
950                 x_fprintf(x_stderr, "unknown helper protocol [%s]\n\nValid helper protools:\n\n", helper_protocol);
951
952                 for (i=0; i<NUM_HELPER_MODES; i++) {
953                         x_fprintf(x_stderr, "%s\n", stdio_helper_protocols[i].name);
954                 }
955
956                 exit(1);
957         }
958
959         if (!opt_username) {
960                 x_fprintf(x_stderr, "username must be specified!\n\n");
961                 poptPrintHelp(pc, stderr, 0);
962                 exit(1);
963         }
964
965         if (opt_workstation == NULL) {
966                 opt_workstation = lp_netbios_name();
967         }
968
969         if (!opt_password) {
970                 opt_password = getpass("password: ");
971         }
972
973         {
974                 char *user;
975
976                 asprintf(&user, "%s%c%s", opt_domain, *lp_winbind_separator(), opt_username);
977                 if (!check_plaintext_auth(user, opt_password, True)) {
978                         return 1;
979                 }
980         }
981
982         /* Exit code */
983
984         poptFreeContext(pc);
985         return 0;
986 }