65dbfb71650018840fdbb31400dac9a962c01a6a
[tprouty/samba.git] / source / utils / ntlm_auth.c
1 /* 
2    Unix SMB/CIFS implementation.
3
4    Winbind status program.
5
6    Copyright (C) Tim Potter      2000-2003
7    Copyright (C) Andrew Bartlett <abartlet@samba.org> 2003-2004
8    Copyright (C) Francesco Chemolli <kinkie@kame.usr.dsi.unimi.it> 2000 
9
10    This program is free software; you can redistribute it and/or modify
11    it under the terms of the GNU General Public License as published by
12    the Free Software Foundation; either version 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 "utils/ntlm_auth.h"
27
28 #undef DBGC_CLASS
29 #define DBGC_CLASS DBGC_WINBIND
30
31 #define SQUID_BUFFER_SIZE 2010
32
33 enum stdio_helper_mode {
34         SQUID_2_4_BASIC,
35         SQUID_2_5_BASIC,
36         SQUID_2_5_NTLMSSP,
37         NTLMSSP_CLIENT_1,
38         GSS_SPNEGO,
39         GSS_SPNEGO_CLIENT,
40         NTLM_SERVER_1,
41         NUM_HELPER_MODES
42 };
43
44 typedef void (*stdio_helper_function)(enum stdio_helper_mode stdio_helper_mode, 
45                                      char *buf, int length);
46
47 static void manage_squid_basic_request (enum stdio_helper_mode stdio_helper_mode, 
48                                         char *buf, int length);
49
50 static void manage_squid_ntlmssp_request (enum stdio_helper_mode stdio_helper_mode, 
51                                           char *buf, int length);
52
53 static void manage_client_ntlmssp_request (enum stdio_helper_mode stdio_helper_mode, 
54                                            char *buf, int length);
55
56 static void manage_gss_spnego_request (enum stdio_helper_mode stdio_helper_mode, 
57                                        char *buf, int length);
58
59 static void manage_gss_spnego_client_request (enum stdio_helper_mode stdio_helper_mode, 
60                                               char *buf, int length);
61
62 static void manage_ntlm_server_1_request (enum stdio_helper_mode stdio_helper_mode, 
63                                           char *buf, int length);
64
65 static const struct {
66         enum stdio_helper_mode mode;
67         const char *name;
68         stdio_helper_function fn;
69 } stdio_helper_protocols[] = {
70         { SQUID_2_4_BASIC, "squid-2.4-basic", manage_squid_basic_request},
71         { SQUID_2_5_BASIC, "squid-2.5-basic", manage_squid_basic_request},
72         { SQUID_2_5_NTLMSSP, "squid-2.5-ntlmssp", manage_squid_ntlmssp_request},
73         { NTLMSSP_CLIENT_1, "ntlmssp-client-1", manage_client_ntlmssp_request},
74         { GSS_SPNEGO, "gss-spnego", manage_gss_spnego_request},
75         { GSS_SPNEGO_CLIENT, "gss-spnego-client", manage_gss_spnego_client_request},
76         { NTLM_SERVER_1, "ntlm-server-1", manage_ntlm_server_1_request},
77         { NUM_HELPER_MODES, NULL, NULL}
78 };
79
80 extern int winbindd_fd;
81
82 const char *opt_username;
83 const char *opt_domain;
84 const char *opt_workstation;
85 const char *opt_password;
86 static DATA_BLOB opt_challenge;
87 static DATA_BLOB opt_lm_response;
88 static DATA_BLOB opt_nt_response;
89 static int request_lm_key;
90 static int request_user_session_key;
91
92 static const char *require_membership_of;
93 static const char *require_membership_of_sid;
94
95 static char winbind_separator(void)
96 {
97         struct winbindd_response response;
98         static BOOL got_sep;
99         static char sep;
100
101         if (got_sep)
102                 return sep;
103
104         ZERO_STRUCT(response);
105
106         /* Send off request */
107
108         if (winbindd_request_response(WINBINDD_INFO, NULL, &response) !=
109             NSS_STATUS_SUCCESS) {
110                 d_printf("could not obtain winbind separator!\n");
111                 return *lp_winbind_separator();
112         }
113
114         sep = response.data.info.winbind_separator;
115         got_sep = True;
116
117         if (!sep) {
118                 d_printf("winbind separator was NULL!\n");
119                 return *lp_winbind_separator();
120         }
121         
122         return sep;
123 }
124
125 const char *get_winbind_domain(void)
126 {
127         struct winbindd_response response;
128
129         static fstring winbind_domain;
130         if (*winbind_domain) {
131                 return winbind_domain;
132         }
133
134         ZERO_STRUCT(response);
135
136         /* Send off request */
137
138         if (winbindd_request_response(WINBINDD_DOMAIN_NAME, NULL, &response) !=
139             NSS_STATUS_SUCCESS) {
140                 DEBUG(0, ("could not obtain winbind domain name!\n"));
141                 return lp_workgroup();
142         }
143
144         fstrcpy(winbind_domain, response.data.domain_name);
145
146         return winbind_domain;
147
148 }
149
150 const char *get_winbind_netbios_name(void)
151 {
152         struct winbindd_response response;
153
154         static fstring winbind_netbios_name;
155
156         if (*winbind_netbios_name) {
157                 return winbind_netbios_name;
158         }
159
160         ZERO_STRUCT(response);
161
162         /* Send off request */
163
164         if (winbindd_request_response(WINBINDD_NETBIOS_NAME, NULL, &response) !=
165             NSS_STATUS_SUCCESS) {
166                 DEBUG(0, ("could not obtain winbind netbios name!\n"));
167                 return global_myname();
168         }
169
170         fstrcpy(winbind_netbios_name, response.data.netbios_name);
171
172         return winbind_netbios_name;
173
174 }
175
176 DATA_BLOB get_challenge(void) 
177 {
178         static DATA_BLOB chal;
179         if (opt_challenge.length)
180                 return opt_challenge;
181         
182         chal = data_blob(NULL, 8);
183
184         generate_random_buffer(chal.data, chal.length);
185         return chal;
186 }
187
188 /* Copy of parse_domain_user from winbindd_util.c.  Parse a string of the
189    form DOMAIN/user into a domain and a user */
190
191 static BOOL parse_ntlm_auth_domain_user(const char *domuser, fstring domain, 
192                                      fstring user)
193 {
194
195         char *p = strchr(domuser,winbind_separator());
196
197         if (!p) {
198                 return False;
199         }
200         
201         fstrcpy(user, p+1);
202         fstrcpy(domain, domuser);
203         domain[PTR_DIFF(p, domuser)] = 0;
204         strupper_m(domain);
205
206         return True;
207 }
208
209 static BOOL get_require_membership_sid(void) {
210         struct winbindd_request request;
211         struct winbindd_response response;
212
213         if (!require_membership_of) {
214                 return True;
215         }
216
217         if (require_membership_of_sid) {
218                 return True;
219         }
220
221         /* Otherwise, ask winbindd for the name->sid request */
222
223         ZERO_STRUCT(request);
224         ZERO_STRUCT(response);
225
226         if (!parse_ntlm_auth_domain_user(require_membership_of, 
227                                          request.data.name.dom_name, 
228                                          request.data.name.name)) {
229                 DEBUG(0, ("Could not parse %s into seperate domain/name parts!\n", 
230                           require_membership_of));
231                 return False;
232         }
233
234         if (winbindd_request_response(WINBINDD_LOOKUPNAME, &request, &response) !=
235             NSS_STATUS_SUCCESS) {
236                 DEBUG(0, ("Winbindd lookupname failed to resolve %s into a SID!\n", 
237                           require_membership_of));
238                 return False;
239         }
240
241         require_membership_of_sid = SMB_STRDUP(response.data.sid.sid);
242
243         if (require_membership_of_sid)
244                 return True;
245
246         return False;
247 }
248 /* Authenticate a user with a plaintext password */
249
250 static BOOL check_plaintext_auth(const char *user, const char *pass, 
251                                  BOOL stdout_diagnostics)
252 {
253         struct winbindd_request request;
254         struct winbindd_response response;
255         NSS_STATUS result;
256
257         if (!get_require_membership_sid()) {
258                 return False;
259         }
260
261         /* Send off request */
262
263         ZERO_STRUCT(request);
264         ZERO_STRUCT(response);
265
266         fstrcpy(request.data.auth.user, user);
267         fstrcpy(request.data.auth.pass, pass);
268         if (require_membership_of_sid)
269                 fstrcpy(request.data.auth.require_membership_of_sid, require_membership_of_sid);
270
271         result = winbindd_request_response(WINBINDD_PAM_AUTH, &request, &response);
272
273         /* Display response */
274         
275         if (stdout_diagnostics) {
276                 if ((result != NSS_STATUS_SUCCESS) && (response.data.auth.nt_status == 0)) {
277                         d_printf("Reading winbind reply failed! (0x01)\n");
278                 }
279                 
280                 d_printf("%s: %s (0x%x)\n", 
281                          response.data.auth.nt_status_string, 
282                          response.data.auth.error_string, 
283                          response.data.auth.nt_status);
284         } else {
285                 if ((result != NSS_STATUS_SUCCESS) && (response.data.auth.nt_status == 0)) {
286                         DEBUG(1, ("Reading winbind reply failed! (0x01)\n"));
287                 }
288                 
289                 DEBUG(3, ("%s: %s (0x%x)\n", 
290                           response.data.auth.nt_status_string, 
291                           response.data.auth.error_string,
292                           response.data.auth.nt_status));               
293         }
294                 
295         return (result == NSS_STATUS_SUCCESS);
296 }
297
298 /* authenticate a user with an encrypted username/password */
299
300 NTSTATUS contact_winbind_auth_crap(const char *username, 
301                                    const char *domain, 
302                                    const char *workstation,
303                                    const DATA_BLOB *challenge, 
304                                    const DATA_BLOB *lm_response, 
305                                    const DATA_BLOB *nt_response, 
306                                    uint32 flags, 
307                                    uint8 lm_key[8], 
308                                    uint8 user_session_key[16], 
309                                    char **error_string, 
310                                    char **unix_name) 
311 {
312         NTSTATUS nt_status;
313         NSS_STATUS result;
314         struct winbindd_request request;
315         struct winbindd_response response;
316
317         if (!get_require_membership_sid()) {
318                 return NT_STATUS_INVALID_PARAMETER;
319         }
320
321         ZERO_STRUCT(request);
322         ZERO_STRUCT(response);
323
324         request.flags = flags;
325
326         request.data.auth_crap.logon_parameters = MSV1_0_ALLOW_WORKSTATION_TRUST_ACCOUNT | MSV1_0_ALLOW_SERVER_TRUST_ACCOUNT;
327
328         if (require_membership_of_sid)
329                 fstrcpy(request.data.auth_crap.require_membership_of_sid, require_membership_of_sid);
330
331         fstrcpy(request.data.auth_crap.user, username);
332         fstrcpy(request.data.auth_crap.domain, domain);
333
334         fstrcpy(request.data.auth_crap.workstation, 
335                 workstation);
336
337         memcpy(request.data.auth_crap.chal, challenge->data, MIN(challenge->length, 8));
338
339         if (lm_response && lm_response->length) {
340                 memcpy(request.data.auth_crap.lm_resp, 
341                        lm_response->data, 
342                        MIN(lm_response->length, sizeof(request.data.auth_crap.lm_resp)));
343                 request.data.auth_crap.lm_resp_len = lm_response->length;
344         }
345
346         if (nt_response && nt_response->length) {
347                 memcpy(request.data.auth_crap.nt_resp, 
348                        nt_response->data, 
349                        MIN(nt_response->length, sizeof(request.data.auth_crap.nt_resp)));
350                 request.data.auth_crap.nt_resp_len = nt_response->length;
351         }
352         
353         result = winbindd_request_response(WINBINDD_PAM_AUTH_CRAP, &request, &response);
354
355         /* Display response */
356
357         if ((result != NSS_STATUS_SUCCESS) && (response.data.auth.nt_status == 0)) {
358                 nt_status = NT_STATUS_UNSUCCESSFUL;
359                 if (error_string)
360                         *error_string = smb_xstrdup("Reading winbind reply failed!");
361                 free_response(&response);
362                 return nt_status;
363         }
364         
365         nt_status = (NT_STATUS(response.data.auth.nt_status));
366         if (!NT_STATUS_IS_OK(nt_status)) {
367                 if (error_string) 
368                         *error_string = smb_xstrdup(response.data.auth.error_string);
369                 free_response(&response);
370                 return nt_status;
371         }
372
373         if ((flags & WBFLAG_PAM_LMKEY) && lm_key) {
374                 memcpy(lm_key, response.data.auth.first_8_lm_hash, 
375                        sizeof(response.data.auth.first_8_lm_hash));
376         }
377         if ((flags & WBFLAG_PAM_USER_SESSION_KEY) && user_session_key) {
378                 memcpy(user_session_key, response.data.auth.user_session_key, 
379                         sizeof(response.data.auth.user_session_key));
380         }
381
382         if (flags & WBFLAG_PAM_UNIX_NAME) {
383                 *unix_name = SMB_STRDUP((char *)response.extra_data);
384                 if (!*unix_name) {
385                         free_response(&response);
386                         return NT_STATUS_NO_MEMORY;
387                 }
388         }
389
390         free_response(&response);
391         return nt_status;
392 }
393                                    
394 static NTSTATUS winbind_pw_check(struct ntlmssp_state *ntlmssp_state, DATA_BLOB *user_session_key, DATA_BLOB *lm_session_key) 
395 {
396         static const char zeros[16];
397         NTSTATUS nt_status;
398         char *error_string;
399         uint8 lm_key[8]; 
400         uint8 user_sess_key[16]; 
401         char *unix_name;
402
403         nt_status = contact_winbind_auth_crap(ntlmssp_state->user, ntlmssp_state->domain,
404                                               ntlmssp_state->workstation,
405                                               &ntlmssp_state->chal,
406                                               &ntlmssp_state->lm_resp,
407                                               &ntlmssp_state->nt_resp, 
408                                               WBFLAG_PAM_LMKEY | WBFLAG_PAM_USER_SESSION_KEY | WBFLAG_PAM_UNIX_NAME,
409                                               lm_key, user_sess_key, 
410                                               &error_string, &unix_name);
411
412         if (NT_STATUS_IS_OK(nt_status)) {
413                 if (memcmp(lm_key, zeros, 8) != 0) {
414                         *lm_session_key = data_blob(NULL, 16);
415                         memcpy(lm_session_key->data, lm_key, 8);
416                         memset(lm_session_key->data+8, '\0', 8);
417                 }
418                 
419                 if (memcmp(user_sess_key, zeros, 16) != 0) {
420                         *user_session_key = data_blob(user_sess_key, 16);
421                 }
422                 ntlmssp_state->auth_context = talloc_strdup(ntlmssp_state->mem_ctx, unix_name);
423                 SAFE_FREE(unix_name);
424         } else {
425                 DEBUG(NT_STATUS_EQUAL(nt_status, NT_STATUS_ACCESS_DENIED) ? 0 : 3, 
426                       ("Login for user [%s]\\[%s]@[%s] failed due to [%s]\n", 
427                        ntlmssp_state->domain, ntlmssp_state->user, 
428                        ntlmssp_state->workstation, 
429                        error_string ? error_string : "unknown error (NULL)"));
430                 ntlmssp_state->auth_context = NULL;
431         }
432         return nt_status;
433 }
434
435 static NTSTATUS local_pw_check(struct ntlmssp_state *ntlmssp_state, DATA_BLOB *user_session_key, DATA_BLOB *lm_session_key) 
436 {
437         NTSTATUS nt_status;
438         uint8 lm_pw[16], nt_pw[16];
439
440         nt_lm_owf_gen (opt_password, nt_pw, lm_pw);
441         
442         nt_status = ntlm_password_check(ntlmssp_state->mem_ctx, 
443                                         &ntlmssp_state->chal,
444                                         &ntlmssp_state->lm_resp,
445                                         &ntlmssp_state->nt_resp, 
446                                         NULL, NULL,
447                                         ntlmssp_state->user, 
448                                         ntlmssp_state->user, 
449                                         ntlmssp_state->domain,
450                                         lm_pw, nt_pw, user_session_key, lm_session_key);
451         
452         if (NT_STATUS_IS_OK(nt_status)) {
453                 ntlmssp_state->auth_context = talloc_asprintf(ntlmssp_state->mem_ctx, 
454                                                               "%s%c%s", ntlmssp_state->domain, 
455                                                               *lp_winbind_separator(), 
456                                                               ntlmssp_state->user);
457         } else {
458                 DEBUG(3, ("Login for user [%s]\\[%s]@[%s] failed due to [%s]\n", 
459                           ntlmssp_state->domain, ntlmssp_state->user, ntlmssp_state->workstation, 
460                           nt_errstr(nt_status)));
461                 ntlmssp_state->auth_context = NULL;
462         }
463         return nt_status;
464 }
465
466 static NTSTATUS ntlm_auth_start_ntlmssp_client(NTLMSSP_STATE **client_ntlmssp_state) 
467 {
468         NTSTATUS status;
469         if ( (opt_username == NULL) || (opt_domain == NULL) ) {
470                 status = NT_STATUS_UNSUCCESSFUL;
471                 DEBUG(1, ("Need username and domain for NTLMSSP\n"));
472                 return NT_STATUS_INVALID_PARAMETER;
473         }
474
475         status = ntlmssp_client_start(client_ntlmssp_state);
476
477         if (!NT_STATUS_IS_OK(status)) {
478                 DEBUG(1, ("Could not start NTLMSSP client: %s\n",
479                           nt_errstr(status)));
480                 ntlmssp_end(client_ntlmssp_state);
481                 return status;
482         }
483
484         status = ntlmssp_set_username(*client_ntlmssp_state, opt_username);
485
486         if (!NT_STATUS_IS_OK(status)) {
487                 DEBUG(1, ("Could not set username: %s\n",
488                           nt_errstr(status)));
489                 ntlmssp_end(client_ntlmssp_state);
490                 return status;
491         }
492
493         status = ntlmssp_set_domain(*client_ntlmssp_state, opt_domain);
494
495         if (!NT_STATUS_IS_OK(status)) {
496                 DEBUG(1, ("Could not set domain: %s\n",
497                           nt_errstr(status)));
498                 ntlmssp_end(client_ntlmssp_state);
499                 return status;
500         }
501
502         status = ntlmssp_set_password(*client_ntlmssp_state, opt_password);
503         
504         if (!NT_STATUS_IS_OK(status)) {
505                 DEBUG(1, ("Could not set password: %s\n",
506                           nt_errstr(status)));
507                 ntlmssp_end(client_ntlmssp_state);
508                 return status;
509         }
510         return NT_STATUS_OK;
511 }
512
513 static NTSTATUS ntlm_auth_start_ntlmssp_server(NTLMSSP_STATE **ntlmssp_state) 
514 {
515         NTSTATUS status = ntlmssp_server_start(ntlmssp_state);
516         
517         if (!NT_STATUS_IS_OK(status)) {
518                 DEBUG(1, ("Could not start NTLMSSP client: %s\n",
519                           nt_errstr(status)));
520                 return status;
521         }
522
523         /* Have we been given a local password, or should we ask winbind? */
524         if (opt_password) {
525                 (*ntlmssp_state)->check_password = local_pw_check;
526                 (*ntlmssp_state)->get_domain = lp_workgroup;
527                 (*ntlmssp_state)->get_global_myname = global_myname;
528         } else {
529                 (*ntlmssp_state)->check_password = winbind_pw_check;
530                 (*ntlmssp_state)->get_domain = get_winbind_domain;
531                 (*ntlmssp_state)->get_global_myname = get_winbind_netbios_name;
532         }
533         return NT_STATUS_OK;
534 }
535
536 static void manage_squid_ntlmssp_request(enum stdio_helper_mode stdio_helper_mode, 
537                                          char *buf, int length) 
538 {
539         static NTLMSSP_STATE *ntlmssp_state = NULL;
540         DATA_BLOB request, reply;
541         NTSTATUS nt_status;
542
543         if (strlen(buf) < 2) {
544                 DEBUG(1, ("NTLMSSP query [%s] invalid", buf));
545                 x_fprintf(x_stdout, "BH\n");
546                 return;
547         }
548
549         if (strlen(buf) > 3) {
550                 request = base64_decode_data_blob(buf + 3);
551         } else {
552                 request = data_blob(NULL, 0);
553         }
554
555         if ((strncmp(buf, "PW ", 3) == 0)) {
556                 /* The calling application wants us to use a local password (rather than winbindd) */
557
558                 opt_password = SMB_STRNDUP((const char *)request.data, request.length);
559
560                 if (opt_password == NULL) {
561                         DEBUG(1, ("Out of memory\n"));
562                         x_fprintf(x_stdout, "BH\n");
563                         data_blob_free(&request);
564                         return;
565                 }
566
567                 x_fprintf(x_stdout, "OK\n");
568                 data_blob_free(&request);
569                 return;
570         }
571
572         if (strncmp(buf, "YR", 2) == 0) {
573                 if (ntlmssp_state)
574                         ntlmssp_end(&ntlmssp_state);
575         } else if (strncmp(buf, "KK", 2) == 0) {
576                 
577         } else {
578                 DEBUG(1, ("NTLMSSP query [%s] invalid", buf));
579                 x_fprintf(x_stdout, "BH\n");
580                 return;
581         }
582
583         if (!ntlmssp_state) {
584                 if (!NT_STATUS_IS_OK(nt_status = ntlm_auth_start_ntlmssp_server(&ntlmssp_state))) {
585                         x_fprintf(x_stdout, "BH %s\n", nt_errstr(nt_status));
586                         return;
587                 }
588         }
589
590         DEBUG(10, ("got NTLMSSP packet:\n"));
591         dump_data(10, (const char *)request.data, request.length);
592
593         nt_status = ntlmssp_update(ntlmssp_state, request, &reply);
594         
595         if (NT_STATUS_EQUAL(nt_status, NT_STATUS_MORE_PROCESSING_REQUIRED)) {
596                 char *reply_base64 = base64_encode_data_blob(reply);
597                 x_fprintf(x_stdout, "TT %s\n", reply_base64);
598                 SAFE_FREE(reply_base64);
599                 data_blob_free(&reply);
600                 DEBUG(10, ("NTLMSSP challenge\n"));
601         } else if (NT_STATUS_EQUAL(nt_status, NT_STATUS_ACCESS_DENIED)) {
602                 x_fprintf(x_stdout, "BH %s\n", nt_errstr(nt_status));
603                 DEBUG(0, ("NTLMSSP BH: %s\n", nt_errstr(nt_status)));
604
605                 ntlmssp_end(&ntlmssp_state);
606         } else if (!NT_STATUS_IS_OK(nt_status)) {
607                 x_fprintf(x_stdout, "NA %s\n", nt_errstr(nt_status));
608                 DEBUG(10, ("NTLMSSP %s\n", nt_errstr(nt_status)));
609         } else {
610                 x_fprintf(x_stdout, "AF %s\n", (char *)ntlmssp_state->auth_context);
611                 DEBUG(10, ("NTLMSSP OK!\n"));
612         }
613
614         data_blob_free(&request);
615 }
616
617 static void manage_client_ntlmssp_request(enum stdio_helper_mode stdio_helper_mode, 
618                                          char *buf, int length) 
619 {
620         static NTLMSSP_STATE *ntlmssp_state = NULL;
621         DATA_BLOB request, reply;
622         NTSTATUS nt_status;
623         BOOL first = False;
624         
625         if (strlen(buf) < 2) {
626                 DEBUG(1, ("NTLMSSP query [%s] invalid", buf));
627                 x_fprintf(x_stdout, "BH\n");
628                 return;
629         }
630
631         if (strlen(buf) > 3) {
632                 request = base64_decode_data_blob(buf + 3);
633         } else {
634                 request = data_blob(NULL, 0);
635         }
636
637         if (strncmp(buf, "PW ", 3) == 0) {
638                 /* We asked for a password and obviously got it :-) */
639
640                 opt_password = SMB_STRNDUP((const char *)request.data, request.length);
641
642                 if (opt_password == NULL) {
643                         DEBUG(1, ("Out of memory\n"));
644                         x_fprintf(x_stdout, "BH\n");
645                         data_blob_free(&request);
646                         return;
647                 }
648
649                 x_fprintf(x_stdout, "OK\n");
650                 data_blob_free(&request);
651                 return;
652         }
653
654         if (opt_password == NULL) {
655                 
656                 /* Request a password from the calling process.  After
657                    sending it, the calling process should retry asking for the negotiate. */
658                 
659                 DEBUG(10, ("Requesting password\n"));
660                 x_fprintf(x_stdout, "PW\n");
661                 return;
662         }
663
664         if (strncmp(buf, "YR", 2) == 0) {
665                 if (ntlmssp_state)
666                         ntlmssp_end(&ntlmssp_state);
667         } else if (strncmp(buf, "TT", 2) == 0) {
668                 
669         } else {
670                 DEBUG(1, ("NTLMSSP query [%s] invalid", buf));
671                 x_fprintf(x_stdout, "BH\n");
672                 return;
673         }
674
675         if (!ntlmssp_state) {
676                 if (!NT_STATUS_IS_OK(nt_status = ntlm_auth_start_ntlmssp_client(&ntlmssp_state))) {
677                         x_fprintf(x_stdout, "BH %s\n", nt_errstr(nt_status));
678                         return;
679                 }
680                 first = True;
681         }
682
683         DEBUG(10, ("got NTLMSSP packet:\n"));
684         dump_data(10, (const char *)request.data, request.length);
685
686         nt_status = ntlmssp_update(ntlmssp_state, request, &reply);
687         
688         if (NT_STATUS_EQUAL(nt_status, NT_STATUS_MORE_PROCESSING_REQUIRED)) {
689                 char *reply_base64 = base64_encode_data_blob(reply);
690                 if (first) {
691                         x_fprintf(x_stdout, "YR %s\n", reply_base64);
692                 } else { 
693                         x_fprintf(x_stdout, "KK %s\n", reply_base64);
694                 }
695                 SAFE_FREE(reply_base64);
696                 data_blob_free(&reply);
697                 DEBUG(10, ("NTLMSSP challenge\n"));
698         } else if (NT_STATUS_IS_OK(nt_status)) {
699                 char *reply_base64 = base64_encode_data_blob(reply);
700                 x_fprintf(x_stdout, "AF %s\n", reply_base64);
701                 DEBUG(10, ("NTLMSSP OK!\n"));
702                 if (ntlmssp_state)
703                         ntlmssp_end(&ntlmssp_state);
704         } else {
705                 x_fprintf(x_stdout, "BH %s\n", nt_errstr(nt_status));
706                 DEBUG(0, ("NTLMSSP BH: %s\n", nt_errstr(nt_status)));
707                 if (ntlmssp_state)
708                         ntlmssp_end(&ntlmssp_state);
709         }
710
711         data_blob_free(&request);
712 }
713
714 static void manage_squid_basic_request(enum stdio_helper_mode stdio_helper_mode, 
715                                        char *buf, int length) 
716 {
717         char *user, *pass;      
718         user=buf;
719         
720         pass=memchr(buf,' ',length);
721         if (!pass) {
722                 DEBUG(2, ("Password not found. Denying access\n"));
723                 x_fprintf(x_stdout, "ERR\n");
724                 return;
725         }
726         *pass='\0';
727         pass++;
728         
729         if (stdio_helper_mode == SQUID_2_5_BASIC) {
730                 rfc1738_unescape(user);
731                 rfc1738_unescape(pass);
732         }
733         
734         if (check_plaintext_auth(user, pass, False)) {
735                 x_fprintf(x_stdout, "OK\n");
736         } else {
737                 x_fprintf(x_stdout, "ERR\n");
738         }
739 }
740
741 static void offer_gss_spnego_mechs(void) {
742
743         DATA_BLOB token;
744         SPNEGO_DATA spnego;
745         ssize_t len;
746         char *reply_base64;
747
748         pstring principal;
749         pstring myname_lower;
750
751         ZERO_STRUCT(spnego);
752
753         pstrcpy(myname_lower, global_myname());
754         strlower_m(myname_lower);
755
756         pstr_sprintf(principal, "%s$@%s", myname_lower, lp_realm());
757
758         /* Server negTokenInit (mech offerings) */
759         spnego.type = SPNEGO_NEG_TOKEN_INIT;
760         spnego.negTokenInit.mechTypes = SMB_XMALLOC_ARRAY(const char *, 2);
761 #ifdef HAVE_KRB5
762         spnego.negTokenInit.mechTypes[0] = smb_xstrdup(OID_KERBEROS5_OLD);
763         spnego.negTokenInit.mechTypes[1] = smb_xstrdup(OID_NTLMSSP);
764         spnego.negTokenInit.mechTypes[2] = NULL;
765 #else
766         spnego.negTokenInit.mechTypes[0] = smb_xstrdup(OID_NTLMSSP);
767         spnego.negTokenInit.mechTypes[1] = NULL;
768 #endif
769
770
771         spnego.negTokenInit.mechListMIC = data_blob(principal,
772                                                     strlen(principal));
773
774         len = write_spnego_data(&token, &spnego);
775         free_spnego_data(&spnego);
776
777         if (len == -1) {
778                 DEBUG(1, ("Could not write SPNEGO data blob\n"));
779                 x_fprintf(x_stdout, "BH\n");
780                 return;
781         }
782
783         reply_base64 = base64_encode_data_blob(token);
784         x_fprintf(x_stdout, "TT %s *\n", reply_base64);
785
786         SAFE_FREE(reply_base64);
787         data_blob_free(&token);
788         DEBUG(10, ("sent SPNEGO negTokenInit\n"));
789         return;
790 }
791
792 static void manage_gss_spnego_request(enum stdio_helper_mode stdio_helper_mode, 
793                                       char *buf, int length) 
794 {
795         static NTLMSSP_STATE *ntlmssp_state = NULL;
796         SPNEGO_DATA request, response;
797         DATA_BLOB token;
798         NTSTATUS status;
799         ssize_t len;
800
801         char *user = NULL;
802         char *domain = NULL;
803
804         const char *reply_code;
805         char       *reply_base64;
806         pstring     reply_argument;
807
808         if (strlen(buf) < 2) {
809                 DEBUG(1, ("SPENGO query [%s] invalid", buf));
810                 x_fprintf(x_stdout, "BH\n");
811                 return;
812         }
813
814         if (strncmp(buf, "YR", 2) == 0) {
815                 if (ntlmssp_state)
816                         ntlmssp_end(&ntlmssp_state);
817         } else if (strncmp(buf, "KK", 2) == 0) {
818                 
819         } else {
820                 DEBUG(1, ("SPENGO query [%s] invalid", buf));
821                 x_fprintf(x_stdout, "BH\n");
822                 return;
823         }
824
825         if ( (strlen(buf) == 2)) {
826
827                 /* no client data, get the negTokenInit offering
828                    mechanisms */
829
830                 offer_gss_spnego_mechs();
831                 return;
832         }
833
834         /* All subsequent requests have a blob. This might be negTokenInit or negTokenTarg */
835
836         if (strlen(buf) <= 3) {
837                 DEBUG(1, ("GSS-SPNEGO query [%s] invalid\n", buf));
838                 x_fprintf(x_stdout, "BH\n");
839                 return;
840         }
841
842         token = base64_decode_data_blob(buf + 3);
843         len = read_spnego_data(token, &request);
844         data_blob_free(&token);
845
846         if (len == -1) {
847                 DEBUG(1, ("GSS-SPNEGO query [%s] invalid", buf));
848                 x_fprintf(x_stdout, "BH\n");
849                 return;
850         }
851
852         if (request.type == SPNEGO_NEG_TOKEN_INIT) {
853
854                 /* Second request from Client. This is where the
855                    client offers its mechanism to use. */
856
857                 if ( (request.negTokenInit.mechTypes == NULL) ||
858                      (request.negTokenInit.mechTypes[0] == NULL) ) {
859                         DEBUG(1, ("Client did not offer any mechanism"));
860                         x_fprintf(x_stdout, "BH\n");
861                         return;
862                 }
863
864                 status = NT_STATUS_UNSUCCESSFUL;
865                 if (strcmp(request.negTokenInit.mechTypes[0], OID_NTLMSSP) == 0) {
866
867                         if ( request.negTokenInit.mechToken.data == NULL ) {
868                                 DEBUG(1, ("Client did not provide  NTLMSSP data\n"));
869                                 x_fprintf(x_stdout, "BH\n");
870                                 return;
871                         }
872
873                         if ( ntlmssp_state != NULL ) {
874                                 DEBUG(1, ("Client wants a new NTLMSSP challenge, but "
875                                           "already got one\n"));
876                                 x_fprintf(x_stdout, "BH\n");
877                                 ntlmssp_end(&ntlmssp_state);
878                                 return;
879                         }
880
881                         if (!NT_STATUS_IS_OK(status = ntlm_auth_start_ntlmssp_server(&ntlmssp_state))) {
882                                 x_fprintf(x_stdout, "BH %s\n", nt_errstr(status));
883                                 return;
884                         }
885
886                         DEBUG(10, ("got NTLMSSP packet:\n"));
887                         dump_data(10, (const char *)request.negTokenInit.mechToken.data,
888                                   request.negTokenInit.mechToken.length);
889
890                         response.type = SPNEGO_NEG_TOKEN_TARG;
891                         response.negTokenTarg.supportedMech = SMB_STRDUP(OID_NTLMSSP);
892                         response.negTokenTarg.mechListMIC = data_blob(NULL, 0);
893
894                         status = ntlmssp_update(ntlmssp_state,
895                                                        request.negTokenInit.mechToken,
896                                                        &response.negTokenTarg.responseToken);
897                 }
898
899 #ifdef HAVE_KRB5
900                 if (strcmp(request.negTokenInit.mechTypes[0], OID_KERBEROS5_OLD) == 0) {
901
902                         TALLOC_CTX *mem_ctx = talloc_init("manage_gss_spnego_request");
903                         char *principal;
904                         DATA_BLOB ap_rep;
905                         DATA_BLOB session_key;
906
907                         if ( request.negTokenInit.mechToken.data == NULL ) {
908                                 DEBUG(1, ("Client did not provide Kerberos data\n"));
909                                 x_fprintf(x_stdout, "BH\n");
910                                 return;
911                         }
912
913                         response.type = SPNEGO_NEG_TOKEN_TARG;
914                         response.negTokenTarg.supportedMech = SMB_STRDUP(OID_KERBEROS5_OLD);
915                         response.negTokenTarg.mechListMIC = data_blob(NULL, 0);
916                         response.negTokenTarg.responseToken = data_blob(NULL, 0);
917
918                         status = ads_verify_ticket(mem_ctx, lp_realm(),
919                                                    &request.negTokenInit.mechToken,
920                                                    &principal, NULL, &ap_rep,
921                                                    &session_key);
922
923                         talloc_destroy(mem_ctx);
924
925                         /* Now in "principal" we have the name we are
926                            authenticated as. */
927
928                         if (NT_STATUS_IS_OK(status)) {
929
930                                 domain = strchr_m(principal, '@');
931
932                                 if (domain == NULL) {
933                                         DEBUG(1, ("Did not get a valid principal "
934                                                   "from ads_verify_ticket\n"));
935                                         x_fprintf(x_stdout, "BH\n");
936                                         return;
937                                 }
938
939                                 *domain++ = '\0';
940                                 domain = SMB_STRDUP(domain);
941                                 user = SMB_STRDUP(principal);
942
943                                 data_blob_free(&ap_rep);
944
945                                 SAFE_FREE(principal);
946                         }
947                 }
948 #endif
949
950         } else {
951
952                 if ( (request.negTokenTarg.supportedMech == NULL) ||
953                      ( strcmp(request.negTokenTarg.supportedMech, OID_NTLMSSP) != 0 ) ) {
954                         /* Kerberos should never send a negTokenTarg, OID_NTLMSSP
955                            is the only one we support that sends this stuff */
956                         DEBUG(1, ("Got a negTokenTarg for something non-NTLMSSP: %s\n",
957                                   request.negTokenTarg.supportedMech));
958                         x_fprintf(x_stdout, "BH\n");
959                         return;
960                 }
961
962                 if (request.negTokenTarg.responseToken.data == NULL) {
963                         DEBUG(1, ("Got a negTokenTarg without a responseToken!\n"));
964                         x_fprintf(x_stdout, "BH\n");
965                         return;
966                 }
967
968                 status = ntlmssp_update(ntlmssp_state,
969                                                request.negTokenTarg.responseToken,
970                                                &response.negTokenTarg.responseToken);
971
972                 response.type = SPNEGO_NEG_TOKEN_TARG;
973                 response.negTokenTarg.supportedMech = SMB_STRDUP(OID_NTLMSSP);
974                 response.negTokenTarg.mechListMIC = data_blob(NULL, 0);
975
976                 if (NT_STATUS_IS_OK(status)) {
977                         user = SMB_STRDUP(ntlmssp_state->user);
978                         domain = SMB_STRDUP(ntlmssp_state->domain);
979                         ntlmssp_end(&ntlmssp_state);
980                 }
981         }
982
983         free_spnego_data(&request);
984
985         if (NT_STATUS_IS_OK(status)) {
986                 response.negTokenTarg.negResult = SPNEGO_ACCEPT_COMPLETED;
987                 reply_code = "AF";
988                 pstr_sprintf(reply_argument, "%s\\%s", domain, user);
989         } else if (NT_STATUS_EQUAL(status,
990                                    NT_STATUS_MORE_PROCESSING_REQUIRED)) {
991                 response.negTokenTarg.negResult = SPNEGO_ACCEPT_INCOMPLETE;
992                 reply_code = "TT";
993                 pstr_sprintf(reply_argument, "*");
994         } else {
995                 response.negTokenTarg.negResult = SPNEGO_REJECT;
996                 reply_code = "NA";
997                 pstrcpy(reply_argument, nt_errstr(status));
998         }
999
1000         SAFE_FREE(user);
1001         SAFE_FREE(domain);
1002
1003         len = write_spnego_data(&token, &response);
1004         free_spnego_data(&response);
1005
1006         if (len == -1) {
1007                 DEBUG(1, ("Could not write SPNEGO data blob\n"));
1008                 x_fprintf(x_stdout, "BH\n");
1009                 return;
1010         }
1011
1012         reply_base64 = base64_encode_data_blob(token);
1013
1014         x_fprintf(x_stdout, "%s %s %s\n",
1015                   reply_code, reply_base64, reply_argument);
1016
1017         SAFE_FREE(reply_base64);
1018         data_blob_free(&token);
1019
1020         return;
1021 }
1022
1023 static NTLMSSP_STATE *client_ntlmssp_state = NULL;
1024
1025 static BOOL manage_client_ntlmssp_init(SPNEGO_DATA spnego)
1026 {
1027         NTSTATUS status;
1028         DATA_BLOB null_blob = data_blob(NULL, 0);
1029         DATA_BLOB to_server;
1030         char *to_server_base64;
1031         const char *my_mechs[] = {OID_NTLMSSP, NULL};
1032
1033         DEBUG(10, ("Got spnego negTokenInit with NTLMSSP\n"));
1034
1035         if (client_ntlmssp_state != NULL) {
1036                 DEBUG(1, ("Request for initial SPNEGO request where "
1037                           "we already have a state\n"));
1038                 return False;
1039         }
1040
1041         if (!client_ntlmssp_state) {
1042                 if (!NT_STATUS_IS_OK(status = ntlm_auth_start_ntlmssp_client(&client_ntlmssp_state))) {
1043                         x_fprintf(x_stdout, "BH %s\n", nt_errstr(status));
1044                         return False;
1045                 }
1046         }
1047
1048
1049         if (opt_password == NULL) {
1050
1051                 /* Request a password from the calling process.  After
1052                    sending it, the calling process should retry with
1053                    the negTokenInit. */
1054
1055                 DEBUG(10, ("Requesting password\n"));
1056                 x_fprintf(x_stdout, "PW\n");
1057                 return True;
1058         }
1059
1060         spnego.type = SPNEGO_NEG_TOKEN_INIT;
1061         spnego.negTokenInit.mechTypes = my_mechs;
1062         spnego.negTokenInit.reqFlags = 0;
1063         spnego.negTokenInit.mechListMIC = null_blob;
1064
1065         status = ntlmssp_update(client_ntlmssp_state, null_blob,
1066                                        &spnego.negTokenInit.mechToken);
1067
1068         if ( !(NT_STATUS_EQUAL(status, NT_STATUS_MORE_PROCESSING_REQUIRED) ||
1069                         NT_STATUS_IS_OK(status)) ) {
1070                 DEBUG(1, ("Expected OK or MORE_PROCESSING_REQUIRED, got: %s\n",
1071                           nt_errstr(status)));
1072                 ntlmssp_end(&client_ntlmssp_state);
1073                 return False;
1074         }
1075
1076         write_spnego_data(&to_server, &spnego);
1077         data_blob_free(&spnego.negTokenInit.mechToken);
1078
1079         to_server_base64 = base64_encode_data_blob(to_server);
1080         data_blob_free(&to_server);
1081         x_fprintf(x_stdout, "KK %s\n", to_server_base64);
1082         SAFE_FREE(to_server_base64);
1083         return True;
1084 }
1085
1086 static void manage_client_ntlmssp_targ(SPNEGO_DATA spnego)
1087 {
1088         NTSTATUS status;
1089         DATA_BLOB null_blob = data_blob(NULL, 0);
1090         DATA_BLOB request;
1091         DATA_BLOB to_server;
1092         char *to_server_base64;
1093
1094         DEBUG(10, ("Got spnego negTokenTarg with NTLMSSP\n"));
1095
1096         if (client_ntlmssp_state == NULL) {
1097                 DEBUG(1, ("Got NTLMSSP tArg without a client state\n"));
1098                 x_fprintf(x_stdout, "BH\n");
1099                 ntlmssp_end(&client_ntlmssp_state);
1100                 return;
1101         }
1102
1103         if (spnego.negTokenTarg.negResult == SPNEGO_REJECT) {
1104                 x_fprintf(x_stdout, "NA\n");
1105                 ntlmssp_end(&client_ntlmssp_state);
1106                 return;
1107         }
1108
1109         if (spnego.negTokenTarg.negResult == SPNEGO_ACCEPT_COMPLETED) {
1110                 x_fprintf(x_stdout, "AF\n");
1111                 ntlmssp_end(&client_ntlmssp_state);
1112                 return;
1113         }
1114
1115         status = ntlmssp_update(client_ntlmssp_state,
1116                                        spnego.negTokenTarg.responseToken,
1117                                        &request);
1118                 
1119         if (!NT_STATUS_EQUAL(status, NT_STATUS_MORE_PROCESSING_REQUIRED)) {
1120                 DEBUG(1, ("Expected MORE_PROCESSING_REQUIRED from "
1121                           "ntlmssp_client_update, got: %s\n",
1122                           nt_errstr(status)));
1123                 x_fprintf(x_stdout, "BH\n");
1124                 data_blob_free(&request);
1125                 ntlmssp_end(&client_ntlmssp_state);
1126                 return;
1127         }
1128
1129         spnego.type = SPNEGO_NEG_TOKEN_TARG;
1130         spnego.negTokenTarg.negResult = SPNEGO_ACCEPT_INCOMPLETE;
1131         spnego.negTokenTarg.supportedMech = (char *)OID_NTLMSSP;
1132         spnego.negTokenTarg.responseToken = request;
1133         spnego.negTokenTarg.mechListMIC = null_blob;
1134         
1135         write_spnego_data(&to_server, &spnego);
1136         data_blob_free(&request);
1137
1138         to_server_base64 = base64_encode_data_blob(to_server);
1139         data_blob_free(&to_server);
1140         x_fprintf(x_stdout, "KK %s\n", to_server_base64);
1141         SAFE_FREE(to_server_base64);
1142         return;
1143 }
1144
1145 #ifdef HAVE_KRB5
1146
1147 static BOOL manage_client_krb5_init(SPNEGO_DATA spnego)
1148 {
1149         char *principal;
1150         DATA_BLOB tkt, to_server;
1151         DATA_BLOB session_key_krb5 = data_blob(NULL, 0);
1152         SPNEGO_DATA reply;
1153         char *reply_base64;
1154         int retval;
1155         
1156         const char *my_mechs[] = {OID_KERBEROS5_OLD, NULL};
1157         ssize_t len;
1158
1159         if ( (spnego.negTokenInit.mechListMIC.data == NULL) ||
1160              (spnego.negTokenInit.mechListMIC.length == 0) ) {
1161                 DEBUG(1, ("Did not get a principal for krb5\n"));
1162                 return False;
1163         }
1164
1165         principal = SMB_MALLOC(spnego.negTokenInit.mechListMIC.length+1);
1166
1167         if (principal == NULL) {
1168                 DEBUG(1, ("Could not malloc principal\n"));
1169                 return False;
1170         }
1171
1172         memcpy(principal, spnego.negTokenInit.mechListMIC.data,
1173                spnego.negTokenInit.mechListMIC.length);
1174         principal[spnego.negTokenInit.mechListMIC.length] = '\0';
1175
1176         retval = cli_krb5_get_ticket(principal, 0, &tkt, &session_key_krb5, 0);
1177
1178         if (retval) {
1179
1180                 pstring user;
1181
1182                 /* Let's try to first get the TGT, for that we need a
1183                    password. */
1184
1185                 if (opt_password == NULL) {
1186                         DEBUG(10, ("Requesting password\n"));
1187                         x_fprintf(x_stdout, "PW\n");
1188                         return True;
1189                 }
1190
1191                 pstr_sprintf(user, "%s@%s", opt_username, opt_domain);
1192
1193                 if ((retval = kerberos_kinit_password(user, opt_password, 
1194                                                       0, NULL, NULL))) {
1195                         DEBUG(10, ("Requesting TGT failed: %s\n", error_message(retval)));
1196                         return False;
1197                 }
1198
1199                 retval = cli_krb5_get_ticket(principal, 0, &tkt, &session_key_krb5, 0);
1200
1201                 if (retval) {
1202                         DEBUG(10, ("Kinit suceeded, but getting a ticket failed: %s\n", error_message(retval)));
1203                         return False;
1204                 }
1205         }
1206
1207         data_blob_free(&session_key_krb5);
1208
1209         ZERO_STRUCT(reply);
1210
1211         reply.type = SPNEGO_NEG_TOKEN_INIT;
1212         reply.negTokenInit.mechTypes = my_mechs;
1213         reply.negTokenInit.reqFlags = 0;
1214         reply.negTokenInit.mechToken = tkt;
1215         reply.negTokenInit.mechListMIC = data_blob(NULL, 0);
1216
1217         len = write_spnego_data(&to_server, &reply);
1218         data_blob_free(&tkt);
1219
1220         if (len == -1) {
1221                 DEBUG(1, ("Could not write SPNEGO data blob\n"));
1222                 return False;
1223         }
1224
1225         reply_base64 = base64_encode_data_blob(to_server);
1226         x_fprintf(x_stdout, "KK %s *\n", reply_base64);
1227
1228         SAFE_FREE(reply_base64);
1229         data_blob_free(&to_server);
1230         DEBUG(10, ("sent GSS-SPNEGO KERBEROS5 negTokenInit\n"));
1231         return True;
1232 }
1233
1234 static void manage_client_krb5_targ(SPNEGO_DATA spnego)
1235 {
1236         switch (spnego.negTokenTarg.negResult) {
1237         case SPNEGO_ACCEPT_INCOMPLETE:
1238                 DEBUG(1, ("Got a Kerberos negTokenTarg with ACCEPT_INCOMPLETE\n"));
1239                 x_fprintf(x_stdout, "BH\n");
1240                 break;
1241         case SPNEGO_ACCEPT_COMPLETED:
1242                 DEBUG(10, ("Accept completed\n"));
1243                 x_fprintf(x_stdout, "AF\n");
1244                 break;
1245         case SPNEGO_REJECT:
1246                 DEBUG(10, ("Rejected\n"));
1247                 x_fprintf(x_stdout, "NA\n");
1248                 break;
1249         default:
1250                 DEBUG(1, ("Got an invalid negTokenTarg\n"));
1251                 x_fprintf(x_stdout, "AF\n");
1252         }
1253 }
1254
1255 #endif
1256
1257 static void manage_gss_spnego_client_request(enum stdio_helper_mode stdio_helper_mode, 
1258                                              char *buf, int length) 
1259 {
1260         DATA_BLOB request;
1261         SPNEGO_DATA spnego;
1262         ssize_t len;
1263
1264         if (strlen(buf) <= 3) {
1265                 DEBUG(1, ("SPNEGO query [%s] too short\n", buf));
1266                 x_fprintf(x_stdout, "BH\n");
1267                 return;
1268         }
1269
1270         request = base64_decode_data_blob(buf+3);
1271
1272         if (strncmp(buf, "PW ", 3) == 0) {
1273
1274                 /* We asked for a password and obviously got it :-) */
1275
1276                 opt_password = SMB_STRNDUP((const char *)request.data, request.length);
1277                 
1278                 if (opt_password == NULL) {
1279                         DEBUG(1, ("Out of memory\n"));
1280                         x_fprintf(x_stdout, "BH\n");
1281                         data_blob_free(&request);
1282                         return;
1283                 }
1284
1285                 x_fprintf(x_stdout, "OK\n");
1286                 data_blob_free(&request);
1287                 return;
1288         }
1289
1290         if ( (strncmp(buf, "TT ", 3) != 0) &&
1291              (strncmp(buf, "AF ", 3) != 0) &&
1292              (strncmp(buf, "NA ", 3) != 0) ) {
1293                 DEBUG(1, ("SPNEGO request [%s] invalid\n", buf));
1294                 x_fprintf(x_stdout, "BH\n");
1295                 data_blob_free(&request);
1296                 return;
1297         }
1298
1299         /* So we got a server challenge to generate a SPNEGO
1300            client-to-server request... */
1301
1302         len = read_spnego_data(request, &spnego);
1303         data_blob_free(&request);
1304
1305         if (len == -1) {
1306                 DEBUG(1, ("Could not read SPNEGO data for [%s]\n", buf));
1307                 x_fprintf(x_stdout, "BH\n");
1308                 return;
1309         }
1310
1311         if (spnego.type == SPNEGO_NEG_TOKEN_INIT) {
1312
1313                 /* The server offers a list of mechanisms */
1314
1315                 const char **mechType = (const char **)spnego.negTokenInit.mechTypes;
1316
1317                 while (*mechType != NULL) {
1318
1319 #ifdef HAVE_KRB5
1320                         if ( (strcmp(*mechType, OID_KERBEROS5_OLD) == 0) ||
1321                              (strcmp(*mechType, OID_KERBEROS5) == 0) ) {
1322                                 if (manage_client_krb5_init(spnego))
1323                                         goto out;
1324                         }
1325 #endif
1326
1327                         if (strcmp(*mechType, OID_NTLMSSP) == 0) {
1328                                 if (manage_client_ntlmssp_init(spnego))
1329                                         goto out;
1330                         }
1331
1332                         mechType++;
1333                 }
1334
1335                 DEBUG(1, ("Server offered no compatible mechanism\n"));
1336                 x_fprintf(x_stdout, "BH\n");
1337                 return;
1338         }
1339
1340         if (spnego.type == SPNEGO_NEG_TOKEN_TARG) {
1341
1342                 if (spnego.negTokenTarg.supportedMech == NULL) {
1343                         /* On accept/reject Windows does not send the
1344                            mechanism anymore. Handle that here and
1345                            shut down the mechanisms. */
1346
1347                         switch (spnego.negTokenTarg.negResult) {
1348                         case SPNEGO_ACCEPT_COMPLETED:
1349                                 x_fprintf(x_stdout, "AF\n");
1350                                 break;
1351                         case SPNEGO_REJECT:
1352                                 x_fprintf(x_stdout, "NA\n");
1353                                 break;
1354                         default:
1355                                 DEBUG(1, ("Got a negTokenTarg with no mech and an "
1356                                           "unknown negResult: %d\n",
1357                                           spnego.negTokenTarg.negResult));
1358                                 x_fprintf(x_stdout, "BH\n");
1359                         }
1360
1361                         ntlmssp_end(&client_ntlmssp_state);
1362                         goto out;
1363                 }
1364
1365                 if (strcmp(spnego.negTokenTarg.supportedMech,
1366                            OID_NTLMSSP) == 0) {
1367                         manage_client_ntlmssp_targ(spnego);
1368                         goto out;
1369                 }
1370
1371 #if HAVE_KRB5
1372                 if (strcmp(spnego.negTokenTarg.supportedMech,
1373                            OID_KERBEROS5_OLD) == 0) {
1374                         manage_client_krb5_targ(spnego);
1375                         goto out;
1376                 }
1377 #endif
1378
1379         }
1380
1381         DEBUG(1, ("Got an SPNEGO token I could not handle [%s]!\n", buf));
1382         x_fprintf(x_stdout, "BH\n");
1383         return;
1384
1385  out:
1386         free_spnego_data(&spnego);
1387         return;
1388 }
1389
1390 static void manage_ntlm_server_1_request(enum stdio_helper_mode stdio_helper_mode, 
1391                                          char *buf, int length) 
1392 {
1393         char *request, *parameter;      
1394         static DATA_BLOB challenge;
1395         static DATA_BLOB lm_response;
1396         static DATA_BLOB nt_response;
1397         static char *full_username;
1398         static char *username;
1399         static char *domain;
1400         static char *plaintext_password;
1401         static BOOL ntlm_server_1_user_session_key;
1402         static BOOL ntlm_server_1_lm_session_key;
1403         
1404         if (strequal(buf, ".")) {
1405                 if (!full_username && !username) {      
1406                         x_fprintf(x_stdout, "Error: No username supplied!\n");
1407                 } else if (plaintext_password) {
1408                         /* handle this request as plaintext */
1409                         if (!full_username) {
1410                                 if (asprintf(&full_username, "%s%c%s", domain, winbind_separator(), username) == -1) {
1411                                         x_fprintf(x_stdout, "Error: Out of memory in asprintf!\n.\n");
1412                                         return;
1413                                 }
1414                         }
1415                         if (check_plaintext_auth(full_username, plaintext_password, False)) {
1416                                 x_fprintf(x_stdout, "Authenticated: Yes\n");
1417                         } else {
1418                                 x_fprintf(x_stdout, "Authenticated: No\n");
1419                         }
1420                 } else if (!lm_response.data && !nt_response.data) {
1421                         x_fprintf(x_stdout, "Error: No password supplied!\n");
1422                 } else if (!challenge.data) {   
1423                         x_fprintf(x_stdout, "Error: No lanman-challenge supplied!\n");
1424                 } else {
1425                         char *error_string = NULL;
1426                         uchar lm_key[8];
1427                         uchar user_session_key[16];
1428                         uint32 flags = 0;
1429
1430                         if (full_username && !username) {
1431                                 fstring fstr_user;
1432                                 fstring fstr_domain;
1433                                 
1434                                 if (!parse_ntlm_auth_domain_user(full_username, fstr_user, fstr_domain)) {
1435                                         /* username might be 'tainted', don't print into our new-line deleimianted stream */
1436                                         x_fprintf(x_stdout, "Error: Could not parse into domain and username\n");
1437                                 }
1438                                 SAFE_FREE(username);
1439                                 SAFE_FREE(domain);
1440                                 username = smb_xstrdup(fstr_user);
1441                                 domain = smb_xstrdup(fstr_domain);
1442                         }
1443
1444                         if (!domain) {
1445                                 domain = smb_xstrdup(get_winbind_domain());
1446                         }
1447
1448                         if (ntlm_server_1_lm_session_key) 
1449                                 flags |= WBFLAG_PAM_LMKEY;
1450                         
1451                         if (ntlm_server_1_user_session_key) 
1452                                 flags |= WBFLAG_PAM_USER_SESSION_KEY;
1453
1454                         if (!NT_STATUS_IS_OK(
1455                                     contact_winbind_auth_crap(username, 
1456                                                               domain, 
1457                                                               global_myname(),
1458                                                               &challenge, 
1459                                                               &lm_response, 
1460                                                               &nt_response, 
1461                                                               flags, 
1462                                                               lm_key, 
1463                                                               user_session_key,
1464                                                               &error_string,
1465                                                               NULL))) {
1466
1467                                 x_fprintf(x_stdout, "Authenticated: No\n");
1468                                 x_fprintf(x_stdout, "Authentication-Error: %s\n.\n", error_string);
1469                                 SAFE_FREE(error_string);
1470                         } else {
1471                                 static char zeros[16];
1472                                 char *hex_lm_key;
1473                                 char *hex_user_session_key;
1474
1475                                 x_fprintf(x_stdout, "Authenticated: Yes\n");
1476
1477                                 if (ntlm_server_1_lm_session_key 
1478                                     && (memcmp(zeros, lm_key, 
1479                                                sizeof(lm_key)) != 0)) {
1480                                         hex_lm_key = hex_encode(NULL,
1481                                                                 (const unsigned char *)lm_key,
1482                                                                 sizeof(lm_key));
1483                                         x_fprintf(x_stdout, "LANMAN-Session-Key: %s\n", hex_lm_key);
1484                                         talloc_free(hex_lm_key);
1485                                 }
1486
1487                                 if (ntlm_server_1_user_session_key 
1488                                     && (memcmp(zeros, user_session_key, 
1489                                                sizeof(user_session_key)) != 0)) {
1490                                         hex_user_session_key = hex_encode(NULL,
1491                                                                           (const unsigned char *)user_session_key, 
1492                                                                           sizeof(user_session_key));
1493                                         x_fprintf(x_stdout, "User-Session-Key: %s\n", hex_user_session_key);
1494                                         talloc_free(hex_user_session_key);
1495                                 }
1496                         }
1497                 }
1498                 /* clear out the state */
1499                 challenge = data_blob(NULL, 0);
1500                 nt_response = data_blob(NULL, 0);
1501                 lm_response = data_blob(NULL, 0);
1502                 SAFE_FREE(full_username);
1503                 SAFE_FREE(username);
1504                 SAFE_FREE(domain);
1505                 SAFE_FREE(plaintext_password);
1506                 ntlm_server_1_user_session_key = False;
1507                 ntlm_server_1_lm_session_key = False;
1508                 x_fprintf(x_stdout, ".\n");
1509
1510                 return;
1511         }
1512
1513         request = buf;
1514
1515         /* Indicates a base64 encoded structure */
1516         parameter = strstr_m(request, ":: ");
1517         if (!parameter) {
1518                 parameter = strstr_m(request, ": ");
1519                 
1520                 if (!parameter) {
1521                         DEBUG(0, ("Parameter not found!\n"));
1522                         x_fprintf(x_stdout, "Error: Parameter not found!\n.\n");
1523                         return;
1524                 }
1525                 
1526                 parameter[0] ='\0';
1527                 parameter++;
1528                 parameter[0] ='\0';
1529                 parameter++;
1530
1531         } else {
1532                 parameter[0] ='\0';
1533                 parameter++;
1534                 parameter[0] ='\0';
1535                 parameter++;
1536                 parameter[0] ='\0';
1537                 parameter++;
1538
1539                 base64_decode_inplace(parameter);
1540         }
1541
1542         if (strequal(request, "LANMAN-Challenge")) {
1543                 challenge = strhex_to_data_blob(NULL, parameter);
1544                 if (challenge.length != 8) {
1545                         x_fprintf(x_stdout, "Error: hex decode of %s failed! (got %d bytes, expected 8)\n.\n", 
1546                                   parameter,
1547                                   (int)challenge.length);
1548                         challenge = data_blob(NULL, 0);
1549                 }
1550         } else if (strequal(request, "NT-Response")) {
1551                 nt_response = strhex_to_data_blob(NULL, parameter);
1552                 if (nt_response.length < 24) {
1553                         x_fprintf(x_stdout, "Error: hex decode of %s failed! (only got %d bytes, needed at least 24)\n.\n", 
1554                                   parameter,
1555                                   (int)nt_response.length);
1556                         nt_response = data_blob(NULL, 0);
1557                 }
1558         } else if (strequal(request, "LANMAN-Response")) {
1559                 lm_response = strhex_to_data_blob(NULL, parameter);
1560                 if (lm_response.length != 24) {
1561                         x_fprintf(x_stdout, "Error: hex decode of %s failed! (got %d bytes, expected 24)\n.\n", 
1562                                   parameter,
1563                                   (int)lm_response.length);
1564                         lm_response = data_blob(NULL, 0);
1565                 }
1566         } else if (strequal(request, "Password")) {
1567                 plaintext_password = smb_xstrdup(parameter);
1568         } else if (strequal(request, "NT-Domain")) {
1569                 domain = smb_xstrdup(parameter);
1570         } else if (strequal(request, "Username")) {
1571                 username = smb_xstrdup(parameter);
1572         } else if (strequal(request, "Full-Username")) {
1573                 full_username = smb_xstrdup(parameter);
1574         } else if (strequal(request, "Request-User-Session-Key")) {
1575                 ntlm_server_1_user_session_key = strequal(parameter, "Yes");
1576         } else if (strequal(request, "Request-LanMan-Session-Key")) {
1577                 ntlm_server_1_lm_session_key = strequal(parameter, "Yes");
1578         } else {
1579                 x_fprintf(x_stdout, "Error: Unknown request %s\n.\n", request);
1580         }
1581 }
1582
1583 static void manage_squid_request(enum stdio_helper_mode helper_mode, stdio_helper_function fn) 
1584 {
1585         char buf[SQUID_BUFFER_SIZE+1];
1586         int length;
1587         char *c;
1588         static BOOL err;
1589
1590         /* this is not a typo - x_fgets doesn't work too well under squid */
1591         if (fgets(buf, sizeof(buf)-1, stdin) == NULL) {
1592                 if (ferror(stdin)) {
1593                         DEBUG(1, ("fgets() failed! dying..... errno=%d (%s)\n", ferror(stdin),
1594                                   strerror(ferror(stdin))));
1595                         
1596                         exit(1);    /* BIIG buffer */
1597                 }
1598                 exit(0);
1599         }
1600     
1601         c=memchr(buf,'\n',sizeof(buf)-1);
1602         if (c) {
1603                 *c = '\0';
1604                 length = c-buf;
1605         } else {
1606                 err = 1;
1607                 return;
1608         }
1609         if (err) {
1610                 DEBUG(2, ("Oversized message\n"));
1611                 x_fprintf(x_stderr, "ERR\n");
1612                 err = 0;
1613                 return;
1614         }
1615
1616         DEBUG(10, ("Got '%s' from squid (length: %d).\n",buf,length));
1617
1618         if (buf[0] == '\0') {
1619                 DEBUG(2, ("Invalid Request\n"));
1620                 x_fprintf(x_stderr, "ERR\n");
1621                 return;
1622         }
1623         
1624         fn(helper_mode, buf, length);
1625 }
1626
1627
1628 static void squid_stream(enum stdio_helper_mode stdio_mode, stdio_helper_function fn) {
1629         /* initialize FDescs */
1630         x_setbuf(x_stdout, NULL);
1631         x_setbuf(x_stderr, NULL);
1632         while(1) {
1633                 manage_squid_request(stdio_mode, fn);
1634         }
1635 }
1636
1637
1638 /* Authenticate a user with a challenge/response */
1639
1640 static BOOL check_auth_crap(void)
1641 {
1642         NTSTATUS nt_status;
1643         uint32 flags = 0;
1644         char lm_key[8];
1645         char user_session_key[16];
1646         char *hex_lm_key;
1647         char *hex_user_session_key;
1648         char *error_string;
1649         static uint8 zeros[16];
1650
1651         x_setbuf(x_stdout, NULL);
1652
1653         if (request_lm_key) 
1654                 flags |= WBFLAG_PAM_LMKEY;
1655
1656         if (request_user_session_key) 
1657                 flags |= WBFLAG_PAM_USER_SESSION_KEY;
1658
1659         flags |= WBFLAG_PAM_NT_STATUS_SQUASH;
1660
1661         nt_status = contact_winbind_auth_crap(opt_username, opt_domain, 
1662                                               opt_workstation,
1663                                               &opt_challenge, 
1664                                               &opt_lm_response, 
1665                                               &opt_nt_response, 
1666                                               flags,
1667                                               (unsigned char *)lm_key, 
1668                                               (unsigned char *)user_session_key, 
1669                                               &error_string, NULL);
1670
1671         if (!NT_STATUS_IS_OK(nt_status)) {
1672                 x_fprintf(x_stdout, "%s (0x%x)\n", 
1673                           error_string,
1674                           NT_STATUS_V(nt_status));
1675                 SAFE_FREE(error_string);
1676                 return False;
1677         }
1678
1679         if (request_lm_key 
1680             && (memcmp(zeros, lm_key, 
1681                        sizeof(lm_key)) != 0)) {
1682                 hex_lm_key = hex_encode(NULL, (const unsigned char *)lm_key,
1683                                         sizeof(lm_key));
1684                 x_fprintf(x_stdout, "LM_KEY: %s\n", hex_lm_key);
1685                 talloc_free(hex_lm_key);
1686         }
1687         if (request_user_session_key 
1688             && (memcmp(zeros, user_session_key, 
1689                        sizeof(user_session_key)) != 0)) {
1690                 hex_user_session_key = hex_encode(NULL, (const unsigned char *)user_session_key, 
1691                                                   sizeof(user_session_key));
1692                 x_fprintf(x_stdout, "NT_KEY: %s\n", hex_user_session_key);
1693                 talloc_free(hex_user_session_key);
1694         }
1695
1696         return True;
1697 }
1698
1699 /* Main program */
1700
1701 enum {
1702         OPT_USERNAME = 1000,
1703         OPT_DOMAIN,
1704         OPT_WORKSTATION,
1705         OPT_CHALLENGE,
1706         OPT_RESPONSE,
1707         OPT_LM,
1708         OPT_NT,
1709         OPT_PASSWORD,
1710         OPT_LM_KEY,
1711         OPT_USER_SESSION_KEY,
1712         OPT_DIAGNOSTICS,
1713         OPT_REQUIRE_MEMBERSHIP
1714 };
1715
1716  int main(int argc, const char **argv)
1717 {
1718         int opt;
1719         static const char *helper_protocol;
1720         static int diagnostics;
1721
1722         static const char *hex_challenge;
1723         static const char *hex_lm_response;
1724         static const char *hex_nt_response;
1725
1726         poptContext pc;
1727
1728         /* NOTE: DO NOT change this interface without considering the implications!
1729            This is an external interface, which other programs will use to interact 
1730            with this helper.
1731         */
1732
1733         /* We do not use single-letter command abbreviations, because they harm future 
1734            interface stability. */
1735
1736         struct poptOption long_options[] = {
1737                 POPT_AUTOHELP
1738                 { "helper-protocol", 0, POPT_ARG_STRING, &helper_protocol, OPT_DOMAIN, "operate as a stdio-based helper", "helper protocol to use"},
1739                 { "username", 0, POPT_ARG_STRING, &opt_username, OPT_USERNAME, "username"},
1740                 { "domain", 0, POPT_ARG_STRING, &opt_domain, OPT_DOMAIN, "domain name"},
1741                 { "workstation", 0, POPT_ARG_STRING, &opt_workstation, OPT_WORKSTATION, "workstation"},
1742                 { "challenge", 0, POPT_ARG_STRING, &hex_challenge, OPT_CHALLENGE, "challenge (HEX encoded)"},
1743                 { "lm-response", 0, POPT_ARG_STRING, &hex_lm_response, OPT_LM, "LM Response to the challenge (HEX encoded)"},
1744                 { "nt-response", 0, POPT_ARG_STRING, &hex_nt_response, OPT_NT, "NT or NTLMv2 Response to the challenge (HEX encoded)"},
1745                 { "password", 0, POPT_ARG_STRING, &opt_password, OPT_PASSWORD, "User's plaintext password"},            
1746                 { "request-lm-key", 0, POPT_ARG_NONE, &request_lm_key, OPT_LM_KEY, "Retrieve LM session key"},
1747                 { "request-nt-key", 0, POPT_ARG_NONE, &request_user_session_key, OPT_USER_SESSION_KEY, "Retrieve User (NT) session key"},
1748                 { "diagnostics", 0, POPT_ARG_NONE, &diagnostics, OPT_DIAGNOSTICS, "Perform diagnostics on the authentictaion chain"},
1749                 { "require-membership-of", 0, POPT_ARG_STRING, &require_membership_of, OPT_REQUIRE_MEMBERSHIP, "Require that a user be a member of this group (either name or SID) for authentication to succeed" },
1750                 POPT_COMMON_SAMBA
1751                 POPT_TABLEEND
1752         };
1753
1754         /* Samba client initialisation */
1755         load_case_tables();
1756
1757         dbf = x_stderr;
1758         
1759         /* Samba client initialisation */
1760
1761         if (!lp_load(dyn_CONFIGFILE, True, False, False)) {
1762                 d_fprintf(stderr, "ntlm_auth: error opening config file %s. Error was %s\n",
1763                         dyn_CONFIGFILE, strerror(errno));
1764                 exit(1);
1765         }
1766
1767         /* Parse options */
1768
1769         pc = poptGetContext("ntlm_auth", argc, argv, long_options, 0);
1770
1771         /* Parse command line options */
1772
1773         if (argc == 1) {
1774                 poptPrintHelp(pc, stderr, 0);
1775                 return 1;
1776         }
1777
1778         pc = poptGetContext(NULL, argc, (const char **)argv, long_options, 
1779                             POPT_CONTEXT_KEEP_FIRST);
1780
1781         while((opt = poptGetNextOpt(pc)) != -1) {
1782                 switch (opt) {
1783                 case OPT_CHALLENGE:
1784                         opt_challenge = strhex_to_data_blob(NULL, hex_challenge);
1785                         if (opt_challenge.length != 8) {
1786                                 x_fprintf(x_stderr, "hex decode of %s failed! (only got %d bytes)\n", 
1787                                           hex_challenge,
1788                                           (int)opt_challenge.length);
1789                                 exit(1);
1790                         }
1791                         break;
1792                 case OPT_LM: 
1793                         opt_lm_response = strhex_to_data_blob(NULL, hex_lm_response);
1794                         if (opt_lm_response.length != 24) {
1795                                 x_fprintf(x_stderr, "hex decode of %s failed! (only got %d bytes)\n", 
1796                                           hex_lm_response,
1797                                           (int)opt_lm_response.length);
1798                                 exit(1);
1799                         }
1800                         break;
1801
1802                 case OPT_NT: 
1803                         opt_nt_response = strhex_to_data_blob(NULL, hex_nt_response);
1804                         if (opt_nt_response.length < 24) {
1805                                 x_fprintf(x_stderr, "hex decode of %s failed! (only got %d bytes)\n", 
1806                                           hex_nt_response,
1807                                           (int)opt_nt_response.length);
1808                                 exit(1);
1809                         }
1810                         break;
1811
1812                 case OPT_REQUIRE_MEMBERSHIP:
1813                         if (StrnCaseCmp("S-", require_membership_of, 2) == 0) {
1814                                 require_membership_of_sid = require_membership_of;
1815                         }
1816                         break;
1817                 }
1818         }
1819
1820         if (helper_protocol) {
1821                 int i;
1822                 for (i=0; i<NUM_HELPER_MODES; i++) {
1823                         if (strcmp(helper_protocol, stdio_helper_protocols[i].name) == 0) {
1824                                 squid_stream(stdio_helper_protocols[i].mode, stdio_helper_protocols[i].fn);
1825                                 exit(0);
1826                         }
1827                 }
1828                 x_fprintf(x_stderr, "unknown helper protocol [%s]\n\nValid helper protools:\n\n", helper_protocol);
1829
1830                 for (i=0; i<NUM_HELPER_MODES; i++) {
1831                         x_fprintf(x_stderr, "%s\n", stdio_helper_protocols[i].name);
1832                 }
1833
1834                 exit(1);
1835         }
1836
1837         if (!opt_username) {
1838                 x_fprintf(x_stderr, "username must be specified!\n\n");
1839                 poptPrintHelp(pc, stderr, 0);
1840                 exit(1);
1841         }
1842
1843         if (opt_domain == NULL) {
1844                 opt_domain = get_winbind_domain();
1845         }
1846
1847         if (opt_workstation == NULL) {
1848                 opt_workstation = "";
1849         }
1850
1851         if (opt_challenge.length) {
1852                 if (!check_auth_crap()) {
1853                         exit(1);
1854                 }
1855                 exit(0);
1856         } 
1857
1858         if (!opt_password) {
1859                 opt_password = getpass("password: ");
1860         }
1861
1862         if (diagnostics) {
1863                 if (!diagnose_ntlm_auth()) {
1864                         return 1;
1865                 }
1866         } else {
1867                 fstring user;
1868
1869                 fstr_sprintf(user, "%s%c%s", opt_domain, winbind_separator(), opt_username);
1870                 if (!check_plaintext_auth(user, opt_password, True)) {
1871                         return 1;
1872                 }
1873         }
1874
1875         /* Exit code */
1876
1877         poptFreeContext(pc);
1878         return 0;
1879 }