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