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