s3-build: Rework object lists to allow gse gensec module
[metze/samba/wip.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 static void manage_gss_spnego_request(struct ntlm_auth_state *state,
1236                                         char *buf, int length)
1237 {
1238         struct spnego_data request, response;
1239         DATA_BLOB token;
1240         DATA_BLOB raw_in_token = data_blob_null;
1241         DATA_BLOB raw_out_token = data_blob_null;
1242         NTSTATUS status;
1243         ssize_t len;
1244         TALLOC_CTX *ctx = talloc_tos();
1245
1246         char *user = NULL;
1247         char *domain = NULL;
1248
1249         const char *reply_code;
1250         char       *reply_base64;
1251         char *reply_argument = NULL;
1252         char *supportedMech = NULL;
1253
1254         if (strlen(buf) < 2) {
1255                 DEBUG(1, ("SPENGO query [%s] invalid\n", buf));
1256                 x_fprintf(x_stdout, "BH SPENGO query invalid\n");
1257                 return;
1258         }
1259
1260         if (strncmp(buf, "YR", 2) == 0) {
1261                 TALLOC_FREE(state->ntlmssp_state);
1262                 TALLOC_FREE(state->spnego_mech);
1263                 TALLOC_FREE(state->spnego_mech_oid);
1264         } else if (strncmp(buf, "KK", 2) == 0) {
1265                 ;
1266         } else {
1267                 DEBUG(1, ("SPENGO query [%s] invalid\n", buf));
1268                 x_fprintf(x_stdout, "BH SPENGO query invalid\n");
1269                 return;
1270         }
1271
1272         if ( (strlen(buf) == 2)) {
1273
1274                 /* no client data, get the negTokenInit offering
1275                    mechanisms */
1276
1277                 offer_gss_spnego_mechs();
1278                 return;
1279         }
1280
1281         /* All subsequent requests have a blob. This might be negTokenInit or negTokenTarg */
1282
1283         if (strlen(buf) <= 3) {
1284                 DEBUG(1, ("GSS-SPNEGO query [%s] invalid\n", buf));
1285                 x_fprintf(x_stdout, "BH GSS-SPNEGO query invalid\n");
1286                 return;
1287         }
1288
1289         token = base64_decode_data_blob(buf + 3);
1290
1291         if ((token.length >= 7)
1292             && (strncmp((char *)token.data, "NTLMSSP", 7) == 0)) {
1293                 char *reply;
1294
1295                 data_blob_free(&token);
1296
1297                 DEBUG(10, ("Could not parse GSS-SPNEGO, trying raw "
1298                            "ntlmssp\n"));
1299
1300                 manage_squid_ntlmssp_request_int(state, buf, length,
1301                                                  talloc_tos(), &reply);
1302                 if (reply == NULL) {
1303                         x_fprintf(x_stdout, "BH Out of memory\n");
1304                         return;
1305                 }
1306
1307                 if (strncmp(reply, "AF ", 3) == 0) {
1308                         x_fprintf(x_stdout, "AF * %s\n", reply+3);
1309                 } else {
1310                         x_fprintf(x_stdout, "%s *\n", reply);
1311                 }
1312
1313                 TALLOC_FREE(reply);
1314                 return;
1315         }
1316
1317         ZERO_STRUCT(request);
1318         len = spnego_read_data(ctx, token, &request);
1319         data_blob_free(&token);
1320
1321         if (len == -1) {
1322                 DEBUG(1, ("GSS-SPNEGO query [%s] invalid\n", buf));
1323                 x_fprintf(x_stdout, "BH GSS-SPNEGO query invalid\n");
1324                 return;
1325         }
1326
1327         if (request.type == SPNEGO_NEG_TOKEN_INIT) {
1328 #ifdef HAVE_KRB5
1329                 int krb5_idx = -1;
1330 #endif
1331                 int ntlm_idx = -1;
1332                 int used_idx = -1;
1333                 int i;
1334
1335                 if (state->spnego_mech) {
1336                         DEBUG(1, ("Client restarted SPNEGO with NegTokenInit "
1337                                   "while mech[%s] was already negotiated\n",
1338                                   state->spnego_mech));
1339                         x_fprintf(x_stdout, "BH Client send NegTokenInit twice\n");
1340                         return;
1341                 }
1342
1343                 /* Second request from Client. This is where the
1344                    client offers its mechanism to use. */
1345
1346                 if ( (request.negTokenInit.mechTypes == NULL) ||
1347                      (request.negTokenInit.mechTypes[0] == NULL) ) {
1348                         DEBUG(1, ("Client did not offer any mechanism\n"));
1349                         x_fprintf(x_stdout, "BH Client did not offer any "
1350                                             "mechanism\n");
1351                         return;
1352                 }
1353
1354                 status = NT_STATUS_UNSUCCESSFUL;
1355                 for (i = 0; request.negTokenInit.mechTypes[i] != NULL; i++) {
1356                         DEBUG(10,("got mech[%d][%s]\n",
1357                                 i, request.negTokenInit.mechTypes[i]));
1358 #ifdef HAVE_KRB5
1359                         if (strcmp(request.negTokenInit.mechTypes[i], OID_KERBEROS5_OLD) == 0) {
1360                                 krb5_idx = i;
1361                                 break;
1362                         }
1363                         if (strcmp(request.negTokenInit.mechTypes[i], OID_KERBEROS5) == 0) {
1364                                 krb5_idx = i;
1365                                 break;
1366                         }
1367 #endif
1368                         if (strcmp(request.negTokenInit.mechTypes[i], OID_NTLMSSP) == 0) {
1369                                 ntlm_idx = i;
1370                                 break;
1371                         }
1372                 }
1373
1374                 used_idx = ntlm_idx;
1375 #ifdef HAVE_KRB5
1376                 if (krb5_idx != -1) {
1377                         ntlm_idx = -1;
1378                         used_idx = krb5_idx;
1379                 }
1380 #endif
1381                 if (ntlm_idx > -1) {
1382                         state->spnego_mech = talloc_strdup(state, "ntlmssp");
1383                         if (state->spnego_mech == NULL) {
1384                                 x_fprintf(x_stdout, "BH Out of memory\n");
1385                                 return;
1386                         }
1387
1388                         if (state->ntlmssp_state) {
1389                                 DEBUG(1, ("Client wants a new NTLMSSP challenge, but "
1390                                           "already got one\n"));
1391                                 x_fprintf(x_stdout, "BH Client wants a new "
1392                                                     "NTLMSSP challenge, but "
1393                                                     "already got one\n");
1394                                 TALLOC_FREE(state->ntlmssp_state);
1395                                 return;
1396                         }
1397
1398                         status = ntlm_auth_start_ntlmssp_server(&state->ntlmssp_state);
1399                         if (!NT_STATUS_IS_OK(status)) {
1400                                 x_fprintf(x_stdout, "BH %s\n", nt_errstr(status));
1401                                 return;
1402                         }
1403                 }
1404
1405 #ifdef HAVE_KRB5
1406                 if (krb5_idx > -1) {
1407                         state->spnego_mech = talloc_strdup(state, "krb5");
1408                         if (state->spnego_mech == NULL) {
1409                                 x_fprintf(x_stdout, "BH Out of memory\n");
1410                                 return;
1411                         }
1412                 }
1413 #endif
1414                 if (used_idx > -1) {
1415                         state->spnego_mech_oid = talloc_strdup(state,
1416                                 request.negTokenInit.mechTypes[used_idx]);
1417                         if (state->spnego_mech_oid == NULL) {
1418                                 x_fprintf(x_stdout, "BH Out of memory\n");
1419                                 return;
1420                         }
1421                         supportedMech = talloc_strdup(ctx, state->spnego_mech_oid);
1422                         if (supportedMech == NULL) {
1423                                 x_fprintf(x_stdout, "BH Out of memory\n");
1424                                 return;
1425                         }
1426
1427                         status = NT_STATUS_MORE_PROCESSING_REQUIRED;
1428                 } else {
1429                         status = NT_STATUS_NOT_SUPPORTED;
1430                 }
1431                 if (used_idx == 0) {
1432                         status = NT_STATUS_OK;
1433                         raw_in_token = request.negTokenInit.mechToken;
1434                 }
1435         } else {
1436                 if (state->spnego_mech == NULL) {
1437                         DEBUG(1,("Got netTokenTarg without negTokenInit\n"));
1438                         x_fprintf(x_stdout, "BH Got a negTokenTarg without "
1439                                             "negTokenInit\n");
1440                         return;
1441                 }
1442
1443                 if ((request.negTokenTarg.supportedMech != NULL) &&
1444                      (strcmp(request.negTokenTarg.supportedMech, state->spnego_mech_oid) != 0 ) ) {
1445                         DEBUG(1, ("Got a negTokenTarg with mech[%s] while [%s] was already negotiated\n",
1446                                   request.negTokenTarg.supportedMech,
1447                                   state->spnego_mech_oid));
1448                         x_fprintf(x_stdout, "BH Got a negTokenTarg with speficied mech\n");
1449                         return;
1450                 }
1451
1452                 status = NT_STATUS_OK;
1453                 raw_in_token = request.negTokenTarg.responseToken;
1454         }
1455
1456         if (!NT_STATUS_IS_OK(status)) {
1457                 /* error or more processing */
1458         } else if (strcmp(state->spnego_mech, "ntlmssp") == 0) {
1459
1460                 DEBUG(10, ("got NTLMSSP packet:\n"));
1461                 dump_data(10, raw_in_token.data, raw_in_token.length);
1462
1463                 status = ntlmssp_update(state->ntlmssp_state,
1464                                         raw_in_token,
1465                                         &raw_out_token);
1466                 if (NT_STATUS_IS_OK(status)) {
1467                         user = talloc_strdup(ctx, state->ntlmssp_state->user);
1468                         domain = talloc_strdup(ctx, state->ntlmssp_state->domain);
1469                 }
1470                 if (!NT_STATUS_EQUAL(status, NT_STATUS_MORE_PROCESSING_REQUIRED)) {
1471                         TALLOC_FREE(state->ntlmssp_state);
1472                 }
1473 #ifdef HAVE_KRB5
1474         } else if (strcmp(state->spnego_mech, "krb5") == 0) {
1475                 char *principal;
1476                 DATA_BLOB ap_rep;
1477                 DATA_BLOB session_key;
1478                 struct PAC_LOGON_INFO *logon_info = NULL;
1479                 DATA_BLOB ticket;
1480                 uint8_t tok_id[2];
1481
1482                 if (!spnego_parse_krb5_wrap(ctx, raw_in_token,
1483                                             &ticket, tok_id)) {
1484                         DEBUG(1, ("spnego_parse_krb5_wrap failed\n"));
1485                         x_fprintf(x_stdout, "BH spnego_parse_krb5_wrap failed\n");
1486                         return;
1487                 }
1488
1489                 status = ads_verify_ticket(ctx, lp_realm(), 0,
1490                                            &ticket,
1491                                            &principal, &logon_info, &ap_rep,
1492                                            &session_key, True);
1493
1494                 /* Now in "principal" we have the name we are authenticated as. */
1495
1496                 if (NT_STATUS_IS_OK(status)) {
1497
1498                         domain = strchr_m(principal, '@');
1499
1500                         if (domain == NULL) {
1501                                 DEBUG(1, ("Did not get a valid principal "
1502                                           "from ads_verify_ticket\n"));
1503                                 x_fprintf(x_stdout, "BH Did not get a "
1504                                           "valid principal from "
1505                                           "ads_verify_ticket\n");
1506                                 return;
1507                         }
1508
1509                         *domain++ = '\0';
1510                         domain = talloc_strdup(ctx, domain);
1511                         user = talloc_strdup(ctx, principal);
1512
1513                         if (logon_info) {
1514                                 netsamlogon_cache_store(
1515                                         user, &logon_info->info3);
1516                         }
1517
1518                         data_blob_free(&ap_rep);
1519                         data_blob_free(&session_key);
1520                 }
1521                 data_blob_free(&ticket);
1522 #endif
1523         }
1524
1525         spnego_free_data(&request);
1526         ZERO_STRUCT(response);
1527         response.type = SPNEGO_NEG_TOKEN_TARG;
1528
1529         if (NT_STATUS_IS_OK(status)) {
1530                 TALLOC_FREE(state->spnego_mech);
1531                 TALLOC_FREE(state->spnego_mech_oid);
1532                 response.negTokenTarg.negResult = SPNEGO_ACCEPT_COMPLETED;
1533                 response.negTokenTarg.responseToken = raw_out_token;
1534                 reply_code = "AF";
1535                 reply_argument = talloc_asprintf(ctx, "%s\\%s", domain, user);
1536         } else if (NT_STATUS_EQUAL(status,
1537                                    NT_STATUS_MORE_PROCESSING_REQUIRED)) {
1538                 response.negTokenTarg.supportedMech = supportedMech;
1539                 response.negTokenTarg.responseToken = raw_out_token;
1540                 response.negTokenTarg.negResult = SPNEGO_ACCEPT_INCOMPLETE;
1541                 reply_code = "TT";
1542                 reply_argument = talloc_strdup(ctx, "*");
1543         } else {
1544                 TALLOC_FREE(state->spnego_mech);
1545                 TALLOC_FREE(state->spnego_mech_oid);
1546                 data_blob_free(&raw_out_token);
1547                 response.negTokenTarg.negResult = SPNEGO_REJECT;
1548                 reply_code = "NA";
1549                 reply_argument = talloc_strdup(ctx, nt_errstr(status));
1550         }
1551
1552         if (!reply_argument) {
1553                 DEBUG(1, ("Could not write SPNEGO data blob\n"));
1554                 x_fprintf(x_stdout, "BH Could not write SPNEGO data blob\n");
1555                 spnego_free_data(&response);
1556                 return;
1557         }
1558
1559         len = spnego_write_data(ctx, &token, &response);
1560         spnego_free_data(&response);
1561
1562         if (len == -1) {
1563                 DEBUG(1, ("Could not write SPNEGO data blob\n"));
1564                 x_fprintf(x_stdout, "BH Could not write SPNEGO data blob\n");
1565                 return;
1566         }
1567
1568         reply_base64 = base64_encode_data_blob(talloc_tos(), token);
1569
1570         x_fprintf(x_stdout, "%s %s %s\n",
1571                   reply_code, reply_base64, reply_argument);
1572
1573         TALLOC_FREE(reply_base64);
1574         data_blob_free(&token);
1575
1576         return;
1577 }
1578
1579 static struct ntlmssp_state *client_ntlmssp_state = NULL;
1580
1581 static bool manage_client_ntlmssp_init(struct spnego_data spnego)
1582 {
1583         NTSTATUS status;
1584         DATA_BLOB null_blob = data_blob_null;
1585         DATA_BLOB to_server;
1586         char *to_server_base64;
1587         const char *my_mechs[] = {OID_NTLMSSP, NULL};
1588         TALLOC_CTX *ctx = talloc_tos();
1589
1590         DEBUG(10, ("Got spnego negTokenInit with NTLMSSP\n"));
1591
1592         if (client_ntlmssp_state != NULL) {
1593                 DEBUG(1, ("Request for initial SPNEGO request where "
1594                           "we already have a state\n"));
1595                 return False;
1596         }
1597
1598         if (!client_ntlmssp_state) {
1599                 if (!NT_STATUS_IS_OK(status = ntlm_auth_start_ntlmssp_client(&client_ntlmssp_state))) {
1600                         x_fprintf(x_stdout, "BH %s\n", nt_errstr(status));
1601                         return False;
1602                 }
1603         }
1604
1605
1606         if (opt_password == NULL) {
1607
1608                 /* Request a password from the calling process.  After
1609                    sending it, the calling process should retry with
1610                    the negTokenInit. */
1611
1612                 DEBUG(10, ("Requesting password\n"));
1613                 x_fprintf(x_stdout, "PW\n");
1614                 return True;
1615         }
1616
1617         spnego.type = SPNEGO_NEG_TOKEN_INIT;
1618         spnego.negTokenInit.mechTypes = my_mechs;
1619         spnego.negTokenInit.reqFlags = data_blob_null;
1620         spnego.negTokenInit.reqFlagsPadding = 0;
1621         spnego.negTokenInit.mechListMIC = null_blob;
1622
1623         status = ntlmssp_update(client_ntlmssp_state, null_blob,
1624                                        &spnego.negTokenInit.mechToken);
1625
1626         if ( !(NT_STATUS_EQUAL(status, NT_STATUS_MORE_PROCESSING_REQUIRED) ||
1627                         NT_STATUS_IS_OK(status)) ) {
1628                 DEBUG(1, ("Expected OK or MORE_PROCESSING_REQUIRED, got: %s\n",
1629                           nt_errstr(status)));
1630                 TALLOC_FREE(client_ntlmssp_state);
1631                 return False;
1632         }
1633
1634         spnego_write_data(ctx, &to_server, &spnego);
1635         data_blob_free(&spnego.negTokenInit.mechToken);
1636
1637         to_server_base64 = base64_encode_data_blob(talloc_tos(), to_server);
1638         data_blob_free(&to_server);
1639         x_fprintf(x_stdout, "KK %s\n", to_server_base64);
1640         TALLOC_FREE(to_server_base64);
1641         return True;
1642 }
1643
1644 static void manage_client_ntlmssp_targ(struct spnego_data spnego)
1645 {
1646         NTSTATUS status;
1647         DATA_BLOB null_blob = data_blob_null;
1648         DATA_BLOB request;
1649         DATA_BLOB to_server;
1650         char *to_server_base64;
1651         TALLOC_CTX *ctx = talloc_tos();
1652
1653         DEBUG(10, ("Got spnego negTokenTarg with NTLMSSP\n"));
1654
1655         if (client_ntlmssp_state == NULL) {
1656                 DEBUG(1, ("Got NTLMSSP tArg without a client state\n"));
1657                 x_fprintf(x_stdout, "BH Got NTLMSSP tArg without a client state\n");
1658                 return;
1659         }
1660
1661         if (spnego.negTokenTarg.negResult == SPNEGO_REJECT) {
1662                 x_fprintf(x_stdout, "NA\n");
1663                 TALLOC_FREE(client_ntlmssp_state);
1664                 return;
1665         }
1666
1667         if (spnego.negTokenTarg.negResult == SPNEGO_ACCEPT_COMPLETED) {
1668                 x_fprintf(x_stdout, "AF\n");
1669                 TALLOC_FREE(client_ntlmssp_state);
1670                 return;
1671         }
1672
1673         status = ntlmssp_update(client_ntlmssp_state,
1674                                        spnego.negTokenTarg.responseToken,
1675                                        &request);
1676
1677         if (!NT_STATUS_EQUAL(status, NT_STATUS_MORE_PROCESSING_REQUIRED)) {
1678                 DEBUG(1, ("Expected MORE_PROCESSING_REQUIRED from "
1679                           "ntlmssp_client_update, got: %s\n",
1680                           nt_errstr(status)));
1681                 x_fprintf(x_stdout, "BH Expected MORE_PROCESSING_REQUIRED from "
1682                                     "ntlmssp_client_update\n");
1683                 data_blob_free(&request);
1684                 TALLOC_FREE(client_ntlmssp_state);
1685                 return;
1686         }
1687
1688         spnego.type = SPNEGO_NEG_TOKEN_TARG;
1689         spnego.negTokenTarg.negResult = SPNEGO_ACCEPT_INCOMPLETE;
1690         spnego.negTokenTarg.supportedMech = (const char *)OID_NTLMSSP;
1691         spnego.negTokenTarg.responseToken = request;
1692         spnego.negTokenTarg.mechListMIC = null_blob;
1693
1694         spnego_write_data(ctx, &to_server, &spnego);
1695         data_blob_free(&request);
1696
1697         to_server_base64 = base64_encode_data_blob(talloc_tos(), to_server);
1698         data_blob_free(&to_server);
1699         x_fprintf(x_stdout, "KK %s\n", to_server_base64);
1700         TALLOC_FREE(to_server_base64);
1701         return;
1702 }
1703
1704 #ifdef HAVE_KRB5
1705
1706 static bool manage_client_krb5_init(struct spnego_data spnego)
1707 {
1708         char *principal;
1709         DATA_BLOB tkt, to_server;
1710         DATA_BLOB session_key_krb5 = data_blob_null;
1711         struct spnego_data reply;
1712         char *reply_base64;
1713         int retval;
1714
1715         const char *my_mechs[] = {OID_KERBEROS5_OLD, NULL};
1716         ssize_t len;
1717         TALLOC_CTX *ctx = talloc_tos();
1718
1719         if ( (spnego.negTokenInit.mechListMIC.data == NULL) ||
1720              (spnego.negTokenInit.mechListMIC.length == 0) ) {
1721                 DEBUG(1, ("Did not get a principal for krb5\n"));
1722                 return False;
1723         }
1724
1725         principal = (char *)SMB_MALLOC(
1726                 spnego.negTokenInit.mechListMIC.length+1);
1727
1728         if (principal == NULL) {
1729                 DEBUG(1, ("Could not malloc principal\n"));
1730                 return False;
1731         }
1732
1733         memcpy(principal, spnego.negTokenInit.mechListMIC.data,
1734                spnego.negTokenInit.mechListMIC.length);
1735         principal[spnego.negTokenInit.mechListMIC.length] = '\0';
1736
1737         retval = cli_krb5_get_ticket(ctx, principal, 0,
1738                                           &tkt, &session_key_krb5,
1739                                           0, NULL, NULL, NULL);
1740         if (retval) {
1741                 char *user = NULL;
1742
1743                 /* Let's try to first get the TGT, for that we need a
1744                    password. */
1745
1746                 if (opt_password == NULL) {
1747                         DEBUG(10, ("Requesting password\n"));
1748                         x_fprintf(x_stdout, "PW\n");
1749                         return True;
1750                 }
1751
1752                 user = talloc_asprintf(talloc_tos(), "%s@%s", opt_username, opt_domain);
1753                 if (!user) {
1754                         return false;
1755                 }
1756
1757                 if ((retval = kerberos_kinit_password(user, opt_password, 0, NULL))) {
1758                         DEBUG(10, ("Requesting TGT failed: %s\n", error_message(retval)));
1759                         return False;
1760                 }
1761
1762                 retval = cli_krb5_get_ticket(ctx, principal, 0,
1763                                                   &tkt, &session_key_krb5,
1764                                                   0, NULL, NULL, NULL);
1765                 if (retval) {
1766                         DEBUG(10, ("Kinit suceeded, but getting a ticket failed: %s\n", error_message(retval)));
1767                         return False;
1768                 }
1769         }
1770
1771         data_blob_free(&session_key_krb5);
1772
1773         ZERO_STRUCT(reply);
1774
1775         reply.type = SPNEGO_NEG_TOKEN_INIT;
1776         reply.negTokenInit.mechTypes = my_mechs;
1777         reply.negTokenInit.reqFlags = data_blob_null;
1778         reply.negTokenInit.reqFlagsPadding = 0;
1779         reply.negTokenInit.mechToken = tkt;
1780         reply.negTokenInit.mechListMIC = data_blob_null;
1781
1782         len = spnego_write_data(ctx, &to_server, &reply);
1783         data_blob_free(&tkt);
1784
1785         if (len == -1) {
1786                 DEBUG(1, ("Could not write SPNEGO data blob\n"));
1787                 return False;
1788         }
1789
1790         reply_base64 = base64_encode_data_blob(talloc_tos(), to_server);
1791         x_fprintf(x_stdout, "KK %s *\n", reply_base64);
1792
1793         TALLOC_FREE(reply_base64);
1794         data_blob_free(&to_server);
1795         DEBUG(10, ("sent GSS-SPNEGO KERBEROS5 negTokenInit\n"));
1796         return True;
1797 }
1798
1799 static void manage_client_krb5_targ(struct spnego_data spnego)
1800 {
1801         switch (spnego.negTokenTarg.negResult) {
1802         case SPNEGO_ACCEPT_INCOMPLETE:
1803                 DEBUG(1, ("Got a Kerberos negTokenTarg with ACCEPT_INCOMPLETE\n"));
1804                 x_fprintf(x_stdout, "BH Got a Kerberos negTokenTarg with "
1805                                     "ACCEPT_INCOMPLETE\n");
1806                 break;
1807         case SPNEGO_ACCEPT_COMPLETED:
1808                 DEBUG(10, ("Accept completed\n"));
1809                 x_fprintf(x_stdout, "AF\n");
1810                 break;
1811         case SPNEGO_REJECT:
1812                 DEBUG(10, ("Rejected\n"));
1813                 x_fprintf(x_stdout, "NA\n");
1814                 break;
1815         default:
1816                 DEBUG(1, ("Got an invalid negTokenTarg\n"));
1817                 x_fprintf(x_stdout, "AF\n");
1818         }
1819 }
1820
1821 #endif
1822
1823 static void manage_gss_spnego_client_request(struct ntlm_auth_state *state,
1824                                                 char *buf, int length)
1825 {
1826         DATA_BLOB request;
1827         struct spnego_data spnego;
1828         ssize_t len;
1829         TALLOC_CTX *ctx = talloc_tos();
1830
1831         if (!opt_username || !*opt_username) {
1832                 x_fprintf(x_stderr, "username must be specified!\n\n");
1833                 exit(1);
1834         }
1835
1836         if (strlen(buf) <= 3) {
1837                 DEBUG(1, ("SPNEGO query [%s] too short\n", buf));
1838                 x_fprintf(x_stdout, "BH SPNEGO query too short\n");
1839                 return;
1840         }
1841
1842         request = base64_decode_data_blob(buf+3);
1843
1844         if (strncmp(buf, "PW ", 3) == 0) {
1845
1846                 /* We asked for a password and obviously got it :-) */
1847
1848                 opt_password = SMB_STRNDUP((const char *)request.data, request.length);
1849
1850                 if (opt_password == NULL) {
1851                         DEBUG(1, ("Out of memory\n"));
1852                         x_fprintf(x_stdout, "BH Out of memory\n");
1853                         data_blob_free(&request);
1854                         return;
1855                 }
1856
1857                 x_fprintf(x_stdout, "OK\n");
1858                 data_blob_free(&request);
1859                 return;
1860         }
1861
1862         if ( (strncmp(buf, "TT ", 3) != 0) &&
1863              (strncmp(buf, "AF ", 3) != 0) &&
1864              (strncmp(buf, "NA ", 3) != 0) ) {
1865                 DEBUG(1, ("SPNEGO request [%s] invalid\n", buf));
1866                 x_fprintf(x_stdout, "BH SPNEGO request invalid\n");
1867                 data_blob_free(&request);
1868                 return;
1869         }
1870
1871         /* So we got a server challenge to generate a SPNEGO
1872            client-to-server request... */
1873
1874         len = spnego_read_data(ctx, request, &spnego);
1875         data_blob_free(&request);
1876
1877         if (len == -1) {
1878                 DEBUG(1, ("Could not read SPNEGO data for [%s]\n", buf));
1879                 x_fprintf(x_stdout, "BH Could not read SPNEGO data\n");
1880                 return;
1881         }
1882
1883         if (spnego.type == SPNEGO_NEG_TOKEN_INIT) {
1884
1885                 /* The server offers a list of mechanisms */
1886
1887                 const char **mechType = (const char **)spnego.negTokenInit.mechTypes;
1888
1889                 while (*mechType != NULL) {
1890
1891 #ifdef HAVE_KRB5
1892                         if ( (strcmp(*mechType, OID_KERBEROS5_OLD) == 0) ||
1893                              (strcmp(*mechType, OID_KERBEROS5) == 0) ) {
1894                                 if (manage_client_krb5_init(spnego))
1895                                         goto out;
1896                         }
1897 #endif
1898
1899                         if (strcmp(*mechType, OID_NTLMSSP) == 0) {
1900                                 if (manage_client_ntlmssp_init(spnego))
1901                                         goto out;
1902                         }
1903
1904                         mechType++;
1905                 }
1906
1907                 DEBUG(1, ("Server offered no compatible mechanism\n"));
1908                 x_fprintf(x_stdout, "BH Server offered no compatible mechanism\n");
1909                 return;
1910         }
1911
1912         if (spnego.type == SPNEGO_NEG_TOKEN_TARG) {
1913
1914                 if (spnego.negTokenTarg.supportedMech == NULL) {
1915                         /* On accept/reject Windows does not send the
1916                            mechanism anymore. Handle that here and
1917                            shut down the mechanisms. */
1918
1919                         switch (spnego.negTokenTarg.negResult) {
1920                         case SPNEGO_ACCEPT_COMPLETED:
1921                                 x_fprintf(x_stdout, "AF\n");
1922                                 break;
1923                         case SPNEGO_REJECT:
1924                                 x_fprintf(x_stdout, "NA\n");
1925                                 break;
1926                         default:
1927                                 DEBUG(1, ("Got a negTokenTarg with no mech and an "
1928                                           "unknown negResult: %d\n",
1929                                           spnego.negTokenTarg.negResult));
1930                                 x_fprintf(x_stdout, "BH Got a negTokenTarg with"
1931                                                     " no mech and an unknown "
1932                                                     "negResult\n");
1933                         }
1934
1935                         TALLOC_FREE(client_ntlmssp_state);
1936                         goto out;
1937                 }
1938
1939                 if (strcmp(spnego.negTokenTarg.supportedMech,
1940                            OID_NTLMSSP) == 0) {
1941                         manage_client_ntlmssp_targ(spnego);
1942                         goto out;
1943                 }
1944
1945 #if HAVE_KRB5
1946                 if (strcmp(spnego.negTokenTarg.supportedMech,
1947                            OID_KERBEROS5_OLD) == 0) {
1948                         manage_client_krb5_targ(spnego);
1949                         goto out;
1950                 }
1951 #endif
1952
1953         }
1954
1955         DEBUG(1, ("Got an SPNEGO token I could not handle [%s]!\n", buf));
1956         x_fprintf(x_stdout, "BH Got an SPNEGO token I could not handle\n");
1957         return;
1958
1959  out:
1960         spnego_free_data(&spnego);
1961         return;
1962 }
1963
1964 static void manage_ntlm_server_1_request(struct ntlm_auth_state *state,
1965                                                 char *buf, int length)
1966 {
1967         char *request, *parameter;      
1968         static DATA_BLOB challenge;
1969         static DATA_BLOB lm_response;
1970         static DATA_BLOB nt_response;
1971         static char *full_username;
1972         static char *username;
1973         static char *domain;
1974         static char *plaintext_password;
1975         static bool ntlm_server_1_user_session_key;
1976         static bool ntlm_server_1_lm_session_key;
1977
1978         if (strequal(buf, ".")) {
1979                 if (!full_username && !username) {      
1980                         x_fprintf(x_stdout, "Error: No username supplied!\n");
1981                 } else if (plaintext_password) {
1982                         /* handle this request as plaintext */
1983                         if (!full_username) {
1984                                 if (asprintf(&full_username, "%s%c%s", domain, winbind_separator(), username) == -1) {
1985                                         x_fprintf(x_stdout, "Error: Out of memory in asprintf!\n.\n");
1986                                         return;
1987                                 }
1988                         }
1989                         if (check_plaintext_auth(full_username, plaintext_password, False)) {
1990                                 x_fprintf(x_stdout, "Authenticated: Yes\n");
1991                         } else {
1992                                 x_fprintf(x_stdout, "Authenticated: No\n");
1993                         }
1994                 } else if (!lm_response.data && !nt_response.data) {
1995                         x_fprintf(x_stdout, "Error: No password supplied!\n");
1996                 } else if (!challenge.data) {   
1997                         x_fprintf(x_stdout, "Error: No lanman-challenge supplied!\n");
1998                 } else {
1999                         char *error_string = NULL;
2000                         uchar lm_key[8];
2001                         uchar user_session_key[16];
2002                         uint32 flags = 0;
2003
2004                         if (full_username && !username) {
2005                                 fstring fstr_user;
2006                                 fstring fstr_domain;
2007
2008                                 if (!parse_ntlm_auth_domain_user(full_username, fstr_user, fstr_domain)) {
2009                                         /* username might be 'tainted', don't print into our new-line deleimianted stream */
2010                                         x_fprintf(x_stdout, "Error: Could not parse into domain and username\n");
2011                                 }
2012                                 SAFE_FREE(username);
2013                                 SAFE_FREE(domain);
2014                                 username = smb_xstrdup(fstr_user);
2015                                 domain = smb_xstrdup(fstr_domain);
2016                         }
2017
2018                         if (!domain) {
2019                                 domain = smb_xstrdup(get_winbind_domain());
2020                         }
2021
2022                         if (ntlm_server_1_lm_session_key) 
2023                                 flags |= WBFLAG_PAM_LMKEY;
2024
2025                         if (ntlm_server_1_user_session_key) 
2026                                 flags |= WBFLAG_PAM_USER_SESSION_KEY;
2027
2028                         if (!NT_STATUS_IS_OK(
2029                                     contact_winbind_auth_crap(username, 
2030                                                               domain, 
2031                                                               lp_netbios_name(),
2032                                                               &challenge, 
2033                                                               &lm_response, 
2034                                                               &nt_response, 
2035                                                               flags, 
2036                                                               lm_key, 
2037                                                               user_session_key,
2038                                                               &error_string,
2039                                                               NULL))) {
2040
2041                                 x_fprintf(x_stdout, "Authenticated: No\n");
2042                                 x_fprintf(x_stdout, "Authentication-Error: %s\n.\n", error_string);
2043                         } else {
2044                                 static char zeros[16];
2045                                 char *hex_lm_key;
2046                                 char *hex_user_session_key;
2047
2048                                 x_fprintf(x_stdout, "Authenticated: Yes\n");
2049
2050                                 if (ntlm_server_1_lm_session_key 
2051                                     && (memcmp(zeros, lm_key, 
2052                                                sizeof(lm_key)) != 0)) {
2053                                         hex_lm_key = hex_encode_talloc(NULL,
2054                                                                 (const unsigned char *)lm_key,
2055                                                                 sizeof(lm_key));
2056                                         x_fprintf(x_stdout, "LANMAN-Session-Key: %s\n", hex_lm_key);
2057                                         TALLOC_FREE(hex_lm_key);
2058                                 }
2059
2060                                 if (ntlm_server_1_user_session_key 
2061                                     && (memcmp(zeros, user_session_key, 
2062                                                sizeof(user_session_key)) != 0)) {
2063                                         hex_user_session_key = hex_encode_talloc(NULL,
2064                                                                           (const unsigned char *)user_session_key, 
2065                                                                           sizeof(user_session_key));
2066                                         x_fprintf(x_stdout, "User-Session-Key: %s\n", hex_user_session_key);
2067                                         TALLOC_FREE(hex_user_session_key);
2068                                 }
2069                         }
2070                         SAFE_FREE(error_string);
2071                 }
2072                 /* clear out the state */
2073                 challenge = data_blob_null;
2074                 nt_response = data_blob_null;
2075                 lm_response = data_blob_null;
2076                 SAFE_FREE(full_username);
2077                 SAFE_FREE(username);
2078                 SAFE_FREE(domain);
2079                 SAFE_FREE(plaintext_password);
2080                 ntlm_server_1_user_session_key = False;
2081                 ntlm_server_1_lm_session_key = False;
2082                 x_fprintf(x_stdout, ".\n");
2083
2084                 return;
2085         }
2086
2087         request = buf;
2088
2089         /* Indicates a base64 encoded structure */
2090         parameter = strstr_m(request, ":: ");
2091         if (!parameter) {
2092                 parameter = strstr_m(request, ": ");
2093
2094                 if (!parameter) {
2095                         DEBUG(0, ("Parameter not found!\n"));
2096                         x_fprintf(x_stdout, "Error: Parameter not found!\n.\n");
2097                         return;
2098                 }
2099
2100                 parameter[0] ='\0';
2101                 parameter++;
2102                 parameter[0] ='\0';
2103                 parameter++;
2104
2105         } else {
2106                 parameter[0] ='\0';
2107                 parameter++;
2108                 parameter[0] ='\0';
2109                 parameter++;
2110                 parameter[0] ='\0';
2111                 parameter++;
2112
2113                 base64_decode_inplace(parameter);
2114         }
2115
2116         if (strequal(request, "LANMAN-Challenge")) {
2117                 challenge = strhex_to_data_blob(NULL, parameter);
2118                 if (challenge.length != 8) {
2119                         x_fprintf(x_stdout, "Error: hex decode of %s failed! (got %d bytes, expected 8)\n.\n", 
2120                                   parameter,
2121                                   (int)challenge.length);
2122                         challenge = data_blob_null;
2123                 }
2124         } else if (strequal(request, "NT-Response")) {
2125                 nt_response = strhex_to_data_blob(NULL, parameter);
2126                 if (nt_response.length < 24) {
2127                         x_fprintf(x_stdout, "Error: hex decode of %s failed! (only got %d bytes, needed at least 24)\n.\n", 
2128                                   parameter,
2129                                   (int)nt_response.length);
2130                         nt_response = data_blob_null;
2131                 }
2132         } else if (strequal(request, "LANMAN-Response")) {
2133                 lm_response = strhex_to_data_blob(NULL, parameter);
2134                 if (lm_response.length != 24) {
2135                         x_fprintf(x_stdout, "Error: hex decode of %s failed! (got %d bytes, expected 24)\n.\n", 
2136                                   parameter,
2137                                   (int)lm_response.length);
2138                         lm_response = data_blob_null;
2139                 }
2140         } else if (strequal(request, "Password")) {
2141                 plaintext_password = smb_xstrdup(parameter);
2142         } else if (strequal(request, "NT-Domain")) {
2143                 domain = smb_xstrdup(parameter);
2144         } else if (strequal(request, "Username")) {
2145                 username = smb_xstrdup(parameter);
2146         } else if (strequal(request, "Full-Username")) {
2147                 full_username = smb_xstrdup(parameter);
2148         } else if (strequal(request, "Request-User-Session-Key")) {
2149                 ntlm_server_1_user_session_key = strequal(parameter, "Yes");
2150         } else if (strequal(request, "Request-LanMan-Session-Key")) {
2151                 ntlm_server_1_lm_session_key = strequal(parameter, "Yes");
2152         } else {
2153                 x_fprintf(x_stdout, "Error: Unknown request %s\n.\n", request);
2154         }
2155 }
2156
2157 static void manage_ntlm_change_password_1_request(struct ntlm_auth_state *state,
2158                                                         char *buf, int length)
2159 {
2160         char *request, *parameter;      
2161         static DATA_BLOB new_nt_pswd;
2162         static DATA_BLOB old_nt_hash_enc;
2163         static DATA_BLOB new_lm_pswd;
2164         static DATA_BLOB old_lm_hash_enc;
2165         static char *full_username = NULL;
2166         static char *username = NULL;
2167         static char *domain = NULL;
2168         static char *newpswd =  NULL;
2169         static char *oldpswd = NULL;
2170
2171         if (strequal(buf, ".")) {
2172                 if(newpswd && oldpswd) {
2173                         uchar old_nt_hash[16];
2174                         uchar old_lm_hash[16];
2175                         uchar new_nt_hash[16];
2176                         uchar new_lm_hash[16];
2177
2178                         new_nt_pswd = data_blob(NULL, 516);
2179                         old_nt_hash_enc = data_blob(NULL, 16);
2180
2181                         /* Calculate the MD4 hash (NT compatible) of the
2182                          * password */
2183                         E_md4hash(oldpswd, old_nt_hash);
2184                         E_md4hash(newpswd, new_nt_hash);
2185
2186                         /* E_deshash returns false for 'long'
2187                            passwords (> 14 DOS chars).  
2188
2189                            Therefore, don't send a buffer
2190                            encrypted with the truncated hash
2191                            (it could allow an even easier
2192                            attack on the password)
2193
2194                            Likewise, obey the admin's restriction
2195                         */
2196
2197                         if (lp_client_lanman_auth() &&
2198                             E_deshash(newpswd, new_lm_hash) &&
2199                             E_deshash(oldpswd, old_lm_hash)) {
2200                                 new_lm_pswd = data_blob(NULL, 516);
2201                                 old_lm_hash_enc = data_blob(NULL, 16);
2202                                 encode_pw_buffer(new_lm_pswd.data, newpswd,
2203                                                  STR_UNICODE);
2204
2205                                 arcfour_crypt(new_lm_pswd.data, old_nt_hash, 516);
2206                                 E_old_pw_hash(new_nt_hash, old_lm_hash,
2207                                               old_lm_hash_enc.data);
2208                         } else {
2209                                 new_lm_pswd.data = NULL;
2210                                 new_lm_pswd.length = 0;
2211                                 old_lm_hash_enc.data = NULL;
2212                                 old_lm_hash_enc.length = 0;
2213                         }
2214
2215                         encode_pw_buffer(new_nt_pswd.data, newpswd,
2216                                          STR_UNICODE);
2217
2218                         arcfour_crypt(new_nt_pswd.data, old_nt_hash, 516);
2219                         E_old_pw_hash(new_nt_hash, old_nt_hash,
2220                                       old_nt_hash_enc.data);
2221                 }
2222
2223                 if (!full_username && !username) {      
2224                         x_fprintf(x_stdout, "Error: No username supplied!\n");
2225                 } else if ((!new_nt_pswd.data || !old_nt_hash_enc.data) &&
2226                            (!new_lm_pswd.data || old_lm_hash_enc.data) ) {
2227                         x_fprintf(x_stdout, "Error: No NT or LM password "
2228                                   "blobs supplied!\n");
2229                 } else {
2230                         char *error_string = NULL;
2231
2232                         if (full_username && !username) {
2233                                 fstring fstr_user;
2234                                 fstring fstr_domain;
2235
2236                                 if (!parse_ntlm_auth_domain_user(full_username,
2237                                                                  fstr_user,
2238                                                                  fstr_domain)) {
2239                                         /* username might be 'tainted', don't
2240                                          * print into our new-line
2241                                          * deleimianted stream */
2242                                         x_fprintf(x_stdout, "Error: Could not "
2243                                                   "parse into domain and "
2244                                                   "username\n");
2245                                         SAFE_FREE(username);
2246                                         username = smb_xstrdup(full_username);
2247                                 } else {
2248                                         SAFE_FREE(username);
2249                                         SAFE_FREE(domain);
2250                                         username = smb_xstrdup(fstr_user);
2251                                         domain = smb_xstrdup(fstr_domain);
2252                                 }
2253
2254                         }
2255
2256                         if(!NT_STATUS_IS_OK(contact_winbind_change_pswd_auth_crap(
2257                                                     username, domain,
2258                                                     new_nt_pswd,
2259                                                     old_nt_hash_enc,
2260                                                     new_lm_pswd,
2261                                                     old_lm_hash_enc,
2262                                                     &error_string))) {
2263                                 x_fprintf(x_stdout, "Password-Change: No\n");
2264                                 x_fprintf(x_stdout, "Password-Change-Error: "
2265                                           "%s\n.\n", error_string);
2266                         } else {
2267                                 x_fprintf(x_stdout, "Password-Change: Yes\n");
2268                         }
2269
2270                         SAFE_FREE(error_string);
2271                 }
2272                 /* clear out the state */
2273                 new_nt_pswd = data_blob_null;
2274                 old_nt_hash_enc = data_blob_null;
2275                 new_lm_pswd = data_blob_null;
2276                 old_nt_hash_enc = data_blob_null;
2277                 SAFE_FREE(full_username);
2278                 SAFE_FREE(username);
2279                 SAFE_FREE(domain);
2280                 SAFE_FREE(newpswd);
2281                 SAFE_FREE(oldpswd);
2282                 x_fprintf(x_stdout, ".\n");
2283
2284                 return;
2285         }
2286
2287         request = buf;
2288
2289         /* Indicates a base64 encoded structure */
2290         parameter = strstr_m(request, ":: ");
2291         if (!parameter) {
2292                 parameter = strstr_m(request, ": ");
2293
2294                 if (!parameter) {
2295                         DEBUG(0, ("Parameter not found!\n"));
2296                         x_fprintf(x_stdout, "Error: Parameter not found!\n.\n");
2297                         return;
2298                 }
2299
2300                 parameter[0] ='\0';
2301                 parameter++;
2302                 parameter[0] ='\0';
2303                 parameter++;
2304         } else {
2305                 parameter[0] ='\0';
2306                 parameter++;
2307                 parameter[0] ='\0';
2308                 parameter++;
2309                 parameter[0] ='\0';
2310                 parameter++;
2311
2312                 base64_decode_inplace(parameter);
2313         }
2314
2315         if (strequal(request, "new-nt-password-blob")) {
2316                 new_nt_pswd = strhex_to_data_blob(NULL, parameter);
2317                 if (new_nt_pswd.length != 516) {
2318                         x_fprintf(x_stdout, "Error: hex decode of %s failed! "
2319                                   "(got %d bytes, expected 516)\n.\n", 
2320                                   parameter,
2321                                   (int)new_nt_pswd.length);
2322                         new_nt_pswd = data_blob_null;
2323                 }
2324         } else if (strequal(request, "old-nt-hash-blob")) {
2325                 old_nt_hash_enc = strhex_to_data_blob(NULL, parameter);
2326                 if (old_nt_hash_enc.length != 16) {
2327                         x_fprintf(x_stdout, "Error: hex decode of %s failed! "
2328                                   "(got %d bytes, expected 16)\n.\n", 
2329                                   parameter,
2330                                   (int)old_nt_hash_enc.length);
2331                         old_nt_hash_enc = data_blob_null;
2332                 }
2333         } else if (strequal(request, "new-lm-password-blob")) {
2334                 new_lm_pswd = strhex_to_data_blob(NULL, parameter);
2335                 if (new_lm_pswd.length != 516) {
2336                         x_fprintf(x_stdout, "Error: hex decode of %s failed! "
2337                                   "(got %d bytes, expected 516)\n.\n", 
2338                                   parameter,
2339                                   (int)new_lm_pswd.length);
2340                         new_lm_pswd = data_blob_null;
2341                 }
2342         }
2343         else if (strequal(request, "old-lm-hash-blob")) {
2344                 old_lm_hash_enc = strhex_to_data_blob(NULL, parameter);
2345                 if (old_lm_hash_enc.length != 16)
2346                 {
2347                         x_fprintf(x_stdout, "Error: hex decode of %s failed! "
2348                                   "(got %d bytes, expected 16)\n.\n", 
2349                                   parameter,
2350                                   (int)old_lm_hash_enc.length);
2351                         old_lm_hash_enc = data_blob_null;
2352                 }
2353         } else if (strequal(request, "nt-domain")) {
2354                 domain = smb_xstrdup(parameter);
2355         } else if(strequal(request, "username")) {
2356                 username = smb_xstrdup(parameter);
2357         } else if(strequal(request, "full-username")) {
2358                 username = smb_xstrdup(parameter);
2359         } else if(strequal(request, "new-password")) {
2360                 newpswd = smb_xstrdup(parameter);
2361         } else if (strequal(request, "old-password")) {
2362                 oldpswd = smb_xstrdup(parameter);
2363         } else {
2364                 x_fprintf(x_stdout, "Error: Unknown request %s\n.\n", request);
2365         }
2366 }
2367
2368 static void manage_squid_request(struct ntlm_auth_state *state,
2369                 stdio_helper_function fn)
2370 {
2371         char *buf;
2372         char tmp[INITIAL_BUFFER_SIZE+1];
2373         int length, buf_size = 0;
2374         char *c;
2375
2376         buf = talloc_strdup(state->mem_ctx, "");
2377         if (!buf) {
2378                 DEBUG(0, ("Failed to allocate input buffer.\n"));
2379                 x_fprintf(x_stderr, "ERR\n");
2380                 exit(1);
2381         }
2382
2383         do {
2384
2385                 /* this is not a typo - x_fgets doesn't work too well under
2386                  * squid */
2387                 if (fgets(tmp, sizeof(tmp)-1, stdin) == NULL) {
2388                         if (ferror(stdin)) {
2389                                 DEBUG(1, ("fgets() failed! dying..... errno=%d "
2390                                           "(%s)\n", ferror(stdin),
2391                                           strerror(ferror(stdin))));
2392
2393                                 exit(1);
2394                         }
2395                         exit(0);
2396                 }
2397
2398                 buf = talloc_strdup_append_buffer(buf, tmp);
2399                 buf_size += INITIAL_BUFFER_SIZE;
2400
2401                 if (buf_size > MAX_BUFFER_SIZE) {
2402                         DEBUG(2, ("Oversized message\n"));
2403                         x_fprintf(x_stderr, "ERR\n");
2404                         talloc_free(buf);
2405                         return;
2406                 }
2407
2408                 c = strchr(buf, '\n');
2409         } while (c == NULL);
2410
2411         *c = '\0';
2412         length = c-buf;
2413
2414         DEBUG(10, ("Got '%s' from squid (length: %d).\n",buf,length));
2415
2416         if (buf[0] == '\0') {
2417                 DEBUG(2, ("Invalid Request\n"));
2418                 x_fprintf(x_stderr, "ERR\n");
2419                 talloc_free(buf);
2420                 return;
2421         }
2422
2423         fn(state, buf, length);
2424         talloc_free(buf);
2425 }
2426
2427
2428 static void squid_stream(enum stdio_helper_mode stdio_mode, stdio_helper_function fn) {
2429         TALLOC_CTX *mem_ctx;
2430         struct ntlm_auth_state *state;
2431
2432         /* initialize FDescs */
2433         x_setbuf(x_stdout, NULL);
2434         x_setbuf(x_stderr, NULL);
2435
2436         mem_ctx = talloc_init("ntlm_auth");
2437         if (!mem_ctx) {
2438                 DEBUG(0, ("squid_stream: Failed to create talloc context\n"));
2439                 x_fprintf(x_stderr, "ERR\n");
2440                 exit(1);
2441         }
2442
2443         state = talloc_zero(mem_ctx, struct ntlm_auth_state);
2444         if (!state) {
2445                 DEBUG(0, ("squid_stream: Failed to talloc ntlm_auth_state\n"));
2446                 x_fprintf(x_stderr, "ERR\n");
2447                 exit(1);
2448         }
2449
2450         state->mem_ctx = mem_ctx;
2451         state->helper_mode = stdio_mode;
2452
2453         while(1) {
2454                 TALLOC_CTX *frame = talloc_stackframe();
2455                 manage_squid_request(state, fn);
2456                 TALLOC_FREE(frame);
2457         }
2458 }
2459
2460
2461 /* Authenticate a user with a challenge/response */
2462
2463 static bool check_auth_crap(void)
2464 {
2465         NTSTATUS nt_status;
2466         uint32 flags = 0;
2467         char lm_key[8];
2468         char user_session_key[16];
2469         char *hex_lm_key;
2470         char *hex_user_session_key;
2471         char *error_string;
2472         static uint8 zeros[16];
2473
2474         x_setbuf(x_stdout, NULL);
2475
2476         if (request_lm_key) 
2477                 flags |= WBFLAG_PAM_LMKEY;
2478
2479         if (request_user_session_key) 
2480                 flags |= WBFLAG_PAM_USER_SESSION_KEY;
2481
2482         flags |= WBFLAG_PAM_NT_STATUS_SQUASH;
2483
2484         nt_status = contact_winbind_auth_crap(opt_username, opt_domain, 
2485                                               opt_workstation,
2486                                               &opt_challenge, 
2487                                               &opt_lm_response, 
2488                                               &opt_nt_response, 
2489                                               flags,
2490                                               (unsigned char *)lm_key, 
2491                                               (unsigned char *)user_session_key, 
2492                                               &error_string, NULL);
2493
2494         if (!NT_STATUS_IS_OK(nt_status)) {
2495                 x_fprintf(x_stdout, "%s (0x%x)\n", 
2496                           error_string,
2497                           NT_STATUS_V(nt_status));
2498                 SAFE_FREE(error_string);
2499                 return False;
2500         }
2501
2502         if (request_lm_key 
2503             && (memcmp(zeros, lm_key, 
2504                        sizeof(lm_key)) != 0)) {
2505                 hex_lm_key = hex_encode_talloc(talloc_tos(), (const unsigned char *)lm_key,
2506                                         sizeof(lm_key));
2507                 x_fprintf(x_stdout, "LM_KEY: %s\n", hex_lm_key);
2508                 TALLOC_FREE(hex_lm_key);
2509         }
2510         if (request_user_session_key 
2511             && (memcmp(zeros, user_session_key, 
2512                        sizeof(user_session_key)) != 0)) {
2513                 hex_user_session_key = hex_encode_talloc(talloc_tos(), (const unsigned char *)user_session_key, 
2514                                                   sizeof(user_session_key));
2515                 x_fprintf(x_stdout, "NT_KEY: %s\n", hex_user_session_key);
2516                 TALLOC_FREE(hex_user_session_key);
2517         }
2518
2519         return True;
2520 }
2521
2522 /* Main program */
2523
2524 enum {
2525         OPT_USERNAME = 1000,
2526         OPT_DOMAIN,
2527         OPT_WORKSTATION,
2528         OPT_CHALLENGE,
2529         OPT_RESPONSE,
2530         OPT_LM,
2531         OPT_NT,
2532         OPT_PASSWORD,
2533         OPT_LM_KEY,
2534         OPT_USER_SESSION_KEY,
2535         OPT_DIAGNOSTICS,
2536         OPT_REQUIRE_MEMBERSHIP,
2537         OPT_USE_CACHED_CREDS,
2538         OPT_PAM_WINBIND_CONF
2539 };
2540
2541  int main(int argc, const char **argv)
2542 {
2543         TALLOC_CTX *frame = talloc_stackframe();
2544         int opt;
2545         static const char *helper_protocol;
2546         static int diagnostics;
2547
2548         static const char *hex_challenge;
2549         static const char *hex_lm_response;
2550         static const char *hex_nt_response;
2551
2552         poptContext pc;
2553
2554         /* NOTE: DO NOT change this interface without considering the implications!
2555            This is an external interface, which other programs will use to interact 
2556            with this helper.
2557         */
2558
2559         /* We do not use single-letter command abbreviations, because they harm future 
2560            interface stability. */
2561
2562         struct poptOption long_options[] = {
2563                 POPT_AUTOHELP
2564                 { "helper-protocol", 0, POPT_ARG_STRING, &helper_protocol, OPT_DOMAIN, "operate as a stdio-based helper", "helper protocol to use"},
2565                 { "username", 0, POPT_ARG_STRING, &opt_username, OPT_USERNAME, "username"},
2566                 { "domain", 0, POPT_ARG_STRING, &opt_domain, OPT_DOMAIN, "domain name"},
2567                 { "workstation", 0, POPT_ARG_STRING, &opt_workstation, OPT_WORKSTATION, "workstation"},
2568                 { "challenge", 0, POPT_ARG_STRING, &hex_challenge, OPT_CHALLENGE, "challenge (HEX encoded)"},
2569                 { "lm-response", 0, POPT_ARG_STRING, &hex_lm_response, OPT_LM, "LM Response to the challenge (HEX encoded)"},
2570                 { "nt-response", 0, POPT_ARG_STRING, &hex_nt_response, OPT_NT, "NT or NTLMv2 Response to the challenge (HEX encoded)"},
2571                 { "password", 0, POPT_ARG_STRING, &opt_password, OPT_PASSWORD, "User's plaintext password"},            
2572                 { "request-lm-key", 0, POPT_ARG_NONE, &request_lm_key, OPT_LM_KEY, "Retrieve LM session key"},
2573                 { "request-nt-key", 0, POPT_ARG_NONE, &request_user_session_key, OPT_USER_SESSION_KEY, "Retrieve User (NT) session key"},
2574                 { "use-cached-creds", 0, POPT_ARG_NONE, &use_cached_creds, OPT_USE_CACHED_CREDS, "Use cached credentials if no password is given"},
2575                 { "diagnostics", 0, POPT_ARG_NONE, &diagnostics,
2576                   OPT_DIAGNOSTICS,
2577                   "Perform diagnostics on the authentication chain"},
2578                 { "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" },
2579                 { "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" },
2580                 POPT_COMMON_CONFIGFILE
2581                 POPT_COMMON_VERSION
2582                 POPT_TABLEEND
2583         };
2584
2585         /* Samba client initialisation */
2586         load_case_tables();
2587
2588         setup_logging("ntlm_auth", DEBUG_STDERR);
2589
2590         /* Parse options */
2591
2592         pc = poptGetContext("ntlm_auth", argc, argv, long_options, 0);
2593
2594         /* Parse command line options */
2595
2596         if (argc == 1) {
2597                 poptPrintHelp(pc, stderr, 0);
2598                 return 1;
2599         }
2600
2601         while((opt = poptGetNextOpt(pc)) != -1) {
2602                 /* Get generic config options like --configfile */
2603         }
2604
2605         poptFreeContext(pc);
2606
2607         if (!lp_load_global(get_dyn_CONFIGFILE())) {
2608                 d_fprintf(stderr, "ntlm_auth: error opening config file %s. Error was %s\n",
2609                         get_dyn_CONFIGFILE(), strerror(errno));
2610                 exit(1);
2611         }
2612
2613         pc = poptGetContext(NULL, argc, (const char **)argv, long_options, 
2614                             POPT_CONTEXT_KEEP_FIRST);
2615
2616         while((opt = poptGetNextOpt(pc)) != -1) {
2617                 switch (opt) {
2618                 case OPT_CHALLENGE:
2619                         opt_challenge = strhex_to_data_blob(NULL, hex_challenge);
2620                         if (opt_challenge.length != 8) {
2621                                 x_fprintf(x_stderr, "hex decode of %s failed! (only got %d bytes)\n", 
2622                                           hex_challenge,
2623                                           (int)opt_challenge.length);
2624                                 exit(1);
2625                         }
2626                         break;
2627                 case OPT_LM: 
2628                         opt_lm_response = strhex_to_data_blob(NULL, hex_lm_response);
2629                         if (opt_lm_response.length != 24) {
2630                                 x_fprintf(x_stderr, "hex decode of %s failed! (only got %d bytes)\n", 
2631                                           hex_lm_response,
2632                                           (int)opt_lm_response.length);
2633                                 exit(1);
2634                         }
2635                         break;
2636
2637                 case OPT_NT: 
2638                         opt_nt_response = strhex_to_data_blob(NULL, hex_nt_response);
2639                         if (opt_nt_response.length < 24) {
2640                                 x_fprintf(x_stderr, "hex decode of %s failed! (only got %d bytes)\n", 
2641                                           hex_nt_response,
2642                                           (int)opt_nt_response.length);
2643                                 exit(1);
2644                         }
2645                         break;
2646
2647                 case OPT_REQUIRE_MEMBERSHIP:
2648                         if (strncasecmp_m("S-", require_membership_of, 2) == 0) {
2649                                 require_membership_of_sid = require_membership_of;
2650                         }
2651                         break;
2652                 }
2653         }
2654
2655         if (opt_username) {
2656                 char *domain = SMB_STRDUP(opt_username);
2657                 char *p = strchr_m(domain, *lp_winbind_separator());
2658                 if (p) {
2659                         opt_username = p+1;
2660                         *p = '\0';
2661                         if (opt_domain && !strequal(opt_domain, domain)) {
2662                                 x_fprintf(x_stderr, "Domain specified in username (%s) "
2663                                         "doesn't match specified domain (%s)!\n\n",
2664                                         domain, opt_domain);
2665                                 poptPrintHelp(pc, stderr, 0);
2666                                 exit(1);
2667                         }
2668                         opt_domain = domain;
2669                 } else {
2670                         SAFE_FREE(domain);
2671                 }
2672         }
2673
2674         /* Note: if opt_domain is "" then send no domain */
2675         if (opt_domain == NULL) {
2676                 opt_domain = get_winbind_domain();
2677         }
2678
2679         if (opt_workstation == NULL) {
2680                 opt_workstation = "";
2681         }
2682
2683         if (helper_protocol) {
2684                 int i;
2685                 for (i=0; i<NUM_HELPER_MODES; i++) {
2686                         if (strcmp(helper_protocol, stdio_helper_protocols[i].name) == 0) {
2687                                 squid_stream(stdio_helper_protocols[i].mode, stdio_helper_protocols[i].fn);
2688                                 exit(0);
2689                         }
2690                 }
2691                 x_fprintf(x_stderr, "unknown helper protocol [%s]\n\nValid helper protools:\n\n", helper_protocol);
2692
2693                 for (i=0; i<NUM_HELPER_MODES; i++) {
2694                         x_fprintf(x_stderr, "%s\n", stdio_helper_protocols[i].name);
2695                 }
2696
2697                 exit(1);
2698         }
2699
2700         if (!opt_username || !*opt_username) {
2701                 x_fprintf(x_stderr, "username must be specified!\n\n");
2702                 poptPrintHelp(pc, stderr, 0);
2703                 exit(1);
2704         }
2705
2706         if (opt_challenge.length) {
2707                 if (!check_auth_crap()) {
2708                         exit(1);
2709                 }
2710                 exit(0);
2711         } 
2712
2713         if (!opt_password) {
2714                 opt_password = getpass("password: ");
2715         }
2716
2717         if (diagnostics) {
2718                 if (!diagnose_ntlm_auth()) {
2719                         return 1;
2720                 }
2721         } else {
2722                 fstring user;
2723
2724                 fstr_sprintf(user, "%s%c%s", opt_domain, winbind_separator(), opt_username);
2725                 if (!check_plaintext_auth(user, opt_password, True)) {
2726                         return 1;
2727                 }
2728         }
2729
2730         /* Exit code */
2731
2732         poptFreeContext(pc);
2733         TALLOC_FREE(frame);
2734         return 0;
2735 }