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