r4620: - add interface functions to the auth subsystem so that callers doesn't need to
[kai/samba.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 "libcli/security/security.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                         talloc_free(*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, GENSEC_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, GENSEC_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->security_token->num_sids; i++) {
436                         struct security_token *token = session_info->security_token; 
437                         const char *sidstr = dom_sid_string(session_info, 
438                                                             token->sids[i]);
439                         grouplist = talloc_asprintf_append(grouplist, "%s,", sidstr);
440                 }
441
442                 mux_printf(mux_id, "GL %s\n", grouplist);
443                 talloc_free(session_info);
444                 data_blob_free(&in);
445                 return;
446         }
447
448         /* update */
449
450         nt_status = gensec_update(*gensec_state, NULL, in, &out);
451         
452         /* don't leak 'bad password'/'no such user' info to the network client */
453         nt_status = auth_nt_status_squash(nt_status);
454
455         if (out.length) {
456                 out_base64 = base64_encode_data_blob(out);
457         } else {
458                 out_base64 = NULL;
459         }
460         if (NT_STATUS_EQUAL(nt_status, NT_STATUS_MORE_PROCESSING_REQUIRED)) {
461                 reply_arg = "*";
462                 if (first) {
463                         reply_code = "YR";
464                 } else if ((*gensec_state)->gensec_role == GENSEC_CLIENT) { 
465                         reply_code = "KK";
466                 } else if ((*gensec_state)->gensec_role == GENSEC_SERVER) { 
467                         reply_code = "TT";
468                 } else {
469                         abort();
470                 }
471
472
473         } else if (NT_STATUS_EQUAL(nt_status, NT_STATUS_ACCESS_DENIED)) {
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_EQUAL(nt_status, NT_STATUS_UNSUCCESSFUL)) {
478                 reply_code = "BH";
479                 reply_arg = nt_errstr(nt_status);
480                 DEBUG(1, ("GENSEC login failed: %s\n", nt_errstr(nt_status)));
481         } else if (!NT_STATUS_IS_OK(nt_status)) {
482                 reply_code = "NA";
483                 reply_arg = nt_errstr(nt_status);
484                 DEBUG(1, ("GENSEC login failed: %s\n", nt_errstr(nt_status)));
485         } else if /* OK */ ((*gensec_state)->gensec_role == GENSEC_SERVER) {
486                 struct auth_session_info *session_info;
487
488                 nt_status = gensec_session_info(*gensec_state, &session_info);
489                 if (!NT_STATUS_IS_OK(nt_status)) {
490                         reply_code = "BH";
491                         reply_arg = nt_errstr(nt_status);
492                         DEBUG(1, ("GENSEC failed to retreive the session info: %s\n", nt_errstr(nt_status)));
493                 } else {
494
495                         reply_code = "AF";
496                         reply_arg = talloc_asprintf(*gensec_state, 
497                                                     "%s%s%s", session_info->server_info->domain_name, 
498                                                     lp_winbind_separator(), session_info->server_info->account_name);
499                         talloc_free(session_info);
500                 }
501         } else if ((*gensec_state)->gensec_role == GENSEC_CLIENT) {
502                 reply_code = "AF";
503                 reply_arg = NULL;
504         } else {
505                 abort();
506         }
507
508         switch (stdio_helper_mode) {
509         case GSS_SPNEGO_SERVER:
510                 mux_printf(mux_id, "%s %s %s\n", reply_code, 
511                           out_base64 ? out_base64 : "*", 
512                           reply_arg ? reply_arg : "*");
513                 break;
514         default:
515                 if (out_base64) {
516                         mux_printf(mux_id, "%s %s\n", reply_code, out_base64);
517                 } else if (reply_arg) {
518                         mux_printf(mux_id, "%s %s\n", reply_code, reply_arg);
519                 } else {
520                         mux_printf(mux_id, "%s\n", reply_code);
521                 }
522         }
523
524         SAFE_FREE(out_base64);
525         return;
526 }
527
528 static void manage_ntlm_server_1_request(enum stdio_helper_mode stdio_helper_mode, 
529                                          char *buf, int length, void **private,
530                                          unsigned int mux_id) 
531 {
532         char *request, *parameter;      
533         static DATA_BLOB challenge;
534         static DATA_BLOB lm_response;
535         static DATA_BLOB nt_response;
536         static char *full_username;
537         static char *username;
538         static char *domain;
539         static char *plaintext_password;
540         static BOOL ntlm_server_1_user_session_key;
541         static BOOL ntlm_server_1_lm_session_key;
542         
543         if (strequal(buf, ".")) {
544                 if (!full_username && !username) {      
545                         mux_printf(mux_id, "Error: No username supplied!\n");
546                 } else if (plaintext_password) {
547                         /* handle this request as plaintext */
548                         if (!full_username) {
549                                 if (asprintf(&full_username, "%s%c%s", domain, *lp_winbind_separator(), username) == -1) {
550                                         mux_printf(mux_id, "Error: Out of memory in asprintf!\n.\n");
551                                         return;
552                                 }
553                         }
554                         if (check_plaintext_auth(full_username, plaintext_password, False)) {
555                                 mux_printf(mux_id, "Authenticated: Yes\n");
556                         } else {
557                                 mux_printf(mux_id, "Authenticated: No\n");
558                         }
559                 } else if (!lm_response.data && !nt_response.data) {
560                         mux_printf(mux_id, "Error: No password supplied!\n");
561                 } else if (!challenge.data) {   
562                         mux_printf(mux_id, "Error: No lanman-challenge supplied!\n");
563                 } else {
564                         char *error_string = NULL;
565                         DATA_BLOB lm_key;
566                         DATA_BLOB user_session_key;
567                         uint32 flags = 0;
568
569                         if (full_username && !username) {
570                                 fstring fstr_user;
571                                 fstring fstr_domain;
572                                 
573                                 if (!parse_ntlm_auth_domain_user(full_username, fstr_user, fstr_domain)) {
574                                         /* username might be 'tainted', don't print into our new-line deleimianted stream */
575                                         mux_printf(mux_id, "Error: Could not parse into domain and username\n");
576                                 }
577                                 SAFE_FREE(username);
578                                 SAFE_FREE(domain);
579                                 username = smb_xstrdup(fstr_user);
580                                 domain = smb_xstrdup(fstr_domain);
581                         }
582
583                         if (!domain) {
584                                 domain = smb_xstrdup(lp_workgroup());
585                         }
586
587                         if (ntlm_server_1_lm_session_key) 
588                                 flags |= NTLM_AUTH_FLAG_LMKEY;
589                         
590                         if (ntlm_server_1_user_session_key) 
591                                 flags |= NTLM_AUTH_FLAG_USER_SESSION_KEY;
592
593                         if (!NT_STATUS_IS_OK(
594                                     local_pw_check_specified(username, 
595                                                               domain, 
596                                                               lp_netbios_name(),
597                                                               &challenge, 
598                                                               &lm_response, 
599                                                               &nt_response, 
600                                                               flags, 
601                                                               &lm_key, 
602                                                               &user_session_key,
603                                                               &error_string,
604                                                               NULL))) {
605
606                                 mux_printf(mux_id, "Authenticated: No\n");
607                                 mux_printf(mux_id, "Authentication-Error: %s\n.\n", error_string);
608                                 SAFE_FREE(error_string);
609                         } else {
610                                 static char zeros[16];
611                                 char *hex_lm_key;
612                                 char *hex_user_session_key;
613
614                                 mux_printf(mux_id, "Authenticated: Yes\n");
615
616                                 if (ntlm_server_1_lm_session_key 
617                                     && lm_key.length 
618                                     && (memcmp(zeros, lm_key.data, 
619                                                                 lm_key.length) != 0)) {
620                                         hex_encode(lm_key.data,
621                                                    lm_key.length,
622                                                    &hex_lm_key);
623                                         mux_printf(mux_id, "LANMAN-Session-Key: %s\n", hex_lm_key);
624                                         SAFE_FREE(hex_lm_key);
625                                 }
626
627                                 if (ntlm_server_1_user_session_key 
628                                     && user_session_key.length 
629                                     && (memcmp(zeros, user_session_key.data, 
630                                                user_session_key.length) != 0)) {
631                                         hex_encode(user_session_key.data, 
632                                                    user_session_key.length, 
633                                                    &hex_user_session_key);
634                                         mux_printf(mux_id, "User-Session-Key: %s\n", hex_user_session_key);
635                                         SAFE_FREE(hex_user_session_key);
636                                 }
637                         }
638                 }
639                 /* clear out the state */
640                 challenge = data_blob(NULL, 0);
641                 nt_response = data_blob(NULL, 0);
642                 lm_response = data_blob(NULL, 0);
643                 SAFE_FREE(full_username);
644                 SAFE_FREE(username);
645                 SAFE_FREE(domain);
646                 SAFE_FREE(plaintext_password);
647                 ntlm_server_1_user_session_key = False;
648                 ntlm_server_1_lm_session_key = False;
649                 mux_printf(mux_id, ".\n");
650
651                 return;
652         }
653
654         request = buf;
655
656         /* Indicates a base64 encoded structure */
657         parameter = strstr(request, ":: ");
658         if (!parameter) {
659                 parameter = strstr(request, ": ");
660                 
661                 if (!parameter) {
662                         DEBUG(0, ("Parameter not found!\n"));
663                         mux_printf(mux_id, "Error: Parameter not found!\n.\n");
664                         return;
665                 }
666                 
667                 parameter[0] ='\0';
668                 parameter++;
669                 parameter[0] ='\0';
670                 parameter++;
671
672         } else {
673                 parameter[0] ='\0';
674                 parameter++;
675                 parameter[0] ='\0';
676                 parameter++;
677                 parameter[0] ='\0';
678                 parameter++;
679
680                 base64_decode_inplace(parameter);
681         }
682
683         if (strequal(request, "LANMAN-Challenge")) {
684                 challenge = strhex_to_data_blob(parameter);
685                 if (challenge.length != 8) {
686                         mux_printf(mux_id, "Error: hex decode of %s failed! (got %d bytes, expected 8)\n.\n", 
687                                   parameter,
688                                   (int)challenge.length);
689                         challenge = data_blob(NULL, 0);
690                 }
691         } else if (strequal(request, "NT-Response")) {
692                 nt_response = strhex_to_data_blob(parameter);
693                 if (nt_response.length < 24) {
694                         mux_printf(mux_id, "Error: hex decode of %s failed! (only got %d bytes, needed at least 24)\n.\n", 
695                                   parameter,
696                                   (int)nt_response.length);
697                         nt_response = data_blob(NULL, 0);
698                 }
699         } else if (strequal(request, "LANMAN-Response")) {
700                 lm_response = strhex_to_data_blob(parameter);
701                 if (lm_response.length != 24) {
702                         mux_printf(mux_id, "Error: hex decode of %s failed! (got %d bytes, expected 24)\n.\n", 
703                                   parameter,
704                                   (int)lm_response.length);
705                         lm_response = data_blob(NULL, 0);
706                 }
707         } else if (strequal(request, "Password")) {
708                 plaintext_password = smb_xstrdup(parameter);
709         } else if (strequal(request, "NT-Domain")) {
710                 domain = smb_xstrdup(parameter);
711         } else if (strequal(request, "Username")) {
712                 username = smb_xstrdup(parameter);
713         } else if (strequal(request, "Full-Username")) {
714                 full_username = smb_xstrdup(parameter);
715         } else if (strequal(request, "Request-User-Session-Key")) {
716                 ntlm_server_1_user_session_key = strequal(parameter, "Yes");
717         } else if (strequal(request, "Request-LanMan-Session-Key")) {
718                 ntlm_server_1_lm_session_key = strequal(parameter, "Yes");
719         } else {
720                 mux_printf(mux_id, "Error: Unknown request %s\n.\n", request);
721         }
722 }
723
724 static void manage_squid_request(enum stdio_helper_mode helper_mode, 
725                                  stdio_helper_function fn) 
726 {
727         char buf[SQUID_BUFFER_SIZE+1];
728         unsigned int mux_id;
729         int length;
730         char *c;
731         static BOOL err;
732         struct mux_private {
733                 unsigned int max_mux;
734                 void **private_pointers;
735         };
736         
737         static struct mux_private *mux_private;
738         static void *normal_private;
739         void **private;
740
741         /* this is not a typo - x_fgets doesn't work too well under squid */
742         if (fgets(buf, sizeof(buf)-1, stdin) == NULL) {
743                 if (ferror(stdin)) {
744                         DEBUG(1, ("fgets() failed! dying..... errno=%d (%s)\n", ferror(stdin),
745                                   strerror(ferror(stdin))));
746                         
747                         exit(1);    /* BIIG buffer */
748                 }
749                 exit(0);
750         }
751     
752         c=memchr(buf,'\n',sizeof(buf)-1);
753         if (c) {
754                 *c = '\0';
755                 length = c-buf;
756         } else {
757                 err = 1;
758                 return;
759         }
760         if (err) {
761                 DEBUG(0, ("Oversized message\n"));
762                 x_fprintf(x_stdout, "ERR\n");
763                 err = 0;
764                 return;
765         }
766
767         DEBUG(10, ("Got '%s' from squid (length: %d).\n",buf,length));
768
769         if (buf[0] == '\0') {
770                 DEBUG(0, ("Invalid Request (empty)\n"));
771                 x_fprintf(x_stdout, "ERR\n");
772                 return;
773         }
774
775         if (opt_multiplex) {
776                 if (sscanf(buf, "%u ", &mux_id) != 1) {
777                         DEBUG(0, ("Invalid Request - no multiplex id\n"));
778                         x_fprintf(x_stdout, "ERR\n");
779                         return;
780                 }
781                 if (!mux_private) {
782                         mux_private = talloc_p(NULL, struct mux_private);
783                         mux_private->max_mux = 0;
784                         mux_private->private_pointers = NULL;
785                 }
786                 
787                 c=memchr(buf,' ',sizeof(buf)-1);
788                 c++;
789                 if (mux_id >= mux_private->max_mux) {
790                         unsigned int prev_max = mux_private->max_mux;
791                         mux_private->max_mux = mux_id + 1;
792                         mux_private->private_pointers
793                                 = talloc_realloc_p(mux_private, 
794                                                    mux_private->private_pointers, 
795                                                    void *, mux_private->max_mux);
796                         memset(&mux_private->private_pointers[prev_max], '\0',  
797                                (sizeof(*mux_private->private_pointers) * (mux_private->max_mux - prev_max))); 
798                 };
799
800                 private = &mux_private->private_pointers[mux_id];
801         } else {
802                 c = buf;
803                 private = &normal_private;
804         }
805         
806         fn(helper_mode, c, length, private, mux_id);
807 }
808
809 static void squid_stream(enum stdio_helper_mode stdio_mode, 
810                          stdio_helper_function fn) {
811         /* initialize FDescs */
812         x_setbuf(x_stdout, NULL);
813         x_setbuf(x_stderr, NULL);
814         while(1) {
815                 manage_squid_request(stdio_mode, fn);
816         }
817 }
818
819
820 /* Main program */
821
822 enum {
823         OPT_USERNAME = 1000,
824         OPT_DOMAIN,
825         OPT_WORKSTATION,
826         OPT_CHALLENGE,
827         OPT_RESPONSE,
828         OPT_LM,
829         OPT_NT,
830         OPT_PASSWORD,
831         OPT_LM_KEY,
832         OPT_USER_SESSION_KEY,
833         OPT_DIAGNOSTICS,
834         OPT_REQUIRE_MEMBERSHIP,
835         OPT_MULTIPLEX,
836 };
837
838  int main(int argc, const char **argv)
839 {
840         static const char *helper_protocol;
841         int opt;
842
843         poptContext pc;
844
845         /* NOTE: DO NOT change this interface without considering the implications!
846            This is an external interface, which other programs will use to interact 
847            with this helper.
848         */
849
850         /* We do not use single-letter command abbreviations, because they harm future 
851            interface stability. */
852
853         struct poptOption long_options[] = {
854                 POPT_AUTOHELP
855                 { "helper-protocol", 0, POPT_ARG_STRING, &helper_protocol, OPT_DOMAIN, "operate as a stdio-based helper", "helper protocol to use"},
856                 { "domain", 0, POPT_ARG_STRING, &opt_domain, OPT_DOMAIN, "domain name"},
857                 { "workstation", 0, POPT_ARG_STRING, &opt_workstation, OPT_WORKSTATION, "workstation"},
858                 { "username", 0, POPT_ARG_STRING, &opt_username, OPT_PASSWORD, "Username"},             
859                 { "password", 0, POPT_ARG_STRING, &opt_password, OPT_PASSWORD, "User's plaintext password"},            
860                 { "multiplex", 0, POPT_ARG_NONE, &opt_multiplex, OPT_MULTIPLEX, "Multiplex Mode"},
861                 POPT_COMMON_SAMBA
862                 POPT_TABLEEND
863         };
864
865         /* Samba client initialisation */
866
867         setup_logging("ntlm_auth", DEBUG_STDERR);
868
869         if (!lp_load(dyn_CONFIGFILE, True, False, False)) {
870                 d_fprintf(stderr, "wbinfo: error opening config file %s. Error was %s\n",
871                         dyn_CONFIGFILE, strerror(errno));
872                 exit(1);
873         }
874
875         /* Parse options */
876
877         pc = poptGetContext("ntlm_auth", argc, argv, long_options, 0);
878
879         /* Parse command line options */
880
881         if (argc == 1) {
882                 poptPrintHelp(pc, stderr, 0);
883                 return 1;
884         }
885
886         pc = poptGetContext(NULL, argc, (const char **)argv, long_options, 
887                             POPT_CONTEXT_KEEP_FIRST);
888
889         while((opt = poptGetNextOpt(pc)) != -1) {
890                 if (opt < -1) {
891                         break;
892                 }
893         }
894         if (opt < -1) {
895                 fprintf(stderr, "%s: %s\n",
896                         poptBadOption(pc, POPT_BADOPTION_NOALIAS),
897                         poptStrerror(opt));
898                 return 1;
899         }
900
901         ntlm_auth_init_subsystems;
902
903
904         if (opt_domain == NULL) {
905                 opt_domain = lp_workgroup();
906         }
907
908         if (helper_protocol) {
909                 int i;
910                 for (i=0; i<NUM_HELPER_MODES; i++) {
911                         if (strcmp(helper_protocol, stdio_helper_protocols[i].name) == 0) {
912                                 squid_stream(stdio_helper_protocols[i].mode, stdio_helper_protocols[i].fn);
913                                 exit(0);
914                         }
915                 }
916                 x_fprintf(x_stderr, "unknown helper protocol [%s]\n\nValid helper protools:\n\n", helper_protocol);
917
918                 for (i=0; i<NUM_HELPER_MODES; i++) {
919                         x_fprintf(x_stderr, "%s\n", stdio_helper_protocols[i].name);
920                 }
921
922                 exit(1);
923         }
924
925         if (!opt_username) {
926                 x_fprintf(x_stderr, "username must be specified!\n\n");
927                 poptPrintHelp(pc, stderr, 0);
928                 exit(1);
929         }
930
931         if (opt_workstation == NULL) {
932                 opt_workstation = lp_netbios_name();
933         }
934
935         if (!opt_password) {
936                 opt_password = getpass("password: ");
937         }
938
939         {
940                 char *user;
941
942                 asprintf(&user, "%s%c%s", opt_domain, *lp_winbind_separator(), opt_username);
943                 if (!check_plaintext_auth(user, opt_password, True)) {
944                         return 1;
945                 }
946         }
947
948         /* Exit code */
949
950         poptFreeContext(pc);
951         return 0;
952 }