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