ntlmssp: Move ntlmssp code to auth/ntlmssp
[obnox/samba/samba-obnox.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    Copyright (C) Robert O'Callahan 2006 (added cached credential code).
10    Copyright (C) Kai Blin <kai@samba.org> 2008
11
12    This program is free software; you can redistribute it and/or modify
13    it under the terms of the GNU General Public License as published by
14    the Free Software Foundation; either version 3 of the License, or
15    (at your option) any later version.
16
17    This program is distributed in the hope that it will be useful,
18    but WITHOUT ANY WARRANTY; without even the implied warranty of
19    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20    GNU General Public License for more details.
21
22    You should have received a copy of the GNU General Public License
23    along with this program.  If not, see <http://www.gnu.org/licenses/>.
24 */
25
26 #include "includes.h"
27 #include "popt_common.h"
28 #include "utils/ntlm_auth.h"
29 #include "../libcli/auth/libcli_auth.h"
30 #include "../libcli/auth/spnego.h"
31 #include "../auth/ntlmssp/ntlmssp.h"
32 #include "smb_krb5.h"
33 #include <iniparser.h>
34 #include "../lib/crypto/arcfour.h"
35 #include "libads/kerberos_proto.h"
36 #include "nsswitch/winbind_client.h"
37 #include "librpc/gen_ndr/krb5pac.h"
38 #include "../lib/util/asn1.h"
39
40 #ifndef PAM_WINBIND_CONFIG_FILE
41 #define PAM_WINBIND_CONFIG_FILE "/etc/security/pam_winbind.conf"
42 #endif
43
44 #define WINBIND_KRB5_AUTH       0x00000080
45
46 #undef DBGC_CLASS
47 #define DBGC_CLASS DBGC_WINBIND
48
49 #define INITIAL_BUFFER_SIZE 300
50 #define MAX_BUFFER_SIZE 630000
51
52 enum stdio_helper_mode {
53         SQUID_2_4_BASIC,
54         SQUID_2_5_BASIC,
55         SQUID_2_5_NTLMSSP,
56         NTLMSSP_CLIENT_1,
57         GSS_SPNEGO,
58         GSS_SPNEGO_CLIENT,
59         NTLM_SERVER_1,
60         NTLM_CHANGE_PASSWORD_1,
61         NUM_HELPER_MODES
62 };
63
64 enum ntlm_auth_cli_state {
65         CLIENT_INITIAL = 0,
66         CLIENT_RESPONSE,
67         CLIENT_FINISHED,
68         CLIENT_ERROR
69 };
70
71 enum ntlm_auth_svr_state {
72         SERVER_INITIAL = 0,
73         SERVER_CHALLENGE,
74         SERVER_FINISHED,
75         SERVER_ERROR
76 };
77
78 struct ntlm_auth_state {
79         TALLOC_CTX *mem_ctx;
80         enum stdio_helper_mode helper_mode;
81         enum ntlm_auth_cli_state cli_state;
82         enum ntlm_auth_svr_state svr_state;
83         struct ntlmssp_state *ntlmssp_state;
84         uint32_t neg_flags;
85         char *want_feature_list;
86         char *spnego_mech;
87         char *spnego_mech_oid;
88         bool have_session_key;
89         DATA_BLOB session_key;
90         DATA_BLOB initial_message;
91 };
92
93 typedef void (*stdio_helper_function)(struct ntlm_auth_state *state, char *buf,
94                                         int length);
95
96 static void manage_squid_basic_request (struct ntlm_auth_state *state,
97                                         char *buf, int length);
98
99 static void manage_squid_ntlmssp_request (struct ntlm_auth_state *state,
100                                         char *buf, int length);
101
102 static void manage_client_ntlmssp_request (struct ntlm_auth_state *state,
103                                         char *buf, int length);
104
105 static void manage_gss_spnego_request (struct ntlm_auth_state *state,
106                                         char *buf, int length);
107
108 static void manage_gss_spnego_client_request (struct ntlm_auth_state *state,
109                                         char *buf, int length);
110
111 static void manage_ntlm_server_1_request (struct ntlm_auth_state *state,
112                                         char *buf, int length);
113
114 static void manage_ntlm_change_password_1_request(struct ntlm_auth_state *state,
115                                         char *buf, int length);
116
117 static const struct {
118         enum stdio_helper_mode mode;
119         const char *name;
120         stdio_helper_function fn;
121 } stdio_helper_protocols[] = {
122         { SQUID_2_4_BASIC, "squid-2.4-basic", manage_squid_basic_request},
123         { SQUID_2_5_BASIC, "squid-2.5-basic", manage_squid_basic_request},
124         { SQUID_2_5_NTLMSSP, "squid-2.5-ntlmssp", manage_squid_ntlmssp_request},
125         { NTLMSSP_CLIENT_1, "ntlmssp-client-1", manage_client_ntlmssp_request},
126         { GSS_SPNEGO, "gss-spnego", manage_gss_spnego_request},
127         { GSS_SPNEGO_CLIENT, "gss-spnego-client", manage_gss_spnego_client_request},
128         { NTLM_SERVER_1, "ntlm-server-1", manage_ntlm_server_1_request},
129         { NTLM_CHANGE_PASSWORD_1, "ntlm-change-password-1", manage_ntlm_change_password_1_request},
130         { NUM_HELPER_MODES, NULL, NULL}
131 };
132
133 const char *opt_username;
134 const char *opt_domain;
135 const char *opt_workstation;
136 const char *opt_password;
137 static DATA_BLOB opt_challenge;
138 static DATA_BLOB opt_lm_response;
139 static DATA_BLOB opt_nt_response;
140 static int request_lm_key;
141 static int request_user_session_key;
142 static int use_cached_creds;
143
144 static const char *require_membership_of;
145 static const char *require_membership_of_sid;
146 static const char *opt_pam_winbind_conf;
147
148 static char winbind_separator(void)
149 {
150         struct winbindd_response response;
151         static bool got_sep;
152         static char sep;
153
154         if (got_sep)
155                 return sep;
156
157         ZERO_STRUCT(response);
158
159         /* Send off request */
160
161         if (winbindd_request_response(WINBINDD_INFO, NULL, &response) !=
162             NSS_STATUS_SUCCESS) {
163                 d_printf("could not obtain winbind separator!\n");
164                 return *lp_winbind_separator();
165         }
166
167         sep = response.data.info.winbind_separator;
168         got_sep = True;
169
170         if (!sep) {
171                 d_printf("winbind separator was NULL!\n");
172                 return *lp_winbind_separator();
173         }
174
175         return sep;
176 }
177
178 const char *get_winbind_domain(void)
179 {
180         struct winbindd_response response;
181
182         static fstring winbind_domain;
183         if (*winbind_domain) {
184                 return winbind_domain;
185         }
186
187         ZERO_STRUCT(response);
188
189         /* Send off request */
190
191         if (winbindd_request_response(WINBINDD_DOMAIN_NAME, NULL, &response) !=
192             NSS_STATUS_SUCCESS) {
193                 DEBUG(0, ("could not obtain winbind domain name!\n"));
194                 return lp_workgroup();
195         }
196
197         fstrcpy(winbind_domain, response.data.domain_name);
198
199         return winbind_domain;
200
201 }
202
203 const char *get_winbind_netbios_name(void)
204 {
205         struct winbindd_response response;
206
207         static fstring winbind_netbios_name;
208
209         if (*winbind_netbios_name) {
210                 return winbind_netbios_name;
211         }
212
213         ZERO_STRUCT(response);
214
215         /* Send off request */
216
217         if (winbindd_request_response(WINBINDD_NETBIOS_NAME, NULL, &response) !=
218             NSS_STATUS_SUCCESS) {
219                 DEBUG(0, ("could not obtain winbind netbios name!\n"));
220                 return lp_netbios_name();
221         }
222
223         fstrcpy(winbind_netbios_name, response.data.netbios_name);
224
225         return winbind_netbios_name;
226
227 }
228
229 DATA_BLOB get_challenge(void) 
230 {
231         static DATA_BLOB chal;
232         if (opt_challenge.length)
233                 return opt_challenge;
234
235         chal = data_blob(NULL, 8);
236
237         generate_random_buffer(chal.data, chal.length);
238         return chal;
239 }
240
241 /* Copy of parse_domain_user from winbindd_util.c.  Parse a string of the
242    form DOMAIN/user into a domain and a user */
243
244 static bool parse_ntlm_auth_domain_user(const char *domuser, fstring domain, 
245                                      fstring user)
246 {
247
248         char *p = strchr(domuser,winbind_separator());
249
250         if (!p) {
251                 return False;
252         }
253
254         fstrcpy(user, p+1);
255         fstrcpy(domain, domuser);
256         domain[PTR_DIFF(p, domuser)] = 0;
257         strupper_m(domain);
258
259         return True;
260 }
261
262 static bool get_require_membership_sid(void) {
263         struct winbindd_request request;
264         struct winbindd_response response;
265
266         if (!require_membership_of) {
267                 return True;
268         }
269
270         if (require_membership_of_sid) {
271                 return True;
272         }
273
274         /* Otherwise, ask winbindd for the name->sid request */
275
276         ZERO_STRUCT(request);
277         ZERO_STRUCT(response);
278
279         if (!parse_ntlm_auth_domain_user(require_membership_of, 
280                                          request.data.name.dom_name, 
281                                          request.data.name.name)) {
282                 DEBUG(0, ("Could not parse %s into seperate domain/name parts!\n", 
283                           require_membership_of));
284                 return False;
285         }
286
287         if (winbindd_request_response(WINBINDD_LOOKUPNAME, &request, &response) !=
288             NSS_STATUS_SUCCESS) {
289                 DEBUG(0, ("Winbindd lookupname failed to resolve %s into a SID!\n", 
290                           require_membership_of));
291                 return False;
292         }
293
294         require_membership_of_sid = SMB_STRDUP(response.data.sid.sid);
295
296         if (require_membership_of_sid)
297                 return True;
298
299         return False;
300 }
301
302 /* 
303  * Get some configuration from pam_winbind.conf to see if we 
304  * need to contact trusted domain
305  */
306
307 int get_pam_winbind_config()
308 {
309         int ctrl = 0;
310         dictionary *d = NULL;
311
312         if (!opt_pam_winbind_conf || !*opt_pam_winbind_conf) {
313                 opt_pam_winbind_conf = PAM_WINBIND_CONFIG_FILE;
314         }
315
316         d = iniparser_load(discard_const_p(char, opt_pam_winbind_conf));
317
318         if (!d) {
319                 return 0;
320         }
321
322         if (iniparser_getboolean(d, discard_const_p(char, "global:krb5_auth"), false)) {
323                 ctrl |= WINBIND_KRB5_AUTH;
324         }
325
326         iniparser_freedict(d);
327
328         return ctrl;
329 }
330
331 /* Authenticate a user with a plaintext password */
332
333 static bool check_plaintext_auth(const char *user, const char *pass,
334                                  bool stdout_diagnostics)
335 {
336         struct winbindd_request request;
337         struct winbindd_response response;
338         NSS_STATUS result;
339
340         if (!get_require_membership_sid()) {
341                 return False;
342         }
343
344         /* Send off request */
345
346         ZERO_STRUCT(request);
347         ZERO_STRUCT(response);
348
349         fstrcpy(request.data.auth.user, user);
350         fstrcpy(request.data.auth.pass, pass);
351         if (require_membership_of_sid) {
352                 strlcpy(request.data.auth.require_membership_of_sid,
353                         require_membership_of_sid,
354                         sizeof(request.data.auth.require_membership_of_sid));
355         }
356
357         result = winbindd_request_response(WINBINDD_PAM_AUTH, &request, &response);
358
359         /* Display response */
360
361         if (stdout_diagnostics) {
362                 if ((result != NSS_STATUS_SUCCESS) && (response.data.auth.nt_status == 0)) {
363                         d_printf("Reading winbind reply failed! (0x01)\n");
364                 }
365
366                 d_printf("%s: %s (0x%x)\n",
367                          response.data.auth.nt_status_string,
368                          response.data.auth.error_string,
369                          response.data.auth.nt_status);
370         } else {
371                 if ((result != NSS_STATUS_SUCCESS) && (response.data.auth.nt_status == 0)) {
372                         DEBUG(1, ("Reading winbind reply failed! (0x01)\n"));
373                 }
374
375                 DEBUG(3, ("%s: %s (0x%x)\n",
376                           response.data.auth.nt_status_string,
377                           response.data.auth.error_string,
378                           response.data.auth.nt_status));
379         }
380
381         return (result == NSS_STATUS_SUCCESS);
382 }
383
384 /* authenticate a user with an encrypted username/password */
385
386 NTSTATUS contact_winbind_auth_crap(const char *username,
387                                    const char *domain,
388                                    const char *workstation,
389                                    const DATA_BLOB *challenge,
390                                    const DATA_BLOB *lm_response,
391                                    const DATA_BLOB *nt_response,
392                                    uint32 flags,
393                                    uint8 lm_key[8],
394                                    uint8 user_session_key[16],
395                                    char **error_string,
396                                    char **unix_name)
397 {
398         NTSTATUS nt_status;
399         NSS_STATUS result;
400         struct winbindd_request request;
401         struct winbindd_response response;
402
403         if (!get_require_membership_sid()) {
404                 return NT_STATUS_INVALID_PARAMETER;
405         }
406
407         ZERO_STRUCT(request);
408         ZERO_STRUCT(response);
409
410         request.flags = flags;
411
412         request.data.auth_crap.logon_parameters = MSV1_0_ALLOW_WORKSTATION_TRUST_ACCOUNT | MSV1_0_ALLOW_SERVER_TRUST_ACCOUNT;
413
414         if (require_membership_of_sid)
415                 fstrcpy(request.data.auth_crap.require_membership_of_sid, require_membership_of_sid);
416
417         fstrcpy(request.data.auth_crap.user, username);
418         fstrcpy(request.data.auth_crap.domain, domain);
419
420         fstrcpy(request.data.auth_crap.workstation, 
421                 workstation);
422
423         memcpy(request.data.auth_crap.chal, challenge->data, MIN(challenge->length, 8));
424
425         if (lm_response && lm_response->length) {
426                 memcpy(request.data.auth_crap.lm_resp, 
427                        lm_response->data, 
428                        MIN(lm_response->length, sizeof(request.data.auth_crap.lm_resp)));
429                 request.data.auth_crap.lm_resp_len = lm_response->length;
430         }
431
432         if (nt_response && nt_response->length) {
433                 if (nt_response->length > sizeof(request.data.auth_crap.nt_resp)) {
434                         request.flags = request.flags | WBFLAG_BIG_NTLMV2_BLOB;
435                         request.extra_len = nt_response->length;
436                         request.extra_data.data = SMB_MALLOC_ARRAY(char, request.extra_len);
437                         if (request.extra_data.data == NULL) {
438                                 return NT_STATUS_NO_MEMORY;
439                         }
440                         memcpy(request.extra_data.data, nt_response->data,
441                                nt_response->length);
442
443                 } else {
444                         memcpy(request.data.auth_crap.nt_resp,
445                                nt_response->data, nt_response->length);
446                 }
447                 request.data.auth_crap.nt_resp_len = nt_response->length;
448         }
449
450         result = winbindd_request_response(WINBINDD_PAM_AUTH_CRAP, &request, &response);
451         SAFE_FREE(request.extra_data.data);
452
453         /* Display response */
454
455         if ((result != NSS_STATUS_SUCCESS) && (response.data.auth.nt_status == 0)) {
456                 nt_status = NT_STATUS_UNSUCCESSFUL;
457                 if (error_string)
458                         *error_string = smb_xstrdup("Reading winbind reply failed!");
459                 winbindd_free_response(&response);
460                 return nt_status;
461         }
462
463         nt_status = (NT_STATUS(response.data.auth.nt_status));
464         if (!NT_STATUS_IS_OK(nt_status)) {
465                 if (error_string) 
466                         *error_string = smb_xstrdup(response.data.auth.error_string);
467                 winbindd_free_response(&response);
468                 return nt_status;
469         }
470
471         if ((flags & WBFLAG_PAM_LMKEY) && lm_key) {
472                 memcpy(lm_key, response.data.auth.first_8_lm_hash, 
473                        sizeof(response.data.auth.first_8_lm_hash));
474         }
475         if ((flags & WBFLAG_PAM_USER_SESSION_KEY) && user_session_key) {
476                 memcpy(user_session_key, response.data.auth.user_session_key, 
477                         sizeof(response.data.auth.user_session_key));
478         }
479
480         if (flags & WBFLAG_PAM_UNIX_NAME) {
481                 *unix_name = SMB_STRDUP(response.data.auth.unix_username);
482                 if (!*unix_name) {
483                         winbindd_free_response(&response);
484                         return NT_STATUS_NO_MEMORY;
485                 }
486         }
487
488         winbindd_free_response(&response);
489         return nt_status;
490 }
491
492 /* contact server to change user password using auth crap */
493 static NTSTATUS contact_winbind_change_pswd_auth_crap(const char *username,
494                                                       const char *domain,
495                                                       const DATA_BLOB new_nt_pswd,
496                                                       const DATA_BLOB old_nt_hash_enc,
497                                                       const DATA_BLOB new_lm_pswd,
498                                                       const DATA_BLOB old_lm_hash_enc,
499                                                       char  **error_string)
500 {
501         NTSTATUS nt_status;
502         NSS_STATUS result;
503         struct winbindd_request request;
504         struct winbindd_response response;
505
506         if (!get_require_membership_sid())
507         {
508                 if(error_string)
509                         *error_string = smb_xstrdup("Can't get membership sid.");
510                 return NT_STATUS_INVALID_PARAMETER;
511         }
512
513         ZERO_STRUCT(request);
514         ZERO_STRUCT(response);
515
516         if(username != NULL)
517                 fstrcpy(request.data.chng_pswd_auth_crap.user, username);
518         if(domain != NULL)
519                 fstrcpy(request.data.chng_pswd_auth_crap.domain,domain);
520
521         if(new_nt_pswd.length)
522         {
523                 memcpy(request.data.chng_pswd_auth_crap.new_nt_pswd, new_nt_pswd.data, sizeof(request.data.chng_pswd_auth_crap.new_nt_pswd));
524                 request.data.chng_pswd_auth_crap.new_nt_pswd_len = new_nt_pswd.length;
525         }
526
527         if(old_nt_hash_enc.length)
528         {
529                 memcpy(request.data.chng_pswd_auth_crap.old_nt_hash_enc, old_nt_hash_enc.data, sizeof(request.data.chng_pswd_auth_crap.old_nt_hash_enc));
530                 request.data.chng_pswd_auth_crap.old_nt_hash_enc_len = old_nt_hash_enc.length;
531         }
532
533         if(new_lm_pswd.length)
534         {
535                 memcpy(request.data.chng_pswd_auth_crap.new_lm_pswd, new_lm_pswd.data, sizeof(request.data.chng_pswd_auth_crap.new_lm_pswd));
536                 request.data.chng_pswd_auth_crap.new_lm_pswd_len = new_lm_pswd.length;
537         }
538
539         if(old_lm_hash_enc.length)
540         {
541                 memcpy(request.data.chng_pswd_auth_crap.old_lm_hash_enc, old_lm_hash_enc.data, sizeof(request.data.chng_pswd_auth_crap.old_lm_hash_enc));
542                 request.data.chng_pswd_auth_crap.old_lm_hash_enc_len = old_lm_hash_enc.length;
543         }
544
545         result = winbindd_request_response(WINBINDD_PAM_CHNG_PSWD_AUTH_CRAP, &request, &response);
546
547         /* Display response */
548
549         if ((result != NSS_STATUS_SUCCESS) && (response.data.auth.nt_status == 0))
550         {
551                 nt_status = NT_STATUS_UNSUCCESSFUL;
552                 if (error_string)
553                         *error_string = smb_xstrdup("Reading winbind reply failed!");
554                 winbindd_free_response(&response);
555                 return nt_status;
556         }
557
558         nt_status = (NT_STATUS(response.data.auth.nt_status));
559         if (!NT_STATUS_IS_OK(nt_status))
560         {
561                 if (error_string) 
562                         *error_string = smb_xstrdup(response.data.auth.error_string);
563                 winbindd_free_response(&response);
564                 return nt_status;
565         }
566
567         winbindd_free_response(&response);
568
569     return nt_status;
570 }
571
572 static NTSTATUS winbind_pw_check(struct ntlmssp_state *ntlmssp_state, TALLOC_CTX *mem_ctx,
573                                  DATA_BLOB *user_session_key, DATA_BLOB *lm_session_key)
574 {
575         static const char zeros[16] = { 0, };
576         NTSTATUS nt_status;
577         char *error_string = NULL;
578         uint8 lm_key[8]; 
579         uint8 user_sess_key[16]; 
580         char *unix_name = NULL;
581
582         nt_status = contact_winbind_auth_crap(ntlmssp_state->user, ntlmssp_state->domain,
583                                               ntlmssp_state->client.netbios_name,
584                                               &ntlmssp_state->chal,
585                                               &ntlmssp_state->lm_resp,
586                                               &ntlmssp_state->nt_resp, 
587                                               WBFLAG_PAM_LMKEY | WBFLAG_PAM_USER_SESSION_KEY | WBFLAG_PAM_UNIX_NAME,
588                                               lm_key, user_sess_key, 
589                                               &error_string, &unix_name);
590
591         if (NT_STATUS_IS_OK(nt_status)) {
592                 if (memcmp(lm_key, zeros, 8) != 0) {
593                         *lm_session_key = data_blob_talloc(mem_ctx, NULL, 16);
594                         memcpy(lm_session_key->data, lm_key, 8);
595                         memset(lm_session_key->data+8, '\0', 8);
596                 }
597
598                 if (memcmp(user_sess_key, zeros, 16) != 0) {
599                         *user_session_key = data_blob_talloc(mem_ctx, user_sess_key, 16);
600                 }
601                 ntlmssp_state->callback_private = talloc_strdup(ntlmssp_state,
602                                                                 unix_name);
603         } else {
604                 DEBUG(NT_STATUS_EQUAL(nt_status, NT_STATUS_ACCESS_DENIED) ? 0 : 3, 
605                       ("Login for user [%s]\\[%s]@[%s] failed due to [%s]\n", 
606                        ntlmssp_state->domain, ntlmssp_state->user, 
607                        ntlmssp_state->client.netbios_name,
608                        error_string ? error_string : "unknown error (NULL)"));
609                 ntlmssp_state->callback_private = NULL;
610         }
611
612         SAFE_FREE(error_string);
613         SAFE_FREE(unix_name);
614         return nt_status;
615 }
616
617 static NTSTATUS local_pw_check(struct ntlmssp_state *ntlmssp_state, TALLOC_CTX *mem_ctx,
618                                DATA_BLOB *user_session_key, DATA_BLOB *lm_session_key)
619 {
620         NTSTATUS nt_status;
621         struct samr_Password lm_pw, nt_pw;
622
623         nt_lm_owf_gen (opt_password, nt_pw.hash, lm_pw.hash);
624
625         nt_status = ntlm_password_check(mem_ctx,
626                                         true, true, 0,
627                                         &ntlmssp_state->chal,
628                                         &ntlmssp_state->lm_resp,
629                                         &ntlmssp_state->nt_resp, 
630                                         ntlmssp_state->user, 
631                                         ntlmssp_state->user, 
632                                         ntlmssp_state->domain,
633                                         &lm_pw, &nt_pw, user_session_key, lm_session_key);
634
635         if (NT_STATUS_IS_OK(nt_status)) {
636                 ntlmssp_state->callback_private = talloc_asprintf(ntlmssp_state,
637                                                               "%s%c%s", ntlmssp_state->domain, 
638                                                               *lp_winbind_separator(), 
639                                                               ntlmssp_state->user);
640         } else {
641                 DEBUG(3, ("Login for user [%s]\\[%s]@[%s] failed due to [%s]\n", 
642                           ntlmssp_state->domain, ntlmssp_state->user,
643                           ntlmssp_state->client.netbios_name,
644                           nt_errstr(nt_status)));
645                 ntlmssp_state->callback_private = NULL;
646         }
647         return nt_status;
648 }
649
650 static NTSTATUS ntlm_auth_start_ntlmssp_client(struct ntlmssp_state **client_ntlmssp_state)
651 {
652         NTSTATUS status;
653         if ( (opt_username == NULL) || (opt_domain == NULL) ) {
654                 status = NT_STATUS_UNSUCCESSFUL;
655                 DEBUG(1, ("Need username and domain for NTLMSSP\n"));
656                 return NT_STATUS_INVALID_PARAMETER;
657         }
658
659         status = ntlmssp_client_start(NULL,
660                                       lp_netbios_name(),
661                                       lp_workgroup(),
662                                       lp_client_ntlmv2_auth(),
663                                       client_ntlmssp_state);
664
665         if (!NT_STATUS_IS_OK(status)) {
666                 DEBUG(1, ("Could not start NTLMSSP client: %s\n",
667                           nt_errstr(status)));
668                 TALLOC_FREE(*client_ntlmssp_state);
669                 return status;
670         }
671
672         status = ntlmssp_set_username(*client_ntlmssp_state, opt_username);
673
674         if (!NT_STATUS_IS_OK(status)) {
675                 DEBUG(1, ("Could not set username: %s\n",
676                           nt_errstr(status)));
677                 TALLOC_FREE(*client_ntlmssp_state);
678                 return status;
679         }
680
681         status = ntlmssp_set_domain(*client_ntlmssp_state, opt_domain);
682
683         if (!NT_STATUS_IS_OK(status)) {
684                 DEBUG(1, ("Could not set domain: %s\n",
685                           nt_errstr(status)));
686                 TALLOC_FREE(*client_ntlmssp_state);
687                 return status;
688         }
689
690         if (opt_password) {
691                 status = ntlmssp_set_password(*client_ntlmssp_state, opt_password);
692
693                 if (!NT_STATUS_IS_OK(status)) {
694                         DEBUG(1, ("Could not set password: %s\n",
695                                   nt_errstr(status)));
696                         TALLOC_FREE(*client_ntlmssp_state);
697                         return status;
698                 }
699         }
700
701         return NT_STATUS_OK;
702 }
703
704 static NTSTATUS ntlm_auth_start_ntlmssp_server(struct ntlmssp_state **ntlmssp_state)
705 {
706         NTSTATUS status;
707         const char *netbios_name;
708         const char *netbios_domain;
709         const char *dns_name;
710         char *dns_domain;
711         bool is_standalone = false;
712
713         if (opt_password) {
714                 netbios_name = lp_netbios_name();
715                 netbios_domain = lp_workgroup();
716         } else {
717                 netbios_name = get_winbind_netbios_name();
718                 netbios_domain = get_winbind_domain();
719         }
720         /* This should be a 'netbios domain -> DNS domain' mapping */
721         dns_domain = get_mydnsdomname(talloc_tos());
722         if (dns_domain) {
723                 strlower_m(dns_domain);
724         }
725         dns_name = get_mydnsfullname();
726
727         status = ntlmssp_server_start(NULL,
728                                       is_standalone,
729                                       netbios_name,
730                                       netbios_domain,
731                                       dns_name,
732                                       dns_domain,
733                                       ntlmssp_state);
734         if (!NT_STATUS_IS_OK(status)) {
735                 DEBUG(1, ("Could not start NTLMSSP server: %s\n",
736                           nt_errstr(status)));
737                 return status;
738         }
739
740         (*ntlmssp_state)->neg_flags |=
741                 (NTLMSSP_NEGOTIATE_SIGN |
742                  NTLMSSP_NEGOTIATE_SEAL);
743
744         /* Have we been given a local password, or should we ask winbind? */
745         if (opt_password) {
746                 (*ntlmssp_state)->check_password = local_pw_check;
747         } else {
748                 (*ntlmssp_state)->check_password = winbind_pw_check;
749         }
750         return NT_STATUS_OK;
751 }
752
753 /*******************************************************************
754  Used by firefox to drive NTLM auth to IIS servers.
755 *******************************************************************/
756
757 static NTSTATUS do_ccache_ntlm_auth(DATA_BLOB initial_msg, DATA_BLOB challenge_msg,
758                                 DATA_BLOB *reply)
759 {
760         struct winbindd_request wb_request;
761         struct winbindd_response wb_response;
762         int ctrl = 0;
763         NSS_STATUS result;
764
765         /* get winbindd to do the ntlmssp step on our behalf */
766         ZERO_STRUCT(wb_request);
767         ZERO_STRUCT(wb_response);
768
769         /*
770          * This is tricky here. If we set krb5_auth in pam_winbind.conf
771          * creds for users in trusted domain will be stored the winbindd
772          * child of the trusted domain. If we ask the primary domain for
773          * ntlm_ccache_auth, it will fail. So, we have to ask the trusted
774          * domain's child for ccache_ntlm_auth. that is to say, we have to 
775          * set WBFLAG_PAM_CONTACT_TRUSTDOM in request.flags.
776          */
777         ctrl = get_pam_winbind_config();
778
779         if (ctrl & WINBIND_KRB5_AUTH) {
780                 wb_request.flags |= WBFLAG_PAM_CONTACT_TRUSTDOM;
781         }
782
783         fstr_sprintf(wb_request.data.ccache_ntlm_auth.user,
784                 "%s%c%s", opt_domain, winbind_separator(), opt_username);
785         wb_request.data.ccache_ntlm_auth.uid = geteuid();
786         wb_request.data.ccache_ntlm_auth.initial_blob_len = initial_msg.length;
787         wb_request.data.ccache_ntlm_auth.challenge_blob_len = challenge_msg.length;
788         wb_request.extra_len = initial_msg.length + challenge_msg.length;
789
790         if (wb_request.extra_len > 0) {
791                 wb_request.extra_data.data = SMB_MALLOC_ARRAY(char, wb_request.extra_len);
792                 if (wb_request.extra_data.data == NULL) {
793                         return NT_STATUS_NO_MEMORY;
794                 }
795
796                 memcpy(wb_request.extra_data.data, initial_msg.data, initial_msg.length);
797                 memcpy(wb_request.extra_data.data + initial_msg.length,
798                         challenge_msg.data, challenge_msg.length);
799         }
800
801         result = winbindd_request_response(WINBINDD_CCACHE_NTLMAUTH, &wb_request, &wb_response);
802         SAFE_FREE(wb_request.extra_data.data);
803
804         if (result != NSS_STATUS_SUCCESS) {
805                 winbindd_free_response(&wb_response);
806                 return NT_STATUS_UNSUCCESSFUL;
807         }
808
809         if (reply) {
810                 *reply = data_blob(wb_response.extra_data.data,
811                                 wb_response.data.ccache_ntlm_auth.auth_blob_len);
812                 if (wb_response.data.ccache_ntlm_auth.auth_blob_len > 0 &&
813                                 reply->data == NULL) {
814                         winbindd_free_response(&wb_response);
815                         return NT_STATUS_NO_MEMORY;
816                 }
817         }
818
819         winbindd_free_response(&wb_response);
820         return NT_STATUS_MORE_PROCESSING_REQUIRED;
821 }
822
823 static void manage_squid_ntlmssp_request_int(struct ntlm_auth_state *state,
824                                              char *buf, int length,
825                                              TALLOC_CTX *mem_ctx,
826                                              char **response)
827 {
828         DATA_BLOB request, reply;
829         NTSTATUS nt_status;
830
831         if (strlen(buf) < 2) {
832                 DEBUG(1, ("NTLMSSP query [%s] invalid\n", buf));
833                 *response = talloc_strdup(mem_ctx, "BH NTLMSSP query invalid");
834                 return;
835         }
836
837         if (strlen(buf) > 3) {
838                 if(strncmp(buf, "SF ", 3) == 0){
839                         DEBUG(10, ("Setting flags to negotioate\n"));
840                         TALLOC_FREE(state->want_feature_list);
841                         state->want_feature_list = talloc_strdup(state->mem_ctx,
842                                         buf+3);
843                         *response = talloc_strdup(mem_ctx, "OK");
844                         return;
845                 }
846                 request = base64_decode_data_blob(buf + 3);
847         } else {
848                 request = data_blob_null;
849         }
850
851         if ((strncmp(buf, "PW ", 3) == 0)) {
852                 /* The calling application wants us to use a local password
853                  * (rather than winbindd) */
854
855                 opt_password = SMB_STRNDUP((const char *)request.data,
856                                 request.length);
857
858                 if (opt_password == NULL) {
859                         DEBUG(1, ("Out of memory\n"));
860                         *response = talloc_strdup(mem_ctx, "BH Out of memory");
861                         data_blob_free(&request);
862                         return;
863                 }
864
865                 *response = talloc_strdup(mem_ctx, "OK");
866                 data_blob_free(&request);
867                 return;
868         }
869
870         if (strncmp(buf, "YR", 2) == 0) {
871                 TALLOC_FREE(state->ntlmssp_state);
872                 state->svr_state = SERVER_INITIAL;
873         } else if (strncmp(buf, "KK", 2) == 0) {
874                 /* No special preprocessing required */
875         } else if (strncmp(buf, "GF", 2) == 0) {
876                 DEBUG(10, ("Requested negotiated NTLMSSP flags\n"));
877
878                 if (state->svr_state == SERVER_FINISHED) {
879                         *response = talloc_asprintf(mem_ctx, "GF 0x%08x",
880                                                  state->neg_flags);
881                 }
882                 else {
883                         *response = talloc_strdup(mem_ctx, "BH\n");
884                 }
885                 data_blob_free(&request);
886                 return;
887         } else if (strncmp(buf, "GK", 2) == 0) {
888                 DEBUG(10, ("Requested NTLMSSP session key\n"));
889                 if(state->have_session_key) {
890                         char *key64 = base64_encode_data_blob(state->mem_ctx,
891                                         state->session_key);
892                         *response = talloc_asprintf(mem_ctx, "GK %s",
893                                                  key64 ? key64 : "<NULL>");
894                         TALLOC_FREE(key64);
895                 } else {
896                         *response = talloc_strdup(mem_ctx, "BH");
897                 }
898
899                 data_blob_free(&request);
900                 return;
901         } else {
902                 DEBUG(1, ("NTLMSSP query [%s] invalid\n", buf));
903                 *response = talloc_strdup(mem_ctx, "BH NTLMSSP query invalid");
904                 return;
905         }
906
907         if (!state->ntlmssp_state) {
908                 nt_status = ntlm_auth_start_ntlmssp_server(
909                                 &state->ntlmssp_state);
910                 if (!NT_STATUS_IS_OK(nt_status)) {
911                         *response = talloc_asprintf(
912                                 mem_ctx, "BH %s", nt_errstr(nt_status));
913                         return;
914                 }
915                 ntlmssp_want_feature_list(state->ntlmssp_state,
916                                 state->want_feature_list);
917         }
918
919         DEBUG(10, ("got NTLMSSP packet:\n"));
920         dump_data(10, request.data, request.length);
921
922         nt_status = ntlmssp_update(state->ntlmssp_state, request, &reply);
923
924         if (NT_STATUS_EQUAL(nt_status, NT_STATUS_MORE_PROCESSING_REQUIRED)) {
925                 char *reply_base64 = base64_encode_data_blob(state->mem_ctx,
926                                 reply);
927                 *response = talloc_asprintf(mem_ctx, "TT %s", reply_base64);
928                 TALLOC_FREE(reply_base64);
929                 data_blob_free(&reply);
930                 state->svr_state = SERVER_CHALLENGE;
931                 DEBUG(10, ("NTLMSSP challenge\n"));
932         } else if (NT_STATUS_EQUAL(nt_status, NT_STATUS_ACCESS_DENIED)) {
933                 *response = talloc_asprintf(mem_ctx, "BH %s",
934                                          nt_errstr(nt_status));
935                 DEBUG(0, ("NTLMSSP BH: %s\n", nt_errstr(nt_status)));
936
937                 TALLOC_FREE(state->ntlmssp_state);
938         } else if (!NT_STATUS_IS_OK(nt_status)) {
939                 *response = talloc_asprintf(mem_ctx, "NA %s",
940                                          nt_errstr(nt_status));
941                 DEBUG(10, ("NTLMSSP %s\n", nt_errstr(nt_status)));
942         } else {
943                 *response = talloc_asprintf(
944                         mem_ctx, "AF %s",
945                         (char *)state->ntlmssp_state->callback_private);
946                 DEBUG(10, ("NTLMSSP OK!\n"));
947
948                 if(state->have_session_key)
949                         data_blob_free(&state->session_key);
950                 state->session_key = data_blob(
951                                 state->ntlmssp_state->session_key.data,
952                                 state->ntlmssp_state->session_key.length);
953                 state->neg_flags = state->ntlmssp_state->neg_flags;
954                 state->have_session_key = true;
955                 state->svr_state = SERVER_FINISHED;
956         }
957
958         data_blob_free(&request);
959 }
960
961 static void manage_squid_ntlmssp_request(struct ntlm_auth_state *state,
962                                          char *buf, int length)
963 {
964         char *response;
965
966         manage_squid_ntlmssp_request_int(state, buf, length,
967                                          talloc_tos(), &response);
968
969         if (response == NULL) {
970                 x_fprintf(x_stdout, "BH Out of memory\n");
971                 return;
972         }
973         x_fprintf(x_stdout, "%s\n", response);
974         TALLOC_FREE(response);
975 }
976
977 static void manage_client_ntlmssp_request(struct ntlm_auth_state *state,
978                                                 char *buf, int length)
979 {
980         DATA_BLOB request, reply;
981         NTSTATUS nt_status;
982
983         if (!opt_username || !*opt_username) {
984                 x_fprintf(x_stderr, "username must be specified!\n\n");
985                 exit(1);
986         }
987
988         if (strlen(buf) < 2) {
989                 DEBUG(1, ("NTLMSSP query [%s] invalid\n", buf));
990                 x_fprintf(x_stdout, "BH NTLMSSP query invalid\n");
991                 return;
992         }
993
994         if (strlen(buf) > 3) {
995                 if(strncmp(buf, "SF ", 3) == 0) {
996                         DEBUG(10, ("Looking for flags to negotiate\n"));
997                         talloc_free(state->want_feature_list);
998                         state->want_feature_list = talloc_strdup(state->mem_ctx,
999                                         buf+3);
1000                         x_fprintf(x_stdout, "OK\n");
1001                         return;
1002                 }
1003                 request = base64_decode_data_blob(buf + 3);
1004         } else {
1005                 request = data_blob_null;
1006         }
1007
1008         if (strncmp(buf, "PW ", 3) == 0) {
1009                 /* We asked for a password and obviously got it :-) */
1010
1011                 opt_password = SMB_STRNDUP((const char *)request.data,
1012                                 request.length);
1013
1014                 if (opt_password == NULL) {
1015                         DEBUG(1, ("Out of memory\n"));
1016                         x_fprintf(x_stdout, "BH Out of memory\n");
1017                         data_blob_free(&request);
1018                         return;
1019                 }
1020
1021                 x_fprintf(x_stdout, "OK\n");
1022                 data_blob_free(&request);
1023                 return;
1024         }
1025
1026         if (!state->ntlmssp_state && use_cached_creds) {
1027                 /* check whether cached credentials are usable. */
1028                 DATA_BLOB empty_blob = data_blob_null;
1029
1030                 nt_status = do_ccache_ntlm_auth(empty_blob, empty_blob, NULL);
1031                 if (!NT_STATUS_EQUAL(nt_status, NT_STATUS_MORE_PROCESSING_REQUIRED)) {
1032                         /* failed to use cached creds */
1033                         use_cached_creds = False;
1034                 }
1035         }
1036
1037         if (opt_password == NULL && !use_cached_creds) {
1038                 /* Request a password from the calling process.  After
1039                    sending it, the calling process should retry asking for the
1040                    negotiate. */
1041
1042                 DEBUG(10, ("Requesting password\n"));
1043                 x_fprintf(x_stdout, "PW\n");
1044                 return;
1045         }
1046
1047         if (strncmp(buf, "YR", 2) == 0) {
1048                 TALLOC_FREE(state->ntlmssp_state);
1049                 state->cli_state = CLIENT_INITIAL;
1050         } else if (strncmp(buf, "TT", 2) == 0) {
1051                 /* No special preprocessing required */
1052         } else if (strncmp(buf, "GF", 2) == 0) {
1053                 DEBUG(10, ("Requested negotiated NTLMSSP flags\n"));
1054
1055                 if(state->cli_state == CLIENT_FINISHED) {
1056                         x_fprintf(x_stdout, "GF 0x%08x\n", state->neg_flags);
1057                 }
1058                 else {
1059                         x_fprintf(x_stdout, "BH\n");
1060                 }
1061
1062                 data_blob_free(&request);
1063                 return;
1064         } else if (strncmp(buf, "GK", 2) == 0 ) {
1065                 DEBUG(10, ("Requested session key\n"));
1066
1067                 if(state->cli_state == CLIENT_FINISHED) {
1068                         char *key64 = base64_encode_data_blob(state->mem_ctx,
1069                                         state->session_key);
1070                         x_fprintf(x_stdout, "GK %s\n", key64?key64:"<NULL>");
1071                         TALLOC_FREE(key64);
1072                 }
1073                 else {
1074                         x_fprintf(x_stdout, "BH\n");
1075                 }
1076
1077                 data_blob_free(&request);
1078                 return;
1079         } else {
1080                 DEBUG(1, ("NTLMSSP query [%s] invalid\n", buf));
1081                 x_fprintf(x_stdout, "BH NTLMSSP query invalid\n");
1082                 return;
1083         }
1084
1085         if (!state->ntlmssp_state) {
1086                 nt_status = ntlm_auth_start_ntlmssp_client(
1087                                 &state->ntlmssp_state);
1088                 if (!NT_STATUS_IS_OK(nt_status)) {
1089                         x_fprintf(x_stdout, "BH %s\n", nt_errstr(nt_status));
1090                         return;
1091                 }
1092                 ntlmssp_want_feature_list(state->ntlmssp_state,
1093                                 state->want_feature_list);
1094                 state->initial_message = data_blob_null;
1095         }
1096
1097         DEBUG(10, ("got NTLMSSP packet:\n"));
1098         dump_data(10, request.data, request.length);
1099
1100         if (use_cached_creds && !opt_password &&
1101                         (state->cli_state == CLIENT_RESPONSE)) {
1102                 nt_status = do_ccache_ntlm_auth(state->initial_message, request,
1103                                 &reply);
1104         } else {
1105                 nt_status = ntlmssp_update(state->ntlmssp_state, request,
1106                                 &reply);
1107         }
1108
1109         if (NT_STATUS_EQUAL(nt_status, NT_STATUS_MORE_PROCESSING_REQUIRED)) {
1110                 char *reply_base64 = base64_encode_data_blob(state->mem_ctx,
1111                                 reply);
1112                 if (state->cli_state == CLIENT_INITIAL) {
1113                         x_fprintf(x_stdout, "YR %s\n", reply_base64);
1114                         state->initial_message = reply;
1115                         state->cli_state = CLIENT_RESPONSE;
1116                 } else {
1117                         x_fprintf(x_stdout, "KK %s\n", reply_base64);
1118                         data_blob_free(&reply);
1119                 }
1120                 TALLOC_FREE(reply_base64);
1121                 DEBUG(10, ("NTLMSSP challenge\n"));
1122         } else if (NT_STATUS_IS_OK(nt_status)) {
1123                 char *reply_base64 = base64_encode_data_blob(talloc_tos(),
1124                                 reply);
1125                 x_fprintf(x_stdout, "AF %s\n", reply_base64);
1126                 TALLOC_FREE(reply_base64);
1127
1128                 if(state->have_session_key)
1129                         data_blob_free(&state->session_key);
1130
1131                 state->session_key = data_blob(
1132                                 state->ntlmssp_state->session_key.data,
1133                                 state->ntlmssp_state->session_key.length);
1134                 state->neg_flags = state->ntlmssp_state->neg_flags;
1135                 state->have_session_key = true;
1136
1137                 DEBUG(10, ("NTLMSSP OK!\n"));
1138                 state->cli_state = CLIENT_FINISHED;
1139                 TALLOC_FREE(state->ntlmssp_state);
1140         } else {
1141                 x_fprintf(x_stdout, "BH %s\n", nt_errstr(nt_status));
1142                 DEBUG(0, ("NTLMSSP BH: %s\n", nt_errstr(nt_status)));
1143                 state->cli_state = CLIENT_ERROR;
1144                 TALLOC_FREE(state->ntlmssp_state);
1145         }
1146
1147         data_blob_free(&request);
1148 }
1149
1150 static void manage_squid_basic_request(struct ntlm_auth_state *state,
1151                                         char *buf, int length)
1152 {
1153         char *user, *pass;      
1154         user=buf;
1155
1156         pass=(char *)memchr(buf,' ',length);
1157         if (!pass) {
1158                 DEBUG(2, ("Password not found. Denying access\n"));
1159                 x_fprintf(x_stdout, "ERR\n");
1160                 return;
1161         }
1162         *pass='\0';
1163         pass++;
1164
1165         if (state->helper_mode == SQUID_2_5_BASIC) {
1166                 rfc1738_unescape(user);
1167                 rfc1738_unescape(pass);
1168         }
1169
1170         if (check_plaintext_auth(user, pass, False)) {
1171                 x_fprintf(x_stdout, "OK\n");
1172         } else {
1173                 x_fprintf(x_stdout, "ERR\n");
1174         }
1175 }
1176
1177 static void offer_gss_spnego_mechs(void) {
1178
1179         DATA_BLOB token;
1180         struct spnego_data spnego;
1181         ssize_t len;
1182         char *reply_base64;
1183         TALLOC_CTX *ctx = talloc_tos();
1184         char *principal;
1185         char *myname_lower;
1186
1187         ZERO_STRUCT(spnego);
1188
1189         myname_lower = talloc_strdup(ctx, lp_netbios_name());
1190         if (!myname_lower) {
1191                 return;
1192         }
1193         strlower_m(myname_lower);
1194
1195         principal = talloc_asprintf(ctx, "%s$@%s", myname_lower, lp_realm());
1196         if (!principal) {
1197                 return;
1198         }
1199
1200         /* Server negTokenInit (mech offerings) */
1201         spnego.type = SPNEGO_NEG_TOKEN_INIT;
1202         spnego.negTokenInit.mechTypes = talloc_array(ctx, const char *, 4);
1203 #ifdef HAVE_KRB5
1204         spnego.negTokenInit.mechTypes[0] = talloc_strdup(ctx, OID_KERBEROS5_OLD);
1205         spnego.negTokenInit.mechTypes[1] = talloc_strdup(ctx, OID_KERBEROS5);
1206         spnego.negTokenInit.mechTypes[2] = talloc_strdup(ctx, OID_NTLMSSP);
1207         spnego.negTokenInit.mechTypes[3] = NULL;
1208 #else
1209         spnego.negTokenInit.mechTypes[0] = talloc_strdup(ctx, OID_NTLMSSP);
1210         spnego.negTokenInit.mechTypes[1] = NULL;
1211 #endif
1212
1213
1214         spnego.negTokenInit.mechListMIC = data_blob_talloc(ctx, principal,
1215                                                     strlen(principal));
1216
1217         len = spnego_write_data(ctx, &token, &spnego);
1218         spnego_free_data(&spnego);
1219
1220         if (len == -1) {
1221                 DEBUG(1, ("Could not write SPNEGO data blob\n"));
1222                 x_fprintf(x_stdout, "BH Could not write SPNEGO data blob\n");
1223                 return;
1224         }
1225
1226         reply_base64 = base64_encode_data_blob(talloc_tos(), token);
1227         x_fprintf(x_stdout, "TT %s *\n", reply_base64);
1228
1229         TALLOC_FREE(reply_base64);
1230         data_blob_free(&token);
1231         DEBUG(10, ("sent SPNEGO negTokenInit\n"));
1232         return;
1233 }
1234
1235 bool spnego_parse_krb5_wrap(TALLOC_CTX *ctx, DATA_BLOB blob, DATA_BLOB *ticket, uint8 tok_id[2])
1236 {
1237         bool ret;
1238         ASN1_DATA *data;
1239         int data_remaining;
1240
1241         data = asn1_init(talloc_tos());
1242         if (data == NULL) {
1243                 return false;
1244         }
1245
1246         asn1_load(data, blob);
1247         asn1_start_tag(data, ASN1_APPLICATION(0));
1248         asn1_check_OID(data, OID_KERBEROS5);
1249
1250         data_remaining = asn1_tag_remaining(data);
1251
1252         if (data_remaining < 3) {
1253                 data->has_error = True;
1254         } else {
1255                 asn1_read(data, tok_id, 2);
1256                 data_remaining -= 2;
1257                 *ticket = data_blob_talloc(ctx, NULL, data_remaining);
1258                 asn1_read(data, ticket->data, ticket->length);
1259         }
1260
1261         asn1_end_tag(data);
1262
1263         ret = !data->has_error;
1264
1265         if (data->has_error) {
1266                 data_blob_free(ticket);
1267         }
1268
1269         asn1_free(data);
1270
1271         return ret;
1272 }
1273
1274 static void manage_gss_spnego_request(struct ntlm_auth_state *state,
1275                                         char *buf, int length)
1276 {
1277         struct spnego_data request, response;
1278         DATA_BLOB token;
1279         DATA_BLOB raw_in_token = data_blob_null;
1280         DATA_BLOB raw_out_token = data_blob_null;
1281         NTSTATUS status;
1282         ssize_t len;
1283         TALLOC_CTX *ctx = talloc_tos();
1284
1285         char *user = NULL;
1286         char *domain = NULL;
1287
1288         const char *reply_code;
1289         char       *reply_base64;
1290         char *reply_argument = NULL;
1291         char *supportedMech = NULL;
1292
1293         if (strlen(buf) < 2) {
1294                 DEBUG(1, ("SPENGO query [%s] invalid\n", buf));
1295                 x_fprintf(x_stdout, "BH SPENGO query invalid\n");
1296                 return;
1297         }
1298
1299         if (strncmp(buf, "YR", 2) == 0) {
1300                 TALLOC_FREE(state->ntlmssp_state);
1301                 TALLOC_FREE(state->spnego_mech);
1302                 TALLOC_FREE(state->spnego_mech_oid);
1303         } else if (strncmp(buf, "KK", 2) == 0) {
1304                 ;
1305         } else {
1306                 DEBUG(1, ("SPENGO query [%s] invalid\n", buf));
1307                 x_fprintf(x_stdout, "BH SPENGO query invalid\n");
1308                 return;
1309         }
1310
1311         if ( (strlen(buf) == 2)) {
1312
1313                 /* no client data, get the negTokenInit offering
1314                    mechanisms */
1315
1316                 offer_gss_spnego_mechs();
1317                 return;
1318         }
1319
1320         /* All subsequent requests have a blob. This might be negTokenInit or negTokenTarg */
1321
1322         if (strlen(buf) <= 3) {
1323                 DEBUG(1, ("GSS-SPNEGO query [%s] invalid\n", buf));
1324                 x_fprintf(x_stdout, "BH GSS-SPNEGO query invalid\n");
1325                 return;
1326         }
1327
1328         token = base64_decode_data_blob(buf + 3);
1329
1330         if ((token.length >= 7)
1331             && (strncmp((char *)token.data, "NTLMSSP", 7) == 0)) {
1332                 char *reply;
1333
1334                 data_blob_free(&token);
1335
1336                 DEBUG(10, ("Could not parse GSS-SPNEGO, trying raw "
1337                            "ntlmssp\n"));
1338
1339                 manage_squid_ntlmssp_request_int(state, buf, length,
1340                                                  talloc_tos(), &reply);
1341                 if (reply == NULL) {
1342                         x_fprintf(x_stdout, "BH Out of memory\n");
1343                         return;
1344                 }
1345
1346                 if (strncmp(reply, "AF ", 3) == 0) {
1347                         x_fprintf(x_stdout, "AF * %s\n", reply+3);
1348                 } else {
1349                         x_fprintf(x_stdout, "%s *\n", reply);
1350                 }
1351
1352                 TALLOC_FREE(reply);
1353                 return;
1354         }
1355
1356         ZERO_STRUCT(request);
1357         len = spnego_read_data(ctx, token, &request);
1358         data_blob_free(&token);
1359
1360         if (len == -1) {
1361                 DEBUG(1, ("GSS-SPNEGO query [%s] invalid\n", buf));
1362                 x_fprintf(x_stdout, "BH GSS-SPNEGO query invalid\n");
1363                 return;
1364         }
1365
1366         if (request.type == SPNEGO_NEG_TOKEN_INIT) {
1367 #ifdef HAVE_KRB5
1368                 int krb5_idx = -1;
1369 #endif
1370                 int ntlm_idx = -1;
1371                 int used_idx = -1;
1372                 int i;
1373
1374                 if (state->spnego_mech) {
1375                         DEBUG(1, ("Client restarted SPNEGO with NegTokenInit "
1376                                   "while mech[%s] was already negotiated\n",
1377                                   state->spnego_mech));
1378                         x_fprintf(x_stdout, "BH Client send NegTokenInit twice\n");
1379                         return;
1380                 }
1381
1382                 /* Second request from Client. This is where the
1383                    client offers its mechanism to use. */
1384
1385                 if ( (request.negTokenInit.mechTypes == NULL) ||
1386                      (request.negTokenInit.mechTypes[0] == NULL) ) {
1387                         DEBUG(1, ("Client did not offer any mechanism\n"));
1388                         x_fprintf(x_stdout, "BH Client did not offer any "
1389                                             "mechanism\n");
1390                         return;
1391                 }
1392
1393                 status = NT_STATUS_UNSUCCESSFUL;
1394                 for (i = 0; request.negTokenInit.mechTypes[i] != NULL; i++) {
1395                         DEBUG(10,("got mech[%d][%s]\n",
1396                                 i, request.negTokenInit.mechTypes[i]));
1397 #ifdef HAVE_KRB5
1398                         if (strcmp(request.negTokenInit.mechTypes[i], OID_KERBEROS5_OLD) == 0) {
1399                                 krb5_idx = i;
1400                                 break;
1401                         }
1402                         if (strcmp(request.negTokenInit.mechTypes[i], OID_KERBEROS5) == 0) {
1403                                 krb5_idx = i;
1404                                 break;
1405                         }
1406 #endif
1407                         if (strcmp(request.negTokenInit.mechTypes[i], OID_NTLMSSP) == 0) {
1408                                 ntlm_idx = i;
1409                                 break;
1410                         }
1411                 }
1412
1413                 used_idx = ntlm_idx;
1414 #ifdef HAVE_KRB5
1415                 if (krb5_idx != -1) {
1416                         ntlm_idx = -1;
1417                         used_idx = krb5_idx;
1418                 }
1419 #endif
1420                 if (ntlm_idx > -1) {
1421                         state->spnego_mech = talloc_strdup(state, "ntlmssp");
1422                         if (state->spnego_mech == NULL) {
1423                                 x_fprintf(x_stdout, "BH Out of memory\n");
1424                                 return;
1425                         }
1426
1427                         if (state->ntlmssp_state) {
1428                                 DEBUG(1, ("Client wants a new NTLMSSP challenge, but "
1429                                           "already got one\n"));
1430                                 x_fprintf(x_stdout, "BH Client wants a new "
1431                                                     "NTLMSSP challenge, but "
1432                                                     "already got one\n");
1433                                 TALLOC_FREE(state->ntlmssp_state);
1434                                 return;
1435                         }
1436
1437                         status = ntlm_auth_start_ntlmssp_server(&state->ntlmssp_state);
1438                         if (!NT_STATUS_IS_OK(status)) {
1439                                 x_fprintf(x_stdout, "BH %s\n", nt_errstr(status));
1440                                 return;
1441                         }
1442                 }
1443
1444 #ifdef HAVE_KRB5
1445                 if (krb5_idx > -1) {
1446                         state->spnego_mech = talloc_strdup(state, "krb5");
1447                         if (state->spnego_mech == NULL) {
1448                                 x_fprintf(x_stdout, "BH Out of memory\n");
1449                                 return;
1450                         }
1451                 }
1452 #endif
1453                 if (used_idx > -1) {
1454                         state->spnego_mech_oid = talloc_strdup(state,
1455                                 request.negTokenInit.mechTypes[used_idx]);
1456                         if (state->spnego_mech_oid == NULL) {
1457                                 x_fprintf(x_stdout, "BH Out of memory\n");
1458                                 return;
1459                         }
1460                         supportedMech = talloc_strdup(ctx, state->spnego_mech_oid);
1461                         if (supportedMech == NULL) {
1462                                 x_fprintf(x_stdout, "BH Out of memory\n");
1463                                 return;
1464                         }
1465
1466                         status = NT_STATUS_MORE_PROCESSING_REQUIRED;
1467                 } else {
1468                         status = NT_STATUS_NOT_SUPPORTED;
1469                 }
1470                 if (used_idx == 0) {
1471                         status = NT_STATUS_OK;
1472                         raw_in_token = request.negTokenInit.mechToken;
1473                 }
1474         } else {
1475                 if (state->spnego_mech == NULL) {
1476                         DEBUG(1,("Got netTokenTarg without negTokenInit\n"));
1477                         x_fprintf(x_stdout, "BH Got a negTokenTarg without "
1478                                             "negTokenInit\n");
1479                         return;
1480                 }
1481
1482                 if ((request.negTokenTarg.supportedMech != NULL) &&
1483                      (strcmp(request.negTokenTarg.supportedMech, state->spnego_mech_oid) != 0 ) ) {
1484                         DEBUG(1, ("Got a negTokenTarg with mech[%s] while [%s] was already negotiated\n",
1485                                   request.negTokenTarg.supportedMech,
1486                                   state->spnego_mech_oid));
1487                         x_fprintf(x_stdout, "BH Got a negTokenTarg with speficied mech\n");
1488                         return;
1489                 }
1490
1491                 status = NT_STATUS_OK;
1492                 raw_in_token = request.negTokenTarg.responseToken;
1493         }
1494
1495         if (!NT_STATUS_IS_OK(status)) {
1496                 /* error or more processing */
1497         } else if (strcmp(state->spnego_mech, "ntlmssp") == 0) {
1498
1499                 DEBUG(10, ("got NTLMSSP packet:\n"));
1500                 dump_data(10, raw_in_token.data, raw_in_token.length);
1501
1502                 status = ntlmssp_update(state->ntlmssp_state,
1503                                         raw_in_token,
1504                                         &raw_out_token);
1505                 if (NT_STATUS_IS_OK(status)) {
1506                         user = talloc_strdup(ctx, state->ntlmssp_state->user);
1507                         domain = talloc_strdup(ctx, state->ntlmssp_state->domain);
1508                 }
1509                 if (!NT_STATUS_EQUAL(status, NT_STATUS_MORE_PROCESSING_REQUIRED)) {
1510                         TALLOC_FREE(state->ntlmssp_state);
1511                 }
1512 #ifdef HAVE_KRB5
1513         } else if (strcmp(state->spnego_mech, "krb5") == 0) {
1514                 char *principal;
1515                 DATA_BLOB ap_rep;
1516                 DATA_BLOB session_key;
1517                 struct PAC_LOGON_INFO *logon_info = NULL;
1518                 DATA_BLOB ticket;
1519                 uint8_t tok_id[2];
1520
1521                 if (!spnego_parse_krb5_wrap(ctx, raw_in_token,
1522                                             &ticket, tok_id)) {
1523                         DEBUG(1, ("spnego_parse_krb5_wrap failed\n"));
1524                         x_fprintf(x_stdout, "BH spnego_parse_krb5_wrap failed\n");
1525                         return;
1526                 }
1527
1528                 status = ads_verify_ticket(ctx, lp_realm(), 0,
1529                                            &ticket,
1530                                            &principal, &logon_info, &ap_rep,
1531                                            &session_key, True);
1532
1533                 /* Now in "principal" we have the name we are authenticated as. */
1534
1535                 if (NT_STATUS_IS_OK(status)) {
1536
1537                         domain = strchr_m(principal, '@');
1538
1539                         if (domain == NULL) {
1540                                 DEBUG(1, ("Did not get a valid principal "
1541                                           "from ads_verify_ticket\n"));
1542                                 x_fprintf(x_stdout, "BH Did not get a "
1543                                           "valid principal from "
1544                                           "ads_verify_ticket\n");
1545                                 return;
1546                         }
1547
1548                         *domain++ = '\0';
1549                         domain = talloc_strdup(ctx, domain);
1550                         user = talloc_strdup(ctx, principal);
1551
1552                         if (logon_info) {
1553                                 netsamlogon_cache_store(
1554                                         user, &logon_info->info3);
1555                         }
1556
1557                         data_blob_free(&ap_rep);
1558                         data_blob_free(&session_key);
1559                 }
1560                 data_blob_free(&ticket);
1561 #endif
1562         }
1563
1564         spnego_free_data(&request);
1565         ZERO_STRUCT(response);
1566         response.type = SPNEGO_NEG_TOKEN_TARG;
1567
1568         if (NT_STATUS_IS_OK(status)) {
1569                 TALLOC_FREE(state->spnego_mech);
1570                 TALLOC_FREE(state->spnego_mech_oid);
1571                 response.negTokenTarg.negResult = SPNEGO_ACCEPT_COMPLETED;
1572                 response.negTokenTarg.responseToken = raw_out_token;
1573                 reply_code = "AF";
1574                 reply_argument = talloc_asprintf(ctx, "%s\\%s", domain, user);
1575         } else if (NT_STATUS_EQUAL(status,
1576                                    NT_STATUS_MORE_PROCESSING_REQUIRED)) {
1577                 response.negTokenTarg.supportedMech = supportedMech;
1578                 response.negTokenTarg.responseToken = raw_out_token;
1579                 response.negTokenTarg.negResult = SPNEGO_ACCEPT_INCOMPLETE;
1580                 reply_code = "TT";
1581                 reply_argument = talloc_strdup(ctx, "*");
1582         } else {
1583                 TALLOC_FREE(state->spnego_mech);
1584                 TALLOC_FREE(state->spnego_mech_oid);
1585                 data_blob_free(&raw_out_token);
1586                 response.negTokenTarg.negResult = SPNEGO_REJECT;
1587                 reply_code = "NA";
1588                 reply_argument = talloc_strdup(ctx, nt_errstr(status));
1589         }
1590
1591         if (!reply_argument) {
1592                 DEBUG(1, ("Could not write SPNEGO data blob\n"));
1593                 x_fprintf(x_stdout, "BH Could not write SPNEGO data blob\n");
1594                 spnego_free_data(&response);
1595                 return;
1596         }
1597
1598         len = spnego_write_data(ctx, &token, &response);
1599         spnego_free_data(&response);
1600
1601         if (len == -1) {
1602                 DEBUG(1, ("Could not write SPNEGO data blob\n"));
1603                 x_fprintf(x_stdout, "BH Could not write SPNEGO data blob\n");
1604                 return;
1605         }
1606
1607         reply_base64 = base64_encode_data_blob(talloc_tos(), token);
1608
1609         x_fprintf(x_stdout, "%s %s %s\n",
1610                   reply_code, reply_base64, reply_argument);
1611
1612         TALLOC_FREE(reply_base64);
1613         data_blob_free(&token);
1614
1615         return;
1616 }
1617
1618 static struct ntlmssp_state *client_ntlmssp_state = NULL;
1619
1620 static bool manage_client_ntlmssp_init(struct spnego_data spnego)
1621 {
1622         NTSTATUS status;
1623         DATA_BLOB null_blob = data_blob_null;
1624         DATA_BLOB to_server;
1625         char *to_server_base64;
1626         const char *my_mechs[] = {OID_NTLMSSP, NULL};
1627         TALLOC_CTX *ctx = talloc_tos();
1628
1629         DEBUG(10, ("Got spnego negTokenInit with NTLMSSP\n"));
1630
1631         if (client_ntlmssp_state != NULL) {
1632                 DEBUG(1, ("Request for initial SPNEGO request where "
1633                           "we already have a state\n"));
1634                 return False;
1635         }
1636
1637         if (!client_ntlmssp_state) {
1638                 if (!NT_STATUS_IS_OK(status = ntlm_auth_start_ntlmssp_client(&client_ntlmssp_state))) {
1639                         x_fprintf(x_stdout, "BH %s\n", nt_errstr(status));
1640                         return False;
1641                 }
1642         }
1643
1644
1645         if (opt_password == NULL) {
1646
1647                 /* Request a password from the calling process.  After
1648                    sending it, the calling process should retry with
1649                    the negTokenInit. */
1650
1651                 DEBUG(10, ("Requesting password\n"));
1652                 x_fprintf(x_stdout, "PW\n");
1653                 return True;
1654         }
1655
1656         spnego.type = SPNEGO_NEG_TOKEN_INIT;
1657         spnego.negTokenInit.mechTypes = my_mechs;
1658         spnego.negTokenInit.reqFlags = data_blob_null;
1659         spnego.negTokenInit.reqFlagsPadding = 0;
1660         spnego.negTokenInit.mechListMIC = null_blob;
1661
1662         status = ntlmssp_update(client_ntlmssp_state, null_blob,
1663                                        &spnego.negTokenInit.mechToken);
1664
1665         if ( !(NT_STATUS_EQUAL(status, NT_STATUS_MORE_PROCESSING_REQUIRED) ||
1666                         NT_STATUS_IS_OK(status)) ) {
1667                 DEBUG(1, ("Expected OK or MORE_PROCESSING_REQUIRED, got: %s\n",
1668                           nt_errstr(status)));
1669                 TALLOC_FREE(client_ntlmssp_state);
1670                 return False;
1671         }
1672
1673         spnego_write_data(ctx, &to_server, &spnego);
1674         data_blob_free(&spnego.negTokenInit.mechToken);
1675
1676         to_server_base64 = base64_encode_data_blob(talloc_tos(), to_server);
1677         data_blob_free(&to_server);
1678         x_fprintf(x_stdout, "KK %s\n", to_server_base64);
1679         TALLOC_FREE(to_server_base64);
1680         return True;
1681 }
1682
1683 static void manage_client_ntlmssp_targ(struct spnego_data spnego)
1684 {
1685         NTSTATUS status;
1686         DATA_BLOB null_blob = data_blob_null;
1687         DATA_BLOB request;
1688         DATA_BLOB to_server;
1689         char *to_server_base64;
1690         TALLOC_CTX *ctx = talloc_tos();
1691
1692         DEBUG(10, ("Got spnego negTokenTarg with NTLMSSP\n"));
1693
1694         if (client_ntlmssp_state == NULL) {
1695                 DEBUG(1, ("Got NTLMSSP tArg without a client state\n"));
1696                 x_fprintf(x_stdout, "BH Got NTLMSSP tArg without a client state\n");
1697                 return;
1698         }
1699
1700         if (spnego.negTokenTarg.negResult == SPNEGO_REJECT) {
1701                 x_fprintf(x_stdout, "NA\n");
1702                 TALLOC_FREE(client_ntlmssp_state);
1703                 return;
1704         }
1705
1706         if (spnego.negTokenTarg.negResult == SPNEGO_ACCEPT_COMPLETED) {
1707                 x_fprintf(x_stdout, "AF\n");
1708                 TALLOC_FREE(client_ntlmssp_state);
1709                 return;
1710         }
1711
1712         status = ntlmssp_update(client_ntlmssp_state,
1713                                        spnego.negTokenTarg.responseToken,
1714                                        &request);
1715
1716         if (!NT_STATUS_EQUAL(status, NT_STATUS_MORE_PROCESSING_REQUIRED)) {
1717                 DEBUG(1, ("Expected MORE_PROCESSING_REQUIRED from "
1718                           "ntlmssp_client_update, got: %s\n",
1719                           nt_errstr(status)));
1720                 x_fprintf(x_stdout, "BH Expected MORE_PROCESSING_REQUIRED from "
1721                                     "ntlmssp_client_update\n");
1722                 data_blob_free(&request);
1723                 TALLOC_FREE(client_ntlmssp_state);
1724                 return;
1725         }
1726
1727         spnego.type = SPNEGO_NEG_TOKEN_TARG;
1728         spnego.negTokenTarg.negResult = SPNEGO_ACCEPT_INCOMPLETE;
1729         spnego.negTokenTarg.supportedMech = (const char *)OID_NTLMSSP;
1730         spnego.negTokenTarg.responseToken = request;
1731         spnego.negTokenTarg.mechListMIC = null_blob;
1732
1733         spnego_write_data(ctx, &to_server, &spnego);
1734         data_blob_free(&request);
1735
1736         to_server_base64 = base64_encode_data_blob(talloc_tos(), to_server);
1737         data_blob_free(&to_server);
1738         x_fprintf(x_stdout, "KK %s\n", to_server_base64);
1739         TALLOC_FREE(to_server_base64);
1740         return;
1741 }
1742
1743 #ifdef HAVE_KRB5
1744
1745 static bool manage_client_krb5_init(struct spnego_data spnego)
1746 {
1747         char *principal;
1748         DATA_BLOB tkt, to_server;
1749         DATA_BLOB session_key_krb5 = data_blob_null;
1750         struct spnego_data reply;
1751         char *reply_base64;
1752         int retval;
1753
1754         const char *my_mechs[] = {OID_KERBEROS5_OLD, NULL};
1755         ssize_t len;
1756         TALLOC_CTX *ctx = talloc_tos();
1757
1758         if ( (spnego.negTokenInit.mechListMIC.data == NULL) ||
1759              (spnego.negTokenInit.mechListMIC.length == 0) ) {
1760                 DEBUG(1, ("Did not get a principal for krb5\n"));
1761                 return False;
1762         }
1763
1764         principal = (char *)SMB_MALLOC(
1765                 spnego.negTokenInit.mechListMIC.length+1);
1766
1767         if (principal == NULL) {
1768                 DEBUG(1, ("Could not malloc principal\n"));
1769                 return False;
1770         }
1771
1772         memcpy(principal, spnego.negTokenInit.mechListMIC.data,
1773                spnego.negTokenInit.mechListMIC.length);
1774         principal[spnego.negTokenInit.mechListMIC.length] = '\0';
1775
1776         retval = cli_krb5_get_ticket(ctx, principal, 0,
1777                                           &tkt, &session_key_krb5,
1778                                           0, NULL, NULL, NULL);
1779         if (retval) {
1780                 char *user = NULL;
1781
1782                 /* Let's try to first get the TGT, for that we need a
1783                    password. */
1784
1785                 if (opt_password == NULL) {
1786                         DEBUG(10, ("Requesting password\n"));
1787                         x_fprintf(x_stdout, "PW\n");
1788                         return True;
1789                 }
1790
1791                 user = talloc_asprintf(talloc_tos(), "%s@%s", opt_username, opt_domain);
1792                 if (!user) {
1793                         return false;
1794                 }
1795
1796                 if ((retval = kerberos_kinit_password(user, opt_password, 0, NULL))) {
1797                         DEBUG(10, ("Requesting TGT failed: %s\n", error_message(retval)));
1798                         return False;
1799                 }
1800
1801                 retval = cli_krb5_get_ticket(ctx, principal, 0,
1802                                                   &tkt, &session_key_krb5,
1803                                                   0, NULL, NULL, NULL);
1804                 if (retval) {
1805                         DEBUG(10, ("Kinit suceeded, but getting a ticket failed: %s\n", error_message(retval)));
1806                         return False;
1807                 }
1808         }
1809
1810         data_blob_free(&session_key_krb5);
1811
1812         ZERO_STRUCT(reply);
1813
1814         reply.type = SPNEGO_NEG_TOKEN_INIT;
1815         reply.negTokenInit.mechTypes = my_mechs;
1816         reply.negTokenInit.reqFlags = data_blob_null;
1817         reply.negTokenInit.reqFlagsPadding = 0;
1818         reply.negTokenInit.mechToken = tkt;
1819         reply.negTokenInit.mechListMIC = data_blob_null;
1820
1821         len = spnego_write_data(ctx, &to_server, &reply);
1822         data_blob_free(&tkt);
1823
1824         if (len == -1) {
1825                 DEBUG(1, ("Could not write SPNEGO data blob\n"));
1826                 return False;
1827         }
1828
1829         reply_base64 = base64_encode_data_blob(talloc_tos(), to_server);
1830         x_fprintf(x_stdout, "KK %s *\n", reply_base64);
1831
1832         TALLOC_FREE(reply_base64);
1833         data_blob_free(&to_server);
1834         DEBUG(10, ("sent GSS-SPNEGO KERBEROS5 negTokenInit\n"));
1835         return True;
1836 }
1837
1838 static void manage_client_krb5_targ(struct spnego_data spnego)
1839 {
1840         switch (spnego.negTokenTarg.negResult) {
1841         case SPNEGO_ACCEPT_INCOMPLETE:
1842                 DEBUG(1, ("Got a Kerberos negTokenTarg with ACCEPT_INCOMPLETE\n"));
1843                 x_fprintf(x_stdout, "BH Got a Kerberos negTokenTarg with "
1844                                     "ACCEPT_INCOMPLETE\n");
1845                 break;
1846         case SPNEGO_ACCEPT_COMPLETED:
1847                 DEBUG(10, ("Accept completed\n"));
1848                 x_fprintf(x_stdout, "AF\n");
1849                 break;
1850         case SPNEGO_REJECT:
1851                 DEBUG(10, ("Rejected\n"));
1852                 x_fprintf(x_stdout, "NA\n");
1853                 break;
1854         default:
1855                 DEBUG(1, ("Got an invalid negTokenTarg\n"));
1856                 x_fprintf(x_stdout, "AF\n");
1857         }
1858 }
1859
1860 #endif
1861
1862 static void manage_gss_spnego_client_request(struct ntlm_auth_state *state,
1863                                                 char *buf, int length)
1864 {
1865         DATA_BLOB request;
1866         struct spnego_data spnego;
1867         ssize_t len;
1868         TALLOC_CTX *ctx = talloc_tos();
1869
1870         if (!opt_username || !*opt_username) {
1871                 x_fprintf(x_stderr, "username must be specified!\n\n");
1872                 exit(1);
1873         }
1874
1875         if (strlen(buf) <= 3) {
1876                 DEBUG(1, ("SPNEGO query [%s] too short\n", buf));
1877                 x_fprintf(x_stdout, "BH SPNEGO query too short\n");
1878                 return;
1879         }
1880
1881         request = base64_decode_data_blob(buf+3);
1882
1883         if (strncmp(buf, "PW ", 3) == 0) {
1884
1885                 /* We asked for a password and obviously got it :-) */
1886
1887                 opt_password = SMB_STRNDUP((const char *)request.data, request.length);
1888
1889                 if (opt_password == NULL) {
1890                         DEBUG(1, ("Out of memory\n"));
1891                         x_fprintf(x_stdout, "BH Out of memory\n");
1892                         data_blob_free(&request);
1893                         return;
1894                 }
1895
1896                 x_fprintf(x_stdout, "OK\n");
1897                 data_blob_free(&request);
1898                 return;
1899         }
1900
1901         if ( (strncmp(buf, "TT ", 3) != 0) &&
1902              (strncmp(buf, "AF ", 3) != 0) &&
1903              (strncmp(buf, "NA ", 3) != 0) ) {
1904                 DEBUG(1, ("SPNEGO request [%s] invalid\n", buf));
1905                 x_fprintf(x_stdout, "BH SPNEGO request invalid\n");
1906                 data_blob_free(&request);
1907                 return;
1908         }
1909
1910         /* So we got a server challenge to generate a SPNEGO
1911            client-to-server request... */
1912
1913         len = spnego_read_data(ctx, request, &spnego);
1914         data_blob_free(&request);
1915
1916         if (len == -1) {
1917                 DEBUG(1, ("Could not read SPNEGO data for [%s]\n", buf));
1918                 x_fprintf(x_stdout, "BH Could not read SPNEGO data\n");
1919                 return;
1920         }
1921
1922         if (spnego.type == SPNEGO_NEG_TOKEN_INIT) {
1923
1924                 /* The server offers a list of mechanisms */
1925
1926                 const char **mechType = (const char **)spnego.negTokenInit.mechTypes;
1927
1928                 while (*mechType != NULL) {
1929
1930 #ifdef HAVE_KRB5
1931                         if ( (strcmp(*mechType, OID_KERBEROS5_OLD) == 0) ||
1932                              (strcmp(*mechType, OID_KERBEROS5) == 0) ) {
1933                                 if (manage_client_krb5_init(spnego))
1934                                         goto out;
1935                         }
1936 #endif
1937
1938                         if (strcmp(*mechType, OID_NTLMSSP) == 0) {
1939                                 if (manage_client_ntlmssp_init(spnego))
1940                                         goto out;
1941                         }
1942
1943                         mechType++;
1944                 }
1945
1946                 DEBUG(1, ("Server offered no compatible mechanism\n"));
1947                 x_fprintf(x_stdout, "BH Server offered no compatible mechanism\n");
1948                 return;
1949         }
1950
1951         if (spnego.type == SPNEGO_NEG_TOKEN_TARG) {
1952
1953                 if (spnego.negTokenTarg.supportedMech == NULL) {
1954                         /* On accept/reject Windows does not send the
1955                            mechanism anymore. Handle that here and
1956                            shut down the mechanisms. */
1957
1958                         switch (spnego.negTokenTarg.negResult) {
1959                         case SPNEGO_ACCEPT_COMPLETED:
1960                                 x_fprintf(x_stdout, "AF\n");
1961                                 break;
1962                         case SPNEGO_REJECT:
1963                                 x_fprintf(x_stdout, "NA\n");
1964                                 break;
1965                         default:
1966                                 DEBUG(1, ("Got a negTokenTarg with no mech and an "
1967                                           "unknown negResult: %d\n",
1968                                           spnego.negTokenTarg.negResult));
1969                                 x_fprintf(x_stdout, "BH Got a negTokenTarg with"
1970                                                     " no mech and an unknown "
1971                                                     "negResult\n");
1972                         }
1973
1974                         TALLOC_FREE(client_ntlmssp_state);
1975                         goto out;
1976                 }
1977
1978                 if (strcmp(spnego.negTokenTarg.supportedMech,
1979                            OID_NTLMSSP) == 0) {
1980                         manage_client_ntlmssp_targ(spnego);
1981                         goto out;
1982                 }
1983
1984 #if HAVE_KRB5
1985                 if (strcmp(spnego.negTokenTarg.supportedMech,
1986                            OID_KERBEROS5_OLD) == 0) {
1987                         manage_client_krb5_targ(spnego);
1988                         goto out;
1989                 }
1990 #endif
1991
1992         }
1993
1994         DEBUG(1, ("Got an SPNEGO token I could not handle [%s]!\n", buf));
1995         x_fprintf(x_stdout, "BH Got an SPNEGO token I could not handle\n");
1996         return;
1997
1998  out:
1999         spnego_free_data(&spnego);
2000         return;
2001 }
2002
2003 static void manage_ntlm_server_1_request(struct ntlm_auth_state *state,
2004                                                 char *buf, int length)
2005 {
2006         char *request, *parameter;      
2007         static DATA_BLOB challenge;
2008         static DATA_BLOB lm_response;
2009         static DATA_BLOB nt_response;
2010         static char *full_username;
2011         static char *username;
2012         static char *domain;
2013         static char *plaintext_password;
2014         static bool ntlm_server_1_user_session_key;
2015         static bool ntlm_server_1_lm_session_key;
2016
2017         if (strequal(buf, ".")) {
2018                 if (!full_username && !username) {      
2019                         x_fprintf(x_stdout, "Error: No username supplied!\n");
2020                 } else if (plaintext_password) {
2021                         /* handle this request as plaintext */
2022                         if (!full_username) {
2023                                 if (asprintf(&full_username, "%s%c%s", domain, winbind_separator(), username) == -1) {
2024                                         x_fprintf(x_stdout, "Error: Out of memory in asprintf!\n.\n");
2025                                         return;
2026                                 }
2027                         }
2028                         if (check_plaintext_auth(full_username, plaintext_password, False)) {
2029                                 x_fprintf(x_stdout, "Authenticated: Yes\n");
2030                         } else {
2031                                 x_fprintf(x_stdout, "Authenticated: No\n");
2032                         }
2033                 } else if (!lm_response.data && !nt_response.data) {
2034                         x_fprintf(x_stdout, "Error: No password supplied!\n");
2035                 } else if (!challenge.data) {   
2036                         x_fprintf(x_stdout, "Error: No lanman-challenge supplied!\n");
2037                 } else {
2038                         char *error_string = NULL;
2039                         uchar lm_key[8];
2040                         uchar user_session_key[16];
2041                         uint32 flags = 0;
2042
2043                         if (full_username && !username) {
2044                                 fstring fstr_user;
2045                                 fstring fstr_domain;
2046
2047                                 if (!parse_ntlm_auth_domain_user(full_username, fstr_user, fstr_domain)) {
2048                                         /* username might be 'tainted', don't print into our new-line deleimianted stream */
2049                                         x_fprintf(x_stdout, "Error: Could not parse into domain and username\n");
2050                                 }
2051                                 SAFE_FREE(username);
2052                                 SAFE_FREE(domain);
2053                                 username = smb_xstrdup(fstr_user);
2054                                 domain = smb_xstrdup(fstr_domain);
2055                         }
2056
2057                         if (!domain) {
2058                                 domain = smb_xstrdup(get_winbind_domain());
2059                         }
2060
2061                         if (ntlm_server_1_lm_session_key) 
2062                                 flags |= WBFLAG_PAM_LMKEY;
2063
2064                         if (ntlm_server_1_user_session_key) 
2065                                 flags |= WBFLAG_PAM_USER_SESSION_KEY;
2066
2067                         if (!NT_STATUS_IS_OK(
2068                                     contact_winbind_auth_crap(username, 
2069                                                               domain, 
2070                                                               lp_netbios_name(),
2071                                                               &challenge, 
2072                                                               &lm_response, 
2073                                                               &nt_response, 
2074                                                               flags, 
2075                                                               lm_key, 
2076                                                               user_session_key,
2077                                                               &error_string,
2078                                                               NULL))) {
2079
2080                                 x_fprintf(x_stdout, "Authenticated: No\n");
2081                                 x_fprintf(x_stdout, "Authentication-Error: %s\n.\n", error_string);
2082                         } else {
2083                                 static char zeros[16];
2084                                 char *hex_lm_key;
2085                                 char *hex_user_session_key;
2086
2087                                 x_fprintf(x_stdout, "Authenticated: Yes\n");
2088
2089                                 if (ntlm_server_1_lm_session_key 
2090                                     && (memcmp(zeros, lm_key, 
2091                                                sizeof(lm_key)) != 0)) {
2092                                         hex_lm_key = hex_encode_talloc(NULL,
2093                                                                 (const unsigned char *)lm_key,
2094                                                                 sizeof(lm_key));
2095                                         x_fprintf(x_stdout, "LANMAN-Session-Key: %s\n", hex_lm_key);
2096                                         TALLOC_FREE(hex_lm_key);
2097                                 }
2098
2099                                 if (ntlm_server_1_user_session_key 
2100                                     && (memcmp(zeros, user_session_key, 
2101                                                sizeof(user_session_key)) != 0)) {
2102                                         hex_user_session_key = hex_encode_talloc(NULL,
2103                                                                           (const unsigned char *)user_session_key, 
2104                                                                           sizeof(user_session_key));
2105                                         x_fprintf(x_stdout, "User-Session-Key: %s\n", hex_user_session_key);
2106                                         TALLOC_FREE(hex_user_session_key);
2107                                 }
2108                         }
2109                         SAFE_FREE(error_string);
2110                 }
2111                 /* clear out the state */
2112                 challenge = data_blob_null;
2113                 nt_response = data_blob_null;
2114                 lm_response = data_blob_null;
2115                 SAFE_FREE(full_username);
2116                 SAFE_FREE(username);
2117                 SAFE_FREE(domain);
2118                 SAFE_FREE(plaintext_password);
2119                 ntlm_server_1_user_session_key = False;
2120                 ntlm_server_1_lm_session_key = False;
2121                 x_fprintf(x_stdout, ".\n");
2122
2123                 return;
2124         }
2125
2126         request = buf;
2127
2128         /* Indicates a base64 encoded structure */
2129         parameter = strstr_m(request, ":: ");
2130         if (!parameter) {
2131                 parameter = strstr_m(request, ": ");
2132
2133                 if (!parameter) {
2134                         DEBUG(0, ("Parameter not found!\n"));
2135                         x_fprintf(x_stdout, "Error: Parameter not found!\n.\n");
2136                         return;
2137                 }
2138
2139                 parameter[0] ='\0';
2140                 parameter++;
2141                 parameter[0] ='\0';
2142                 parameter++;
2143
2144         } else {
2145                 parameter[0] ='\0';
2146                 parameter++;
2147                 parameter[0] ='\0';
2148                 parameter++;
2149                 parameter[0] ='\0';
2150                 parameter++;
2151
2152                 base64_decode_inplace(parameter);
2153         }
2154
2155         if (strequal(request, "LANMAN-Challenge")) {
2156                 challenge = strhex_to_data_blob(NULL, parameter);
2157                 if (challenge.length != 8) {
2158                         x_fprintf(x_stdout, "Error: hex decode of %s failed! (got %d bytes, expected 8)\n.\n", 
2159                                   parameter,
2160                                   (int)challenge.length);
2161                         challenge = data_blob_null;
2162                 }
2163         } else if (strequal(request, "NT-Response")) {
2164                 nt_response = strhex_to_data_blob(NULL, parameter);
2165                 if (nt_response.length < 24) {
2166                         x_fprintf(x_stdout, "Error: hex decode of %s failed! (only got %d bytes, needed at least 24)\n.\n", 
2167                                   parameter,
2168                                   (int)nt_response.length);
2169                         nt_response = data_blob_null;
2170                 }
2171         } else if (strequal(request, "LANMAN-Response")) {
2172                 lm_response = strhex_to_data_blob(NULL, parameter);
2173                 if (lm_response.length != 24) {
2174                         x_fprintf(x_stdout, "Error: hex decode of %s failed! (got %d bytes, expected 24)\n.\n", 
2175                                   parameter,
2176                                   (int)lm_response.length);
2177                         lm_response = data_blob_null;
2178                 }
2179         } else if (strequal(request, "Password")) {
2180                 plaintext_password = smb_xstrdup(parameter);
2181         } else if (strequal(request, "NT-Domain")) {
2182                 domain = smb_xstrdup(parameter);
2183         } else if (strequal(request, "Username")) {
2184                 username = smb_xstrdup(parameter);
2185         } else if (strequal(request, "Full-Username")) {
2186                 full_username = smb_xstrdup(parameter);
2187         } else if (strequal(request, "Request-User-Session-Key")) {
2188                 ntlm_server_1_user_session_key = strequal(parameter, "Yes");
2189         } else if (strequal(request, "Request-LanMan-Session-Key")) {
2190                 ntlm_server_1_lm_session_key = strequal(parameter, "Yes");
2191         } else {
2192                 x_fprintf(x_stdout, "Error: Unknown request %s\n.\n", request);
2193         }
2194 }
2195
2196 static void manage_ntlm_change_password_1_request(struct ntlm_auth_state *state,
2197                                                         char *buf, int length)
2198 {
2199         char *request, *parameter;      
2200         static DATA_BLOB new_nt_pswd;
2201         static DATA_BLOB old_nt_hash_enc;
2202         static DATA_BLOB new_lm_pswd;
2203         static DATA_BLOB old_lm_hash_enc;
2204         static char *full_username = NULL;
2205         static char *username = NULL;
2206         static char *domain = NULL;
2207         static char *newpswd =  NULL;
2208         static char *oldpswd = NULL;
2209
2210         if (strequal(buf, ".")) {
2211                 if(newpswd && oldpswd) {
2212                         uchar old_nt_hash[16];
2213                         uchar old_lm_hash[16];
2214                         uchar new_nt_hash[16];
2215                         uchar new_lm_hash[16];
2216
2217                         new_nt_pswd = data_blob(NULL, 516);
2218                         old_nt_hash_enc = data_blob(NULL, 16);
2219
2220                         /* Calculate the MD4 hash (NT compatible) of the
2221                          * password */
2222                         E_md4hash(oldpswd, old_nt_hash);
2223                         E_md4hash(newpswd, new_nt_hash);
2224
2225                         /* E_deshash returns false for 'long'
2226                            passwords (> 14 DOS chars).  
2227
2228                            Therefore, don't send a buffer
2229                            encrypted with the truncated hash
2230                            (it could allow an even easier
2231                            attack on the password)
2232
2233                            Likewise, obey the admin's restriction
2234                         */
2235
2236                         if (lp_client_lanman_auth() &&
2237                             E_deshash(newpswd, new_lm_hash) &&
2238                             E_deshash(oldpswd, old_lm_hash)) {
2239                                 new_lm_pswd = data_blob(NULL, 516);
2240                                 old_lm_hash_enc = data_blob(NULL, 16);
2241                                 encode_pw_buffer(new_lm_pswd.data, newpswd,
2242                                                  STR_UNICODE);
2243
2244                                 arcfour_crypt(new_lm_pswd.data, old_nt_hash, 516);
2245                                 E_old_pw_hash(new_nt_hash, old_lm_hash,
2246                                               old_lm_hash_enc.data);
2247                         } else {
2248                                 new_lm_pswd.data = NULL;
2249                                 new_lm_pswd.length = 0;
2250                                 old_lm_hash_enc.data = NULL;
2251                                 old_lm_hash_enc.length = 0;
2252                         }
2253
2254                         encode_pw_buffer(new_nt_pswd.data, newpswd,
2255                                          STR_UNICODE);
2256
2257                         arcfour_crypt(new_nt_pswd.data, old_nt_hash, 516);
2258                         E_old_pw_hash(new_nt_hash, old_nt_hash,
2259                                       old_nt_hash_enc.data);
2260                 }
2261
2262                 if (!full_username && !username) {      
2263                         x_fprintf(x_stdout, "Error: No username supplied!\n");
2264                 } else if ((!new_nt_pswd.data || !old_nt_hash_enc.data) &&
2265                            (!new_lm_pswd.data || old_lm_hash_enc.data) ) {
2266                         x_fprintf(x_stdout, "Error: No NT or LM password "
2267                                   "blobs supplied!\n");
2268                 } else {
2269                         char *error_string = NULL;
2270
2271                         if (full_username && !username) {
2272                                 fstring fstr_user;
2273                                 fstring fstr_domain;
2274
2275                                 if (!parse_ntlm_auth_domain_user(full_username,
2276                                                                  fstr_user,
2277                                                                  fstr_domain)) {
2278                                         /* username might be 'tainted', don't
2279                                          * print into our new-line
2280                                          * deleimianted stream */
2281                                         x_fprintf(x_stdout, "Error: Could not "
2282                                                   "parse into domain and "
2283                                                   "username\n");
2284                                         SAFE_FREE(username);
2285                                         username = smb_xstrdup(full_username);
2286                                 } else {
2287                                         SAFE_FREE(username);
2288                                         SAFE_FREE(domain);
2289                                         username = smb_xstrdup(fstr_user);
2290                                         domain = smb_xstrdup(fstr_domain);
2291                                 }
2292
2293                         }
2294
2295                         if(!NT_STATUS_IS_OK(contact_winbind_change_pswd_auth_crap(
2296                                                     username, domain,
2297                                                     new_nt_pswd,
2298                                                     old_nt_hash_enc,
2299                                                     new_lm_pswd,
2300                                                     old_lm_hash_enc,
2301                                                     &error_string))) {
2302                                 x_fprintf(x_stdout, "Password-Change: No\n");
2303                                 x_fprintf(x_stdout, "Password-Change-Error: "
2304                                           "%s\n.\n", error_string);
2305                         } else {
2306                                 x_fprintf(x_stdout, "Password-Change: Yes\n");
2307                         }
2308
2309                         SAFE_FREE(error_string);
2310                 }
2311                 /* clear out the state */
2312                 new_nt_pswd = data_blob_null;
2313                 old_nt_hash_enc = data_blob_null;
2314                 new_lm_pswd = data_blob_null;
2315                 old_nt_hash_enc = data_blob_null;
2316                 SAFE_FREE(full_username);
2317                 SAFE_FREE(username);
2318                 SAFE_FREE(domain);
2319                 SAFE_FREE(newpswd);
2320                 SAFE_FREE(oldpswd);
2321                 x_fprintf(x_stdout, ".\n");
2322
2323                 return;
2324         }
2325
2326         request = buf;
2327
2328         /* Indicates a base64 encoded structure */
2329         parameter = strstr_m(request, ":: ");
2330         if (!parameter) {
2331                 parameter = strstr_m(request, ": ");
2332
2333                 if (!parameter) {
2334                         DEBUG(0, ("Parameter not found!\n"));
2335                         x_fprintf(x_stdout, "Error: Parameter not found!\n.\n");
2336                         return;
2337                 }
2338
2339                 parameter[0] ='\0';
2340                 parameter++;
2341                 parameter[0] ='\0';
2342                 parameter++;
2343         } else {
2344                 parameter[0] ='\0';
2345                 parameter++;
2346                 parameter[0] ='\0';
2347                 parameter++;
2348                 parameter[0] ='\0';
2349                 parameter++;
2350
2351                 base64_decode_inplace(parameter);
2352         }
2353
2354         if (strequal(request, "new-nt-password-blob")) {
2355                 new_nt_pswd = strhex_to_data_blob(NULL, parameter);
2356                 if (new_nt_pswd.length != 516) {
2357                         x_fprintf(x_stdout, "Error: hex decode of %s failed! "
2358                                   "(got %d bytes, expected 516)\n.\n", 
2359                                   parameter,
2360                                   (int)new_nt_pswd.length);
2361                         new_nt_pswd = data_blob_null;
2362                 }
2363         } else if (strequal(request, "old-nt-hash-blob")) {
2364                 old_nt_hash_enc = strhex_to_data_blob(NULL, parameter);
2365                 if (old_nt_hash_enc.length != 16) {
2366                         x_fprintf(x_stdout, "Error: hex decode of %s failed! "
2367                                   "(got %d bytes, expected 16)\n.\n", 
2368                                   parameter,
2369                                   (int)old_nt_hash_enc.length);
2370                         old_nt_hash_enc = data_blob_null;
2371                 }
2372         } else if (strequal(request, "new-lm-password-blob")) {
2373                 new_lm_pswd = strhex_to_data_blob(NULL, parameter);
2374                 if (new_lm_pswd.length != 516) {
2375                         x_fprintf(x_stdout, "Error: hex decode of %s failed! "
2376                                   "(got %d bytes, expected 516)\n.\n", 
2377                                   parameter,
2378                                   (int)new_lm_pswd.length);
2379                         new_lm_pswd = data_blob_null;
2380                 }
2381         }
2382         else if (strequal(request, "old-lm-hash-blob")) {
2383                 old_lm_hash_enc = strhex_to_data_blob(NULL, parameter);
2384                 if (old_lm_hash_enc.length != 16)
2385                 {
2386                         x_fprintf(x_stdout, "Error: hex decode of %s failed! "
2387                                   "(got %d bytes, expected 16)\n.\n", 
2388                                   parameter,
2389                                   (int)old_lm_hash_enc.length);
2390                         old_lm_hash_enc = data_blob_null;
2391                 }
2392         } else if (strequal(request, "nt-domain")) {
2393                 domain = smb_xstrdup(parameter);
2394         } else if(strequal(request, "username")) {
2395                 username = smb_xstrdup(parameter);
2396         } else if(strequal(request, "full-username")) {
2397                 username = smb_xstrdup(parameter);
2398         } else if(strequal(request, "new-password")) {
2399                 newpswd = smb_xstrdup(parameter);
2400         } else if (strequal(request, "old-password")) {
2401                 oldpswd = smb_xstrdup(parameter);
2402         } else {
2403                 x_fprintf(x_stdout, "Error: Unknown request %s\n.\n", request);
2404         }
2405 }
2406
2407 static void manage_squid_request(struct ntlm_auth_state *state,
2408                 stdio_helper_function fn)
2409 {
2410         char *buf;
2411         char tmp[INITIAL_BUFFER_SIZE+1];
2412         int length, buf_size = 0;
2413         char *c;
2414
2415         buf = talloc_strdup(state->mem_ctx, "");
2416         if (!buf) {
2417                 DEBUG(0, ("Failed to allocate input buffer.\n"));
2418                 x_fprintf(x_stderr, "ERR\n");
2419                 exit(1);
2420         }
2421
2422         do {
2423
2424                 /* this is not a typo - x_fgets doesn't work too well under
2425                  * squid */
2426                 if (fgets(tmp, sizeof(tmp)-1, stdin) == NULL) {
2427                         if (ferror(stdin)) {
2428                                 DEBUG(1, ("fgets() failed! dying..... errno=%d "
2429                                           "(%s)\n", ferror(stdin),
2430                                           strerror(ferror(stdin))));
2431
2432                                 exit(1);
2433                         }
2434                         exit(0);
2435                 }
2436
2437                 buf = talloc_strdup_append_buffer(buf, tmp);
2438                 buf_size += INITIAL_BUFFER_SIZE;
2439
2440                 if (buf_size > MAX_BUFFER_SIZE) {
2441                         DEBUG(2, ("Oversized message\n"));
2442                         x_fprintf(x_stderr, "ERR\n");
2443                         talloc_free(buf);
2444                         return;
2445                 }
2446
2447                 c = strchr(buf, '\n');
2448         } while (c == NULL);
2449
2450         *c = '\0';
2451         length = c-buf;
2452
2453         DEBUG(10, ("Got '%s' from squid (length: %d).\n",buf,length));
2454
2455         if (buf[0] == '\0') {
2456                 DEBUG(2, ("Invalid Request\n"));
2457                 x_fprintf(x_stderr, "ERR\n");
2458                 talloc_free(buf);
2459                 return;
2460         }
2461
2462         fn(state, buf, length);
2463         talloc_free(buf);
2464 }
2465
2466
2467 static void squid_stream(enum stdio_helper_mode stdio_mode, stdio_helper_function fn) {
2468         TALLOC_CTX *mem_ctx;
2469         struct ntlm_auth_state *state;
2470
2471         /* initialize FDescs */
2472         x_setbuf(x_stdout, NULL);
2473         x_setbuf(x_stderr, NULL);
2474
2475         mem_ctx = talloc_init("ntlm_auth");
2476         if (!mem_ctx) {
2477                 DEBUG(0, ("squid_stream: Failed to create talloc context\n"));
2478                 x_fprintf(x_stderr, "ERR\n");
2479                 exit(1);
2480         }
2481
2482         state = talloc_zero(mem_ctx, struct ntlm_auth_state);
2483         if (!state) {
2484                 DEBUG(0, ("squid_stream: Failed to talloc ntlm_auth_state\n"));
2485                 x_fprintf(x_stderr, "ERR\n");
2486                 exit(1);
2487         }
2488
2489         state->mem_ctx = mem_ctx;
2490         state->helper_mode = stdio_mode;
2491
2492         while(1) {
2493                 TALLOC_CTX *frame = talloc_stackframe();
2494                 manage_squid_request(state, fn);
2495                 TALLOC_FREE(frame);
2496         }
2497 }
2498
2499
2500 /* Authenticate a user with a challenge/response */
2501
2502 static bool check_auth_crap(void)
2503 {
2504         NTSTATUS nt_status;
2505         uint32 flags = 0;
2506         char lm_key[8];
2507         char user_session_key[16];
2508         char *hex_lm_key;
2509         char *hex_user_session_key;
2510         char *error_string;
2511         static uint8 zeros[16];
2512
2513         x_setbuf(x_stdout, NULL);
2514
2515         if (request_lm_key) 
2516                 flags |= WBFLAG_PAM_LMKEY;
2517
2518         if (request_user_session_key) 
2519                 flags |= WBFLAG_PAM_USER_SESSION_KEY;
2520
2521         flags |= WBFLAG_PAM_NT_STATUS_SQUASH;
2522
2523         nt_status = contact_winbind_auth_crap(opt_username, opt_domain, 
2524                                               opt_workstation,
2525                                               &opt_challenge, 
2526                                               &opt_lm_response, 
2527                                               &opt_nt_response, 
2528                                               flags,
2529                                               (unsigned char *)lm_key, 
2530                                               (unsigned char *)user_session_key, 
2531                                               &error_string, NULL);
2532
2533         if (!NT_STATUS_IS_OK(nt_status)) {
2534                 x_fprintf(x_stdout, "%s (0x%x)\n", 
2535                           error_string,
2536                           NT_STATUS_V(nt_status));
2537                 SAFE_FREE(error_string);
2538                 return False;
2539         }
2540
2541         if (request_lm_key 
2542             && (memcmp(zeros, lm_key, 
2543                        sizeof(lm_key)) != 0)) {
2544                 hex_lm_key = hex_encode_talloc(talloc_tos(), (const unsigned char *)lm_key,
2545                                         sizeof(lm_key));
2546                 x_fprintf(x_stdout, "LM_KEY: %s\n", hex_lm_key);
2547                 TALLOC_FREE(hex_lm_key);
2548         }
2549         if (request_user_session_key 
2550             && (memcmp(zeros, user_session_key, 
2551                        sizeof(user_session_key)) != 0)) {
2552                 hex_user_session_key = hex_encode_talloc(talloc_tos(), (const unsigned char *)user_session_key, 
2553                                                   sizeof(user_session_key));
2554                 x_fprintf(x_stdout, "NT_KEY: %s\n", hex_user_session_key);
2555                 TALLOC_FREE(hex_user_session_key);
2556         }
2557
2558         return True;
2559 }
2560
2561 /* Main program */
2562
2563 enum {
2564         OPT_USERNAME = 1000,
2565         OPT_DOMAIN,
2566         OPT_WORKSTATION,
2567         OPT_CHALLENGE,
2568         OPT_RESPONSE,
2569         OPT_LM,
2570         OPT_NT,
2571         OPT_PASSWORD,
2572         OPT_LM_KEY,
2573         OPT_USER_SESSION_KEY,
2574         OPT_DIAGNOSTICS,
2575         OPT_REQUIRE_MEMBERSHIP,
2576         OPT_USE_CACHED_CREDS,
2577         OPT_PAM_WINBIND_CONF
2578 };
2579
2580  int main(int argc, const char **argv)
2581 {
2582         TALLOC_CTX *frame = talloc_stackframe();
2583         int opt;
2584         static const char *helper_protocol;
2585         static int diagnostics;
2586
2587         static const char *hex_challenge;
2588         static const char *hex_lm_response;
2589         static const char *hex_nt_response;
2590
2591         poptContext pc;
2592
2593         /* NOTE: DO NOT change this interface without considering the implications!
2594            This is an external interface, which other programs will use to interact 
2595            with this helper.
2596         */
2597
2598         /* We do not use single-letter command abbreviations, because they harm future 
2599            interface stability. */
2600
2601         struct poptOption long_options[] = {
2602                 POPT_AUTOHELP
2603                 { "helper-protocol", 0, POPT_ARG_STRING, &helper_protocol, OPT_DOMAIN, "operate as a stdio-based helper", "helper protocol to use"},
2604                 { "username", 0, POPT_ARG_STRING, &opt_username, OPT_USERNAME, "username"},
2605                 { "domain", 0, POPT_ARG_STRING, &opt_domain, OPT_DOMAIN, "domain name"},
2606                 { "workstation", 0, POPT_ARG_STRING, &opt_workstation, OPT_WORKSTATION, "workstation"},
2607                 { "challenge", 0, POPT_ARG_STRING, &hex_challenge, OPT_CHALLENGE, "challenge (HEX encoded)"},
2608                 { "lm-response", 0, POPT_ARG_STRING, &hex_lm_response, OPT_LM, "LM Response to the challenge (HEX encoded)"},
2609                 { "nt-response", 0, POPT_ARG_STRING, &hex_nt_response, OPT_NT, "NT or NTLMv2 Response to the challenge (HEX encoded)"},
2610                 { "password", 0, POPT_ARG_STRING, &opt_password, OPT_PASSWORD, "User's plaintext password"},            
2611                 { "request-lm-key", 0, POPT_ARG_NONE, &request_lm_key, OPT_LM_KEY, "Retrieve LM session key"},
2612                 { "request-nt-key", 0, POPT_ARG_NONE, &request_user_session_key, OPT_USER_SESSION_KEY, "Retrieve User (NT) session key"},
2613                 { "use-cached-creds", 0, POPT_ARG_NONE, &use_cached_creds, OPT_USE_CACHED_CREDS, "Use cached credentials if no password is given"},
2614                 { "diagnostics", 0, POPT_ARG_NONE, &diagnostics,
2615                   OPT_DIAGNOSTICS,
2616                   "Perform diagnostics on the authentication chain"},
2617                 { "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" },
2618                 { "pam-winbind-conf", 0, POPT_ARG_STRING, &opt_pam_winbind_conf, OPT_PAM_WINBIND_CONF, "Require that request must set WBFLAG_PAM_CONTACT_TRUSTDOM when krb5 auth is required" },
2619                 POPT_COMMON_CONFIGFILE
2620                 POPT_COMMON_VERSION
2621                 POPT_TABLEEND
2622         };
2623
2624         /* Samba client initialisation */
2625         load_case_tables();
2626
2627         setup_logging("ntlm_auth", DEBUG_STDERR);
2628
2629         /* Parse options */
2630
2631         pc = poptGetContext("ntlm_auth", argc, argv, long_options, 0);
2632
2633         /* Parse command line options */
2634
2635         if (argc == 1) {
2636                 poptPrintHelp(pc, stderr, 0);
2637                 return 1;
2638         }
2639
2640         while((opt = poptGetNextOpt(pc)) != -1) {
2641                 /* Get generic config options like --configfile */
2642         }
2643
2644         poptFreeContext(pc);
2645
2646         if (!lp_load_global(get_dyn_CONFIGFILE())) {
2647                 d_fprintf(stderr, "ntlm_auth: error opening config file %s. Error was %s\n",
2648                         get_dyn_CONFIGFILE(), strerror(errno));
2649                 exit(1);
2650         }
2651
2652         pc = poptGetContext(NULL, argc, (const char **)argv, long_options, 
2653                             POPT_CONTEXT_KEEP_FIRST);
2654
2655         while((opt = poptGetNextOpt(pc)) != -1) {
2656                 switch (opt) {
2657                 case OPT_CHALLENGE:
2658                         opt_challenge = strhex_to_data_blob(NULL, hex_challenge);
2659                         if (opt_challenge.length != 8) {
2660                                 x_fprintf(x_stderr, "hex decode of %s failed! (only got %d bytes)\n", 
2661                                           hex_challenge,
2662                                           (int)opt_challenge.length);
2663                                 exit(1);
2664                         }
2665                         break;
2666                 case OPT_LM: 
2667                         opt_lm_response = strhex_to_data_blob(NULL, hex_lm_response);
2668                         if (opt_lm_response.length != 24) {
2669                                 x_fprintf(x_stderr, "hex decode of %s failed! (only got %d bytes)\n", 
2670                                           hex_lm_response,
2671                                           (int)opt_lm_response.length);
2672                                 exit(1);
2673                         }
2674                         break;
2675
2676                 case OPT_NT: 
2677                         opt_nt_response = strhex_to_data_blob(NULL, hex_nt_response);
2678                         if (opt_nt_response.length < 24) {
2679                                 x_fprintf(x_stderr, "hex decode of %s failed! (only got %d bytes)\n", 
2680                                           hex_nt_response,
2681                                           (int)opt_nt_response.length);
2682                                 exit(1);
2683                         }
2684                         break;
2685
2686                 case OPT_REQUIRE_MEMBERSHIP:
2687                         if (strncasecmp_m("S-", require_membership_of, 2) == 0) {
2688                                 require_membership_of_sid = require_membership_of;
2689                         }
2690                         break;
2691                 }
2692         }
2693
2694         if (opt_username) {
2695                 char *domain = SMB_STRDUP(opt_username);
2696                 char *p = strchr_m(domain, *lp_winbind_separator());
2697                 if (p) {
2698                         opt_username = p+1;
2699                         *p = '\0';
2700                         if (opt_domain && !strequal(opt_domain, domain)) {
2701                                 x_fprintf(x_stderr, "Domain specified in username (%s) "
2702                                         "doesn't match specified domain (%s)!\n\n",
2703                                         domain, opt_domain);
2704                                 poptPrintHelp(pc, stderr, 0);
2705                                 exit(1);
2706                         }
2707                         opt_domain = domain;
2708                 } else {
2709                         SAFE_FREE(domain);
2710                 }
2711         }
2712
2713         /* Note: if opt_domain is "" then send no domain */
2714         if (opt_domain == NULL) {
2715                 opt_domain = get_winbind_domain();
2716         }
2717
2718         if (opt_workstation == NULL) {
2719                 opt_workstation = "";
2720         }
2721
2722         if (helper_protocol) {
2723                 int i;
2724                 for (i=0; i<NUM_HELPER_MODES; i++) {
2725                         if (strcmp(helper_protocol, stdio_helper_protocols[i].name) == 0) {
2726                                 squid_stream(stdio_helper_protocols[i].mode, stdio_helper_protocols[i].fn);
2727                                 exit(0);
2728                         }
2729                 }
2730                 x_fprintf(x_stderr, "unknown helper protocol [%s]\n\nValid helper protools:\n\n", helper_protocol);
2731
2732                 for (i=0; i<NUM_HELPER_MODES; i++) {
2733                         x_fprintf(x_stderr, "%s\n", stdio_helper_protocols[i].name);
2734                 }
2735
2736                 exit(1);
2737         }
2738
2739         if (!opt_username || !*opt_username) {
2740                 x_fprintf(x_stderr, "username must be specified!\n\n");
2741                 poptPrintHelp(pc, stderr, 0);
2742                 exit(1);
2743         }
2744
2745         if (opt_challenge.length) {
2746                 if (!check_auth_crap()) {
2747                         exit(1);
2748                 }
2749                 exit(0);
2750         } 
2751
2752         if (!opt_password) {
2753                 opt_password = getpass("password: ");
2754         }
2755
2756         if (diagnostics) {
2757                 if (!diagnose_ntlm_auth()) {
2758                         return 1;
2759                 }
2760         } else {
2761                 fstring user;
2762
2763                 fstr_sprintf(user, "%s%c%s", opt_domain, winbind_separator(), opt_username);
2764                 if (!check_plaintext_auth(user, opt_password, True)) {
2765                         return 1;
2766                 }
2767         }
2768
2769         /* Exit code */
2770
2771         poptFreeContext(pc);
2772         TALLOC_FREE(frame);
2773         return 0;
2774 }