r8901: Fix ntlm_auth segfault (invalid free()). We have moved to talloc
[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/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         struct samr_Password lm_pw, nt_pw;
157         struct samr_Password *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.hash);
164                 if (E_deshash(opt_password, lm_pw.hash)) {
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                                                 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_free(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, void **private2) 
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, void **password)  
237 {
238         DATA_BLOB in;
239         if (strlen(buf) < 2) {
240                 DEBUG(1, ("query [%s] invalid", buf));
241                 mux_printf(mux_id, "BH\n");
242                 return;
243         }
244
245         if (strlen(buf) > 3) {
246                 in = base64_decode_data_blob(NULL, buf + 3);
247         } else {
248                 in = data_blob(NULL, 0);
249         }
250
251         if (strncmp(buf, "PW ", 3) == 0) {
252
253                 *password = talloc_strndup(*private /* hopefully the right gensec context, useful to use for talloc */,
254                                            (const char *)in.data, in.length);
255                 
256                 if (*password == NULL) {
257                         DEBUG(1, ("Out of memory\n"));
258                         mux_printf(mux_id, "BH\n");
259                         data_blob_free(&in);
260                         return;
261                 }
262
263                 mux_printf(mux_id, "OK\n");
264                 data_blob_free(&in);
265                 return;
266         }
267         DEBUG(1, ("Asked for (and expected) a password\n"));
268         mux_printf(mux_id, "BH\n");
269         data_blob_free(&in);
270 }
271
272 /** 
273  * Callback for password credentails.  This is not async, and when
274  * GENSEC and the credentails code is made async, it will look rather
275  * different.
276  */
277
278 static const char *get_password(struct cli_credentials *credentials) 
279 {
280         char *password = NULL;
281         
282         /* Ask for a password */
283         mux_printf((unsigned int)credentials->priv_data, "PW\n");
284         credentials->priv_data = NULL;
285
286         manage_squid_request(NUM_HELPER_MODES /* bogus */, manage_gensec_get_pw_request, (void **)&password);
287         return password;
288 }
289
290 static void manage_gensec_request(enum stdio_helper_mode stdio_helper_mode, 
291                                   char *buf, int length, void **private,
292                                   unsigned int mux_id, void **private2) 
293 {
294         DATA_BLOB in;
295         DATA_BLOB out = data_blob(NULL, 0);
296         char *out_base64 = NULL;
297         const char *reply_arg = NULL;
298         struct gensec_security **gensec_state = (struct gensec_security **)private;
299         NTSTATUS nt_status;
300         BOOL first = False;
301         const char *reply_code;
302         struct cli_credentials *creds;
303
304         TALLOC_CTX *mem_ctx;
305         
306         if (strlen(buf) < 2) {
307                 DEBUG(1, ("query [%s] invalid", buf));
308                 mux_printf(mux_id, "BH\n");
309                 return;
310         }
311
312         if (strlen(buf) > 3) {
313                 in = base64_decode_data_blob(NULL, buf + 3);
314         } else {
315                 in = data_blob(NULL, 0);
316         }
317
318         if (strncmp(buf, "YR", 2) == 0) {
319                 if (gensec_state && *gensec_state) {
320                         talloc_free(*gensec_state);
321                         *gensec_state = NULL;
322                 }
323         } else if ( (strncmp(buf, "OK", 2) == 0)) {
324                 /* do nothing */
325                 data_blob_free(&in);
326                 return;
327         } else if ( (strncmp(buf, "TT ", 3) != 0) &&
328                     (strncmp(buf, "KK ", 3) != 0) &&
329                     (strncmp(buf, "AF ", 3) != 0) &&
330                     (strncmp(buf, "NA ", 3) != 0) && 
331                     (strncmp(buf, "UG", 2) != 0) && 
332                     (strncmp(buf, "PW ", 3) != 0)) {
333                 DEBUG(1, ("SPNEGO request [%s] invalid\n", buf));
334                 mux_printf(mux_id, "BH\n");
335                 data_blob_free(&in);
336                 return;
337         }
338
339         /* setup gensec */
340         if (!(gensec_state && *gensec_state)) {
341                 switch (stdio_helper_mode) {
342                 case GSS_SPNEGO_CLIENT:
343                 case NTLMSSP_CLIENT_1:
344                         /* setup the client side */
345
346                         nt_status = gensec_client_start(NULL, gensec_state, NULL);
347                         if (!NT_STATUS_IS_OK(nt_status)) {
348                                 exit(1);
349                         }
350
351                         creds = cli_credentials_init(*gensec_state);
352                         cli_credentials_set_conf(creds);
353                         if (opt_username) {
354                                 cli_credentials_set_username(creds, opt_username, CRED_SPECIFIED);
355                         } 
356                         if (opt_domain) {
357                                 cli_credentials_set_domain(creds, opt_domain, CRED_SPECIFIED);
358                         }
359                         if (opt_password) {
360                                 cli_credentials_set_password(creds, opt_password, CRED_SPECIFIED);
361                         } else {
362                                 creds->password_obtained = CRED_CALLBACK;
363                                 creds->password_cb = get_password;
364                                 creds->priv_data = (void*)mux_id;
365                         }
366
367                         gensec_set_credentials(*gensec_state, creds);
368
369                         break;
370                 case GSS_SPNEGO_SERVER:
371                 case SQUID_2_5_NTLMSSP:
372                         if (!NT_STATUS_IS_OK(gensec_server_start(NULL, gensec_state, NULL))) {
373                                 exit(1);
374                         }
375                         break;
376                 default:
377                         abort();
378                 }
379
380                 switch (stdio_helper_mode) {
381                 case GSS_SPNEGO_CLIENT:
382                 case GSS_SPNEGO_SERVER:
383                         nt_status = gensec_start_mech_by_oid(*gensec_state, GENSEC_OID_SPNEGO);
384                         if (!in.length) {
385                                 first = True;
386                         }
387                         break;
388                 case NTLMSSP_CLIENT_1:
389                         if (!in.length) {
390                                 first = True;
391                         }
392                 case SQUID_2_5_NTLMSSP:
393                         nt_status = gensec_start_mech_by_oid(*gensec_state, GENSEC_OID_NTLMSSP);
394                         break;
395                 default:
396                         abort();
397                 }
398
399                 if (!NT_STATUS_IS_OK(nt_status)) {
400                         DEBUG(1, ("GENSEC mech failed to start: %s\n", nt_errstr(nt_status)));
401                         mux_printf(mux_id, "BH\n");
402                         return;
403                 }
404         }
405         
406         if (strncmp(buf, "PW ", 3) == 0) {
407
408                 cli_credentials_set_password((*gensec_state)->credentials, 
409                                              talloc_strndup((*gensec_state), 
410                                                             (const char *)in.data, 
411                                                             in.length),
412                                              CRED_SPECIFIED);
413                 mux_printf(mux_id, "OK\n");
414                 data_blob_free(&in);
415                 return;
416         }
417
418         /* update */
419         mem_ctx = talloc_named(NULL, 0, "manage_gensec_request internal mem_ctx");
420         
421         if (strncmp(buf, "UG", 2) == 0) {
422                 int i;
423                 char *grouplist = NULL;
424                 struct auth_session_info *session_info;
425
426                 if (!NT_STATUS_IS_OK(gensec_session_info(*gensec_state, &session_info))) { 
427                         DEBUG(1, ("gensec_session_info failed: %s\n", nt_errstr(nt_status)));
428                         mux_printf(mux_id, "BH %s\n", nt_errstr(nt_status));
429                         data_blob_free(&in);
430                         return;
431                 }
432                 
433                 /* get the string onto the context */
434                 grouplist = talloc_strdup(mem_ctx, "");
435                 
436                 for (i=0; i<session_info->security_token->num_sids; i++) {
437                         struct security_token *token = session_info->security_token; 
438                         const char *sidstr = dom_sid_string(session_info, 
439                                                             token->sids[i]);
440                         grouplist = talloc_asprintf_append(grouplist, "%s,", sidstr);
441                 }
442
443                 mux_printf(mux_id, "GL %s\n", grouplist);
444                 talloc_free(session_info);
445                 data_blob_free(&in);
446                 talloc_free(mem_ctx);
447                 return;
448         }
449
450         nt_status = gensec_update(*gensec_state, mem_ctx, 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(mem_ctx, out);
457         } else {
458                 out_base64 = NULL;
459         }
460
461         if (NT_STATUS_EQUAL(nt_status, NT_STATUS_MORE_PROCESSING_REQUIRED)) {
462                 reply_arg = "*";
463                 if (first) {
464                         reply_code = "YR";
465                 } else if ((*gensec_state)->gensec_role == GENSEC_CLIENT) { 
466                         reply_code = "KK";
467                 } else if ((*gensec_state)->gensec_role == GENSEC_SERVER) { 
468                         reply_code = "TT";
469                 } else {
470                         abort();
471                 }
472
473
474         } else if (NT_STATUS_EQUAL(nt_status, NT_STATUS_ACCESS_DENIED)) {
475                 reply_code = "BH";
476                 reply_arg = nt_errstr(nt_status);
477                 DEBUG(1, ("GENSEC login failed: %s\n", nt_errstr(nt_status)));
478         } else if (NT_STATUS_EQUAL(nt_status, NT_STATUS_UNSUCCESSFUL)) {
479                 reply_code = "BH";
480                 reply_arg = nt_errstr(nt_status);
481                 DEBUG(1, ("GENSEC login failed: %s\n", nt_errstr(nt_status)));
482         } else if (!NT_STATUS_IS_OK(nt_status)) {
483                 reply_code = "NA";
484                 reply_arg = nt_errstr(nt_status);
485                 DEBUG(1, ("GENSEC login failed: %s\n", nt_errstr(nt_status)));
486         } else if /* OK */ ((*gensec_state)->gensec_role == GENSEC_SERVER) {
487                 struct auth_session_info *session_info;
488
489                 nt_status = gensec_session_info(*gensec_state, &session_info);
490                 if (!NT_STATUS_IS_OK(nt_status)) {
491                         reply_code = "BH";
492                         reply_arg = nt_errstr(nt_status);
493                         DEBUG(1, ("GENSEC failed to retreive the session info: %s\n", nt_errstr(nt_status)));
494                 } else {
495
496                         reply_code = "AF";
497                         reply_arg = talloc_asprintf(*gensec_state, 
498                                                     "%s%s%s", session_info->server_info->domain_name, 
499                                                     lp_winbind_separator(), session_info->server_info->account_name);
500                         talloc_free(session_info);
501                 }
502         } else if ((*gensec_state)->gensec_role == GENSEC_CLIENT) {
503                 reply_code = "AF";
504                 reply_arg = NULL;
505         } else {
506                 abort();
507         }
508
509         switch (stdio_helper_mode) {
510         case GSS_SPNEGO_SERVER:
511                 mux_printf(mux_id, "%s %s %s\n", reply_code, 
512                           out_base64 ? out_base64 : "*", 
513                           reply_arg ? reply_arg : "*");
514                 break;
515         default:
516                 if (out_base64) {
517                         mux_printf(mux_id, "%s %s\n", reply_code, out_base64);
518                 } else if (reply_arg) {
519                         mux_printf(mux_id, "%s %s\n", reply_code, reply_arg);
520                 } else {
521                         mux_printf(mux_id, "%s\n", reply_code);
522                 }
523         }
524
525         talloc_free(mem_ctx);
526         return;
527 }
528
529 static void manage_ntlm_server_1_request(enum stdio_helper_mode stdio_helper_mode, 
530                                          char *buf, int length, void **private,
531                                          unsigned int mux_id, void **private2) 
532 {
533         char *request, *parameter;      
534         static DATA_BLOB challenge;
535         static DATA_BLOB lm_response;
536         static DATA_BLOB nt_response;
537         static char *full_username;
538         static char *username;
539         static char *domain;
540         static char *plaintext_password;
541         static BOOL ntlm_server_1_user_session_key;
542         static BOOL ntlm_server_1_lm_session_key;
543         
544         if (strequal(buf, ".")) {
545                 if (!full_username && !username) {      
546                         mux_printf(mux_id, "Error: No username supplied!\n");
547                 } else if (plaintext_password) {
548                         /* handle this request as plaintext */
549                         if (!full_username) {
550                                 if (asprintf(&full_username, "%s%c%s", domain, *lp_winbind_separator(), username) == -1) {
551                                         mux_printf(mux_id, "Error: Out of memory in asprintf!\n.\n");
552                                         return;
553                                 }
554                         }
555                         if (check_plaintext_auth(full_username, plaintext_password, False)) {
556                                 mux_printf(mux_id, "Authenticated: Yes\n");
557                         } else {
558                                 mux_printf(mux_id, "Authenticated: No\n");
559                         }
560                 } else if (!lm_response.data && !nt_response.data) {
561                         mux_printf(mux_id, "Error: No password supplied!\n");
562                 } else if (!challenge.data) {   
563                         mux_printf(mux_id, "Error: No lanman-challenge supplied!\n");
564                 } else {
565                         char *error_string = NULL;
566                         DATA_BLOB lm_key;
567                         DATA_BLOB user_session_key;
568                         uint32_t flags = 0;
569
570                         if (full_username && !username) {
571                                 fstring fstr_user;
572                                 fstring fstr_domain;
573                                 
574                                 if (!parse_ntlm_auth_domain_user(full_username, fstr_user, fstr_domain)) {
575                                         /* username might be 'tainted', don't print into our new-line deleimianted stream */
576                                         mux_printf(mux_id, "Error: Could not parse into domain and username\n");
577                                 }
578                                 SAFE_FREE(username);
579                                 SAFE_FREE(domain);
580                                 username = smb_xstrdup(fstr_user);
581                                 domain = smb_xstrdup(fstr_domain);
582                         }
583
584                         if (!domain) {
585                                 domain = smb_xstrdup(lp_workgroup());
586                         }
587
588                         if (ntlm_server_1_lm_session_key) 
589                                 flags |= NTLM_AUTH_FLAG_LMKEY;
590                         
591                         if (ntlm_server_1_user_session_key) 
592                                 flags |= NTLM_AUTH_FLAG_USER_SESSION_KEY;
593
594                         if (!NT_STATUS_IS_OK(
595                                     local_pw_check_specified(username, 
596                                                               domain, 
597                                                               lp_netbios_name(),
598                                                               &challenge, 
599                                                               &lm_response, 
600                                                               &nt_response, 
601                                                               flags, 
602                                                               &lm_key, 
603                                                               &user_session_key,
604                                                               &error_string,
605                                                               NULL))) {
606
607                                 mux_printf(mux_id, "Authenticated: No\n");
608                                 mux_printf(mux_id, "Authentication-Error: %s\n.\n", error_string);
609                                 SAFE_FREE(error_string);
610                         } else {
611                                 static char zeros[16];
612                                 char *hex_lm_key;
613                                 char *hex_user_session_key;
614
615                                 mux_printf(mux_id, "Authenticated: Yes\n");
616
617                                 if (ntlm_server_1_lm_session_key 
618                                     && lm_key.length 
619                                     && (memcmp(zeros, lm_key.data, 
620                                                                 lm_key.length) != 0)) {
621                                         hex_encode(lm_key.data,
622                                                    lm_key.length,
623                                                    &hex_lm_key);
624                                         mux_printf(mux_id, "LANMAN-Session-Key: %s\n", hex_lm_key);
625                                         SAFE_FREE(hex_lm_key);
626                                 }
627
628                                 if (ntlm_server_1_user_session_key 
629                                     && user_session_key.length 
630                                     && (memcmp(zeros, user_session_key.data, 
631                                                user_session_key.length) != 0)) {
632                                         hex_encode(user_session_key.data, 
633                                                    user_session_key.length, 
634                                                    &hex_user_session_key);
635                                         mux_printf(mux_id, "User-Session-Key: %s\n", hex_user_session_key);
636                                         SAFE_FREE(hex_user_session_key);
637                                 }
638                         }
639                 }
640                 /* clear out the state */
641                 challenge = data_blob(NULL, 0);
642                 nt_response = data_blob(NULL, 0);
643                 lm_response = data_blob(NULL, 0);
644                 SAFE_FREE(full_username);
645                 SAFE_FREE(username);
646                 SAFE_FREE(domain);
647                 SAFE_FREE(plaintext_password);
648                 ntlm_server_1_user_session_key = False;
649                 ntlm_server_1_lm_session_key = False;
650                 mux_printf(mux_id, ".\n");
651
652                 return;
653         }
654
655         request = buf;
656
657         /* Indicates a base64 encoded structure */
658         parameter = strstr(request, ":: ");
659         if (!parameter) {
660                 parameter = strstr(request, ": ");
661                 
662                 if (!parameter) {
663                         DEBUG(0, ("Parameter not found!\n"));
664                         mux_printf(mux_id, "Error: Parameter not found!\n.\n");
665                         return;
666                 }
667                 
668                 parameter[0] ='\0';
669                 parameter++;
670                 parameter[0] ='\0';
671                 parameter++;
672
673         } else {
674                 parameter[0] ='\0';
675                 parameter++;
676                 parameter[0] ='\0';
677                 parameter++;
678                 parameter[0] ='\0';
679                 parameter++;
680
681                 base64_decode_inplace(parameter);
682         }
683
684         if (strequal(request, "LANMAN-Challenge")) {
685                 challenge = strhex_to_data_blob(parameter);
686                 if (challenge.length != 8) {
687                         mux_printf(mux_id, "Error: hex decode of %s failed! (got %d bytes, expected 8)\n.\n", 
688                                   parameter,
689                                   (int)challenge.length);
690                         challenge = data_blob(NULL, 0);
691                 }
692         } else if (strequal(request, "NT-Response")) {
693                 nt_response = strhex_to_data_blob(parameter);
694                 if (nt_response.length < 24) {
695                         mux_printf(mux_id, "Error: hex decode of %s failed! (only got %d bytes, needed at least 24)\n.\n", 
696                                   parameter,
697                                   (int)nt_response.length);
698                         nt_response = data_blob(NULL, 0);
699                 }
700         } else if (strequal(request, "LANMAN-Response")) {
701                 lm_response = strhex_to_data_blob(parameter);
702                 if (lm_response.length != 24) {
703                         mux_printf(mux_id, "Error: hex decode of %s failed! (got %d bytes, expected 24)\n.\n", 
704                                   parameter,
705                                   (int)lm_response.length);
706                         lm_response = data_blob(NULL, 0);
707                 }
708         } else if (strequal(request, "Password")) {
709                 plaintext_password = smb_xstrdup(parameter);
710         } else if (strequal(request, "NT-Domain")) {
711                 domain = smb_xstrdup(parameter);
712         } else if (strequal(request, "Username")) {
713                 username = smb_xstrdup(parameter);
714         } else if (strequal(request, "Full-Username")) {
715                 full_username = smb_xstrdup(parameter);
716         } else if (strequal(request, "Request-User-Session-Key")) {
717                 ntlm_server_1_user_session_key = strequal(parameter, "Yes");
718         } else if (strequal(request, "Request-LanMan-Session-Key")) {
719                 ntlm_server_1_lm_session_key = strequal(parameter, "Yes");
720         } else {
721                 mux_printf(mux_id, "Error: Unknown request %s\n.\n", request);
722         }
723 }
724
725 static void manage_squid_request(enum stdio_helper_mode helper_mode, 
726                                  stdio_helper_function fn, void **private2) 
727 {
728         char buf[SQUID_BUFFER_SIZE+1];
729         unsigned int mux_id;
730         int length;
731         char *c;
732         static BOOL err;
733         struct mux_private {
734                 unsigned int max_mux;
735                 void **private_pointers;
736         };
737         
738         static struct mux_private *mux_private;
739         static void *normal_private;
740         void **private;
741
742         /* this is not a typo - x_fgets doesn't work too well under squid */
743         if (fgets(buf, sizeof(buf)-1, stdin) == NULL) {
744                 if (ferror(stdin)) {
745                         DEBUG(1, ("fgets() failed! dying..... errno=%d (%s)\n", ferror(stdin),
746                                   strerror(ferror(stdin))));
747                         
748                         exit(1);    /* BIIG buffer */
749                 }
750                 exit(0);
751         }
752     
753         c=memchr(buf,'\n',sizeof(buf)-1);
754         if (c) {
755                 *c = '\0';
756                 length = c-buf;
757         } else {
758                 err = 1;
759                 return;
760         }
761         if (err) {
762                 DEBUG(0, ("Oversized message\n"));
763                 x_fprintf(x_stdout, "ERR\n");
764                 err = 0;
765                 return;
766         }
767
768         DEBUG(10, ("Got '%s' from squid (length: %d).\n",buf,length));
769
770         if (buf[0] == '\0') {
771                 DEBUG(0, ("Invalid Request (empty)\n"));
772                 x_fprintf(x_stdout, "ERR\n");
773                 return;
774         }
775
776         if (opt_multiplex) {
777                 if (sscanf(buf, "%u ", &mux_id) != 1) {
778                         DEBUG(0, ("Invalid Request - no multiplex id\n"));
779                         x_fprintf(x_stdout, "ERR\n");
780                         return;
781                 }
782                 if (!mux_private) {
783                         mux_private = talloc(NULL, struct mux_private);
784                         mux_private->max_mux = 0;
785                         mux_private->private_pointers = NULL;
786                 }
787                 
788                 c=strchr(buf,' ');
789                 if (!c) {
790                         DEBUG(0, ("Invalid Request - no data after multiplex id\n"));
791                         x_fprintf(x_stdout, "ERR\n");
792                         return;
793                 }
794                 c++;
795                 if (mux_id >= mux_private->max_mux) {
796                         unsigned int prev_max = mux_private->max_mux;
797                         mux_private->max_mux = mux_id + 1;
798                         mux_private->private_pointers
799                                 = talloc_realloc(mux_private, 
800                                                    mux_private->private_pointers, 
801                                                    void *, mux_private->max_mux);
802                         memset(&mux_private->private_pointers[prev_max], '\0',  
803                                (sizeof(*mux_private->private_pointers) * (mux_private->max_mux - prev_max))); 
804                 };
805
806                 private = &mux_private->private_pointers[mux_id];
807         } else {
808                 c = buf;
809                 private = &normal_private;
810         }
811         
812         fn(helper_mode, c, length, private, mux_id, private2);
813 }
814
815 static void squid_stream(enum stdio_helper_mode stdio_mode, 
816                          stdio_helper_function fn) {
817         /* initialize FDescs */
818         x_setbuf(x_stdout, NULL);
819         x_setbuf(x_stderr, NULL);
820         while(1) {
821                 manage_squid_request(stdio_mode, fn, NULL);
822         }
823 }
824
825
826 /* Main program */
827
828 enum {
829         OPT_USERNAME = 1000,
830         OPT_DOMAIN,
831         OPT_WORKSTATION,
832         OPT_CHALLENGE,
833         OPT_RESPONSE,
834         OPT_LM,
835         OPT_NT,
836         OPT_PASSWORD,
837         OPT_LM_KEY,
838         OPT_USER_SESSION_KEY,
839         OPT_DIAGNOSTICS,
840         OPT_REQUIRE_MEMBERSHIP,
841         OPT_MULTIPLEX,
842 };
843
844  int main(int argc, const char **argv)
845 {
846         static const char *helper_protocol;
847         int opt;
848
849         poptContext pc;
850
851         /* NOTE: DO NOT change this interface without considering the implications!
852            This is an external interface, which other programs will use to interact 
853            with this helper.
854         */
855
856         /* We do not use single-letter command abbreviations, because they harm future 
857            interface stability. */
858
859         struct poptOption long_options[] = {
860                 POPT_AUTOHELP
861                 { "helper-protocol", 0, POPT_ARG_STRING, &helper_protocol, OPT_DOMAIN, "operate as a stdio-based helper", "helper protocol to use"},
862                 { "domain", 0, POPT_ARG_STRING, &opt_domain, OPT_DOMAIN, "domain name"},
863                 { "workstation", 0, POPT_ARG_STRING, &opt_workstation, OPT_WORKSTATION, "workstation"},
864                 { "username", 0, POPT_ARG_STRING, &opt_username, OPT_PASSWORD, "Username"},             
865                 { "password", 0, POPT_ARG_STRING, &opt_password, OPT_PASSWORD, "User's plaintext password"},            
866                 { "multiplex", 0, POPT_ARG_NONE, &opt_multiplex, OPT_MULTIPLEX, "Multiplex Mode"},
867                 POPT_COMMON_SAMBA
868                 POPT_TABLEEND
869         };
870
871         /* Samba client initialisation */
872
873         setup_logging(NULL, DEBUG_STDERR);
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 }