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