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