r25007: Remove more uses of pstring, move ntlmauth-specific utility function to ntlm...
[kai/samba.git] / source4 / utils / ntlm_auth.c
1 /* 
2    Unix SMB/CIFS implementation.
3
4    Winbind status program.
5
6    Copyright (C) Tim Potter      2000-2003
7    Copyright (C) Andrew Bartlett <abartlet@samba.org> 2003-2004
8    Copyright (C) Francesco Chemolli <kinkie@kame.usr.dsi.unimi.it> 2000 
9
10    This program is free software; you can redistribute it and/or modify
11    it under the terms of the GNU General Public License as published by
12    the Free Software Foundation; either version 3 of the License, or
13    (at your option) any later version.
14    
15    This program is distributed in the hope that it will be useful,
16    but WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18    GNU General Public License for more details.
19    
20    You should have received a copy of the GNU General Public License
21    along with this program.  If not, see <http://www.gnu.org/licenses/>.
22 */
23
24 #include "includes.h"
25 #include "system/filesys.h"
26 #include "lib/cmdline/popt_common.h"
27 #include "lib/ldb/include/ldb.h"
28 #include "auth/credentials/credentials.h"
29 #include "auth/gensec/gensec.h"
30 #include "auth/auth.h"
31 #include "librpc/gen_ndr/ndr_netlogon.h"
32 #include "auth/auth_sam.h"
33 #include "pstring.h"
34 #include "libcli/auth/libcli_auth.h"
35 #include "libcli/security/security.h"
36 #include "lib/events/events.h"
37 #include "lib/messaging/messaging.h"
38 #include "lib/messaging/irpc.h"
39 #include "auth/ntlmssp/ntlmssp.h"
40
41 #define INITIAL_BUFFER_SIZE 300
42 #define MAX_BUFFER_SIZE 63000
43
44 enum stdio_helper_mode {
45         SQUID_2_4_BASIC,
46         SQUID_2_5_BASIC,
47         SQUID_2_5_NTLMSSP,
48         NTLMSSP_CLIENT_1,
49         GSS_SPNEGO_CLIENT,
50         GSS_SPNEGO_SERVER,
51         NTLM_SERVER_1,
52         NUM_HELPER_MODES
53 };
54
55 #define NTLM_AUTH_FLAG_USER_SESSION_KEY     0x0004
56 #define NTLM_AUTH_FLAG_LMKEY                0x0008
57
58
59 typedef void (*stdio_helper_function)(enum stdio_helper_mode stdio_helper_mode, 
60                                       char *buf, int length, void **private,
61                                       unsigned int mux_id, void **private2);
62
63 static void manage_squid_basic_request (enum stdio_helper_mode stdio_helper_mode, 
64                                         char *buf, int length, void **private,
65                                         unsigned int mux_id, void **private2);
66
67 static void manage_gensec_request (enum stdio_helper_mode stdio_helper_mode, 
68                                    char *buf, int length, void **private,
69                                    unsigned int mux_id, void **private2);
70
71 static void manage_ntlm_server_1_request (enum stdio_helper_mode stdio_helper_mode, 
72                                           char *buf, int length, void **private,
73                                           unsigned int mux_id, void **private2);
74
75 static void manage_squid_request(enum stdio_helper_mode helper_mode, 
76                                  stdio_helper_function fn, void **private2);
77
78 static const struct {
79         enum stdio_helper_mode mode;
80         const char *name;
81         stdio_helper_function fn;
82 } stdio_helper_protocols[] = {
83         { SQUID_2_4_BASIC, "squid-2.4-basic", manage_squid_basic_request},
84         { SQUID_2_5_BASIC, "squid-2.5-basic", manage_squid_basic_request},
85         { SQUID_2_5_NTLMSSP, "squid-2.5-ntlmssp", manage_gensec_request},
86         { GSS_SPNEGO_CLIENT, "gss-spnego-client", manage_gensec_request},
87         { GSS_SPNEGO_SERVER, "gss-spnego", manage_gensec_request},
88         { NTLMSSP_CLIENT_1, "ntlmssp-client-1", manage_gensec_request},
89         { NTLM_SERVER_1, "ntlm-server-1", manage_ntlm_server_1_request},
90         { NUM_HELPER_MODES, NULL, NULL}
91 };
92
93 extern int winbindd_fd;
94
95 static const char *opt_username;
96 static const char *opt_domain;
97 static const char *opt_workstation;
98 static const char *opt_password;
99 static int opt_multiplex;
100 static int use_cached_creds;
101
102
103 static void mux_printf(unsigned int mux_id, const char *format, ...) PRINTF_ATTRIBUTE(2, 3);
104
105 static void mux_printf(unsigned int mux_id, const char *format, ...)
106 {
107         va_list ap;
108
109         if (opt_multiplex) {
110                 x_fprintf(x_stdout, "%d ", mux_id);
111         }
112
113         va_start(ap, format);
114         x_vfprintf(x_stdout, format, ap);
115         va_end(ap);
116 }
117
118
119
120 /* Copy of parse_domain_user from winbindd_util.c.  Parse a string of the
121    form DOMAIN/user into a domain and a user */
122
123 static bool parse_ntlm_auth_domain_user(const char *domuser, fstring domain, 
124                                         fstring user)
125 {
126
127         char *p = strchr(domuser,*lp_winbind_separator());
128
129         if (!p) {
130                 return False;
131         }
132         
133         fstrcpy(user, p+1);
134         fstrcpy(domain, domuser);
135         domain[PTR_DIFF(p, domuser)] = 0;
136
137         return True;
138 }
139
140 /**
141  * Decode a base64 string into a DATA_BLOB - simple and slow algorithm
142  **/
143 static DATA_BLOB base64_decode_data_blob(TALLOC_CTX *mem_ctx, const char *s)
144 {
145         DATA_BLOB ret = data_blob_talloc(mem_ctx, s, strlen(s)+1);
146         ret.length = ldb_base64_decode((char *)ret.data);
147         return ret;
148 }
149
150 /**
151  * Encode a base64 string into a talloc()ed string caller to free.
152  **/
153 static char *base64_encode_data_blob(TALLOC_CTX *mem_ctx, DATA_BLOB data)
154 {
155         return ldb_base64_encode(mem_ctx, (const char *)data.data, data.length);
156 }
157
158 /**
159  * Decode a base64 string in-place - wrapper for the above
160  **/
161 static void base64_decode_inplace(char *s)
162 {
163         ldb_base64_decode(s);
164 }
165
166
167
168 /* Authenticate a user with a plaintext password */
169
170 static BOOL check_plaintext_auth(const char *user, const char *pass, 
171                                  BOOL stdout_diagnostics)
172 {
173         return (strcmp(pass, opt_password) == 0);
174 }
175
176 /* authenticate a user with an encrypted username/password */
177
178 static NTSTATUS local_pw_check_specified(const char *username, 
179                                          const char *domain, 
180                                          const char *workstation,
181                                          const DATA_BLOB *challenge, 
182                                          const DATA_BLOB *lm_response, 
183                                          const DATA_BLOB *nt_response, 
184                                          uint32_t flags, 
185                                          DATA_BLOB *lm_session_key, 
186                                          DATA_BLOB *user_session_key, 
187                                          char **error_string, 
188                                          char **unix_name) 
189 {
190         NTSTATUS nt_status;
191         struct samr_Password lm_pw, nt_pw;
192         struct samr_Password *lm_pwd, *nt_pwd;
193         TALLOC_CTX *mem_ctx = talloc_init("local_pw_check_specified");
194         if (!mem_ctx) {
195                 nt_status = NT_STATUS_NO_MEMORY;
196         } else {
197                 
198                 E_md4hash(opt_password, nt_pw.hash);
199                 if (E_deshash(opt_password, lm_pw.hash)) {
200                         lm_pwd = &lm_pw;
201                 } else {
202                         lm_pwd = NULL;
203                 }
204                 nt_pwd = &nt_pw;
205                 
206                 
207                 nt_status = ntlm_password_check(mem_ctx, 
208                                                 MSV1_0_ALLOW_SERVER_TRUST_ACCOUNT |
209                                                 MSV1_0_ALLOW_WORKSTATION_TRUST_ACCOUNT,
210                                                 challenge,
211                                                 lm_response,
212                                                 nt_response,
213                                                 username,
214                                                 username,
215                                                 domain,
216                                                 lm_pwd, nt_pwd, user_session_key, lm_session_key);
217                 
218                 if (NT_STATUS_IS_OK(nt_status)) {
219                         if (unix_name) {
220                                 asprintf(unix_name, 
221                                          "%s%c%s", domain,
222                                          *lp_winbind_separator(), 
223                                          username);
224                         }
225                 } else {
226                         DEBUG(3, ("Login for user [%s]\\[%s]@[%s] failed due to [%s]\n", 
227                                   domain, username, workstation, 
228                                   nt_errstr(nt_status)));
229                 }
230                 talloc_free(mem_ctx);
231         }
232         if (error_string) {
233                 *error_string = strdup(nt_errstr(nt_status));
234         }
235         return nt_status;
236         
237         
238 }
239
240 static void manage_squid_basic_request(enum stdio_helper_mode stdio_helper_mode, 
241                                        char *buf, int length, void **private,
242                                        unsigned int mux_id, void **private2) 
243 {
244         char *user, *pass;      
245         user=buf;
246         
247         pass = memchr(buf, ' ', length);
248         if (!pass) {
249                 DEBUG(2, ("Password not found. Denying access\n"));
250                 mux_printf(mux_id, "ERR\n");
251                 return;
252         }
253         *pass='\0';
254         pass++;
255         
256         if (stdio_helper_mode == SQUID_2_5_BASIC) {
257                 rfc1738_unescape(user);
258                 rfc1738_unescape(pass);
259         }
260         
261         if (check_plaintext_auth(user, pass, False)) {
262                 mux_printf(mux_id, "OK\n");
263         } else {
264                 mux_printf(mux_id, "ERR\n");
265         }
266 }
267
268 /* This is a bit hairy, but the basic idea is to do a password callback
269    to the calling application.  The callback comes from within gensec */
270
271 static void manage_gensec_get_pw_request(enum stdio_helper_mode stdio_helper_mode, 
272                                          char *buf, int length, void **private,
273                                          unsigned int mux_id, void **password)  
274 {
275         DATA_BLOB in;
276         if (strlen(buf) < 2) {
277                 DEBUG(1, ("query [%s] invalid", buf));
278                 mux_printf(mux_id, "BH\n");
279                 return;
280         }
281
282         if (strlen(buf) > 3) {
283                 in = base64_decode_data_blob(NULL, buf + 3);
284         } else {
285                 in = data_blob(NULL, 0);
286         }
287
288         if (strncmp(buf, "PW ", 3) == 0) {
289
290                 *password = talloc_strndup(*private /* hopefully the right gensec context, useful to use for talloc */,
291                                            (const char *)in.data, in.length);
292                 
293                 if (*password == NULL) {
294                         DEBUG(1, ("Out of memory\n"));
295                         mux_printf(mux_id, "BH\n");
296                         data_blob_free(&in);
297                         return;
298                 }
299
300                 mux_printf(mux_id, "OK\n");
301                 data_blob_free(&in);
302                 return;
303         }
304         DEBUG(1, ("Asked for (and expected) a password\n"));
305         mux_printf(mux_id, "BH\n");
306         data_blob_free(&in);
307 }
308
309 /** 
310  * Callback for password credentails.  This is not async, and when
311  * GENSEC and the credentails code is made async, it will look rather
312  * different.
313  */
314
315 static const char *get_password(struct cli_credentials *credentials) 
316 {
317         char *password = NULL;
318         
319         /* Ask for a password */
320         mux_printf((unsigned int)credentials->priv_data, "PW\n");
321         credentials->priv_data = NULL;
322
323         manage_squid_request(NUM_HELPER_MODES /* bogus */, manage_gensec_get_pw_request, (void **)&password);
324         return password;
325 }
326
327 /**
328  Check if a string is part of a list.
329 **/
330 static bool in_list(const char *s, const char *list, bool casesensitive)
331 {
332         pstring tok;
333         const char *p=list;
334
335         if (!list)
336                 return false;
337
338         while (next_token(&p, tok, LIST_SEP, sizeof(tok))) {
339                 if ((casesensitive?strcmp:strcasecmp_m)(tok,s) == 0)
340                         return true;
341         }
342         return false;
343 }
344
345 static void gensec_want_feature_list(struct gensec_security *state, char* feature_list)
346 {
347         if (in_list("NTLMSSP_FEATURE_SESSION_KEY", feature_list, True)) {
348                 DEBUG(10, ("want GENSEC_FEATURE_SESSION_KEY\n"));
349                 gensec_want_feature(state, GENSEC_FEATURE_SESSION_KEY);
350         }
351         if (in_list("NTLMSSP_FEATURE_SIGN", feature_list, True)) {
352                 DEBUG(10, ("want GENSEC_FEATURE_SIGN\n"));
353                 gensec_want_feature(state, GENSEC_FEATURE_SIGN);
354         }
355         if (in_list("NTLMSSP_FEATURE_SEAL", feature_list, True)) {
356                 DEBUG(10, ("want GENSEC_FEATURE_SEAL\n"));
357                 gensec_want_feature(state, GENSEC_FEATURE_SEAL);
358         }
359 }
360
361 static void manage_gensec_request(enum stdio_helper_mode stdio_helper_mode, 
362                                   char *buf, int length, void **private,
363                                   unsigned int mux_id, void **private2) 
364 {
365         DATA_BLOB in;
366         DATA_BLOB out = data_blob(NULL, 0);
367         char *out_base64 = NULL;
368         const char *reply_arg = NULL;
369         struct gensec_ntlm_state {
370                 struct gensec_security *gensec_state;
371                 const char *set_password;
372         };
373         struct gensec_ntlm_state *state;
374         struct event_context *ev;
375         struct messaging_context *msg;
376
377         NTSTATUS nt_status;
378         BOOL first = False;
379         const char *reply_code;
380         struct cli_credentials *creds;
381
382         static char *want_feature_list = NULL;
383         static DATA_BLOB session_key;
384
385         TALLOC_CTX *mem_ctx;
386
387         if (*private) {
388                 state = (struct gensec_ntlm_state *)*private;
389         } else {
390                 state = talloc_zero(NULL, struct gensec_ntlm_state);
391                 if (!state) {
392                         mux_printf(mux_id, "BH No Memory\n");
393                         exit(1);
394                 }
395                 *private = state;
396                 if (opt_password) {
397                         state->set_password = opt_password;
398                 }
399         }
400         
401         if (strlen(buf) < 2) {
402                 DEBUG(1, ("query [%s] invalid", buf));
403                 mux_printf(mux_id, "BH\n");
404                 return;
405         }
406
407         if (strlen(buf) > 3) {
408                 if(strncmp(buf, "SF ", 3) == 0) {
409                         DEBUG(10, ("Setting flags to negotiate\n"));
410                         talloc_free(want_feature_list);
411                         want_feature_list = talloc_strndup(state, buf+3, strlen(buf)-3);
412                         mux_printf(mux_id, "OK\n");
413                         return;
414                 }
415                 in = base64_decode_data_blob(NULL, buf + 3);
416         } else {
417                 in = data_blob(NULL, 0);
418         }
419
420         if (strncmp(buf, "YR", 2) == 0) {
421                 if (state->gensec_state) {
422                         talloc_free(state->gensec_state);
423                         state->gensec_state = NULL;
424                 }
425         } else if ( (strncmp(buf, "OK", 2) == 0)) {
426                 /* Just return BH, like ntlm_auth from Samba 3 does. */
427                 mux_printf(mux_id, "BH\n");
428                 data_blob_free(&in);
429                 return;
430         } else if ( (strncmp(buf, "TT ", 3) != 0) &&
431                     (strncmp(buf, "KK ", 3) != 0) &&
432                     (strncmp(buf, "AF ", 3) != 0) &&
433                     (strncmp(buf, "NA ", 3) != 0) && 
434                     (strncmp(buf, "UG", 2) != 0) && 
435                     (strncmp(buf, "PW ", 3) != 0) &&
436                     (strncmp(buf, "GK", 2) != 0) &&
437                     (strncmp(buf, "GF", 2) != 0)) {
438                 DEBUG(1, ("SPNEGO request [%s] invalid\n", buf));
439                 mux_printf(mux_id, "BH\n");
440                 data_blob_free(&in);
441                 return;
442         }
443
444         /* setup gensec */
445         if (!(state->gensec_state)) {
446                 switch (stdio_helper_mode) {
447                 case GSS_SPNEGO_CLIENT:
448                 case NTLMSSP_CLIENT_1:
449                         /* setup the client side */
450
451                         nt_status = gensec_client_start(NULL, &state->gensec_state, NULL);
452                         if (!NT_STATUS_IS_OK(nt_status)) {
453                                 exit(1);
454                         }
455
456                         break;
457                 case GSS_SPNEGO_SERVER:
458                 case SQUID_2_5_NTLMSSP:
459                         ev = event_context_init(state);
460                         if (!ev) {
461                                 exit(1);
462                         }
463                         msg = messaging_client_init(state, ev);
464                         if (!msg) {
465                                 exit(1);
466                         }
467                         if (!NT_STATUS_IS_OK(gensec_server_start(state, ev, msg, &state->gensec_state))) {
468                                 exit(1);
469                         }
470                         break;
471                 default:
472                         abort();
473                 }
474
475                 creds = cli_credentials_init(state->gensec_state);
476                 cli_credentials_set_conf(creds);
477                 if (opt_username) {
478                         cli_credentials_set_username(creds, opt_username, CRED_SPECIFIED);
479                 }
480                 if (opt_domain) {
481                         cli_credentials_set_domain(creds, opt_domain, CRED_SPECIFIED);
482                 }
483                 if (state->set_password) {
484                         cli_credentials_set_password(creds, state->set_password, CRED_SPECIFIED);
485                 } else {
486                         cli_credentials_set_password_callback(creds, get_password);
487                         creds->priv_data = (void*)mux_id;
488                 }
489                 if (opt_workstation) {
490                         cli_credentials_set_workstation(creds, opt_workstation, CRED_SPECIFIED);
491                 }
492                 
493                 switch (stdio_helper_mode) {
494                 case GSS_SPNEGO_SERVER:
495                 case SQUID_2_5_NTLMSSP:
496                         cli_credentials_set_machine_account(creds);
497                         break;
498                 default:
499                         break;
500                 }
501
502                 gensec_set_credentials(state->gensec_state, creds);
503                 gensec_want_feature_list(state->gensec_state, want_feature_list);
504
505                 switch (stdio_helper_mode) {
506                 case GSS_SPNEGO_CLIENT:
507                 case GSS_SPNEGO_SERVER:
508                         nt_status = gensec_start_mech_by_oid(state->gensec_state, GENSEC_OID_SPNEGO);
509                         if (!in.length) {
510                                 first = True;
511                         }
512                         break;
513                 case NTLMSSP_CLIENT_1:
514                         if (!in.length) {
515                                 first = True;
516                         }
517                         /* fall through */
518                 case SQUID_2_5_NTLMSSP:
519                         nt_status = gensec_start_mech_by_oid(state->gensec_state, GENSEC_OID_NTLMSSP);
520                         break;
521                 default:
522                         abort();
523                 }
524
525                 if (!NT_STATUS_IS_OK(nt_status)) {
526                         DEBUG(1, ("GENSEC mech failed to start: %s\n", nt_errstr(nt_status)));
527                         mux_printf(mux_id, "BH\n");
528                         return;
529                 }
530
531         }
532
533         /* update */
534         mem_ctx = talloc_named(NULL, 0, "manage_gensec_request internal mem_ctx");
535         
536         if (strncmp(buf, "PW ", 3) == 0) {
537                 state->set_password = talloc_strndup(state,
538                                                      (const char *)in.data, 
539                                                      in.length);
540                 
541                 cli_credentials_set_password(gensec_get_credentials(state->gensec_state),
542                                              state->set_password,
543                                              CRED_SPECIFIED);
544                 mux_printf(mux_id, "OK\n");
545                 data_blob_free(&in);
546                 talloc_free(mem_ctx);
547                 return;
548         }
549
550         if (strncmp(buf, "UG", 2) == 0) {
551                 int i;
552                 char *grouplist = NULL;
553                 struct auth_session_info *session_info;
554
555                 nt_status = gensec_session_info(state->gensec_state, &session_info); 
556                 if (!NT_STATUS_IS_OK(nt_status)) {
557                         DEBUG(1, ("gensec_session_info failed: %s\n", nt_errstr(nt_status)));
558                         mux_printf(mux_id, "BH %s\n", nt_errstr(nt_status));
559                         data_blob_free(&in);
560                         talloc_free(mem_ctx);
561                         return;
562                 }
563                 
564                 /* get the string onto the context */
565                 grouplist = talloc_strdup(mem_ctx, "");
566                 
567                 for (i=0; i<session_info->security_token->num_sids; i++) {
568                         struct security_token *token = session_info->security_token; 
569                         const char *sidstr = dom_sid_string(session_info, 
570                                                             token->sids[i]);
571                         grouplist = talloc_asprintf_append(grouplist, "%s,", sidstr);
572                 }
573
574                 mux_printf(mux_id, "GL %s\n", grouplist);
575                 talloc_free(session_info);
576                 data_blob_free(&in);
577                 talloc_free(mem_ctx);
578                 return;
579         }
580
581         if (strncmp(buf, "GK", 2) == 0) {
582                 char *base64_key;
583                 DEBUG(10, ("Requested session key\n"));
584                 nt_status = gensec_session_key(state->gensec_state, &session_key);
585                 if(!NT_STATUS_IS_OK(nt_status)) {
586                         DEBUG(1, ("gensec_session_key failed: %s\n", nt_errstr(nt_status)));
587                         mux_printf(mux_id, "BH No session key\n");
588                         talloc_free(mem_ctx);
589                         return;
590                 } else {
591                         base64_key = base64_encode_data_blob(state, session_key);
592                         mux_printf(mux_id, "GK %s\n", base64_key);
593                         talloc_free(base64_key);
594                 }
595                 talloc_free(mem_ctx);
596                 return;
597         }
598
599         if (strncmp(buf, "GF", 2) == 0) {
600                 struct gensec_ntlmssp_state *gensec_ntlmssp_state;
601                 uint32_t neg_flags;
602
603                 gensec_ntlmssp_state = talloc_get_type(state->gensec_state->private_data, 
604                                 struct gensec_ntlmssp_state);
605                 neg_flags = gensec_ntlmssp_state->neg_flags;
606
607                 DEBUG(10, ("Requested negotiated feature flags\n"));
608                 mux_printf(mux_id, "GF 0x%08x\n", neg_flags);
609                 return;
610         }
611
612         nt_status = gensec_update(state->gensec_state, mem_ctx, in, &out);
613         
614         /* don't leak 'bad password'/'no such user' info to the network client */
615         nt_status = auth_nt_status_squash(nt_status);
616
617         if (out.length) {
618                 out_base64 = base64_encode_data_blob(mem_ctx, out);
619         } else {
620                 out_base64 = NULL;
621         }
622
623         if (NT_STATUS_EQUAL(nt_status, NT_STATUS_MORE_PROCESSING_REQUIRED)) {
624                 reply_arg = "*";
625                 if (first) {
626                         reply_code = "YR";
627                 } else if (state->gensec_state->gensec_role == GENSEC_CLIENT) { 
628                         reply_code = "KK";
629                 } else if (state->gensec_state->gensec_role == GENSEC_SERVER) { 
630                         reply_code = "TT";
631                 } else {
632                         abort();
633                 }
634
635
636         } else if (NT_STATUS_EQUAL(nt_status, NT_STATUS_ACCESS_DENIED)) {
637                 reply_code = "BH";
638                 reply_arg = nt_errstr(nt_status);
639                 DEBUG(1, ("GENSEC login failed: %s\n", nt_errstr(nt_status)));
640         } else if (NT_STATUS_EQUAL(nt_status, NT_STATUS_UNSUCCESSFUL)) {
641                 reply_code = "BH";
642                 reply_arg = nt_errstr(nt_status);
643                 DEBUG(1, ("GENSEC login failed: %s\n", nt_errstr(nt_status)));
644         } else if (!NT_STATUS_IS_OK(nt_status)) {
645                 reply_code = "NA";
646                 reply_arg = nt_errstr(nt_status);
647                 DEBUG(1, ("GENSEC login failed: %s\n", nt_errstr(nt_status)));
648         } else if /* OK */ (state->gensec_state->gensec_role == GENSEC_SERVER) {
649                 struct auth_session_info *session_info;
650
651                 nt_status = gensec_session_info(state->gensec_state, &session_info);
652                 if (!NT_STATUS_IS_OK(nt_status)) {
653                         reply_code = "BH";
654                         reply_arg = nt_errstr(nt_status);
655                         DEBUG(1, ("GENSEC failed to retreive the session info: %s\n", nt_errstr(nt_status)));
656                 } else {
657
658                         reply_code = "AF";
659                         reply_arg = talloc_asprintf(state->gensec_state, 
660                                                     "%s%s%s", session_info->server_info->domain_name, 
661                                                     lp_winbind_separator(), session_info->server_info->account_name);
662                         talloc_free(session_info);
663                 }
664         } else if (state->gensec_state->gensec_role == GENSEC_CLIENT) {
665                 reply_code = "AF";
666                 reply_arg = out_base64;
667         } else {
668                 abort();
669         }
670
671         switch (stdio_helper_mode) {
672         case GSS_SPNEGO_SERVER:
673                 mux_printf(mux_id, "%s %s %s\n", reply_code, 
674                           out_base64 ? out_base64 : "*", 
675                           reply_arg ? reply_arg : "*");
676                 break;
677         default:
678                 if (out_base64) {
679                         mux_printf(mux_id, "%s %s\n", reply_code, out_base64);
680                 } else if (reply_arg) {
681                         mux_printf(mux_id, "%s %s\n", reply_code, reply_arg);
682                 } else {
683                         mux_printf(mux_id, "%s\n", reply_code);
684                 }
685         }
686
687         talloc_free(mem_ctx);
688         return;
689 }
690
691 static void manage_ntlm_server_1_request(enum stdio_helper_mode stdio_helper_mode, 
692                                          char *buf, int length, void **private,
693                                          unsigned int mux_id, void **private2) 
694 {
695         char *request, *parameter;      
696         static DATA_BLOB challenge;
697         static DATA_BLOB lm_response;
698         static DATA_BLOB nt_response;
699         static char *full_username;
700         static char *username;
701         static char *domain;
702         static char *plaintext_password;
703         static BOOL ntlm_server_1_user_session_key;
704         static BOOL ntlm_server_1_lm_session_key;
705         
706         if (strequal(buf, ".")) {
707                 if (!full_username && !username) {      
708                         mux_printf(mux_id, "Error: No username supplied!\n");
709                 } else if (plaintext_password) {
710                         /* handle this request as plaintext */
711                         if (!full_username) {
712                                 if (asprintf(&full_username, "%s%c%s", domain, *lp_winbind_separator(), username) == -1) {
713                                         mux_printf(mux_id, "Error: Out of memory in asprintf!\n.\n");
714                                         return;
715                                 }
716                         }
717                         if (check_plaintext_auth(full_username, plaintext_password, False)) {
718                                 mux_printf(mux_id, "Authenticated: Yes\n");
719                         } else {
720                                 mux_printf(mux_id, "Authenticated: No\n");
721                         }
722                 } else if (!lm_response.data && !nt_response.data) {
723                         mux_printf(mux_id, "Error: No password supplied!\n");
724                 } else if (!challenge.data) {   
725                         mux_printf(mux_id, "Error: No lanman-challenge supplied!\n");
726                 } else {
727                         char *error_string = NULL;
728                         DATA_BLOB lm_key;
729                         DATA_BLOB user_session_key;
730                         uint32_t flags = 0;
731
732                         if (full_username && !username) {
733                                 fstring fstr_user;
734                                 fstring fstr_domain;
735                                 
736                                 if (!parse_ntlm_auth_domain_user(full_username, fstr_user, fstr_domain)) {
737                                         /* username might be 'tainted', don't print into our new-line deleimianted stream */
738                                         mux_printf(mux_id, "Error: Could not parse into domain and username\n");
739                                 }
740                                 SAFE_FREE(username);
741                                 SAFE_FREE(domain);
742                                 username = smb_xstrdup(fstr_user);
743                                 domain = smb_xstrdup(fstr_domain);
744                         }
745
746                         if (!domain) {
747                                 domain = smb_xstrdup(lp_workgroup());
748                         }
749
750                         if (ntlm_server_1_lm_session_key) 
751                                 flags |= NTLM_AUTH_FLAG_LMKEY;
752                         
753                         if (ntlm_server_1_user_session_key) 
754                                 flags |= NTLM_AUTH_FLAG_USER_SESSION_KEY;
755
756                         if (!NT_STATUS_IS_OK(
757                                     local_pw_check_specified(username, 
758                                                               domain, 
759                                                               lp_netbios_name(),
760                                                               &challenge, 
761                                                               &lm_response, 
762                                                               &nt_response, 
763                                                               flags, 
764                                                               &lm_key, 
765                                                               &user_session_key,
766                                                               &error_string,
767                                                               NULL))) {
768
769                                 mux_printf(mux_id, "Authenticated: No\n");
770                                 mux_printf(mux_id, "Authentication-Error: %s\n.\n", error_string);
771                                 SAFE_FREE(error_string);
772                         } else {
773                                 static char zeros[16];
774                                 char *hex_lm_key;
775                                 char *hex_user_session_key;
776
777                                 mux_printf(mux_id, "Authenticated: Yes\n");
778
779                                 if (ntlm_server_1_lm_session_key 
780                                     && lm_key.length 
781                                     && (memcmp(zeros, lm_key.data, 
782                                                                 lm_key.length) != 0)) {
783                                         hex_encode(lm_key.data,
784                                                    lm_key.length,
785                                                    &hex_lm_key);
786                                         mux_printf(mux_id, "LANMAN-Session-Key: %s\n", hex_lm_key);
787                                         SAFE_FREE(hex_lm_key);
788                                 }
789
790                                 if (ntlm_server_1_user_session_key 
791                                     && user_session_key.length 
792                                     && (memcmp(zeros, user_session_key.data, 
793                                                user_session_key.length) != 0)) {
794                                         hex_encode(user_session_key.data, 
795                                                    user_session_key.length, 
796                                                    &hex_user_session_key);
797                                         mux_printf(mux_id, "User-Session-Key: %s\n", hex_user_session_key);
798                                         SAFE_FREE(hex_user_session_key);
799                                 }
800                         }
801                 }
802                 /* clear out the state */
803                 challenge = data_blob(NULL, 0);
804                 nt_response = data_blob(NULL, 0);
805                 lm_response = data_blob(NULL, 0);
806                 SAFE_FREE(full_username);
807                 SAFE_FREE(username);
808                 SAFE_FREE(domain);
809                 SAFE_FREE(plaintext_password);
810                 ntlm_server_1_user_session_key = False;
811                 ntlm_server_1_lm_session_key = False;
812                 mux_printf(mux_id, ".\n");
813
814                 return;
815         }
816
817         request = buf;
818
819         /* Indicates a base64 encoded structure */
820         parameter = strstr(request, ":: ");
821         if (!parameter) {
822                 parameter = strstr(request, ": ");
823                 
824                 if (!parameter) {
825                         DEBUG(0, ("Parameter not found!\n"));
826                         mux_printf(mux_id, "Error: Parameter not found!\n.\n");
827                         return;
828                 }
829                 
830                 parameter[0] ='\0';
831                 parameter++;
832                 parameter[0] ='\0';
833                 parameter++;
834
835         } else {
836                 parameter[0] ='\0';
837                 parameter++;
838                 parameter[0] ='\0';
839                 parameter++;
840                 parameter[0] ='\0';
841                 parameter++;
842
843                 base64_decode_inplace(parameter);
844         }
845
846         if (strequal(request, "LANMAN-Challenge")) {
847                 challenge = strhex_to_data_blob(parameter);
848                 if (challenge.length != 8) {
849                         mux_printf(mux_id, "Error: hex decode of %s failed! (got %d bytes, expected 8)\n.\n", 
850                                   parameter,
851                                   (int)challenge.length);
852                         challenge = data_blob(NULL, 0);
853                 }
854         } else if (strequal(request, "NT-Response")) {
855                 nt_response = strhex_to_data_blob(parameter);
856                 if (nt_response.length < 24) {
857                         mux_printf(mux_id, "Error: hex decode of %s failed! (only got %d bytes, needed at least 24)\n.\n", 
858                                   parameter,
859                                   (int)nt_response.length);
860                         nt_response = data_blob(NULL, 0);
861                 }
862         } else if (strequal(request, "LANMAN-Response")) {
863                 lm_response = strhex_to_data_blob(parameter);
864                 if (lm_response.length != 24) {
865                         mux_printf(mux_id, "Error: hex decode of %s failed! (got %d bytes, expected 24)\n.\n", 
866                                   parameter,
867                                   (int)lm_response.length);
868                         lm_response = data_blob(NULL, 0);
869                 }
870         } else if (strequal(request, "Password")) {
871                 plaintext_password = smb_xstrdup(parameter);
872         } else if (strequal(request, "NT-Domain")) {
873                 domain = smb_xstrdup(parameter);
874         } else if (strequal(request, "Username")) {
875                 username = smb_xstrdup(parameter);
876         } else if (strequal(request, "Full-Username")) {
877                 full_username = smb_xstrdup(parameter);
878         } else if (strequal(request, "Request-User-Session-Key")) {
879                 ntlm_server_1_user_session_key = strequal(parameter, "Yes");
880         } else if (strequal(request, "Request-LanMan-Session-Key")) {
881                 ntlm_server_1_lm_session_key = strequal(parameter, "Yes");
882         } else {
883                 mux_printf(mux_id, "Error: Unknown request %s\n.\n", request);
884         }
885 }
886
887 static void manage_squid_request(enum stdio_helper_mode helper_mode, 
888                                  stdio_helper_function fn, void **private2) 
889 {
890         char *buf;
891         char tmp[INITIAL_BUFFER_SIZE+1];
892         unsigned int mux_id = 0;
893         int length, buf_size = 0;
894         char *c;
895         struct mux_private {
896                 unsigned int max_mux;
897                 void **private_pointers;
898         };
899
900         static struct mux_private *mux_private;
901         static void *normal_private;
902         void **private;
903
904         buf = talloc(NULL, char);
905         buf[0] = '\0';
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_append_string(buf, 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();
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();
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(), 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 }