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