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