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