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