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