r240: I'm pretty happy with the 'ntlm-server-1' helper protocol now, and as
[abartlet/samba.git/.git] / source3 / 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_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(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(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(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, False);
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_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(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_sid = strdup(response.data.sid.sid);
242
243         if (require_membership_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_sid)
269                 fstrcpy(request.data.auth.required_membership_sid, require_membership_sid);
270
271         result = winbindd_request(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         if (require_membership_sid)
327                 fstrcpy(request.data.auth_crap.required_membership_sid, require_membership_sid);
328
329         if (push_utf8_fstring(request.data.auth_crap.user, username) == -1) {
330                 *error_string = smb_xstrdup(
331                         "unable to create utf8 string for username");
332                 return NT_STATUS_UNSUCCESSFUL;
333         }
334
335         if (push_utf8_fstring(request.data.auth_crap.domain, domain) == -1) {
336                 *error_string = smb_xstrdup(
337                         "unable to create utf8 string for domain");
338                 return NT_STATUS_UNSUCCESSFUL;
339         }
340
341         if (push_utf8_fstring(request.data.auth_crap.workstation, 
342                               workstation) == -1) {
343                 *error_string = smb_xstrdup(
344                         "unable to create utf8 string for workstation");
345                 return NT_STATUS_UNSUCCESSFUL;
346         }
347
348         memcpy(request.data.auth_crap.chal, challenge->data, MIN(challenge->length, 8));
349
350         if (lm_response && lm_response->length) {
351                 memcpy(request.data.auth_crap.lm_resp, 
352                        lm_response->data, 
353                        MIN(lm_response->length, sizeof(request.data.auth_crap.lm_resp)));
354                 request.data.auth_crap.lm_resp_len = lm_response->length;
355         }
356
357         if (nt_response && nt_response->length) {
358                 memcpy(request.data.auth_crap.nt_resp, 
359                        nt_response->data, 
360                        MIN(nt_response->length, sizeof(request.data.auth_crap.nt_resp)));
361                 request.data.auth_crap.nt_resp_len = nt_response->length;
362         }
363         
364         result = winbindd_request(WINBINDD_PAM_AUTH_CRAP, &request, &response);
365
366         /* Display response */
367
368         if ((result != NSS_STATUS_SUCCESS) && (response.data.auth.nt_status == 0)) {
369                 nt_status = NT_STATUS_UNSUCCESSFUL;
370                 if (error_string)
371                         *error_string = smb_xstrdup("Reading winbind reply failed!");
372                 return nt_status;
373         }
374         
375         nt_status = (NT_STATUS(response.data.auth.nt_status));
376         if (!NT_STATUS_IS_OK(nt_status)) {
377                 if (error_string) 
378                         *error_string = smb_xstrdup(response.data.auth.error_string);
379                 return nt_status;
380         }
381
382         if ((flags & WBFLAG_PAM_LMKEY) && lm_key) {
383                 memcpy(lm_key, response.data.auth.first_8_lm_hash, 
384                        sizeof(response.data.auth.first_8_lm_hash));
385         }
386         if ((flags & WBFLAG_PAM_USER_SESSION_KEY) && user_session_key) {
387                 memcpy(user_session_key, response.data.auth.user_session_key, 
388                         sizeof(response.data.auth.user_session_key));
389         }
390
391         if (flags & WBFLAG_PAM_UNIX_NAME) {
392                 if (pull_utf8_allocate(unix_name, (char *)response.extra_data) == -1) {
393                         return NT_STATUS_NO_MEMORY;
394                 }
395         }
396
397         return nt_status;
398 }
399                                    
400 static NTSTATUS winbind_pw_check(struct ntlmssp_state *ntlmssp_state, DATA_BLOB *user_session_key, DATA_BLOB *lm_session_key) 
401 {
402         static const char zeros[16];
403         NTSTATUS nt_status;
404         char *error_string;
405         uint8 lm_key[8]; 
406         uint8 user_sess_key[16]; 
407         char *unix_name;
408
409         nt_status = contact_winbind_auth_crap(ntlmssp_state->user, ntlmssp_state->domain,
410                                               ntlmssp_state->workstation,
411                                               &ntlmssp_state->chal,
412                                               &ntlmssp_state->lm_resp,
413                                               &ntlmssp_state->nt_resp, 
414                                               WBFLAG_PAM_LMKEY | WBFLAG_PAM_USER_SESSION_KEY | WBFLAG_PAM_UNIX_NAME,
415                                               lm_key, user_sess_key, 
416                                               &error_string, &unix_name);
417
418         if (NT_STATUS_IS_OK(nt_status)) {
419                 if (memcmp(lm_key, zeros, 8) != 0) {
420                         *lm_session_key = data_blob(NULL, 16);
421                         memcpy(lm_session_key->data, lm_key, 8);
422                         memset(lm_session_key->data+8, '\0', 8);
423                 }
424                 
425                 if (memcmp(user_sess_key, zeros, 16) != 0) {
426                         *user_session_key = data_blob(user_sess_key, 16);
427                 }
428                 ntlmssp_state->auth_context = talloc_strdup(ntlmssp_state->mem_ctx, unix_name);
429                 SAFE_FREE(unix_name);
430         } else {
431                 DEBUG(NT_STATUS_EQUAL(nt_status, NT_STATUS_ACCESS_DENIED) ? 0 : 3, 
432                       ("Login for user [%s]\\[%s]@[%s] failed due to [%s]\n", 
433                        ntlmssp_state->domain, ntlmssp_state->user, 
434                        ntlmssp_state->workstation, 
435                        error_string ? error_string : "unknown error (NULL)"));
436                 ntlmssp_state->auth_context = NULL;
437         }
438         return nt_status;
439 }
440
441 static NTSTATUS local_pw_check(struct ntlmssp_state *ntlmssp_state, DATA_BLOB *user_session_key, DATA_BLOB *lm_session_key) 
442 {
443         NTSTATUS nt_status;
444         uint8 lm_pw[16], nt_pw[16];
445
446         nt_lm_owf_gen (opt_password, nt_pw, lm_pw);
447         
448         nt_status = ntlm_password_check(ntlmssp_state->mem_ctx, 
449                                         &ntlmssp_state->chal,
450                                         &ntlmssp_state->lm_resp,
451                                         &ntlmssp_state->nt_resp, 
452                                         NULL, NULL,
453                                         ntlmssp_state->user, 
454                                         ntlmssp_state->user, 
455                                         ntlmssp_state->domain,
456                                         lm_pw, nt_pw, user_session_key, lm_session_key);
457         
458         if (NT_STATUS_IS_OK(nt_status)) {
459                 ntlmssp_state->auth_context = talloc_asprintf(ntlmssp_state->mem_ctx, 
460                                                               "%s%c%s", ntlmssp_state->domain, 
461                                                               *lp_winbind_separator(), 
462                                                               ntlmssp_state->user);
463         } else {
464                 DEBUG(3, ("Login for user [%s]\\[%s]@[%s] failed due to [%s]\n", 
465                           ntlmssp_state->domain, ntlmssp_state->user, ntlmssp_state->workstation, 
466                           nt_errstr(nt_status)));
467                 ntlmssp_state->auth_context = NULL;
468         }
469         return nt_status;
470 }
471
472 static NTSTATUS ntlm_auth_start_ntlmssp_client(NTLMSSP_STATE **client_ntlmssp_state) 
473 {
474         NTSTATUS status;
475         if ( (opt_username == NULL) || (opt_domain == NULL) ) {
476                 DEBUG(1, ("Need username and domain for NTLMSSP\n"));
477                 return status;
478         }
479
480         status = ntlmssp_client_start(client_ntlmssp_state);
481
482         if (!NT_STATUS_IS_OK(status)) {
483                 DEBUG(1, ("Could not start NTLMSSP client: %s\n",
484                           nt_errstr(status)));
485                 ntlmssp_end(client_ntlmssp_state);
486                 return status;
487         }
488
489         status = ntlmssp_set_username(*client_ntlmssp_state, opt_username);
490
491         if (!NT_STATUS_IS_OK(status)) {
492                 DEBUG(1, ("Could not set username: %s\n",
493                           nt_errstr(status)));
494                 ntlmssp_end(client_ntlmssp_state);
495                 return status;
496         }
497
498         status = ntlmssp_set_domain(*client_ntlmssp_state, opt_domain);
499
500         if (!NT_STATUS_IS_OK(status)) {
501                 DEBUG(1, ("Could not set domain: %s\n",
502                           nt_errstr(status)));
503                 ntlmssp_end(client_ntlmssp_state);
504                 return status;
505         }
506
507         status = ntlmssp_set_password(*client_ntlmssp_state, opt_password);
508         
509         if (!NT_STATUS_IS_OK(status)) {
510                 DEBUG(1, ("Could not set password: %s\n",
511                           nt_errstr(status)));
512                 ntlmssp_end(client_ntlmssp_state);
513                 return status;
514         }
515         return NT_STATUS_OK;
516 }
517
518 static NTSTATUS ntlm_auth_start_ntlmssp_server(NTLMSSP_STATE **ntlmssp_state) 
519 {
520         NTSTATUS status = ntlmssp_server_start(ntlmssp_state);
521         
522         if (!NT_STATUS_IS_OK(status)) {
523                 DEBUG(1, ("Could not start NTLMSSP client: %s\n",
524                           nt_errstr(status)));
525                 return status;
526         }
527
528         /* Have we been given a local password, or should we ask winbind? */
529         if (opt_password) {
530                 (*ntlmssp_state)->check_password = local_pw_check;
531                 (*ntlmssp_state)->get_domain = lp_workgroup;
532                 (*ntlmssp_state)->get_global_myname = global_myname;
533         } else {
534                 (*ntlmssp_state)->check_password = winbind_pw_check;
535                 (*ntlmssp_state)->get_domain = get_winbind_domain;
536                 (*ntlmssp_state)->get_global_myname = get_winbind_netbios_name;
537         }
538         return NT_STATUS_OK;
539 }
540
541 static void manage_squid_ntlmssp_request(enum stdio_helper_mode stdio_helper_mode, 
542                                          char *buf, int length) 
543 {
544         static NTLMSSP_STATE *ntlmssp_state = NULL;
545         DATA_BLOB request, reply;
546         NTSTATUS nt_status;
547
548         if (strlen(buf) < 2) {
549                 DEBUG(1, ("NTLMSSP query [%s] invalid", buf));
550                 x_fprintf(x_stdout, "BH\n");
551                 return;
552         }
553
554         if (strlen(buf) > 3) {
555                 request = base64_decode_data_blob(buf + 3);
556         } else {
557                 request = data_blob(NULL, 0);
558         }
559
560         if ((strncmp(buf, "PW ", 3) == 0)) {
561                 /* The calling application wants us to use a local password (rather than winbindd) */
562
563                 opt_password = strndup((const char *)request.data, request.length);
564
565                 if (opt_password == NULL) {
566                         DEBUG(1, ("Out of memory\n"));
567                         x_fprintf(x_stdout, "BH\n");
568                         data_blob_free(&request);
569                         return;
570                 }
571
572                 x_fprintf(x_stdout, "OK\n");
573                 data_blob_free(&request);
574                 return;
575         }
576
577         if (strncmp(buf, "YR", 2) == 0) {
578                 if (ntlmssp_state)
579                         ntlmssp_end(&ntlmssp_state);
580         } else if (strncmp(buf, "KK", 2) == 0) {
581                 
582         } else {
583                 DEBUG(1, ("NTLMSSP query [%s] invalid", buf));
584                 x_fprintf(x_stdout, "BH\n");
585                 return;
586         }
587
588         if (!ntlmssp_state) {
589                 if (!NT_STATUS_IS_OK(nt_status = ntlm_auth_start_ntlmssp_server(&ntlmssp_state))) {
590                         x_fprintf(x_stdout, "BH %s\n", nt_errstr(nt_status));
591                         return;
592                 }
593         }
594
595         DEBUG(10, ("got NTLMSSP packet:\n"));
596         dump_data(10, (const char *)request.data, request.length);
597
598         nt_status = ntlmssp_update(ntlmssp_state, request, &reply);
599         
600         if (NT_STATUS_EQUAL(nt_status, NT_STATUS_MORE_PROCESSING_REQUIRED)) {
601                 char *reply_base64 = base64_encode_data_blob(reply);
602                 x_fprintf(x_stdout, "TT %s\n", reply_base64);
603                 SAFE_FREE(reply_base64);
604                 data_blob_free(&reply);
605                 DEBUG(10, ("NTLMSSP challenge\n"));
606         } else if (NT_STATUS_EQUAL(nt_status, NT_STATUS_ACCESS_DENIED)) {
607                 x_fprintf(x_stdout, "BH %s\n", nt_errstr(nt_status));
608                 DEBUG(0, ("NTLMSSP BH: %s\n", nt_errstr(nt_status)));
609
610                 ntlmssp_end(&ntlmssp_state);
611         } else if (!NT_STATUS_IS_OK(nt_status)) {
612                 x_fprintf(x_stdout, "NA %s\n", nt_errstr(nt_status));
613                 DEBUG(10, ("NTLMSSP %s\n", nt_errstr(nt_status)));
614         } else {
615                 x_fprintf(x_stdout, "AF %s\n", (char *)ntlmssp_state->auth_context);
616                 DEBUG(10, ("NTLMSSP OK!\n"));
617         }
618
619         data_blob_free(&request);
620 }
621
622 static void manage_client_ntlmssp_request(enum stdio_helper_mode stdio_helper_mode, 
623                                          char *buf, int length) 
624 {
625         static NTLMSSP_STATE *ntlmssp_state = NULL;
626         DATA_BLOB request, reply;
627         NTSTATUS nt_status;
628         BOOL first = False;
629         
630         if (strlen(buf) < 2) {
631                 DEBUG(1, ("NTLMSSP query [%s] invalid", buf));
632                 x_fprintf(x_stdout, "BH\n");
633                 return;
634         }
635
636         if (strlen(buf) > 3) {
637                 request = base64_decode_data_blob(buf + 3);
638         } else {
639                 request = data_blob(NULL, 0);
640         }
641
642         if (strncmp(buf, "PW ", 3) == 0) {
643                 /* We asked for a password and obviously got it :-) */
644
645                 opt_password = strndup((const char *)request.data, request.length);
646
647                 if (opt_password == NULL) {
648                         DEBUG(1, ("Out of memory\n"));
649                         x_fprintf(x_stdout, "BH\n");
650                         data_blob_free(&request);
651                         return;
652                 }
653
654                 x_fprintf(x_stdout, "OK\n");
655                 data_blob_free(&request);
656                 return;
657         }
658
659         if (opt_password == NULL) {
660                 
661                 /* Request a password from the calling process.  After
662                    sending it, the calling process should retry asking for the negotiate. */
663                 
664                 DEBUG(10, ("Requesting password\n"));
665                 x_fprintf(x_stdout, "PW\n");
666                 return;
667         }
668
669         if (strncmp(buf, "YR", 2) == 0) {
670                 if (ntlmssp_state)
671                         ntlmssp_end(&ntlmssp_state);
672         } else if (strncmp(buf, "TT", 2) == 0) {
673                 
674         } else {
675                 DEBUG(1, ("NTLMSSP query [%s] invalid", buf));
676                 x_fprintf(x_stdout, "BH\n");
677                 return;
678         }
679
680         if (!ntlmssp_state) {
681                 if (!NT_STATUS_IS_OK(nt_status = ntlm_auth_start_ntlmssp_client(&ntlmssp_state))) {
682                         x_fprintf(x_stdout, "BH %s\n", nt_errstr(nt_status));
683                         return;
684                 }
685                 first = True;
686         }
687
688         DEBUG(10, ("got NTLMSSP packet:\n"));
689         dump_data(10, (const char *)request.data, request.length);
690
691         nt_status = ntlmssp_update(ntlmssp_state, request, &reply);
692         
693         if (NT_STATUS_EQUAL(nt_status, NT_STATUS_MORE_PROCESSING_REQUIRED)) {
694                 char *reply_base64 = base64_encode_data_blob(reply);
695                 if (first) {
696                         x_fprintf(x_stdout, "YR %s\n", reply_base64);
697                 } else { 
698                         x_fprintf(x_stdout, "KK %s\n", reply_base64);
699                 }
700                 SAFE_FREE(reply_base64);
701                 data_blob_free(&reply);
702                 DEBUG(10, ("NTLMSSP challenge\n"));
703         } else if (NT_STATUS_IS_OK(nt_status)) {
704                 x_fprintf(x_stdout, "AF\n");
705                 DEBUG(10, ("NTLMSSP OK!\n"));
706                 if (ntlmssp_state)
707                         ntlmssp_end(&ntlmssp_state);
708         } else {
709                 x_fprintf(x_stdout, "BH %s\n", nt_errstr(nt_status));
710                 DEBUG(0, ("NTLMSSP BH: %s\n", nt_errstr(nt_status)));
711                 if (ntlmssp_state)
712                         ntlmssp_end(&ntlmssp_state);
713         }
714
715         data_blob_free(&request);
716 }
717
718 static void manage_squid_basic_request(enum stdio_helper_mode stdio_helper_mode, 
719                                        char *buf, int length) 
720 {
721         char *user, *pass;      
722         user=buf;
723         
724         pass=memchr(buf,' ',length);
725         if (!pass) {
726                 DEBUG(2, ("Password not found. Denying access\n"));
727                 x_fprintf(x_stdout, "ERR\n");
728                 return;
729         }
730         *pass='\0';
731         pass++;
732         
733         if (stdio_helper_mode == SQUID_2_5_BASIC) {
734                 rfc1738_unescape(user);
735                 rfc1738_unescape(pass);
736         }
737         
738         if (check_plaintext_auth(user, pass, False)) {
739                 x_fprintf(x_stdout, "OK\n");
740         } else {
741                 x_fprintf(x_stdout, "ERR\n");
742         }
743 }
744
745 static void offer_gss_spnego_mechs(void) {
746
747         DATA_BLOB token;
748         SPNEGO_DATA spnego;
749         ssize_t len;
750         char *reply_base64;
751
752         pstring principal;
753         pstring myname_lower;
754
755         ZERO_STRUCT(spnego);
756
757         pstrcpy(myname_lower, global_myname());
758         strlower_m(myname_lower);
759
760         pstr_sprintf(principal, "%s$@%s", myname_lower, lp_realm());
761
762         /* Server negTokenInit (mech offerings) */
763         spnego.type = SPNEGO_NEG_TOKEN_INIT;
764         spnego.negTokenInit.mechTypes = smb_xmalloc(sizeof(char *) * 3);
765 #ifdef HAVE_KRB5
766         spnego.negTokenInit.mechTypes[0] = smb_xstrdup(OID_KERBEROS5_OLD);
767         spnego.negTokenInit.mechTypes[1] = smb_xstrdup(OID_NTLMSSP);
768         spnego.negTokenInit.mechTypes[2] = NULL;
769 #else
770         spnego.negTokenInit.mechTypes[0] = smb_xstrdup(OID_NTLMSSP);
771         spnego.negTokenInit.mechTypes[1] = NULL;
772 #endif
773
774
775         spnego.negTokenInit.mechListMIC = data_blob(principal,
776                                                     strlen(principal));
777
778         len = write_spnego_data(&token, &spnego);
779         free_spnego_data(&spnego);
780
781         if (len == -1) {
782                 DEBUG(1, ("Could not write SPNEGO data blob\n"));
783                 x_fprintf(x_stdout, "BH\n");
784                 return;
785         }
786
787         reply_base64 = base64_encode_data_blob(token);
788         x_fprintf(x_stdout, "TT %s *\n", reply_base64);
789
790         SAFE_FREE(reply_base64);
791         data_blob_free(&token);
792         DEBUG(10, ("sent SPNEGO negTokenInit\n"));
793         return;
794 }
795
796 static void manage_gss_spnego_request(enum stdio_helper_mode stdio_helper_mode, 
797                                       char *buf, int length) 
798 {
799         static NTLMSSP_STATE *ntlmssp_state = NULL;
800         SPNEGO_DATA request, response;
801         DATA_BLOB token;
802         NTSTATUS status;
803         ssize_t len;
804
805         char *user = NULL;
806         char *domain = NULL;
807
808         const char *reply_code;
809         char       *reply_base64;
810         pstring     reply_argument;
811
812         if (strlen(buf) < 2) {
813
814                 if (ntlmssp_state != NULL) {
815                         DEBUG(1, ("Request for initial SPNEGO request where "
816                                   "we already have a state\n"));
817                         x_fprintf(x_stdout, "BH\n");
818                         return;
819                 }
820
821                 DEBUG(1, ("NTLMSSP query [%s] invalid", buf));
822                 x_fprintf(x_stdout, "BH\n");
823                 return;
824         }
825
826         if ( (strlen(buf) == 2) && (strcmp(buf, "YR") == 0) ) {
827
828                 /* Initial request, get the negTokenInit offering
829                    mechanisms */
830
831                 offer_gss_spnego_mechs();
832                 return;
833         }
834
835         /* All subsequent requests are "KK" (Knock, Knock ;)) and have
836            a blob. This might be negTokenInit or negTokenTarg */
837
838         if ( (strlen(buf) <= 3) || (strncmp(buf, "KK", 2) != 0) ) {
839                 DEBUG(1, ("GSS-SPNEGO query [%s] invalid\n", buf));
840                 x_fprintf(x_stdout, "BH\n");
841                 return;
842         }
843
844         token = base64_decode_data_blob(buf + 3);
845         len = read_spnego_data(token, &request);
846         data_blob_free(&token);
847
848         if (len == -1) {
849                 DEBUG(1, ("GSS-SPNEGO query [%s] invalid", buf));
850                 x_fprintf(x_stdout, "BH\n");
851                 return;
852         }
853
854         if (request.type == SPNEGO_NEG_TOKEN_INIT) {
855
856                 /* Second request from Client. This is where the
857                    client offers its mechanism to use. */
858
859                 if ( (request.negTokenInit.mechTypes == NULL) ||
860                      (request.negTokenInit.mechTypes[0] == NULL) ) {
861                         DEBUG(1, ("Client did not offer any mechanism"));
862                         x_fprintf(x_stdout, "BH\n");
863                         return;
864                 }
865
866                 if (strcmp(request.negTokenInit.mechTypes[0], OID_NTLMSSP) == 0) {
867
868                         if ( request.negTokenInit.mechToken.data == NULL ) {
869                                 DEBUG(1, ("Client did not provide  NTLMSSP data\n"));
870                                 x_fprintf(x_stdout, "BH\n");
871                                 return;
872                         }
873
874                         if ( ntlmssp_state != NULL ) {
875                                 DEBUG(1, ("Client wants a new NTLMSSP challenge, but "
876                                           "already got one\n"));
877                                 x_fprintf(x_stdout, "BH\n");
878                                 ntlmssp_end(&ntlmssp_state);
879                                 return;
880                         }
881
882                         if (!NT_STATUS_IS_OK(status = ntlm_auth_start_ntlmssp_server(&ntlmssp_state))) {
883                                 x_fprintf(x_stdout, "BH %s\n", nt_errstr(status));
884                                 return;
885                         }
886
887                         DEBUG(10, ("got NTLMSSP packet:\n"));
888                         dump_data(10, (const char *)request.negTokenInit.mechToken.data,
889                                   request.negTokenInit.mechToken.length);
890
891                         response.type = SPNEGO_NEG_TOKEN_TARG;
892                         response.negTokenTarg.supportedMech = strdup(OID_NTLMSSP);
893                         response.negTokenTarg.mechListMIC = data_blob(NULL, 0);
894
895                         status = ntlmssp_update(ntlmssp_state,
896                                                        request.negTokenInit.mechToken,
897                                                        &response.negTokenTarg.responseToken);
898                 }
899
900 #ifdef HAVE_KRB5
901                 if (strcmp(request.negTokenInit.mechTypes[0], OID_KERBEROS5_OLD) == 0) {
902
903                         char *principal;
904                         DATA_BLOB auth_data;
905                         DATA_BLOB ap_rep;
906                         DATA_BLOB session_key;
907
908                         if ( request.negTokenInit.mechToken.data == NULL ) {
909                                 DEBUG(1, ("Client did not provide Kerberos data\n"));
910                                 x_fprintf(x_stdout, "BH\n");
911                                 return;
912                         }
913
914                         response.type = SPNEGO_NEG_TOKEN_TARG;
915                         response.negTokenTarg.supportedMech = strdup(OID_KERBEROS5_OLD);
916                         response.negTokenTarg.mechListMIC = data_blob(NULL, 0);
917                         response.negTokenTarg.responseToken = data_blob(NULL, 0);
918
919                         status = ads_verify_ticket(lp_realm(),
920                                                    &request.negTokenInit.mechToken,
921                                                    &principal, &auth_data, &ap_rep,
922                                                    &session_key);
923
924                         /* Now in "principal" we have the name we are
925                            authenticated as. */
926
927                         if (NT_STATUS_IS_OK(status)) {
928
929                                 domain = strchr(principal, '@');
930
931                                 if (domain == NULL) {
932                                         DEBUG(1, ("Did not get a valid principal "
933                                                   "from ads_verify_ticket\n"));
934                                         x_fprintf(x_stdout, "BH\n");
935                                         return;
936                                 }
937
938                                 *domain++ = '\0';
939                                 domain = strdup(domain);
940                                 user = strdup(principal);
941
942                                 data_blob_free(&ap_rep);
943                                 data_blob_free(&auth_data);
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 = strdup(OID_NTLMSSP);
974                 response.negTokenTarg.mechListMIC = data_blob(NULL, 0);
975
976                 if (NT_STATUS_IS_OK(status)) {
977                         user = strdup(ntlmssp_state->user);
978                         domain = 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                 DEBUG(1, ("Expected MORE_PROCESSING_REQUIRED, got: %s\n",
1070                           nt_errstr(status)));
1071                 ntlmssp_end(&client_ntlmssp_state);
1072                 return False;
1073         }
1074
1075         write_spnego_data(&to_server, &spnego);
1076         data_blob_free(&spnego.negTokenInit.mechToken);
1077
1078         to_server_base64 = base64_encode_data_blob(to_server);
1079         data_blob_free(&to_server);
1080         x_fprintf(x_stdout, "KK %s\n", to_server_base64);
1081         SAFE_FREE(to_server_base64);
1082         return True;
1083 }
1084
1085 static void manage_client_ntlmssp_targ(SPNEGO_DATA spnego)
1086 {
1087         NTSTATUS status;
1088         DATA_BLOB null_blob = data_blob(NULL, 0);
1089         DATA_BLOB request;
1090         DATA_BLOB to_server;
1091         char *to_server_base64;
1092
1093         DEBUG(10, ("Got spnego negTokenTarg with NTLMSSP\n"));
1094
1095         if (client_ntlmssp_state == NULL) {
1096                 DEBUG(1, ("Got NTLMSSP tArg without a client state\n"));
1097                 x_fprintf(x_stdout, "BH\n");
1098                 ntlmssp_end(&client_ntlmssp_state);
1099                 return;
1100         }
1101
1102         if (spnego.negTokenTarg.negResult == SPNEGO_REJECT) {
1103                 x_fprintf(x_stdout, "NA\n");
1104                 ntlmssp_end(&client_ntlmssp_state);
1105                 return;
1106         }
1107
1108         if (spnego.negTokenTarg.negResult == SPNEGO_ACCEPT_COMPLETED) {
1109                 x_fprintf(x_stdout, "AF\n");
1110                 ntlmssp_end(&client_ntlmssp_state);
1111                 return;
1112         }
1113
1114         status = ntlmssp_update(client_ntlmssp_state,
1115                                        spnego.negTokenTarg.responseToken,
1116                                        &request);
1117                 
1118         if (!NT_STATUS_EQUAL(status, NT_STATUS_MORE_PROCESSING_REQUIRED)) {
1119                 DEBUG(1, ("Expected MORE_PROCESSING_REQUIRED from "
1120                           "ntlmssp_client_update, got: %s\n",
1121                           nt_errstr(status)));
1122                 x_fprintf(x_stdout, "BH\n");
1123                 data_blob_free(&request);
1124                 ntlmssp_end(&client_ntlmssp_state);
1125                 return;
1126         }
1127
1128         spnego.type = SPNEGO_NEG_TOKEN_TARG;
1129         spnego.negTokenTarg.negResult = SPNEGO_ACCEPT_INCOMPLETE;
1130         spnego.negTokenTarg.supportedMech = OID_NTLMSSP;
1131         spnego.negTokenTarg.responseToken = request;
1132         spnego.negTokenTarg.mechListMIC = null_blob;
1133         
1134         write_spnego_data(&to_server, &spnego);
1135         data_blob_free(&request);
1136
1137         to_server_base64 = base64_encode_data_blob(to_server);
1138         data_blob_free(&to_server);
1139         x_fprintf(x_stdout, "KK %s\n", to_server_base64);
1140         SAFE_FREE(to_server_base64);
1141         return;
1142 }
1143
1144 #ifdef HAVE_KRB5
1145
1146 static BOOL manage_client_krb5_init(SPNEGO_DATA spnego)
1147 {
1148         char *principal;
1149         DATA_BLOB tkt, to_server;
1150         DATA_BLOB session_key_krb5;
1151         SPNEGO_DATA reply;
1152         char *reply_base64;
1153         int retval;
1154         
1155         const char *my_mechs[] = {OID_KERBEROS5_OLD, NULL};
1156         ssize_t len;
1157
1158         if ( (spnego.negTokenInit.mechListMIC.data == NULL) ||
1159              (spnego.negTokenInit.mechListMIC.length == 0) ) {
1160                 DEBUG(1, ("Did not get a principal for krb5\n"));
1161                 return False;
1162         }
1163
1164         principal = malloc(spnego.negTokenInit.mechListMIC.length+1);
1165
1166         if (principal == NULL) {
1167                 DEBUG(1, ("Could not malloc principal\n"));
1168                 return False;
1169         }
1170
1171         memcpy(principal, spnego.negTokenInit.mechListMIC.data,
1172                spnego.negTokenInit.mechListMIC.length);
1173         principal[spnego.negTokenInit.mechListMIC.length] = '\0';
1174
1175         retval = cli_krb5_get_ticket(principal, 0, &tkt, &session_key_krb5);
1176
1177         if (retval) {
1178
1179                 pstring user;
1180
1181                 /* Let's try to first get the TGT, for that we need a
1182                    password. */
1183
1184                 if (opt_password == NULL) {
1185                         DEBUG(10, ("Requesting password\n"));
1186                         x_fprintf(x_stdout, "PW\n");
1187                         return True;
1188                 }
1189
1190                 pstr_sprintf(user, "%s@%s", opt_username, opt_domain);
1191
1192                 if ((retval = kerberos_kinit_password(user, opt_password, 
1193                                                       0, NULL))) {
1194                         DEBUG(10, ("Requesting TGT failed: %s\n", error_message(retval)));
1195                         x_fprintf(x_stdout, "NA\n");
1196                         return True;
1197                 }
1198
1199                 retval = cli_krb5_get_ticket(principal, 0, &tkt, &session_key_krb5);
1200
1201                 if (retval) {
1202                         DEBUG(10, ("Kinit suceeded, but getting a ticket failed: %s\n", error_message(retval)));
1203                 }
1204         }
1205
1206         data_blob_free(&session_key_krb5);
1207
1208         ZERO_STRUCT(reply);
1209
1210         reply.type = SPNEGO_NEG_TOKEN_INIT;
1211         reply.negTokenInit.mechTypes = my_mechs;
1212         reply.negTokenInit.reqFlags = 0;
1213         reply.negTokenInit.mechToken = tkt;
1214         reply.negTokenInit.mechListMIC = data_blob(NULL, 0);
1215
1216         len = write_spnego_data(&to_server, &reply);
1217         data_blob_free(&tkt);
1218
1219         if (len == -1) {
1220                 DEBUG(1, ("Could not write SPNEGO data blob\n"));
1221                 return False;
1222         }
1223
1224         reply_base64 = base64_encode_data_blob(to_server);
1225         x_fprintf(x_stdout, "KK %s *\n", reply_base64);
1226
1227         SAFE_FREE(reply_base64);
1228         data_blob_free(&to_server);
1229         DEBUG(10, ("sent GSS-SPNEGO KERBEROS5 negTokenInit\n"));
1230         return True;
1231 }
1232
1233 static void manage_client_krb5_targ(SPNEGO_DATA spnego)
1234 {
1235         switch (spnego.negTokenTarg.negResult) {
1236         case SPNEGO_ACCEPT_INCOMPLETE:
1237                 DEBUG(1, ("Got a Kerberos negTokenTarg with ACCEPT_INCOMPLETE\n"));
1238                 x_fprintf(x_stdout, "BH\n");
1239                 break;
1240         case SPNEGO_ACCEPT_COMPLETED:
1241                 DEBUG(10, ("Accept completed\n"));
1242                 x_fprintf(x_stdout, "AF\n");
1243                 break;
1244         case SPNEGO_REJECT:
1245                 DEBUG(10, ("Rejected\n"));
1246                 x_fprintf(x_stdout, "NA\n");
1247                 break;
1248         default:
1249                 DEBUG(1, ("Got an invalid negTokenTarg\n"));
1250                 x_fprintf(x_stdout, "AF\n");
1251         }
1252 }
1253
1254 #endif
1255
1256 static void manage_gss_spnego_client_request(enum stdio_helper_mode stdio_helper_mode, 
1257                                              char *buf, int length) 
1258 {
1259         DATA_BLOB request;
1260         SPNEGO_DATA spnego;
1261         ssize_t len;
1262
1263         if (strlen(buf) <= 3) {
1264                 DEBUG(1, ("SPNEGO query [%s] too short\n", buf));
1265                 x_fprintf(x_stdout, "BH\n");
1266                 return;
1267         }
1268
1269         request = base64_decode_data_blob(buf+3);
1270
1271         if (strncmp(buf, "PW ", 3) == 0) {
1272
1273                 /* We asked for a password and obviously got it :-) */
1274
1275                 opt_password = strndup((const char *)request.data, request.length);
1276                 
1277                 if (opt_password == NULL) {
1278                         DEBUG(1, ("Out of memory\n"));
1279                         x_fprintf(x_stdout, "BH\n");
1280                         data_blob_free(&request);
1281                         return;
1282                 }
1283
1284                 x_fprintf(x_stdout, "OK\n");
1285                 data_blob_free(&request);
1286                 return;
1287         }
1288
1289         if ( (strncmp(buf, "TT ", 3) != 0) &&
1290              (strncmp(buf, "AF ", 3) != 0) &&
1291              (strncmp(buf, "NA ", 3) != 0) ) {
1292                 DEBUG(1, ("SPNEGO request [%s] invalid\n", buf));
1293                 x_fprintf(x_stdout, "BH\n");
1294                 data_blob_free(&request);
1295                 return;
1296         }
1297
1298         /* So we got a server challenge to generate a SPNEGO
1299            client-to-server request... */
1300
1301         len = read_spnego_data(request, &spnego);
1302         data_blob_free(&request);
1303
1304         if (len == -1) {
1305                 DEBUG(1, ("Could not read SPNEGO data for [%s]\n", buf));
1306                 x_fprintf(x_stdout, "BH\n");
1307                 return;
1308         }
1309
1310         if (spnego.type == SPNEGO_NEG_TOKEN_INIT) {
1311
1312                 /* The server offers a list of mechanisms */
1313
1314                 const char **mechType = spnego.negTokenInit.mechTypes;
1315
1316                 while (*mechType != NULL) {
1317
1318 #ifdef HAVE_KRB5
1319                         if ( (strcmp(*mechType, OID_KERBEROS5_OLD) == 0) ||
1320                              (strcmp(*mechType, OID_KERBEROS5) == 0) ) {
1321                                 if (manage_client_krb5_init(spnego))
1322                                         goto out;
1323                         }
1324 #endif
1325
1326                         if (strcmp(*mechType, OID_NTLMSSP) == 0) {
1327                                 if (manage_client_ntlmssp_init(spnego))
1328                                         goto out;
1329                         }
1330
1331                         mechType++;
1332                 }
1333
1334                 DEBUG(1, ("Server offered no compatible mechanism\n"));
1335                 x_fprintf(x_stdout, "BH\n");
1336                 return;
1337         }
1338
1339         if (spnego.type == SPNEGO_NEG_TOKEN_TARG) {
1340
1341                 if (spnego.negTokenTarg.supportedMech == NULL) {
1342                         /* On accept/reject Windows does not send the
1343                            mechanism anymore. Handle that here and
1344                            shut down the mechanisms. */
1345
1346                         switch (spnego.negTokenTarg.negResult) {
1347                         case SPNEGO_ACCEPT_COMPLETED:
1348                                 x_fprintf(x_stdout, "AF\n");
1349                                 break;
1350                         case SPNEGO_REJECT:
1351                                 x_fprintf(x_stdout, "NA\n");
1352                                 break;
1353                         default:
1354                                 DEBUG(1, ("Got a negTokenTarg with no mech and an "
1355                                           "unknown negResult: %d\n",
1356                                           spnego.negTokenTarg.negResult));
1357                                 x_fprintf(x_stdout, "BH\n");
1358                         }
1359
1360                         ntlmssp_end(&client_ntlmssp_state);
1361                         goto out;
1362                 }
1363
1364                 if (strcmp(spnego.negTokenTarg.supportedMech,
1365                            OID_NTLMSSP) == 0) {
1366                         manage_client_ntlmssp_targ(spnego);
1367                         goto out;
1368                 }
1369
1370 #if HAVE_KRB5
1371                 if (strcmp(spnego.negTokenTarg.supportedMech,
1372                            OID_KERBEROS5_OLD) == 0) {
1373                         manage_client_krb5_targ(spnego);
1374                         goto out;
1375                 }
1376 #endif
1377
1378         }
1379
1380         DEBUG(1, ("Got an SPNEGO token I could not handle [%s]!\n", buf));
1381         x_fprintf(x_stdout, "BH\n");
1382         return;
1383
1384  out:
1385         free_spnego_data(&spnego);
1386         return;
1387 }
1388
1389 static void manage_ntlm_server_1_request(enum stdio_helper_mode stdio_helper_mode, 
1390                                          char *buf, int length) 
1391 {
1392         char *request, *parameter;      
1393         static DATA_BLOB challenge;
1394         static DATA_BLOB lm_response;
1395         static DATA_BLOB nt_response;
1396         static char *full_username;
1397         static char *username;
1398         static char *domain;
1399         static char *plaintext_password;
1400         static BOOL ntlm_server_1_user_session_key;
1401         static BOOL ntlm_server_1_lm_session_key;
1402         
1403         if (strequal(buf, ".")) {
1404                 if (!full_username && !username) {      
1405                         x_fprintf(x_stdout, "Error: No username supplied!\n");
1406                 } else if (plaintext_password) {
1407                         /* handle this request as plaintext */
1408                         if (!full_username) {
1409                                 if (asprintf(&full_username, "%s%c%s", domain, winbind_separator(), username) == -1) {
1410                                         x_fprintf(x_stdout, "Error: Out of memory in asprintf!\n.\n");
1411                                         return;
1412                                 }
1413                         }
1414                         if (check_plaintext_auth(full_username, plaintext_password, False)) {
1415                                 x_fprintf(x_stdout, "Authenticated: Yes\n");
1416                         } else {
1417                                 x_fprintf(x_stdout, "Authenticated: No\n");
1418                         }
1419                 } else if (!lm_response.data && !nt_response.data) {
1420                         x_fprintf(x_stdout, "Error: No password supplied!\n");
1421                 } else if (!challenge.data) {   
1422                         x_fprintf(x_stdout, "Error: No lanman-challenge supplied!\n");
1423                 } else {
1424                         char *error_string = NULL;
1425                         uchar lm_key[8];
1426                         uchar user_session_key[16];
1427                         uint32 flags = 0;
1428
1429                         if (full_username && !username) {
1430                                 fstring fstr_user;
1431                                 fstring fstr_domain;
1432                                 
1433                                 if (!parse_ntlm_auth_domain_user(full_username, fstr_user, fstr_domain)) {
1434                                         /* username might be 'tainted', don't print into our new-line deleimianted stream */
1435                                         x_fprintf(x_stdout, "Error: Could not parse into domain and username\n");
1436                                 }
1437                                 SAFE_FREE(username);
1438                                 SAFE_FREE(domain);
1439                                 username = smb_xstrdup(fstr_user);
1440                                 domain = smb_xstrdup(fstr_domain);
1441                         }
1442
1443                         if (!domain) {
1444                                 domain = smb_xstrdup(get_winbind_domain());
1445                         }
1446
1447                         if (ntlm_server_1_lm_session_key) 
1448                                 flags |= WBFLAG_PAM_LMKEY;
1449                         
1450                         if (ntlm_server_1_user_session_key) 
1451                                 flags |= WBFLAG_PAM_USER_SESSION_KEY;
1452
1453                         if (!NT_STATUS_IS_OK(
1454                                     contact_winbind_auth_crap(username, 
1455                                                               domain, 
1456                                                               global_myname(),
1457                                                               &challenge, 
1458                                                               &lm_response, 
1459                                                               &nt_response, 
1460                                                               flags, 
1461                                                               lm_key, 
1462                                                               user_session_key,
1463                                                               &error_string,
1464                                                               NULL))) {
1465
1466                                 x_fprintf(x_stdout, "Authenticated: No\n");
1467                                 x_fprintf(x_stdout, "Authentication-Error: %s\n.\n", error_string);
1468                                 SAFE_FREE(error_string);
1469                         } else {
1470                                 static char zeros[16];
1471                                 char *hex_lm_key;
1472                                 char *hex_user_session_key;
1473
1474                                 x_fprintf(x_stdout, "Authenticated: Yes\n");
1475
1476                                 if (ntlm_server_1_lm_session_key 
1477                                     && (memcmp(zeros, lm_key, 
1478                                                sizeof(lm_key)) != 0)) {
1479                                         hex_encode((const unsigned char *)lm_key,
1480                                                    sizeof(lm_key),
1481                                                    &hex_lm_key);
1482                                         x_fprintf(x_stdout, "LANMAN-Session-Key: %s\n", hex_lm_key);
1483                                         SAFE_FREE(hex_lm_key);
1484                                 }
1485
1486                                 if (ntlm_server_1_user_session_key 
1487                                     && (memcmp(zeros, user_session_key, 
1488                                                sizeof(user_session_key)) != 0)) {
1489                                         hex_encode((const unsigned char *)user_session_key, 
1490                                                    sizeof(user_session_key), 
1491                                                    &hex_user_session_key);
1492                                         x_fprintf(x_stdout, "User-Session-Key: %s\n", hex_user_session_key);
1493                                         SAFE_FREE(hex_user_session_key);
1494                                 }
1495                         }
1496                 }
1497                 /* clear out the state */
1498                 challenge = data_blob(NULL, 0);
1499                 nt_response = data_blob(NULL, 0);
1500                 lm_response = data_blob(NULL, 0);
1501                 SAFE_FREE(full_username);
1502                 SAFE_FREE(username);
1503                 SAFE_FREE(domain);
1504                 SAFE_FREE(plaintext_password);
1505                 ntlm_server_1_user_session_key = False;
1506                 ntlm_server_1_lm_session_key = False;
1507                 x_fprintf(x_stdout, ".\n");
1508
1509                 return;
1510         }
1511
1512         request = buf;
1513
1514         /* Indicates a base64 encoded structure */
1515         parameter = strstr_m(request, ":: ");
1516         if (!parameter) {
1517                 parameter = strstr_m(request, ": ");
1518                 
1519                 if (!parameter) {
1520                         DEBUG(0, ("Parameter not found!\n"));
1521                         x_fprintf(x_stdout, "Error: Parameter not found!\n.\n");
1522                         return;
1523                 }
1524                 
1525                 parameter[0] ='\0';
1526                 parameter++;
1527                 parameter[0] ='\0';
1528                 parameter++;
1529
1530         } else {
1531                 parameter[0] ='\0';
1532                 parameter++;
1533                 parameter[0] ='\0';
1534                 parameter++;
1535                 parameter[0] ='\0';
1536                 parameter++;
1537
1538                 base64_decode_inplace(parameter);
1539         }
1540
1541         if (strequal(request, "LANMAN-Challenge")) {
1542                 challenge = strhex_to_data_blob(parameter);
1543                 if (challenge.length != 8) {
1544                         x_fprintf(x_stdout, "Error: hex decode of %s failed! (got %d bytes, expected 8)\n.\n", 
1545                                   parameter,
1546                                   (int)challenge.length);
1547                         challenge = data_blob(NULL, 0);
1548                 }
1549         } else if (strequal(request, "NT-Response")) {
1550                 nt_response = strhex_to_data_blob(parameter);
1551                 if (nt_response.length < 24) {
1552                         x_fprintf(x_stdout, "Error: hex decode of %s failed! (only got %d bytes, needed at least 24)\n.\n", 
1553                                   parameter,
1554                                   (int)opt_nt_response.length);
1555                         nt_response = data_blob(NULL, 0);
1556                 }
1557         } else if (strequal(request, "LANMAN-Response")) {
1558                 lm_response = strhex_to_data_blob(parameter);
1559                 if (lm_response.length != 24) {
1560                         x_fprintf(x_stdout, "Error: hex decode of %s failed! (got %d bytes, expected 24)\n.\n", 
1561                                   parameter,
1562                                   (int)lm_response.length);
1563                         lm_response = data_blob(NULL, 0);
1564                 }
1565         } else if (strequal(request, "Password")) {
1566                 plaintext_password = smb_xstrdup(parameter);
1567         } else if (strequal(request, "NT-Domain")) {
1568                 domain = smb_xstrdup(parameter);
1569         } else if (strequal(request, "Username")) {
1570                 username = smb_xstrdup(parameter);
1571         } else if (strequal(request, "Full-Username")) {
1572                 full_username = smb_xstrdup(parameter);
1573         } else if (strequal(request, "Request-User-Session-Key")) {
1574                 ntlm_server_1_user_session_key = strequal(parameter, "Yes");
1575         } else if (strequal(request, "Request-LanMan-Session-Key")) {
1576                 ntlm_server_1_lm_session_key = strequal(parameter, "Yes");
1577         } else {
1578                 x_fprintf(x_stdout, "Error: Unknown request %s\n.\n", request);
1579         }
1580 }
1581
1582 static void manage_squid_request(enum stdio_helper_mode helper_mode, stdio_helper_function fn) 
1583 {
1584         char buf[SQUID_BUFFER_SIZE+1];
1585         int length;
1586         char *c;
1587         static BOOL err;
1588
1589         /* this is not a typo - x_fgets doesn't work too well under squid */
1590         if (fgets(buf, sizeof(buf)-1, stdin) == NULL) {
1591                 DEBUG(1, ("fgets() failed! dying..... errno=%d (%s)\n", ferror(stdin),
1592                           strerror(ferror(stdin))));
1593                 exit(1);    /* BIIG buffer */
1594         }
1595     
1596         c=memchr(buf,'\n',sizeof(buf)-1);
1597         if (c) {
1598                 *c = '\0';
1599                 length = c-buf;
1600         } else {
1601                 err = 1;
1602                 return;
1603         }
1604         if (err) {
1605                 DEBUG(2, ("Oversized message\n"));
1606                 x_fprintf(x_stderr, "ERR\n");
1607                 err = 0;
1608                 return;
1609         }
1610
1611         DEBUG(10, ("Got '%s' from squid (length: %d).\n",buf,length));
1612
1613         if (buf[0] == '\0') {
1614                 DEBUG(2, ("Invalid Request\n"));
1615                 x_fprintf(x_stderr, "ERR\n");
1616                 return;
1617         }
1618         
1619         fn(helper_mode, buf, length);
1620 }
1621
1622
1623 static void squid_stream(enum stdio_helper_mode stdio_mode, stdio_helper_function fn) {
1624         /* initialize FDescs */
1625         x_setbuf(x_stdout, NULL);
1626         x_setbuf(x_stderr, NULL);
1627         while(1) {
1628                 manage_squid_request(stdio_mode, fn);
1629         }
1630 }
1631
1632
1633 /* Authenticate a user with a challenge/response */
1634
1635 static BOOL check_auth_crap(void)
1636 {
1637         NTSTATUS nt_status;
1638         uint32 flags = 0;
1639         char lm_key[8];
1640         char user_session_key[16];
1641         char *hex_lm_key;
1642         char *hex_user_session_key;
1643         char *error_string;
1644         static uint8 zeros[16];
1645
1646         x_setbuf(x_stdout, NULL);
1647
1648         if (request_lm_key) 
1649                 flags |= WBFLAG_PAM_LMKEY;
1650
1651         if (request_user_session_key) 
1652                 flags |= WBFLAG_PAM_USER_SESSION_KEY;
1653
1654         flags |= WBFLAG_PAM_NT_STATUS_SQUASH;
1655
1656         nt_status = contact_winbind_auth_crap(opt_username, opt_domain, 
1657                                               opt_workstation,
1658                                               &opt_challenge, 
1659                                               &opt_lm_response, 
1660                                               &opt_nt_response, 
1661                                               flags,
1662                                               (unsigned char *)lm_key, 
1663                                               (unsigned char *)user_session_key, 
1664                                               &error_string, NULL);
1665
1666         if (!NT_STATUS_IS_OK(nt_status)) {
1667                 x_fprintf(x_stdout, "%s (0x%x)\n", 
1668                           error_string,
1669                           NT_STATUS_V(nt_status));
1670                 SAFE_FREE(error_string);
1671                 return False;
1672         }
1673
1674         if (request_lm_key 
1675             && (memcmp(zeros, lm_key, 
1676                        sizeof(lm_key)) != 0)) {
1677                 hex_encode((const unsigned char *)lm_key,
1678                            sizeof(lm_key),
1679                            &hex_lm_key);
1680                 x_fprintf(x_stdout, "LM_KEY: %s\n", hex_lm_key);
1681                 SAFE_FREE(hex_lm_key);
1682         }
1683         if (request_user_session_key 
1684             && (memcmp(zeros, user_session_key, 
1685                        sizeof(user_session_key)) != 0)) {
1686                 hex_encode((const unsigned char *)user_session_key, 
1687                            sizeof(user_session_key), 
1688                            &hex_user_session_key);
1689                 x_fprintf(x_stdout, "NT_KEY: %s\n", hex_user_session_key);
1690                 SAFE_FREE(hex_user_session_key);
1691         }
1692
1693         return True;
1694 }
1695
1696 /* Main program */
1697
1698 enum {
1699         OPT_USERNAME = 1000,
1700         OPT_DOMAIN,
1701         OPT_WORKSTATION,
1702         OPT_CHALLENGE,
1703         OPT_RESPONSE,
1704         OPT_LM,
1705         OPT_NT,
1706         OPT_PASSWORD,
1707         OPT_LM_KEY,
1708         OPT_USER_SESSION_KEY,
1709         OPT_DIAGNOSTICS,
1710         OPT_REQUIRE_MEMBERSHIP
1711 };
1712
1713  int main(int argc, const char **argv)
1714 {
1715         int opt;
1716         static const char *helper_protocol;
1717         static int diagnostics;
1718
1719         static const char *hex_challenge;
1720         static const char *hex_lm_response;
1721         static const char *hex_nt_response;
1722
1723         poptContext pc;
1724
1725         /* NOTE: DO NOT change this interface without considering the implications!
1726            This is an external interface, which other programs will use to interact 
1727            with this helper.
1728         */
1729
1730         /* We do not use single-letter command abbreviations, because they harm future 
1731            interface stability. */
1732
1733         struct poptOption long_options[] = {
1734                 POPT_AUTOHELP
1735                 { "helper-protocol", 0, POPT_ARG_STRING, &helper_protocol, OPT_DOMAIN, "operate as a stdio-based helper", "helper protocol to use"},
1736                 { "username", 0, POPT_ARG_STRING, &opt_username, OPT_USERNAME, "username"},
1737                 { "domain", 0, POPT_ARG_STRING, &opt_domain, OPT_DOMAIN, "domain name"},
1738                 { "workstation", 0, POPT_ARG_STRING, &opt_workstation, OPT_WORKSTATION, "workstation"},
1739                 { "challenge", 0, POPT_ARG_STRING, &hex_challenge, OPT_CHALLENGE, "challenge (HEX encoded)"},
1740                 { "lm-response", 0, POPT_ARG_STRING, &hex_lm_response, OPT_LM, "LM Response to the challenge (HEX encoded)"},
1741                 { "nt-response", 0, POPT_ARG_STRING, &hex_nt_response, OPT_NT, "NT or NTLMv2 Response to the challenge (HEX encoded)"},
1742                 { "password", 0, POPT_ARG_STRING, &opt_password, OPT_PASSWORD, "User's plaintext password"},            
1743                 { "request-lm-key", 0, POPT_ARG_NONE, &request_lm_key, OPT_LM_KEY, "Retreive LM session key"},
1744                 { "request-nt-key", 0, POPT_ARG_NONE, &request_user_session_key, OPT_USER_SESSION_KEY, "Retreive User (NT) session key"},
1745                 { "diagnostics", 0, POPT_ARG_NONE, &diagnostics, OPT_DIAGNOSTICS, "Perform diagnostics on the authentictaion chain"},
1746                 { "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" },
1747                 POPT_COMMON_SAMBA
1748                 POPT_TABLEEND
1749         };
1750
1751         /* Samba client initialisation */
1752
1753         dbf = x_stderr;
1754         
1755         /* Samba client initialisation */
1756
1757         if (!lp_load(dyn_CONFIGFILE, True, False, False)) {
1758                 d_fprintf(stderr, "wbinfo: error opening config file %s. Error was %s\n",
1759                         dyn_CONFIGFILE, strerror(errno));
1760                 exit(1);
1761         }
1762
1763         /* Parse options */
1764
1765         pc = poptGetContext("ntlm_auth", argc, argv, long_options, 0);
1766
1767         /* Parse command line options */
1768
1769         if (argc == 1) {
1770                 poptPrintHelp(pc, stderr, 0);
1771                 return 1;
1772         }
1773
1774         pc = poptGetContext(NULL, argc, (const char **)argv, long_options, 
1775                             POPT_CONTEXT_KEEP_FIRST);
1776
1777         while((opt = poptGetNextOpt(pc)) != -1) {
1778                 switch (opt) {
1779                 case OPT_CHALLENGE:
1780                         opt_challenge = strhex_to_data_blob(hex_challenge);
1781                         if (opt_challenge.length != 8) {
1782                                 x_fprintf(x_stderr, "hex decode of %s failed! (only got %d bytes)\n", 
1783                                           hex_challenge,
1784                                           (int)opt_challenge.length);
1785                                 exit(1);
1786                         }
1787                         break;
1788                 case OPT_LM: 
1789                         opt_lm_response = strhex_to_data_blob(hex_lm_response);
1790                         if (opt_lm_response.length != 24) {
1791                                 x_fprintf(x_stderr, "hex decode of %s failed! (only got %d bytes)\n", 
1792                                           hex_lm_response,
1793                                           (int)opt_lm_response.length);
1794                                 exit(1);
1795                         }
1796                         break;
1797
1798                 case OPT_NT: 
1799                         opt_nt_response = strhex_to_data_blob(hex_nt_response);
1800                         if (opt_nt_response.length < 24) {
1801                                 x_fprintf(x_stderr, "hex decode of %s failed! (only got %d bytes)\n", 
1802                                           hex_nt_response,
1803                                           (int)opt_nt_response.length);
1804                                 exit(1);
1805                         }
1806                         break;
1807
1808                 case OPT_REQUIRE_MEMBERSHIP:
1809                         if (StrnCaseCmp("S-", require_membership_of, 2) == 0) {
1810                                 require_membership_sid = require_membership_of;
1811                         }
1812                         break;
1813                 }
1814         }
1815
1816         if (helper_protocol) {
1817                 int i;
1818                 for (i=0; i<NUM_HELPER_MODES; i++) {
1819                         if (strcmp(helper_protocol, stdio_helper_protocols[i].name) == 0) {
1820                                 squid_stream(stdio_helper_protocols[i].mode, stdio_helper_protocols[i].fn);
1821                                 exit(0);
1822                         }
1823                 }
1824                 x_fprintf(x_stderr, "unknown helper protocol [%s]\n\nValid helper protools:\n\n", helper_protocol);
1825
1826                 for (i=0; i<NUM_HELPER_MODES; i++) {
1827                         x_fprintf(x_stderr, "%s\n", stdio_helper_protocols[i].name);
1828                 }
1829
1830                 exit(1);
1831         }
1832
1833         if (!opt_username) {
1834                 x_fprintf(x_stderr, "username must be specified!\n\n");
1835                 poptPrintHelp(pc, stderr, 0);
1836                 exit(1);
1837         }
1838
1839         if (opt_domain == NULL) {
1840                 opt_domain = get_winbind_domain();
1841         }
1842
1843         if (opt_workstation == NULL) {
1844                 opt_workstation = "";
1845         }
1846
1847         if (opt_challenge.length) {
1848                 if (!check_auth_crap()) {
1849                         exit(1);
1850                 }
1851                 exit(0);
1852         } 
1853
1854         if (!opt_password) {
1855                 opt_password = getpass("password: ");
1856         }
1857
1858         if (diagnostics) {
1859                 if (!diagnose_ntlm_auth()) {
1860                         return 1;
1861                 }
1862         } else {
1863                 fstring user;
1864
1865                 fstr_sprintf(user, "%s%c%s", opt_domain, winbind_separator(), opt_username);
1866                 if (!check_plaintext_auth(user, opt_password, True)) {
1867                         return 1;
1868                 }
1869         }
1870
1871         /* Exit code */
1872
1873         poptFreeContext(pc);
1874         return 0;
1875 }