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