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