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