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