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