bbf32f963b4dd920c4c0ee3de478006773f903b8
[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, 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         data_blob_free(&session_key_krb5);
2030
2031         ZERO_STRUCT(reply);
2032
2033         reply.type = SPNEGO_NEG_TOKEN_INIT;
2034         reply.negTokenInit.mechTypes = my_mechs;
2035         reply.negTokenInit.reqFlags = data_blob_null;
2036         reply.negTokenInit.reqFlagsPadding = 0;
2037         reply.negTokenInit.mechToken = tkt;
2038         reply.negTokenInit.mechListMIC = data_blob_null;
2039
2040         len = spnego_write_data(ctx, &to_server, &reply);
2041         data_blob_free(&tkt);
2042
2043         if (len == -1) {
2044                 DEBUG(1, ("Could not write SPNEGO data blob\n"));
2045                 return False;
2046         }
2047
2048         reply_base64 = base64_encode_data_blob(talloc_tos(), to_server);
2049         x_fprintf(x_stdout, "KK %s *\n", reply_base64);
2050
2051         TALLOC_FREE(reply_base64);
2052         data_blob_free(&to_server);
2053         DEBUG(10, ("sent GSS-SPNEGO KERBEROS5 negTokenInit\n"));
2054         return True;
2055 }
2056
2057 static void manage_client_krb5_targ(struct spnego_data spnego)
2058 {
2059         switch (spnego.negTokenTarg.negResult) {
2060         case SPNEGO_ACCEPT_INCOMPLETE:
2061                 DEBUG(1, ("Got a Kerberos negTokenTarg with ACCEPT_INCOMPLETE\n"));
2062                 x_fprintf(x_stdout, "BH Got a Kerberos negTokenTarg with "
2063                                     "ACCEPT_INCOMPLETE\n");
2064                 break;
2065         case SPNEGO_ACCEPT_COMPLETED:
2066                 DEBUG(10, ("Accept completed\n"));
2067                 x_fprintf(x_stdout, "AF\n");
2068                 break;
2069         case SPNEGO_REJECT:
2070                 DEBUG(10, ("Rejected\n"));
2071                 x_fprintf(x_stdout, "NA\n");
2072                 break;
2073         default:
2074                 DEBUG(1, ("Got an invalid negTokenTarg\n"));
2075                 x_fprintf(x_stdout, "AF\n");
2076         }
2077 }
2078
2079 #endif
2080
2081 static void manage_gss_spnego_client_request(struct ntlm_auth_state *state,
2082                                                 char *buf, int length)
2083 {
2084         DATA_BLOB request;
2085         struct spnego_data spnego;
2086         ssize_t len;
2087         TALLOC_CTX *ctx = talloc_tos();
2088
2089         if (!opt_username || !*opt_username) {
2090                 x_fprintf(x_stderr, "username must be specified!\n\n");
2091                 exit(1);
2092         }
2093
2094         if (strlen(buf) <= 3) {
2095                 DEBUG(1, ("SPNEGO query [%s] too short\n", buf));
2096                 x_fprintf(x_stdout, "BH SPNEGO query too short\n");
2097                 return;
2098         }
2099
2100         request = base64_decode_data_blob(buf+3);
2101
2102         if (strncmp(buf, "PW ", 3) == 0) {
2103
2104                 /* We asked for a password and obviously got it :-) */
2105
2106                 opt_password = SMB_STRNDUP((const char *)request.data, request.length);
2107
2108                 if (opt_password == NULL) {
2109                         DEBUG(1, ("Out of memory\n"));
2110                         x_fprintf(x_stdout, "BH Out of memory\n");
2111                         data_blob_free(&request);
2112                         return;
2113                 }
2114
2115                 x_fprintf(x_stdout, "OK\n");
2116                 data_blob_free(&request);
2117                 return;
2118         }
2119
2120         if ( (strncmp(buf, "TT ", 3) != 0) &&
2121              (strncmp(buf, "AF ", 3) != 0) &&
2122              (strncmp(buf, "NA ", 3) != 0) ) {
2123                 DEBUG(1, ("SPNEGO request [%s] invalid\n", buf));
2124                 x_fprintf(x_stdout, "BH SPNEGO request invalid\n");
2125                 data_blob_free(&request);
2126                 return;
2127         }
2128
2129         /* So we got a server challenge to generate a SPNEGO
2130            client-to-server request... */
2131
2132         len = spnego_read_data(ctx, request, &spnego);
2133         data_blob_free(&request);
2134
2135         if (len == -1) {
2136                 DEBUG(1, ("Could not read SPNEGO data for [%s]\n", buf));
2137                 x_fprintf(x_stdout, "BH Could not read SPNEGO data\n");
2138                 return;
2139         }
2140
2141         if (spnego.type == SPNEGO_NEG_TOKEN_INIT) {
2142
2143                 /* The server offers a list of mechanisms */
2144
2145                 const char **mechType = (const char **)spnego.negTokenInit.mechTypes;
2146
2147                 while (*mechType != NULL) {
2148
2149 #ifdef HAVE_KRB5
2150                         if ( (strcmp(*mechType, OID_KERBEROS5_OLD) == 0) ||
2151                              (strcmp(*mechType, OID_KERBEROS5) == 0) ) {
2152                                 if (manage_client_krb5_init(spnego))
2153                                         goto out;
2154                         }
2155 #endif
2156
2157                         if (strcmp(*mechType, OID_NTLMSSP) == 0) {
2158                                 if (manage_client_ntlmssp_init(spnego))
2159                                         goto out;
2160                         }
2161
2162                         mechType++;
2163                 }
2164
2165                 DEBUG(1, ("Server offered no compatible mechanism\n"));
2166                 x_fprintf(x_stdout, "BH Server offered no compatible mechanism\n");
2167                 return;
2168         }
2169
2170         if (spnego.type == SPNEGO_NEG_TOKEN_TARG) {
2171
2172                 if (spnego.negTokenTarg.supportedMech == NULL) {
2173                         /* On accept/reject Windows does not send the
2174                            mechanism anymore. Handle that here and
2175                            shut down the mechanisms. */
2176
2177                         switch (spnego.negTokenTarg.negResult) {
2178                         case SPNEGO_ACCEPT_COMPLETED:
2179                                 x_fprintf(x_stdout, "AF\n");
2180                                 break;
2181                         case SPNEGO_REJECT:
2182                                 x_fprintf(x_stdout, "NA\n");
2183                                 break;
2184                         default:
2185                                 DEBUG(1, ("Got a negTokenTarg with no mech and an "
2186                                           "unknown negResult: %d\n",
2187                                           spnego.negTokenTarg.negResult));
2188                                 x_fprintf(x_stdout, "BH Got a negTokenTarg with"
2189                                                     " no mech and an unknown "
2190                                                     "negResult\n");
2191                         }
2192
2193                         TALLOC_FREE(client_ntlmssp_state);
2194                         goto out;
2195                 }
2196
2197                 if (strcmp(spnego.negTokenTarg.supportedMech,
2198                            OID_NTLMSSP) == 0) {
2199                         manage_client_ntlmssp_targ(spnego);
2200                         goto out;
2201                 }
2202
2203 #if HAVE_KRB5
2204                 if (strcmp(spnego.negTokenTarg.supportedMech,
2205                            OID_KERBEROS5_OLD) == 0) {
2206                         manage_client_krb5_targ(spnego);
2207                         goto out;
2208                 }
2209 #endif
2210
2211         }
2212
2213         DEBUG(1, ("Got an SPNEGO token I could not handle [%s]!\n", buf));
2214         x_fprintf(x_stdout, "BH Got an SPNEGO token I could not handle\n");
2215         return;
2216
2217  out:
2218         spnego_free_data(&spnego);
2219         return;
2220 }
2221
2222 static void manage_ntlm_server_1_request(struct ntlm_auth_state *state,
2223                                                 char *buf, int length)
2224 {
2225         char *request, *parameter;      
2226         static DATA_BLOB challenge;
2227         static DATA_BLOB lm_response;
2228         static DATA_BLOB nt_response;
2229         static char *full_username;
2230         static char *username;
2231         static char *domain;
2232         static char *plaintext_password;
2233         static bool ntlm_server_1_user_session_key;
2234         static bool ntlm_server_1_lm_session_key;
2235
2236         if (strequal(buf, ".")) {
2237                 if (!full_username && !username) {      
2238                         x_fprintf(x_stdout, "Error: No username supplied!\n");
2239                 } else if (plaintext_password) {
2240                         /* handle this request as plaintext */
2241                         if (!full_username) {
2242                                 if (asprintf(&full_username, "%s%c%s", domain, winbind_separator(), username) == -1) {
2243                                         x_fprintf(x_stdout, "Error: Out of memory in asprintf!\n.\n");
2244                                         return;
2245                                 }
2246                         }
2247                         if (check_plaintext_auth(full_username, plaintext_password, False)) {
2248                                 x_fprintf(x_stdout, "Authenticated: Yes\n");
2249                         } else {
2250                                 x_fprintf(x_stdout, "Authenticated: No\n");
2251                         }
2252                 } else if (!lm_response.data && !nt_response.data) {
2253                         x_fprintf(x_stdout, "Error: No password supplied!\n");
2254                 } else if (!challenge.data) {   
2255                         x_fprintf(x_stdout, "Error: No lanman-challenge supplied!\n");
2256                 } else {
2257                         char *error_string = NULL;
2258                         uchar lm_key[8];
2259                         uchar user_session_key[16];
2260                         uint32 flags = 0;
2261
2262                         if (full_username && !username) {
2263                                 fstring fstr_user;
2264                                 fstring fstr_domain;
2265
2266                                 if (!parse_ntlm_auth_domain_user(full_username, fstr_user, fstr_domain)) {
2267                                         /* username might be 'tainted', don't print into our new-line deleimianted stream */
2268                                         x_fprintf(x_stdout, "Error: Could not parse into domain and username\n");
2269                                 }
2270                                 SAFE_FREE(username);
2271                                 SAFE_FREE(domain);
2272                                 username = smb_xstrdup(fstr_user);
2273                                 domain = smb_xstrdup(fstr_domain);
2274                         }
2275
2276                         if (!domain) {
2277                                 domain = smb_xstrdup(get_winbind_domain());
2278                         }
2279
2280                         if (ntlm_server_1_lm_session_key) 
2281                                 flags |= WBFLAG_PAM_LMKEY;
2282
2283                         if (ntlm_server_1_user_session_key) 
2284                                 flags |= WBFLAG_PAM_USER_SESSION_KEY;
2285
2286                         if (!NT_STATUS_IS_OK(
2287                                     contact_winbind_auth_crap(username, 
2288                                                               domain, 
2289                                                               lp_netbios_name(),
2290                                                               &challenge, 
2291                                                               &lm_response, 
2292                                                               &nt_response, 
2293                                                               flags, 0,
2294                                                               lm_key, 
2295                                                               user_session_key,
2296                                                               &error_string,
2297                                                               NULL))) {
2298
2299                                 x_fprintf(x_stdout, "Authenticated: No\n");
2300                                 x_fprintf(x_stdout, "Authentication-Error: %s\n.\n", error_string);
2301                         } else {
2302                                 static char zeros[16];
2303                                 char *hex_lm_key;
2304                                 char *hex_user_session_key;
2305
2306                                 x_fprintf(x_stdout, "Authenticated: Yes\n");
2307
2308                                 if (ntlm_server_1_lm_session_key 
2309                                     && (memcmp(zeros, lm_key, 
2310                                                sizeof(lm_key)) != 0)) {
2311                                         hex_lm_key = hex_encode_talloc(NULL,
2312                                                                 (const unsigned char *)lm_key,
2313                                                                 sizeof(lm_key));
2314                                         x_fprintf(x_stdout, "LANMAN-Session-Key: %s\n", hex_lm_key);
2315                                         TALLOC_FREE(hex_lm_key);
2316                                 }
2317
2318                                 if (ntlm_server_1_user_session_key 
2319                                     && (memcmp(zeros, user_session_key, 
2320                                                sizeof(user_session_key)) != 0)) {
2321                                         hex_user_session_key = hex_encode_talloc(NULL,
2322                                                                           (const unsigned char *)user_session_key, 
2323                                                                           sizeof(user_session_key));
2324                                         x_fprintf(x_stdout, "User-Session-Key: %s\n", hex_user_session_key);
2325                                         TALLOC_FREE(hex_user_session_key);
2326                                 }
2327                         }
2328                         SAFE_FREE(error_string);
2329                 }
2330                 /* clear out the state */
2331                 challenge = data_blob_null;
2332                 nt_response = data_blob_null;
2333                 lm_response = data_blob_null;
2334                 SAFE_FREE(full_username);
2335                 SAFE_FREE(username);
2336                 SAFE_FREE(domain);
2337                 SAFE_FREE(plaintext_password);
2338                 ntlm_server_1_user_session_key = False;
2339                 ntlm_server_1_lm_session_key = False;
2340                 x_fprintf(x_stdout, ".\n");
2341
2342                 return;
2343         }
2344
2345         request = buf;
2346
2347         /* Indicates a base64 encoded structure */
2348         parameter = strstr_m(request, ":: ");
2349         if (!parameter) {
2350                 parameter = strstr_m(request, ": ");
2351
2352                 if (!parameter) {
2353                         DEBUG(0, ("Parameter not found!\n"));
2354                         x_fprintf(x_stdout, "Error: Parameter not found!\n.\n");
2355                         return;
2356                 }
2357
2358                 parameter[0] ='\0';
2359                 parameter++;
2360                 parameter[0] ='\0';
2361                 parameter++;
2362
2363         } else {
2364                 parameter[0] ='\0';
2365                 parameter++;
2366                 parameter[0] ='\0';
2367                 parameter++;
2368                 parameter[0] ='\0';
2369                 parameter++;
2370
2371                 base64_decode_inplace(parameter);
2372         }
2373
2374         if (strequal(request, "LANMAN-Challenge")) {
2375                 challenge = strhex_to_data_blob(NULL, parameter);
2376                 if (challenge.length != 8) {
2377                         x_fprintf(x_stdout, "Error: hex decode of %s failed! (got %d bytes, expected 8)\n.\n", 
2378                                   parameter,
2379                                   (int)challenge.length);
2380                         challenge = data_blob_null;
2381                 }
2382         } else if (strequal(request, "NT-Response")) {
2383                 nt_response = strhex_to_data_blob(NULL, parameter);
2384                 if (nt_response.length < 24) {
2385                         x_fprintf(x_stdout, "Error: hex decode of %s failed! (only got %d bytes, needed at least 24)\n.\n", 
2386                                   parameter,
2387                                   (int)nt_response.length);
2388                         nt_response = data_blob_null;
2389                 }
2390         } else if (strequal(request, "LANMAN-Response")) {
2391                 lm_response = strhex_to_data_blob(NULL, parameter);
2392                 if (lm_response.length != 24) {
2393                         x_fprintf(x_stdout, "Error: hex decode of %s failed! (got %d bytes, expected 24)\n.\n", 
2394                                   parameter,
2395                                   (int)lm_response.length);
2396                         lm_response = data_blob_null;
2397                 }
2398         } else if (strequal(request, "Password")) {
2399                 plaintext_password = smb_xstrdup(parameter);
2400         } else if (strequal(request, "NT-Domain")) {
2401                 domain = smb_xstrdup(parameter);
2402         } else if (strequal(request, "Username")) {
2403                 username = smb_xstrdup(parameter);
2404         } else if (strequal(request, "Full-Username")) {
2405                 full_username = smb_xstrdup(parameter);
2406         } else if (strequal(request, "Request-User-Session-Key")) {
2407                 ntlm_server_1_user_session_key = strequal(parameter, "Yes");
2408         } else if (strequal(request, "Request-LanMan-Session-Key")) {
2409                 ntlm_server_1_lm_session_key = strequal(parameter, "Yes");
2410         } else {
2411                 x_fprintf(x_stdout, "Error: Unknown request %s\n.\n", request);
2412         }
2413 }
2414
2415 static void manage_ntlm_change_password_1_request(struct ntlm_auth_state *state,
2416                                                         char *buf, int length)
2417 {
2418         char *request, *parameter;      
2419         static DATA_BLOB new_nt_pswd;
2420         static DATA_BLOB old_nt_hash_enc;
2421         static DATA_BLOB new_lm_pswd;
2422         static DATA_BLOB old_lm_hash_enc;
2423         static char *full_username = NULL;
2424         static char *username = NULL;
2425         static char *domain = NULL;
2426         static char *newpswd =  NULL;
2427         static char *oldpswd = NULL;
2428
2429         if (strequal(buf, ".")) {
2430                 if(newpswd && oldpswd) {
2431                         uchar old_nt_hash[16];
2432                         uchar old_lm_hash[16];
2433                         uchar new_nt_hash[16];
2434                         uchar new_lm_hash[16];
2435
2436                         new_nt_pswd = data_blob(NULL, 516);
2437                         old_nt_hash_enc = data_blob(NULL, 16);
2438
2439                         /* Calculate the MD4 hash (NT compatible) of the
2440                          * password */
2441                         E_md4hash(oldpswd, old_nt_hash);
2442                         E_md4hash(newpswd, new_nt_hash);
2443
2444                         /* E_deshash returns false for 'long'
2445                            passwords (> 14 DOS chars).  
2446
2447                            Therefore, don't send a buffer
2448                            encrypted with the truncated hash
2449                            (it could allow an even easier
2450                            attack on the password)
2451
2452                            Likewise, obey the admin's restriction
2453                         */
2454
2455                         if (lp_client_lanman_auth() &&
2456                             E_deshash(newpswd, new_lm_hash) &&
2457                             E_deshash(oldpswd, old_lm_hash)) {
2458                                 new_lm_pswd = data_blob(NULL, 516);
2459                                 old_lm_hash_enc = data_blob(NULL, 16);
2460                                 encode_pw_buffer(new_lm_pswd.data, newpswd,
2461                                                  STR_UNICODE);
2462
2463                                 arcfour_crypt(new_lm_pswd.data, old_nt_hash, 516);
2464                                 E_old_pw_hash(new_nt_hash, old_lm_hash,
2465                                               old_lm_hash_enc.data);
2466                         } else {
2467                                 new_lm_pswd.data = NULL;
2468                                 new_lm_pswd.length = 0;
2469                                 old_lm_hash_enc.data = NULL;
2470                                 old_lm_hash_enc.length = 0;
2471                         }
2472
2473                         encode_pw_buffer(new_nt_pswd.data, newpswd,
2474                                          STR_UNICODE);
2475
2476                         arcfour_crypt(new_nt_pswd.data, old_nt_hash, 516);
2477                         E_old_pw_hash(new_nt_hash, old_nt_hash,
2478                                       old_nt_hash_enc.data);
2479                 }
2480
2481                 if (!full_username && !username) {      
2482                         x_fprintf(x_stdout, "Error: No username supplied!\n");
2483                 } else if ((!new_nt_pswd.data || !old_nt_hash_enc.data) &&
2484                            (!new_lm_pswd.data || old_lm_hash_enc.data) ) {
2485                         x_fprintf(x_stdout, "Error: No NT or LM password "
2486                                   "blobs supplied!\n");
2487                 } else {
2488                         char *error_string = NULL;
2489
2490                         if (full_username && !username) {
2491                                 fstring fstr_user;
2492                                 fstring fstr_domain;
2493
2494                                 if (!parse_ntlm_auth_domain_user(full_username,
2495                                                                  fstr_user,
2496                                                                  fstr_domain)) {
2497                                         /* username might be 'tainted', don't
2498                                          * print into our new-line
2499                                          * deleimianted stream */
2500                                         x_fprintf(x_stdout, "Error: Could not "
2501                                                   "parse into domain and "
2502                                                   "username\n");
2503                                         SAFE_FREE(username);
2504                                         username = smb_xstrdup(full_username);
2505                                 } else {
2506                                         SAFE_FREE(username);
2507                                         SAFE_FREE(domain);
2508                                         username = smb_xstrdup(fstr_user);
2509                                         domain = smb_xstrdup(fstr_domain);
2510                                 }
2511
2512                         }
2513
2514                         if(!NT_STATUS_IS_OK(contact_winbind_change_pswd_auth_crap(
2515                                                     username, domain,
2516                                                     new_nt_pswd,
2517                                                     old_nt_hash_enc,
2518                                                     new_lm_pswd,
2519                                                     old_lm_hash_enc,
2520                                                     &error_string))) {
2521                                 x_fprintf(x_stdout, "Password-Change: No\n");
2522                                 x_fprintf(x_stdout, "Password-Change-Error: "
2523                                           "%s\n.\n", error_string);
2524                         } else {
2525                                 x_fprintf(x_stdout, "Password-Change: Yes\n");
2526                         }
2527
2528                         SAFE_FREE(error_string);
2529                 }
2530                 /* clear out the state */
2531                 new_nt_pswd = data_blob_null;
2532                 old_nt_hash_enc = data_blob_null;
2533                 new_lm_pswd = data_blob_null;
2534                 old_nt_hash_enc = data_blob_null;
2535                 SAFE_FREE(full_username);
2536                 SAFE_FREE(username);
2537                 SAFE_FREE(domain);
2538                 SAFE_FREE(newpswd);
2539                 SAFE_FREE(oldpswd);
2540                 x_fprintf(x_stdout, ".\n");
2541
2542                 return;
2543         }
2544
2545         request = buf;
2546
2547         /* Indicates a base64 encoded structure */
2548         parameter = strstr_m(request, ":: ");
2549         if (!parameter) {
2550                 parameter = strstr_m(request, ": ");
2551
2552                 if (!parameter) {
2553                         DEBUG(0, ("Parameter not found!\n"));
2554                         x_fprintf(x_stdout, "Error: Parameter not found!\n.\n");
2555                         return;
2556                 }
2557
2558                 parameter[0] ='\0';
2559                 parameter++;
2560                 parameter[0] ='\0';
2561                 parameter++;
2562         } else {
2563                 parameter[0] ='\0';
2564                 parameter++;
2565                 parameter[0] ='\0';
2566                 parameter++;
2567                 parameter[0] ='\0';
2568                 parameter++;
2569
2570                 base64_decode_inplace(parameter);
2571         }
2572
2573         if (strequal(request, "new-nt-password-blob")) {
2574                 new_nt_pswd = strhex_to_data_blob(NULL, parameter);
2575                 if (new_nt_pswd.length != 516) {
2576                         x_fprintf(x_stdout, "Error: hex decode of %s failed! "
2577                                   "(got %d bytes, expected 516)\n.\n", 
2578                                   parameter,
2579                                   (int)new_nt_pswd.length);
2580                         new_nt_pswd = data_blob_null;
2581                 }
2582         } else if (strequal(request, "old-nt-hash-blob")) {
2583                 old_nt_hash_enc = strhex_to_data_blob(NULL, parameter);
2584                 if (old_nt_hash_enc.length != 16) {
2585                         x_fprintf(x_stdout, "Error: hex decode of %s failed! "
2586                                   "(got %d bytes, expected 16)\n.\n", 
2587                                   parameter,
2588                                   (int)old_nt_hash_enc.length);
2589                         old_nt_hash_enc = data_blob_null;
2590                 }
2591         } else if (strequal(request, "new-lm-password-blob")) {
2592                 new_lm_pswd = strhex_to_data_blob(NULL, parameter);
2593                 if (new_lm_pswd.length != 516) {
2594                         x_fprintf(x_stdout, "Error: hex decode of %s failed! "
2595                                   "(got %d bytes, expected 516)\n.\n", 
2596                                   parameter,
2597                                   (int)new_lm_pswd.length);
2598                         new_lm_pswd = data_blob_null;
2599                 }
2600         }
2601         else if (strequal(request, "old-lm-hash-blob")) {
2602                 old_lm_hash_enc = strhex_to_data_blob(NULL, parameter);
2603                 if (old_lm_hash_enc.length != 16)
2604                 {
2605                         x_fprintf(x_stdout, "Error: hex decode of %s failed! "
2606                                   "(got %d bytes, expected 16)\n.\n", 
2607                                   parameter,
2608                                   (int)old_lm_hash_enc.length);
2609                         old_lm_hash_enc = data_blob_null;
2610                 }
2611         } else if (strequal(request, "nt-domain")) {
2612                 domain = smb_xstrdup(parameter);
2613         } else if(strequal(request, "username")) {
2614                 username = smb_xstrdup(parameter);
2615         } else if(strequal(request, "full-username")) {
2616                 username = smb_xstrdup(parameter);
2617         } else if(strequal(request, "new-password")) {
2618                 newpswd = smb_xstrdup(parameter);
2619         } else if (strequal(request, "old-password")) {
2620                 oldpswd = smb_xstrdup(parameter);
2621         } else {
2622                 x_fprintf(x_stdout, "Error: Unknown request %s\n.\n", request);
2623         }
2624 }
2625
2626 static void manage_squid_request(struct ntlm_auth_state *state,
2627                 stdio_helper_function fn)
2628 {
2629         char *buf;
2630         char tmp[INITIAL_BUFFER_SIZE+1];
2631         int length, buf_size = 0;
2632         char *c;
2633
2634         buf = talloc_strdup(state->mem_ctx, "");
2635         if (!buf) {
2636                 DEBUG(0, ("Failed to allocate input buffer.\n"));
2637                 x_fprintf(x_stderr, "ERR\n");
2638                 exit(1);
2639         }
2640
2641         do {
2642
2643                 /* this is not a typo - x_fgets doesn't work too well under
2644                  * squid */
2645                 if (fgets(tmp, sizeof(tmp)-1, stdin) == NULL) {
2646                         if (ferror(stdin)) {
2647                                 DEBUG(1, ("fgets() failed! dying..... errno=%d "
2648                                           "(%s)\n", ferror(stdin),
2649                                           strerror(ferror(stdin))));
2650
2651                                 exit(1);
2652                         }
2653                         exit(0);
2654                 }
2655
2656                 buf = talloc_strdup_append_buffer(buf, tmp);
2657                 buf_size += INITIAL_BUFFER_SIZE;
2658
2659                 if (buf_size > MAX_BUFFER_SIZE) {
2660                         DEBUG(2, ("Oversized message\n"));
2661                         x_fprintf(x_stderr, "ERR\n");
2662                         talloc_free(buf);
2663                         return;
2664                 }
2665
2666                 c = strchr(buf, '\n');
2667         } while (c == NULL);
2668
2669         *c = '\0';
2670         length = c-buf;
2671
2672         DEBUG(10, ("Got '%s' from squid (length: %d).\n",buf,length));
2673
2674         if (buf[0] == '\0') {
2675                 DEBUG(2, ("Invalid Request\n"));
2676                 x_fprintf(x_stderr, "ERR\n");
2677                 talloc_free(buf);
2678                 return;
2679         }
2680
2681         fn(state, buf, length);
2682         talloc_free(buf);
2683 }
2684
2685
2686 static void squid_stream(enum stdio_helper_mode stdio_mode, stdio_helper_function fn) {
2687         TALLOC_CTX *mem_ctx;
2688         struct ntlm_auth_state *state;
2689
2690         /* initialize FDescs */
2691         x_setbuf(x_stdout, NULL);
2692         x_setbuf(x_stderr, NULL);
2693
2694         mem_ctx = talloc_init("ntlm_auth");
2695         if (!mem_ctx) {
2696                 DEBUG(0, ("squid_stream: Failed to create talloc context\n"));
2697                 x_fprintf(x_stderr, "ERR\n");
2698                 exit(1);
2699         }
2700
2701         state = talloc_zero(mem_ctx, struct ntlm_auth_state);
2702         if (!state) {
2703                 DEBUG(0, ("squid_stream: Failed to talloc ntlm_auth_state\n"));
2704                 x_fprintf(x_stderr, "ERR\n");
2705                 exit(1);
2706         }
2707
2708         state->mem_ctx = mem_ctx;
2709         state->helper_mode = stdio_mode;
2710
2711         while(1) {
2712                 TALLOC_CTX *frame = talloc_stackframe();
2713                 manage_squid_request(state, fn);
2714                 TALLOC_FREE(frame);
2715         }
2716 }
2717
2718
2719 /* Authenticate a user with a challenge/response */
2720
2721 static bool check_auth_crap(void)
2722 {
2723         NTSTATUS nt_status;
2724         uint32 flags = 0;
2725         char lm_key[8];
2726         char user_session_key[16];
2727         char *hex_lm_key;
2728         char *hex_user_session_key;
2729         char *error_string;
2730         static uint8 zeros[16];
2731
2732         x_setbuf(x_stdout, NULL);
2733
2734         if (request_lm_key) 
2735                 flags |= WBFLAG_PAM_LMKEY;
2736
2737         if (request_user_session_key) 
2738                 flags |= WBFLAG_PAM_USER_SESSION_KEY;
2739
2740         flags |= WBFLAG_PAM_NT_STATUS_SQUASH;
2741
2742         nt_status = contact_winbind_auth_crap(opt_username, opt_domain, 
2743                                               opt_workstation,
2744                                               &opt_challenge, 
2745                                               &opt_lm_response, 
2746                                               &opt_nt_response, 
2747                                               flags, 0,
2748                                               (unsigned char *)lm_key, 
2749                                               (unsigned char *)user_session_key, 
2750                                               &error_string, NULL);
2751
2752         if (!NT_STATUS_IS_OK(nt_status)) {
2753                 x_fprintf(x_stdout, "%s (0x%x)\n", 
2754                           error_string,
2755                           NT_STATUS_V(nt_status));
2756                 SAFE_FREE(error_string);
2757                 return False;
2758         }
2759
2760         if (request_lm_key 
2761             && (memcmp(zeros, lm_key, 
2762                        sizeof(lm_key)) != 0)) {
2763                 hex_lm_key = hex_encode_talloc(talloc_tos(), (const unsigned char *)lm_key,
2764                                         sizeof(lm_key));
2765                 x_fprintf(x_stdout, "LM_KEY: %s\n", hex_lm_key);
2766                 TALLOC_FREE(hex_lm_key);
2767         }
2768         if (request_user_session_key 
2769             && (memcmp(zeros, user_session_key, 
2770                        sizeof(user_session_key)) != 0)) {
2771                 hex_user_session_key = hex_encode_talloc(talloc_tos(), (const unsigned char *)user_session_key, 
2772                                                   sizeof(user_session_key));
2773                 x_fprintf(x_stdout, "NT_KEY: %s\n", hex_user_session_key);
2774                 TALLOC_FREE(hex_user_session_key);
2775         }
2776
2777         return True;
2778 }
2779
2780 /* Main program */
2781
2782 enum {
2783         OPT_USERNAME = 1000,
2784         OPT_DOMAIN,
2785         OPT_WORKSTATION,
2786         OPT_CHALLENGE,
2787         OPT_RESPONSE,
2788         OPT_LM,
2789         OPT_NT,
2790         OPT_PASSWORD,
2791         OPT_LM_KEY,
2792         OPT_USER_SESSION_KEY,
2793         OPT_DIAGNOSTICS,
2794         OPT_REQUIRE_MEMBERSHIP,
2795         OPT_USE_CACHED_CREDS,
2796         OPT_PAM_WINBIND_CONF,
2797         OPT_TARGET_SERVICE,
2798         OPT_TARGET_HOSTNAME
2799 };
2800
2801  int main(int argc, const char **argv)
2802 {
2803         TALLOC_CTX *frame = talloc_stackframe();
2804         int opt;
2805         static const char *helper_protocol;
2806         static int diagnostics;
2807
2808         static const char *hex_challenge;
2809         static const char *hex_lm_response;
2810         static const char *hex_nt_response;
2811
2812         poptContext pc;
2813
2814         /* NOTE: DO NOT change this interface without considering the implications!
2815            This is an external interface, which other programs will use to interact 
2816            with this helper.
2817         */
2818
2819         /* We do not use single-letter command abbreviations, because they harm future 
2820            interface stability. */
2821
2822         struct poptOption long_options[] = {
2823                 POPT_AUTOHELP
2824                 { "helper-protocol", 0, POPT_ARG_STRING, &helper_protocol, OPT_DOMAIN, "operate as a stdio-based helper", "helper protocol to use"},
2825                 { "username", 0, POPT_ARG_STRING, &opt_username, OPT_USERNAME, "username"},
2826                 { "domain", 0, POPT_ARG_STRING, &opt_domain, OPT_DOMAIN, "domain name"},
2827                 { "workstation", 0, POPT_ARG_STRING, &opt_workstation, OPT_WORKSTATION, "workstation"},
2828                 { "challenge", 0, POPT_ARG_STRING, &hex_challenge, OPT_CHALLENGE, "challenge (HEX encoded)"},
2829                 { "lm-response", 0, POPT_ARG_STRING, &hex_lm_response, OPT_LM, "LM Response to the challenge (HEX encoded)"},
2830                 { "nt-response", 0, POPT_ARG_STRING, &hex_nt_response, OPT_NT, "NT or NTLMv2 Response to the challenge (HEX encoded)"},
2831                 { "password", 0, POPT_ARG_STRING, &opt_password, OPT_PASSWORD, "User's plaintext password"},            
2832                 { "request-lm-key", 0, POPT_ARG_NONE, &request_lm_key, OPT_LM_KEY, "Retrieve LM session key"},
2833                 { "request-nt-key", 0, POPT_ARG_NONE, &request_user_session_key, OPT_USER_SESSION_KEY, "Retrieve User (NT) session key"},
2834                 { "use-cached-creds", 0, POPT_ARG_NONE, &use_cached_creds, OPT_USE_CACHED_CREDS, "Use cached credentials if no password is given"},
2835                 { "diagnostics", 0, POPT_ARG_NONE, &diagnostics,
2836                   OPT_DIAGNOSTICS,
2837                   "Perform diagnostics on the authentication chain"},
2838                 { "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" },
2839                 { "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" },
2840                 { "target-service", 0, POPT_ARG_STRING, &opt_target_service, OPT_TARGET_SERVICE, "Target service (eg http)" },
2841                 { "target-hostname", 0, POPT_ARG_STRING, &opt_target_hostname, OPT_TARGET_HOSTNAME, "Target hostname" },
2842                 POPT_COMMON_CONFIGFILE
2843                 POPT_COMMON_VERSION
2844                 POPT_TABLEEND
2845         };
2846
2847         /* Samba client initialisation */
2848         load_case_tables();
2849
2850         setup_logging("ntlm_auth", DEBUG_STDERR);
2851
2852         /* Parse options */
2853
2854         pc = poptGetContext("ntlm_auth", argc, argv, long_options, 0);
2855
2856         /* Parse command line options */
2857
2858         if (argc == 1) {
2859                 poptPrintHelp(pc, stderr, 0);
2860                 return 1;
2861         }
2862
2863         while((opt = poptGetNextOpt(pc)) != -1) {
2864                 /* Get generic config options like --configfile */
2865         }
2866
2867         poptFreeContext(pc);
2868
2869         if (!lp_load_global(get_dyn_CONFIGFILE())) {
2870                 d_fprintf(stderr, "ntlm_auth: error opening config file %s. Error was %s\n",
2871                         get_dyn_CONFIGFILE(), strerror(errno));
2872                 exit(1);
2873         }
2874
2875         pc = poptGetContext(NULL, argc, (const char **)argv, long_options, 
2876                             POPT_CONTEXT_KEEP_FIRST);
2877
2878         while((opt = poptGetNextOpt(pc)) != -1) {
2879                 switch (opt) {
2880                 case OPT_CHALLENGE:
2881                         opt_challenge = strhex_to_data_blob(NULL, hex_challenge);
2882                         if (opt_challenge.length != 8) {
2883                                 x_fprintf(x_stderr, "hex decode of %s failed! (only got %d bytes)\n", 
2884                                           hex_challenge,
2885                                           (int)opt_challenge.length);
2886                                 exit(1);
2887                         }
2888                         break;
2889                 case OPT_LM: 
2890                         opt_lm_response = strhex_to_data_blob(NULL, hex_lm_response);
2891                         if (opt_lm_response.length != 24) {
2892                                 x_fprintf(x_stderr, "hex decode of %s failed! (only got %d bytes)\n", 
2893                                           hex_lm_response,
2894                                           (int)opt_lm_response.length);
2895                                 exit(1);
2896                         }
2897                         break;
2898
2899                 case OPT_NT: 
2900                         opt_nt_response = strhex_to_data_blob(NULL, hex_nt_response);
2901                         if (opt_nt_response.length < 24) {
2902                                 x_fprintf(x_stderr, "hex decode of %s failed! (only got %d bytes)\n", 
2903                                           hex_nt_response,
2904                                           (int)opt_nt_response.length);
2905                                 exit(1);
2906                         }
2907                         break;
2908
2909                 case OPT_REQUIRE_MEMBERSHIP:
2910                         if (strncasecmp_m("S-", require_membership_of, 2) == 0) {
2911                                 require_membership_of_sid = require_membership_of;
2912                         }
2913                         break;
2914                 }
2915         }
2916
2917         if (opt_username) {
2918                 char *domain = SMB_STRDUP(opt_username);
2919                 char *p = strchr_m(domain, *lp_winbind_separator());
2920                 if (p) {
2921                         opt_username = p+1;
2922                         *p = '\0';
2923                         if (opt_domain && !strequal(opt_domain, domain)) {
2924                                 x_fprintf(x_stderr, "Domain specified in username (%s) "
2925                                         "doesn't match specified domain (%s)!\n\n",
2926                                         domain, opt_domain);
2927                                 poptPrintHelp(pc, stderr, 0);
2928                                 exit(1);
2929                         }
2930                         opt_domain = domain;
2931                 } else {
2932                         SAFE_FREE(domain);
2933                 }
2934         }
2935
2936         /* Note: if opt_domain is "" then send no domain */
2937         if (opt_domain == NULL) {
2938                 opt_domain = get_winbind_domain();
2939         }
2940
2941         if (opt_workstation == NULL) {
2942                 opt_workstation = "";
2943         }
2944
2945         if (helper_protocol) {
2946                 int i;
2947                 for (i=0; i<NUM_HELPER_MODES; i++) {
2948                         if (strcmp(helper_protocol, stdio_helper_protocols[i].name) == 0) {
2949                                 squid_stream(stdio_helper_protocols[i].mode, stdio_helper_protocols[i].fn);
2950                                 exit(0);
2951                         }
2952                 }
2953                 x_fprintf(x_stderr, "unknown helper protocol [%s]\n\nValid helper protools:\n\n", helper_protocol);
2954
2955                 for (i=0; i<NUM_HELPER_MODES; i++) {
2956                         x_fprintf(x_stderr, "%s\n", stdio_helper_protocols[i].name);
2957                 }
2958
2959                 exit(1);
2960         }
2961
2962         if (!opt_username || !*opt_username) {
2963                 x_fprintf(x_stderr, "username must be specified!\n\n");
2964                 poptPrintHelp(pc, stderr, 0);
2965                 exit(1);
2966         }
2967
2968         if (opt_challenge.length) {
2969                 if (!check_auth_crap()) {
2970                         exit(1);
2971                 }
2972                 exit(0);
2973         } 
2974
2975         if (!opt_password) {
2976                 opt_password = getpass("password: ");
2977         }
2978
2979         if (diagnostics) {
2980                 if (!diagnose_ntlm_auth()) {
2981                         return 1;
2982                 }
2983         } else {
2984                 fstring user;
2985
2986                 fstr_sprintf(user, "%s%c%s", opt_domain, winbind_separator(), opt_username);
2987                 if (!check_plaintext_auth(user, opt_password, True)) {
2988                         return 1;
2989                 }
2990         }
2991
2992         /* Exit code */
2993
2994         poptFreeContext(pc);
2995         TALLOC_FREE(frame);
2996         return 0;
2997 }