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