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