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