a0c02af4471e01232edec4a09a19c9462a4f3561
[metze/samba/wip.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 2 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, write to the Free Software
22    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
23 */
24
25 #include "includes.h"
26 #include "system/filesys.h"
27 #include "lib/cmdline/popt_common.h"
28 #include "lib/ldb/include/ldb.h"
29 #include "auth/credentials/credentials.h"
30 #include "auth/gensec/gensec.h"
31 #include "auth/auth.h"
32 #include "librpc/gen_ndr/ndr_netlogon.h"
33 #include "auth/auth_sam.h"
34 #include "pstring.h"
35 #include "libcli/auth/libcli_auth.h"
36 #include "libcli/security/security.h"
37 #include "lib/events/events.h"
38 #include "lib/messaging/messaging.h"
39 #include "lib/messaging/irpc.h"
40 #include "auth/ntlmssp/ntlmssp.h"
41
42 #define SQUID_BUFFER_SIZE 2010
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 static void gensec_want_feature_list(struct gensec_security *state, char* feature_list)
328 {
329         if (in_list("NTLMSSP_FEATURE_SESSION_KEY", feature_list, True)) {
330                 DEBUG(10, ("want GENSEC_FEATURE_SESSION_KEY\n"));
331                 gensec_want_feature(state, GENSEC_FEATURE_SESSION_KEY);
332         }
333         if (in_list("NTLMSSP_FEATURE_SIGN", feature_list, True)) {
334                 DEBUG(10, ("want GENSEC_FEATURE_SIGN\n"));
335                 gensec_want_feature(state, GENSEC_FEATURE_SIGN);
336         }
337         if (in_list("NTLMSSP_FEATURE_SEAL", feature_list, True)) {
338                 DEBUG(10, ("want GENSEC_FEATURE_SEAL\n"));
339                 gensec_want_feature(state, GENSEC_FEATURE_SEAL);
340         }
341 }
342
343 static void manage_gensec_request(enum stdio_helper_mode stdio_helper_mode, 
344                                   char *buf, int length, void **private,
345                                   unsigned int mux_id, void **private2) 
346 {
347         DATA_BLOB in;
348         DATA_BLOB out = data_blob(NULL, 0);
349         char *out_base64 = NULL;
350         const char *reply_arg = NULL;
351         struct gensec_ntlm_state {
352                 struct gensec_security *gensec_state;
353                 const char *set_password;
354         };
355         struct gensec_ntlm_state *state;
356         struct event_context *ev;
357         struct messaging_context *msg;
358
359         NTSTATUS nt_status;
360         BOOL first = False;
361         const char *reply_code;
362         struct cli_credentials *creds;
363
364         static char *want_feature_list = NULL;
365         static DATA_BLOB session_key;
366
367         TALLOC_CTX *mem_ctx;
368
369         if (*private) {
370                 state = *private;
371         } else {
372                 state = talloc_zero(NULL, struct gensec_ntlm_state);
373                 if (!state) {
374                         mux_printf(mux_id, "BH No Memory\n");
375                         exit(1);
376                 }
377                 *private = state;
378                 if (opt_password) {
379                         state->set_password = opt_password;
380                 }
381         }
382         
383         if (strlen(buf) < 2) {
384                 DEBUG(1, ("query [%s] invalid", buf));
385                 mux_printf(mux_id, "BH\n");
386                 return;
387         }
388
389         if (strlen(buf) > 3) {
390                 if(strncmp(buf, "SF ", 3) == 0) {
391                         DEBUG(10, ("Setting flags to negotiate\n"));
392                         talloc_free(want_feature_list);
393                         want_feature_list = talloc_strndup(state, buf+3, strlen(buf)-3);
394                         mux_printf(mux_id, "OK\n");
395                         return;
396                 }
397                 in = base64_decode_data_blob(NULL, buf + 3);
398         } else {
399                 in = data_blob(NULL, 0);
400         }
401
402         if (strncmp(buf, "YR", 2) == 0) {
403                 if (state->gensec_state) {
404                         talloc_free(state->gensec_state);
405                         state->gensec_state = NULL;
406                 }
407         } else if ( (strncmp(buf, "OK", 2) == 0)) {
408                 /* Just return BH, like ntlm_auth from Samba 3 does. */
409                 mux_printf(mux_id, "BH\n");
410                 data_blob_free(&in);
411                 return;
412         } else if ( (strncmp(buf, "TT ", 3) != 0) &&
413                     (strncmp(buf, "KK ", 3) != 0) &&
414                     (strncmp(buf, "AF ", 3) != 0) &&
415                     (strncmp(buf, "NA ", 3) != 0) && 
416                     (strncmp(buf, "UG", 2) != 0) && 
417                     (strncmp(buf, "PW ", 3) != 0) &&
418                     (strncmp(buf, "GK", 2) != 0) &&
419                     (strncmp(buf, "GF", 2) != 0)) {
420                 DEBUG(1, ("SPNEGO request [%s] invalid\n", buf));
421                 mux_printf(mux_id, "BH\n");
422                 data_blob_free(&in);
423                 return;
424         }
425
426         /* setup gensec */
427         if (!(state->gensec_state)) {
428                 switch (stdio_helper_mode) {
429                 case GSS_SPNEGO_CLIENT:
430                 case NTLMSSP_CLIENT_1:
431                         /* setup the client side */
432
433                         nt_status = gensec_client_start(NULL, &state->gensec_state, NULL);
434                         if (!NT_STATUS_IS_OK(nt_status)) {
435                                 exit(1);
436                         }
437
438                         break;
439                 case GSS_SPNEGO_SERVER:
440                 case SQUID_2_5_NTLMSSP:
441                         ev = event_context_init(state);
442                         if (!ev) {
443                                 exit(1);
444                         }
445                         msg = messaging_client_init(state, ev);
446                         if (!msg) {
447                                 exit(1);
448                         }
449                         if (!NT_STATUS_IS_OK(gensec_server_start(state, ev, msg, &state->gensec_state))) {
450                                 exit(1);
451                         }
452                         break;
453                 default:
454                         abort();
455                 }
456
457                 creds = cli_credentials_init(state->gensec_state);
458                 cli_credentials_set_conf(creds);
459                 if (opt_username) {
460                         cli_credentials_set_username(creds, opt_username, CRED_SPECIFIED);
461                 }
462                 if (opt_domain) {
463                         cli_credentials_set_domain(creds, opt_domain, CRED_SPECIFIED);
464                 }
465                 if (state->set_password) {
466                         cli_credentials_set_password(creds, state->set_password, CRED_SPECIFIED);
467                 } else {
468                         cli_credentials_set_password_callback(creds, get_password);
469                         creds->priv_data = (void*)mux_id;
470                 }
471                 if (opt_workstation) {
472                         cli_credentials_set_workstation(creds, opt_workstation, CRED_SPECIFIED);
473                 }
474                 
475                 switch (stdio_helper_mode) {
476                 case GSS_SPNEGO_SERVER:
477                 case SQUID_2_5_NTLMSSP:
478                         cli_credentials_set_machine_account(creds);
479                         break;
480                 default:
481                         break;
482                 }
483
484                 gensec_set_credentials(state->gensec_state, creds);
485                 gensec_want_feature_list(state->gensec_state, want_feature_list);
486
487                 switch (stdio_helper_mode) {
488                 case GSS_SPNEGO_CLIENT:
489                 case GSS_SPNEGO_SERVER:
490                         nt_status = gensec_start_mech_by_oid(state->gensec_state, GENSEC_OID_SPNEGO);
491                         if (!in.length) {
492                                 first = True;
493                         }
494                         break;
495                 case NTLMSSP_CLIENT_1:
496                         if (!in.length) {
497                                 first = True;
498                         }
499                         /* fall through */
500                 case SQUID_2_5_NTLMSSP:
501                         nt_status = gensec_start_mech_by_oid(state->gensec_state, GENSEC_OID_NTLMSSP);
502                         break;
503                 default:
504                         abort();
505                 }
506
507                 if (!NT_STATUS_IS_OK(nt_status)) {
508                         DEBUG(1, ("GENSEC mech failed to start: %s\n", nt_errstr(nt_status)));
509                         mux_printf(mux_id, "BH\n");
510                         return;
511                 }
512
513         }
514
515         /* update */
516         mem_ctx = talloc_named(NULL, 0, "manage_gensec_request internal mem_ctx");
517         
518         if (strncmp(buf, "PW ", 3) == 0) {
519                 state->set_password = talloc_strndup(state,
520                                                      (const char *)in.data, 
521                                                      in.length);
522                 
523                 cli_credentials_set_password(gensec_get_credentials(state->gensec_state),
524                                              state->set_password,
525                                              CRED_SPECIFIED);
526                 mux_printf(mux_id, "OK\n");
527                 data_blob_free(&in);
528                 talloc_free(mem_ctx);
529                 return;
530         }
531
532         if (strncmp(buf, "UG", 2) == 0) {
533                 int i;
534                 char *grouplist = NULL;
535                 struct auth_session_info *session_info;
536
537                 nt_status = gensec_session_info(state->gensec_state, &session_info); 
538                 if (!NT_STATUS_IS_OK(nt_status)) {
539                         DEBUG(1, ("gensec_session_info failed: %s\n", nt_errstr(nt_status)));
540                         mux_printf(mux_id, "BH %s\n", nt_errstr(nt_status));
541                         data_blob_free(&in);
542                         talloc_free(mem_ctx);
543                         return;
544                 }
545                 
546                 /* get the string onto the context */
547                 grouplist = talloc_strdup(mem_ctx, "");
548                 
549                 for (i=0; i<session_info->security_token->num_sids; i++) {
550                         struct security_token *token = session_info->security_token; 
551                         const char *sidstr = dom_sid_string(session_info, 
552                                                             token->sids[i]);
553                         grouplist = talloc_asprintf_append(grouplist, "%s,", sidstr);
554                 }
555
556                 mux_printf(mux_id, "GL %s\n", grouplist);
557                 talloc_free(session_info);
558                 data_blob_free(&in);
559                 talloc_free(mem_ctx);
560                 return;
561         }
562
563         if (strncmp(buf, "GK", 2) == 0) {
564                 char *base64_key;
565                 DEBUG(10, ("Requested session key\n"));
566                 nt_status = gensec_session_key(state->gensec_state, &session_key);
567                 if(!NT_STATUS_IS_OK(nt_status)) {
568                         DEBUG(1, ("gensec_session_key failed: %s\n", nt_errstr(nt_status)));
569                         mux_printf(mux_id, "BH No session key\n");
570                         talloc_free(mem_ctx);
571                         return;
572                 } else {
573                         base64_key = base64_encode_data_blob(state, session_key);
574                         mux_printf(mux_id, "GK %s\n", base64_key);
575                         talloc_free(base64_key);
576                 }
577                 talloc_free(mem_ctx);
578                 return;
579         }
580
581         if (strncmp(buf, "GF", 2) == 0) {
582                 struct gensec_ntlmssp_state *gensec_ntlmssp_state;
583                 uint32_t neg_flags;
584
585                 gensec_ntlmssp_state = talloc_get_type(state->gensec_state->private_data, 
586                                 struct gensec_ntlmssp_state);
587                 neg_flags = gensec_ntlmssp_state->neg_flags;
588
589                 DEBUG(10, ("Requested negotiated feature flags\n"));
590                 mux_printf(mux_id, "GF 0x%08x\n", neg_flags);
591                 return;
592         }
593
594         nt_status = gensec_update(state->gensec_state, mem_ctx, in, &out);
595         
596         /* don't leak 'bad password'/'no such user' info to the network client */
597         nt_status = auth_nt_status_squash(nt_status);
598
599         if (out.length) {
600                 out_base64 = base64_encode_data_blob(mem_ctx, out);
601         } else {
602                 out_base64 = NULL;
603         }
604
605         if (NT_STATUS_EQUAL(nt_status, NT_STATUS_MORE_PROCESSING_REQUIRED)) {
606                 reply_arg = "*";
607                 if (first) {
608                         reply_code = "YR";
609                 } else if (state->gensec_state->gensec_role == GENSEC_CLIENT) { 
610                         reply_code = "KK";
611                 } else if (state->gensec_state->gensec_role == GENSEC_SERVER) { 
612                         reply_code = "TT";
613                 } else {
614                         abort();
615                 }
616
617
618         } else if (NT_STATUS_EQUAL(nt_status, NT_STATUS_ACCESS_DENIED)) {
619                 reply_code = "BH";
620                 reply_arg = nt_errstr(nt_status);
621                 DEBUG(1, ("GENSEC login failed: %s\n", nt_errstr(nt_status)));
622         } else if (NT_STATUS_EQUAL(nt_status, NT_STATUS_UNSUCCESSFUL)) {
623                 reply_code = "BH";
624                 reply_arg = nt_errstr(nt_status);
625                 DEBUG(1, ("GENSEC login failed: %s\n", nt_errstr(nt_status)));
626         } else if (!NT_STATUS_IS_OK(nt_status)) {
627                 reply_code = "NA";
628                 reply_arg = nt_errstr(nt_status);
629                 DEBUG(1, ("GENSEC login failed: %s\n", nt_errstr(nt_status)));
630         } else if /* OK */ (state->gensec_state->gensec_role == GENSEC_SERVER) {
631                 struct auth_session_info *session_info;
632
633                 nt_status = gensec_session_info(state->gensec_state, &session_info);
634                 if (!NT_STATUS_IS_OK(nt_status)) {
635                         reply_code = "BH";
636                         reply_arg = nt_errstr(nt_status);
637                         DEBUG(1, ("GENSEC failed to retreive the session info: %s\n", nt_errstr(nt_status)));
638                 } else {
639
640                         reply_code = "AF";
641                         reply_arg = talloc_asprintf(state->gensec_state, 
642                                                     "%s%s%s", session_info->server_info->domain_name, 
643                                                     lp_winbind_separator(), session_info->server_info->account_name);
644                         talloc_free(session_info);
645                 }
646         } else if (state->gensec_state->gensec_role == GENSEC_CLIENT) {
647                 reply_code = "AF";
648                 reply_arg = out_base64;
649         } else {
650                 abort();
651         }
652
653         switch (stdio_helper_mode) {
654         case GSS_SPNEGO_SERVER:
655                 mux_printf(mux_id, "%s %s %s\n", reply_code, 
656                           out_base64 ? out_base64 : "*", 
657                           reply_arg ? reply_arg : "*");
658                 break;
659         default:
660                 if (out_base64) {
661                         mux_printf(mux_id, "%s %s\n", reply_code, out_base64);
662                 } else if (reply_arg) {
663                         mux_printf(mux_id, "%s %s\n", reply_code, reply_arg);
664                 } else {
665                         mux_printf(mux_id, "%s\n", reply_code);
666                 }
667         }
668
669         talloc_free(mem_ctx);
670         return;
671 }
672
673 static void manage_ntlm_server_1_request(enum stdio_helper_mode stdio_helper_mode, 
674                                          char *buf, int length, void **private,
675                                          unsigned int mux_id, void **private2) 
676 {
677         char *request, *parameter;      
678         static DATA_BLOB challenge;
679         static DATA_BLOB lm_response;
680         static DATA_BLOB nt_response;
681         static char *full_username;
682         static char *username;
683         static char *domain;
684         static char *plaintext_password;
685         static BOOL ntlm_server_1_user_session_key;
686         static BOOL ntlm_server_1_lm_session_key;
687         
688         if (strequal(buf, ".")) {
689                 if (!full_username && !username) {      
690                         mux_printf(mux_id, "Error: No username supplied!\n");
691                 } else if (plaintext_password) {
692                         /* handle this request as plaintext */
693                         if (!full_username) {
694                                 if (asprintf(&full_username, "%s%c%s", domain, *lp_winbind_separator(), username) == -1) {
695                                         mux_printf(mux_id, "Error: Out of memory in asprintf!\n.\n");
696                                         return;
697                                 }
698                         }
699                         if (check_plaintext_auth(full_username, plaintext_password, False)) {
700                                 mux_printf(mux_id, "Authenticated: Yes\n");
701                         } else {
702                                 mux_printf(mux_id, "Authenticated: No\n");
703                         }
704                 } else if (!lm_response.data && !nt_response.data) {
705                         mux_printf(mux_id, "Error: No password supplied!\n");
706                 } else if (!challenge.data) {   
707                         mux_printf(mux_id, "Error: No lanman-challenge supplied!\n");
708                 } else {
709                         char *error_string = NULL;
710                         DATA_BLOB lm_key;
711                         DATA_BLOB user_session_key;
712                         uint32_t flags = 0;
713
714                         if (full_username && !username) {
715                                 fstring fstr_user;
716                                 fstring fstr_domain;
717                                 
718                                 if (!parse_ntlm_auth_domain_user(full_username, fstr_user, fstr_domain)) {
719                                         /* username might be 'tainted', don't print into our new-line deleimianted stream */
720                                         mux_printf(mux_id, "Error: Could not parse into domain and username\n");
721                                 }
722                                 SAFE_FREE(username);
723                                 SAFE_FREE(domain);
724                                 username = smb_xstrdup(fstr_user);
725                                 domain = smb_xstrdup(fstr_domain);
726                         }
727
728                         if (!domain) {
729                                 domain = smb_xstrdup(lp_workgroup());
730                         }
731
732                         if (ntlm_server_1_lm_session_key) 
733                                 flags |= NTLM_AUTH_FLAG_LMKEY;
734                         
735                         if (ntlm_server_1_user_session_key) 
736                                 flags |= NTLM_AUTH_FLAG_USER_SESSION_KEY;
737
738                         if (!NT_STATUS_IS_OK(
739                                     local_pw_check_specified(username, 
740                                                               domain, 
741                                                               lp_netbios_name(),
742                                                               &challenge, 
743                                                               &lm_response, 
744                                                               &nt_response, 
745                                                               flags, 
746                                                               &lm_key, 
747                                                               &user_session_key,
748                                                               &error_string,
749                                                               NULL))) {
750
751                                 mux_printf(mux_id, "Authenticated: No\n");
752                                 mux_printf(mux_id, "Authentication-Error: %s\n.\n", error_string);
753                                 SAFE_FREE(error_string);
754                         } else {
755                                 static char zeros[16];
756                                 char *hex_lm_key;
757                                 char *hex_user_session_key;
758
759                                 mux_printf(mux_id, "Authenticated: Yes\n");
760
761                                 if (ntlm_server_1_lm_session_key 
762                                     && lm_key.length 
763                                     && (memcmp(zeros, lm_key.data, 
764                                                                 lm_key.length) != 0)) {
765                                         hex_encode(lm_key.data,
766                                                    lm_key.length,
767                                                    &hex_lm_key);
768                                         mux_printf(mux_id, "LANMAN-Session-Key: %s\n", hex_lm_key);
769                                         SAFE_FREE(hex_lm_key);
770                                 }
771
772                                 if (ntlm_server_1_user_session_key 
773                                     && user_session_key.length 
774                                     && (memcmp(zeros, user_session_key.data, 
775                                                user_session_key.length) != 0)) {
776                                         hex_encode(user_session_key.data, 
777                                                    user_session_key.length, 
778                                                    &hex_user_session_key);
779                                         mux_printf(mux_id, "User-Session-Key: %s\n", hex_user_session_key);
780                                         SAFE_FREE(hex_user_session_key);
781                                 }
782                         }
783                 }
784                 /* clear out the state */
785                 challenge = data_blob(NULL, 0);
786                 nt_response = data_blob(NULL, 0);
787                 lm_response = data_blob(NULL, 0);
788                 SAFE_FREE(full_username);
789                 SAFE_FREE(username);
790                 SAFE_FREE(domain);
791                 SAFE_FREE(plaintext_password);
792                 ntlm_server_1_user_session_key = False;
793                 ntlm_server_1_lm_session_key = False;
794                 mux_printf(mux_id, ".\n");
795
796                 return;
797         }
798
799         request = buf;
800
801         /* Indicates a base64 encoded structure */
802         parameter = strstr(request, ":: ");
803         if (!parameter) {
804                 parameter = strstr(request, ": ");
805                 
806                 if (!parameter) {
807                         DEBUG(0, ("Parameter not found!\n"));
808                         mux_printf(mux_id, "Error: Parameter not found!\n.\n");
809                         return;
810                 }
811                 
812                 parameter[0] ='\0';
813                 parameter++;
814                 parameter[0] ='\0';
815                 parameter++;
816
817         } else {
818                 parameter[0] ='\0';
819                 parameter++;
820                 parameter[0] ='\0';
821                 parameter++;
822                 parameter[0] ='\0';
823                 parameter++;
824
825                 base64_decode_inplace(parameter);
826         }
827
828         if (strequal(request, "LANMAN-Challenge")) {
829                 challenge = strhex_to_data_blob(parameter);
830                 if (challenge.length != 8) {
831                         mux_printf(mux_id, "Error: hex decode of %s failed! (got %d bytes, expected 8)\n.\n", 
832                                   parameter,
833                                   (int)challenge.length);
834                         challenge = data_blob(NULL, 0);
835                 }
836         } else if (strequal(request, "NT-Response")) {
837                 nt_response = strhex_to_data_blob(parameter);
838                 if (nt_response.length < 24) {
839                         mux_printf(mux_id, "Error: hex decode of %s failed! (only got %d bytes, needed at least 24)\n.\n", 
840                                   parameter,
841                                   (int)nt_response.length);
842                         nt_response = data_blob(NULL, 0);
843                 }
844         } else if (strequal(request, "LANMAN-Response")) {
845                 lm_response = strhex_to_data_blob(parameter);
846                 if (lm_response.length != 24) {
847                         mux_printf(mux_id, "Error: hex decode of %s failed! (got %d bytes, expected 24)\n.\n", 
848                                   parameter,
849                                   (int)lm_response.length);
850                         lm_response = data_blob(NULL, 0);
851                 }
852         } else if (strequal(request, "Password")) {
853                 plaintext_password = smb_xstrdup(parameter);
854         } else if (strequal(request, "NT-Domain")) {
855                 domain = smb_xstrdup(parameter);
856         } else if (strequal(request, "Username")) {
857                 username = smb_xstrdup(parameter);
858         } else if (strequal(request, "Full-Username")) {
859                 full_username = smb_xstrdup(parameter);
860         } else if (strequal(request, "Request-User-Session-Key")) {
861                 ntlm_server_1_user_session_key = strequal(parameter, "Yes");
862         } else if (strequal(request, "Request-LanMan-Session-Key")) {
863                 ntlm_server_1_lm_session_key = strequal(parameter, "Yes");
864         } else {
865                 mux_printf(mux_id, "Error: Unknown request %s\n.\n", request);
866         }
867 }
868
869 static void manage_squid_request(enum stdio_helper_mode helper_mode, 
870                                  stdio_helper_function fn, void **private2) 
871 {
872         char buf[SQUID_BUFFER_SIZE+1];
873         unsigned int mux_id = 0;
874         int length;
875         char *c;
876         static BOOL err;
877         struct mux_private {
878                 unsigned int max_mux;
879                 void **private_pointers;
880         };
881         
882         static struct mux_private *mux_private;
883         static void *normal_private;
884         void **private;
885
886         /* this is not a typo - x_fgets doesn't work too well under squid */
887         if (fgets(buf, sizeof(buf)-1, stdin) == NULL) {
888                 if (ferror(stdin)) {
889                         DEBUG(1, ("fgets() failed! dying..... errno=%d (%s)\n", ferror(stdin),
890                                   strerror(ferror(stdin))));
891                         
892                         exit(1);    /* BIIG buffer */
893                 }
894                 exit(0);
895         }
896     
897         c=memchr(buf,'\n',sizeof(buf)-1);
898         if (c) {
899                 *c = '\0';
900                 length = c-buf;
901         } else {
902                 err = 1;
903                 return;
904         }
905         if (err) {
906                 DEBUG(0, ("Oversized message\n"));
907                 x_fprintf(x_stdout, "ERR\n");
908                 err = 0;
909                 return;
910         }
911
912         DEBUG(10, ("Got '%s' from squid (length: %d).\n",buf,length));
913
914         if (buf[0] == '\0') {
915                 DEBUG(0, ("Invalid Request (empty)\n"));
916                 x_fprintf(x_stdout, "ERR\n");
917                 return;
918         }
919
920         if (opt_multiplex) {
921                 if (sscanf(buf, "%u ", &mux_id) != 1) {
922                         DEBUG(0, ("Invalid Request - no multiplex id\n"));
923                         x_fprintf(x_stdout, "ERR\n");
924                         return;
925                 }
926                 if (!mux_private) {
927                         mux_private = talloc(NULL, struct mux_private);
928                         mux_private->max_mux = 0;
929                         mux_private->private_pointers = NULL;
930                 }
931                 
932                 c=strchr(buf,' ');
933                 if (!c) {
934                         DEBUG(0, ("Invalid Request - no data after multiplex id\n"));
935                         x_fprintf(x_stdout, "ERR\n");
936                         return;
937                 }
938                 c++;
939                 if (mux_id >= mux_private->max_mux) {
940                         unsigned int prev_max = mux_private->max_mux;
941                         mux_private->max_mux = mux_id + 1;
942                         mux_private->private_pointers
943                                 = talloc_realloc(mux_private, 
944                                                    mux_private->private_pointers, 
945                                                    void *, mux_private->max_mux);
946                         memset(&mux_private->private_pointers[prev_max], '\0',  
947                                (sizeof(*mux_private->private_pointers) * (mux_private->max_mux - prev_max))); 
948                 };
949
950                 private = &mux_private->private_pointers[mux_id];
951         } else {
952                 c = buf;
953                 private = &normal_private;
954         }
955         
956         fn(helper_mode, c, length, private, mux_id, private2);
957 }
958
959 static void squid_stream(enum stdio_helper_mode stdio_mode, 
960                          stdio_helper_function fn) {
961         /* initialize FDescs */
962         x_setbuf(x_stdout, NULL);
963         x_setbuf(x_stderr, NULL);
964         while(1) {
965                 manage_squid_request(stdio_mode, fn, NULL);
966         }
967 }
968
969
970 /* Main program */
971
972 enum {
973         OPT_USERNAME = 1000,
974         OPT_DOMAIN,
975         OPT_WORKSTATION,
976         OPT_CHALLENGE,
977         OPT_RESPONSE,
978         OPT_LM,
979         OPT_NT,
980         OPT_PASSWORD,
981         OPT_LM_KEY,
982         OPT_USER_SESSION_KEY,
983         OPT_DIAGNOSTICS,
984         OPT_REQUIRE_MEMBERSHIP,
985         OPT_MULTIPLEX,
986         OPT_USE_CACHED_CREDS,
987 };
988
989 int main(int argc, const char **argv)
990 {
991         static const char *helper_protocol;
992         int opt;
993
994         poptContext pc;
995
996         /* NOTE: DO NOT change this interface without considering the implications!
997            This is an external interface, which other programs will use to interact 
998            with this helper.
999         */
1000
1001         /* We do not use single-letter command abbreviations, because they harm future 
1002            interface stability. */
1003
1004         struct poptOption long_options[] = {
1005                 POPT_AUTOHELP
1006                 { "helper-protocol", 0, POPT_ARG_STRING, &helper_protocol, OPT_DOMAIN, "operate as a stdio-based helper", "helper protocol to use"},
1007                 { "domain", 0, POPT_ARG_STRING, &opt_domain, OPT_DOMAIN, "domain name"},
1008                 { "workstation", 0, POPT_ARG_STRING, &opt_workstation, OPT_WORKSTATION, "workstation"},
1009                 { "username", 0, POPT_ARG_STRING, &opt_username, OPT_PASSWORD, "Username"},             
1010                 { "password", 0, POPT_ARG_STRING, &opt_password, OPT_PASSWORD, "User's plaintext password"},            
1011                 { "multiplex", 0, POPT_ARG_NONE, &opt_multiplex, OPT_MULTIPLEX, "Multiplex Mode"},
1012                 { "use-cached-creds", 0, POPT_ARG_NONE, &use_cached_creds, OPT_USE_CACHED_CREDS, "silently ignored for compatibility reasons"},
1013                 POPT_COMMON_SAMBA
1014                 POPT_COMMON_VERSION
1015                 { NULL }
1016         };
1017
1018         /* Samba client initialisation */
1019
1020         setup_logging(NULL, DEBUG_STDERR);
1021
1022         /* Parse options */
1023
1024         pc = poptGetContext("ntlm_auth", argc, argv, long_options, 0);
1025
1026         /* Parse command line options */
1027
1028         if (argc == 1) {
1029                 poptPrintHelp(pc, stderr, 0);
1030                 return 1;
1031         }
1032
1033         pc = poptGetContext(NULL, argc, (const char **)argv, long_options, 
1034                             POPT_CONTEXT_KEEP_FIRST);
1035
1036         while((opt = poptGetNextOpt(pc)) != -1) {
1037                 if (opt < -1) {
1038                         break;
1039                 }
1040         }
1041         if (opt < -1) {
1042                 fprintf(stderr, "%s: %s\n",
1043                         poptBadOption(pc, POPT_BADOPTION_NOALIAS),
1044                         poptStrerror(opt));
1045                 return 1;
1046         }
1047
1048         gensec_init();
1049
1050         if (opt_domain == NULL) {
1051                 opt_domain = lp_workgroup();
1052         }
1053
1054         if (helper_protocol) {
1055                 int i;
1056                 for (i=0; i<NUM_HELPER_MODES; i++) {
1057                         if (strcmp(helper_protocol, stdio_helper_protocols[i].name) == 0) {
1058                                 squid_stream(stdio_helper_protocols[i].mode, stdio_helper_protocols[i].fn);
1059                                 exit(0);
1060                         }
1061                 }
1062                 x_fprintf(x_stderr, "unknown helper protocol [%s]\n\nValid helper protools:\n\n", helper_protocol);
1063
1064                 for (i=0; i<NUM_HELPER_MODES; i++) {
1065                         x_fprintf(x_stderr, "%s\n", stdio_helper_protocols[i].name);
1066                 }
1067
1068                 exit(1);
1069         }
1070
1071         if (!opt_username) {
1072                 x_fprintf(x_stderr, "username must be specified!\n\n");
1073                 poptPrintHelp(pc, stderr, 0);
1074                 exit(1);
1075         }
1076
1077         if (opt_workstation == NULL) {
1078                 opt_workstation = lp_netbios_name();
1079         }
1080
1081         if (!opt_password) {
1082                 opt_password = getpass("password: ");
1083         }
1084
1085         {
1086                 char *user;
1087
1088                 asprintf(&user, "%s%c%s", opt_domain, *lp_winbind_separator(), opt_username);
1089                 if (!check_plaintext_auth(user, opt_password, True)) {
1090                         return 1;
1091                 }
1092         }
1093
1094         /* Exit code */
1095
1096         poptFreeContext(pc);
1097         return 0;
1098 }