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