6a702fc0cfad85eea9fe566b3b6c21984da75118
[samba.git] / source3 / utils / ntlm_auth.c
1 /* 
2    Unix SMB/CIFS implementation.
3
4    Winbind status program.
5
6    Copyright (C) Tim Potter      2000-2003
7    Copyright (C) Andrew Bartlett <abartlet@samba.org> 2003-2004
8    Copyright (C) Francesco Chemolli <kinkie@kame.usr.dsi.unimi.it> 2000 
9    Copyright (C) Robert O'Callahan 2006 (added cached credential code).
10
11    This program is free software; you can redistribute it and/or modify
12    it under the terms of the GNU General Public License as published by
13    the Free Software Foundation; either version 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                         PAC_DATA *pac_data = NULL;
1167
1168                         if ( request.negTokenInit.mechToken.data == NULL ) {
1169                                 DEBUG(1, ("Client did not provide Kerberos data\n"));
1170                                 x_fprintf(x_stdout, "BH\n");
1171                                 return;
1172                         }
1173
1174                         response.type = SPNEGO_NEG_TOKEN_TARG;
1175                         response.negTokenTarg.supportedMech = SMB_STRDUP(OID_KERBEROS5_OLD);
1176                         response.negTokenTarg.mechListMIC = data_blob_null;
1177                         response.negTokenTarg.responseToken = data_blob_null;
1178
1179                         status = ads_verify_ticket(mem_ctx, lp_realm(), 0,
1180                                                    &request.negTokenInit.mechToken,
1181                                                    &principal, &pac_data, &ap_rep,
1182                                                    &session_key, True);
1183
1184                         talloc_destroy(mem_ctx);
1185
1186                         /* Now in "principal" we have the name we are
1187                            authenticated as. */
1188
1189                         if (NT_STATUS_IS_OK(status)) {
1190
1191                                 domain = strchr_m(principal, '@');
1192
1193                                 if (domain == NULL) {
1194                                         DEBUG(1, ("Did not get a valid principal "
1195                                                   "from ads_verify_ticket\n"));
1196                                         x_fprintf(x_stdout, "BH\n");
1197                                         return;
1198                                 }
1199
1200                                 *domain++ = '\0';
1201                                 domain = SMB_STRDUP(domain);
1202                                 user = SMB_STRDUP(principal);
1203
1204                                 data_blob_free(&ap_rep);
1205
1206                                 SAFE_FREE(principal);
1207                         }
1208                 }
1209 #endif
1210
1211         } else {
1212
1213                 if ( (request.negTokenTarg.supportedMech == NULL) ||
1214                      ( strcmp(request.negTokenTarg.supportedMech, OID_NTLMSSP) != 0 ) ) {
1215                         /* Kerberos should never send a negTokenTarg, OID_NTLMSSP
1216                            is the only one we support that sends this stuff */
1217                         DEBUG(1, ("Got a negTokenTarg for something non-NTLMSSP: %s\n",
1218                                   request.negTokenTarg.supportedMech));
1219                         x_fprintf(x_stdout, "BH\n");
1220                         return;
1221                 }
1222
1223                 if (request.negTokenTarg.responseToken.data == NULL) {
1224                         DEBUG(1, ("Got a negTokenTarg without a responseToken!\n"));
1225                         x_fprintf(x_stdout, "BH\n");
1226                         return;
1227                 }
1228
1229                 status = ntlmssp_update(ntlmssp_state,
1230                                                request.negTokenTarg.responseToken,
1231                                                &response.negTokenTarg.responseToken);
1232
1233                 response.type = SPNEGO_NEG_TOKEN_TARG;
1234                 response.negTokenTarg.supportedMech = SMB_STRDUP(OID_NTLMSSP);
1235                 response.negTokenTarg.mechListMIC = data_blob_null;
1236
1237                 if (NT_STATUS_IS_OK(status)) {
1238                         user = SMB_STRDUP(ntlmssp_state->user);
1239                         domain = SMB_STRDUP(ntlmssp_state->domain);
1240                         ntlmssp_end(&ntlmssp_state);
1241                 }
1242         }
1243
1244         free_spnego_data(&request);
1245
1246         if (NT_STATUS_IS_OK(status)) {
1247                 response.negTokenTarg.negResult = SPNEGO_ACCEPT_COMPLETED;
1248                 reply_code = "AF";
1249                 reply_argument = talloc_asprintf(ctx, "%s\\%s", domain, user);
1250         } else if (NT_STATUS_EQUAL(status,
1251                                    NT_STATUS_MORE_PROCESSING_REQUIRED)) {
1252                 response.negTokenTarg.negResult = SPNEGO_ACCEPT_INCOMPLETE;
1253                 reply_code = "TT";
1254                 reply_argument = talloc_strdup(ctx, "*");
1255         } else {
1256                 response.negTokenTarg.negResult = SPNEGO_REJECT;
1257                 reply_code = "NA";
1258                 reply_argument = talloc_strdup(ctx, nt_errstr(status));
1259         }
1260
1261         if (!reply_argument) {
1262                 DEBUG(1, ("Could not write SPNEGO data blob\n"));
1263                 x_fprintf(x_stdout, "BH\n");
1264                 return;
1265         }
1266
1267         SAFE_FREE(user);
1268         SAFE_FREE(domain);
1269
1270         len = write_spnego_data(&token, &response);
1271         free_spnego_data(&response);
1272
1273         if (len == -1) {
1274                 DEBUG(1, ("Could not write SPNEGO data blob\n"));
1275                 x_fprintf(x_stdout, "BH\n");
1276                 return;
1277         }
1278
1279         reply_base64 = base64_encode_data_blob(token);
1280
1281         x_fprintf(x_stdout, "%s %s %s\n",
1282                   reply_code, reply_base64, reply_argument);
1283
1284         TALLOC_FREE(reply_base64);
1285         data_blob_free(&token);
1286
1287         return;
1288 }
1289
1290 static NTLMSSP_STATE *client_ntlmssp_state = NULL;
1291
1292 static bool manage_client_ntlmssp_init(SPNEGO_DATA spnego)
1293 {
1294         NTSTATUS status;
1295         DATA_BLOB null_blob = data_blob_null;
1296         DATA_BLOB to_server;
1297         char *to_server_base64;
1298         const char *my_mechs[] = {OID_NTLMSSP, NULL};
1299
1300         DEBUG(10, ("Got spnego negTokenInit with NTLMSSP\n"));
1301
1302         if (client_ntlmssp_state != NULL) {
1303                 DEBUG(1, ("Request for initial SPNEGO request where "
1304                           "we already have a state\n"));
1305                 return False;
1306         }
1307
1308         if (!client_ntlmssp_state) {
1309                 if (!NT_STATUS_IS_OK(status = ntlm_auth_start_ntlmssp_client(&client_ntlmssp_state))) {
1310                         x_fprintf(x_stdout, "BH %s\n", nt_errstr(status));
1311                         return False;
1312                 }
1313         }
1314
1315
1316         if (opt_password == NULL) {
1317
1318                 /* Request a password from the calling process.  After
1319                    sending it, the calling process should retry with
1320                    the negTokenInit. */
1321
1322                 DEBUG(10, ("Requesting password\n"));
1323                 x_fprintf(x_stdout, "PW\n");
1324                 return True;
1325         }
1326
1327         spnego.type = SPNEGO_NEG_TOKEN_INIT;
1328         spnego.negTokenInit.mechTypes = my_mechs;
1329         spnego.negTokenInit.reqFlags = 0;
1330         spnego.negTokenInit.mechListMIC = null_blob;
1331
1332         status = ntlmssp_update(client_ntlmssp_state, null_blob,
1333                                        &spnego.negTokenInit.mechToken);
1334
1335         if ( !(NT_STATUS_EQUAL(status, NT_STATUS_MORE_PROCESSING_REQUIRED) ||
1336                         NT_STATUS_IS_OK(status)) ) {
1337                 DEBUG(1, ("Expected OK or MORE_PROCESSING_REQUIRED, got: %s\n",
1338                           nt_errstr(status)));
1339                 ntlmssp_end(&client_ntlmssp_state);
1340                 return False;
1341         }
1342
1343         write_spnego_data(&to_server, &spnego);
1344         data_blob_free(&spnego.negTokenInit.mechToken);
1345
1346         to_server_base64 = base64_encode_data_blob(to_server);
1347         data_blob_free(&to_server);
1348         x_fprintf(x_stdout, "KK %s\n", to_server_base64);
1349         TALLOC_FREE(to_server_base64);
1350         return True;
1351 }
1352
1353 static void manage_client_ntlmssp_targ(SPNEGO_DATA spnego)
1354 {
1355         NTSTATUS status;
1356         DATA_BLOB null_blob = data_blob_null;
1357         DATA_BLOB request;
1358         DATA_BLOB to_server;
1359         char *to_server_base64;
1360
1361         DEBUG(10, ("Got spnego negTokenTarg with NTLMSSP\n"));
1362
1363         if (client_ntlmssp_state == NULL) {
1364                 DEBUG(1, ("Got NTLMSSP tArg without a client state\n"));
1365                 x_fprintf(x_stdout, "BH\n");
1366                 return;
1367         }
1368
1369         if (spnego.negTokenTarg.negResult == SPNEGO_REJECT) {
1370                 x_fprintf(x_stdout, "NA\n");
1371                 ntlmssp_end(&client_ntlmssp_state);
1372                 return;
1373         }
1374
1375         if (spnego.negTokenTarg.negResult == SPNEGO_ACCEPT_COMPLETED) {
1376                 x_fprintf(x_stdout, "AF\n");
1377                 ntlmssp_end(&client_ntlmssp_state);
1378                 return;
1379         }
1380
1381         status = ntlmssp_update(client_ntlmssp_state,
1382                                        spnego.negTokenTarg.responseToken,
1383                                        &request);
1384                 
1385         if (!NT_STATUS_EQUAL(status, NT_STATUS_MORE_PROCESSING_REQUIRED)) {
1386                 DEBUG(1, ("Expected MORE_PROCESSING_REQUIRED from "
1387                           "ntlmssp_client_update, got: %s\n",
1388                           nt_errstr(status)));
1389                 x_fprintf(x_stdout, "BH\n");
1390                 data_blob_free(&request);
1391                 ntlmssp_end(&client_ntlmssp_state);
1392                 return;
1393         }
1394
1395         spnego.type = SPNEGO_NEG_TOKEN_TARG;
1396         spnego.negTokenTarg.negResult = SPNEGO_ACCEPT_INCOMPLETE;
1397         spnego.negTokenTarg.supportedMech = (char *)OID_NTLMSSP;
1398         spnego.negTokenTarg.responseToken = request;
1399         spnego.negTokenTarg.mechListMIC = null_blob;
1400         
1401         write_spnego_data(&to_server, &spnego);
1402         data_blob_free(&request);
1403
1404         to_server_base64 = base64_encode_data_blob(to_server);
1405         data_blob_free(&to_server);
1406         x_fprintf(x_stdout, "KK %s\n", to_server_base64);
1407         TALLOC_FREE(to_server_base64);
1408         return;
1409 }
1410
1411 #ifdef HAVE_KRB5
1412
1413 static bool manage_client_krb5_init(SPNEGO_DATA spnego)
1414 {
1415         char *principal;
1416         DATA_BLOB tkt, to_server;
1417         DATA_BLOB session_key_krb5 = data_blob_null;
1418         SPNEGO_DATA reply;
1419         char *reply_base64;
1420         int retval;
1421
1422         const char *my_mechs[] = {OID_KERBEROS5_OLD, NULL};
1423         ssize_t len;
1424
1425         if ( (spnego.negTokenInit.mechListMIC.data == NULL) ||
1426              (spnego.negTokenInit.mechListMIC.length == 0) ) {
1427                 DEBUG(1, ("Did not get a principal for krb5\n"));
1428                 return False;
1429         }
1430
1431         principal = (char *)SMB_MALLOC(
1432                 spnego.negTokenInit.mechListMIC.length+1);
1433
1434         if (principal == NULL) {
1435                 DEBUG(1, ("Could not malloc principal\n"));
1436                 return False;
1437         }
1438
1439         memcpy(principal, spnego.negTokenInit.mechListMIC.data,
1440                spnego.negTokenInit.mechListMIC.length);
1441         principal[spnego.negTokenInit.mechListMIC.length] = '\0';
1442
1443         retval = cli_krb5_get_ticket(principal, 0, &tkt, &session_key_krb5, 0, NULL, NULL);
1444
1445         if (retval) {
1446                 char *user = NULL;
1447
1448                 /* Let's try to first get the TGT, for that we need a
1449                    password. */
1450
1451                 if (opt_password == NULL) {
1452                         DEBUG(10, ("Requesting password\n"));
1453                         x_fprintf(x_stdout, "PW\n");
1454                         return True;
1455                 }
1456
1457                 user = talloc_asprintf(talloc_tos(), "%s@%s", opt_username, opt_domain);
1458                 if (!user) {
1459                         return false;
1460                 }
1461
1462                 if ((retval = kerberos_kinit_password(user, opt_password, 0, NULL))) {
1463                         DEBUG(10, ("Requesting TGT failed: %s\n", error_message(retval)));
1464                         return False;
1465                 }
1466
1467                 retval = cli_krb5_get_ticket(principal, 0, &tkt, &session_key_krb5, 0, NULL, NULL);
1468
1469                 if (retval) {
1470                         DEBUG(10, ("Kinit suceeded, but getting a ticket failed: %s\n", error_message(retval)));
1471                         return False;
1472                 }
1473         }
1474
1475         data_blob_free(&session_key_krb5);
1476
1477         ZERO_STRUCT(reply);
1478
1479         reply.type = SPNEGO_NEG_TOKEN_INIT;
1480         reply.negTokenInit.mechTypes = my_mechs;
1481         reply.negTokenInit.reqFlags = 0;
1482         reply.negTokenInit.mechToken = tkt;
1483         reply.negTokenInit.mechListMIC = data_blob_null;
1484
1485         len = write_spnego_data(&to_server, &reply);
1486         data_blob_free(&tkt);
1487
1488         if (len == -1) {
1489                 DEBUG(1, ("Could not write SPNEGO data blob\n"));
1490                 return False;
1491         }
1492
1493         reply_base64 = base64_encode_data_blob(to_server);
1494         x_fprintf(x_stdout, "KK %s *\n", reply_base64);
1495
1496         TALLOC_FREE(reply_base64);
1497         data_blob_free(&to_server);
1498         DEBUG(10, ("sent GSS-SPNEGO KERBEROS5 negTokenInit\n"));
1499         return True;
1500 }
1501
1502 static void manage_client_krb5_targ(SPNEGO_DATA spnego)
1503 {
1504         switch (spnego.negTokenTarg.negResult) {
1505         case SPNEGO_ACCEPT_INCOMPLETE:
1506                 DEBUG(1, ("Got a Kerberos negTokenTarg with ACCEPT_INCOMPLETE\n"));
1507                 x_fprintf(x_stdout, "BH\n");
1508                 break;
1509         case SPNEGO_ACCEPT_COMPLETED:
1510                 DEBUG(10, ("Accept completed\n"));
1511                 x_fprintf(x_stdout, "AF\n");
1512                 break;
1513         case SPNEGO_REJECT:
1514                 DEBUG(10, ("Rejected\n"));
1515                 x_fprintf(x_stdout, "NA\n");
1516                 break;
1517         default:
1518                 DEBUG(1, ("Got an invalid negTokenTarg\n"));
1519                 x_fprintf(x_stdout, "AF\n");
1520         }
1521 }
1522
1523 #endif
1524
1525 static void manage_gss_spnego_client_request(enum stdio_helper_mode stdio_helper_mode, 
1526                                              char *buf, int length) 
1527 {
1528         DATA_BLOB request;
1529         SPNEGO_DATA spnego;
1530         ssize_t len;
1531
1532         if (!opt_username || !*opt_username) {
1533                 x_fprintf(x_stderr, "username must be specified!\n\n");
1534                 exit(1);
1535         }
1536
1537         if (strlen(buf) <= 3) {
1538                 DEBUG(1, ("SPNEGO query [%s] too short\n", buf));
1539                 x_fprintf(x_stdout, "BH\n");
1540                 return;
1541         }
1542
1543         request = base64_decode_data_blob(buf+3);
1544
1545         if (strncmp(buf, "PW ", 3) == 0) {
1546
1547                 /* We asked for a password and obviously got it :-) */
1548
1549                 opt_password = SMB_STRNDUP((const char *)request.data, request.length);
1550                 
1551                 if (opt_password == NULL) {
1552                         DEBUG(1, ("Out of memory\n"));
1553                         x_fprintf(x_stdout, "BH\n");
1554                         data_blob_free(&request);
1555                         return;
1556                 }
1557
1558                 x_fprintf(x_stdout, "OK\n");
1559                 data_blob_free(&request);
1560                 return;
1561         }
1562
1563         if ( (strncmp(buf, "TT ", 3) != 0) &&
1564              (strncmp(buf, "AF ", 3) != 0) &&
1565              (strncmp(buf, "NA ", 3) != 0) ) {
1566                 DEBUG(1, ("SPNEGO request [%s] invalid\n", buf));
1567                 x_fprintf(x_stdout, "BH\n");
1568                 data_blob_free(&request);
1569                 return;
1570         }
1571
1572         /* So we got a server challenge to generate a SPNEGO
1573            client-to-server request... */
1574
1575         len = read_spnego_data(request, &spnego);
1576         data_blob_free(&request);
1577
1578         if (len == -1) {
1579                 DEBUG(1, ("Could not read SPNEGO data for [%s]\n", buf));
1580                 x_fprintf(x_stdout, "BH\n");
1581                 return;
1582         }
1583
1584         if (spnego.type == SPNEGO_NEG_TOKEN_INIT) {
1585
1586                 /* The server offers a list of mechanisms */
1587
1588                 const char **mechType = (const char **)spnego.negTokenInit.mechTypes;
1589
1590                 while (*mechType != NULL) {
1591
1592 #ifdef HAVE_KRB5
1593                         if ( (strcmp(*mechType, OID_KERBEROS5_OLD) == 0) ||
1594                              (strcmp(*mechType, OID_KERBEROS5) == 0) ) {
1595                                 if (manage_client_krb5_init(spnego))
1596                                         goto out;
1597                         }
1598 #endif
1599
1600                         if (strcmp(*mechType, OID_NTLMSSP) == 0) {
1601                                 if (manage_client_ntlmssp_init(spnego))
1602                                         goto out;
1603                         }
1604
1605                         mechType++;
1606                 }
1607
1608                 DEBUG(1, ("Server offered no compatible mechanism\n"));
1609                 x_fprintf(x_stdout, "BH\n");
1610                 return;
1611         }
1612
1613         if (spnego.type == SPNEGO_NEG_TOKEN_TARG) {
1614
1615                 if (spnego.negTokenTarg.supportedMech == NULL) {
1616                         /* On accept/reject Windows does not send the
1617                            mechanism anymore. Handle that here and
1618                            shut down the mechanisms. */
1619
1620                         switch (spnego.negTokenTarg.negResult) {
1621                         case SPNEGO_ACCEPT_COMPLETED:
1622                                 x_fprintf(x_stdout, "AF\n");
1623                                 break;
1624                         case SPNEGO_REJECT:
1625                                 x_fprintf(x_stdout, "NA\n");
1626                                 break;
1627                         default:
1628                                 DEBUG(1, ("Got a negTokenTarg with no mech and an "
1629                                           "unknown negResult: %d\n",
1630                                           spnego.negTokenTarg.negResult));
1631                                 x_fprintf(x_stdout, "BH\n");
1632                         }
1633
1634                         ntlmssp_end(&client_ntlmssp_state);
1635                         goto out;
1636                 }
1637
1638                 if (strcmp(spnego.negTokenTarg.supportedMech,
1639                            OID_NTLMSSP) == 0) {
1640                         manage_client_ntlmssp_targ(spnego);
1641                         goto out;
1642                 }
1643
1644 #if HAVE_KRB5
1645                 if (strcmp(spnego.negTokenTarg.supportedMech,
1646                            OID_KERBEROS5_OLD) == 0) {
1647                         manage_client_krb5_targ(spnego);
1648                         goto out;
1649                 }
1650 #endif
1651
1652         }
1653
1654         DEBUG(1, ("Got an SPNEGO token I could not handle [%s]!\n", buf));
1655         x_fprintf(x_stdout, "BH\n");
1656         return;
1657
1658  out:
1659         free_spnego_data(&spnego);
1660         return;
1661 }
1662
1663 static void manage_ntlm_server_1_request(enum stdio_helper_mode stdio_helper_mode, 
1664                                          char *buf, int length) 
1665 {
1666         char *request, *parameter;      
1667         static DATA_BLOB challenge;
1668         static DATA_BLOB lm_response;
1669         static DATA_BLOB nt_response;
1670         static char *full_username;
1671         static char *username;
1672         static char *domain;
1673         static char *plaintext_password;
1674         static bool ntlm_server_1_user_session_key;
1675         static bool ntlm_server_1_lm_session_key;
1676         
1677         if (strequal(buf, ".")) {
1678                 if (!full_username && !username) {      
1679                         x_fprintf(x_stdout, "Error: No username supplied!\n");
1680                 } else if (plaintext_password) {
1681                         /* handle this request as plaintext */
1682                         if (!full_username) {
1683                                 if (asprintf(&full_username, "%s%c%s", domain, winbind_separator(), username) == -1) {
1684                                         x_fprintf(x_stdout, "Error: Out of memory in asprintf!\n.\n");
1685                                         return;
1686                                 }
1687                         }
1688                         if (check_plaintext_auth(full_username, plaintext_password, False)) {
1689                                 x_fprintf(x_stdout, "Authenticated: Yes\n");
1690                         } else {
1691                                 x_fprintf(x_stdout, "Authenticated: No\n");
1692                         }
1693                 } else if (!lm_response.data && !nt_response.data) {
1694                         x_fprintf(x_stdout, "Error: No password supplied!\n");
1695                 } else if (!challenge.data) {   
1696                         x_fprintf(x_stdout, "Error: No lanman-challenge supplied!\n");
1697                 } else {
1698                         char *error_string = NULL;
1699                         uchar lm_key[8];
1700                         uchar user_session_key[16];
1701                         uint32 flags = 0;
1702
1703                         if (full_username && !username) {
1704                                 fstring fstr_user;
1705                                 fstring fstr_domain;
1706                                 
1707                                 if (!parse_ntlm_auth_domain_user(full_username, fstr_user, fstr_domain)) {
1708                                         /* username might be 'tainted', don't print into our new-line deleimianted stream */
1709                                         x_fprintf(x_stdout, "Error: Could not parse into domain and username\n");
1710                                 }
1711                                 SAFE_FREE(username);
1712                                 SAFE_FREE(domain);
1713                                 username = smb_xstrdup(fstr_user);
1714                                 domain = smb_xstrdup(fstr_domain);
1715                         }
1716
1717                         if (!domain) {
1718                                 domain = smb_xstrdup(get_winbind_domain());
1719                         }
1720
1721                         if (ntlm_server_1_lm_session_key) 
1722                                 flags |= WBFLAG_PAM_LMKEY;
1723                         
1724                         if (ntlm_server_1_user_session_key) 
1725                                 flags |= WBFLAG_PAM_USER_SESSION_KEY;
1726
1727                         if (!NT_STATUS_IS_OK(
1728                                     contact_winbind_auth_crap(username, 
1729                                                               domain, 
1730                                                               global_myname(),
1731                                                               &challenge, 
1732                                                               &lm_response, 
1733                                                               &nt_response, 
1734                                                               flags, 
1735                                                               lm_key, 
1736                                                               user_session_key,
1737                                                               &error_string,
1738                                                               NULL))) {
1739
1740                                 x_fprintf(x_stdout, "Authenticated: No\n");
1741                                 x_fprintf(x_stdout, "Authentication-Error: %s\n.\n", error_string);
1742                                 SAFE_FREE(error_string);
1743                         } else {
1744                                 static char zeros[16];
1745                                 char *hex_lm_key;
1746                                 char *hex_user_session_key;
1747
1748                                 x_fprintf(x_stdout, "Authenticated: Yes\n");
1749
1750                                 if (ntlm_server_1_lm_session_key 
1751                                     && (memcmp(zeros, lm_key, 
1752                                                sizeof(lm_key)) != 0)) {
1753                                         hex_lm_key = hex_encode(NULL,
1754                                                                 (const unsigned char *)lm_key,
1755                                                                 sizeof(lm_key));
1756                                         x_fprintf(x_stdout, "LANMAN-Session-Key: %s\n", hex_lm_key);
1757                                         TALLOC_FREE(hex_lm_key);
1758                                 }
1759
1760                                 if (ntlm_server_1_user_session_key 
1761                                     && (memcmp(zeros, user_session_key, 
1762                                                sizeof(user_session_key)) != 0)) {
1763                                         hex_user_session_key = hex_encode(NULL,
1764                                                                           (const unsigned char *)user_session_key, 
1765                                                                           sizeof(user_session_key));
1766                                         x_fprintf(x_stdout, "User-Session-Key: %s\n", hex_user_session_key);
1767                                         TALLOC_FREE(hex_user_session_key);
1768                                 }
1769                         }
1770                 }
1771                 /* clear out the state */
1772                 challenge = data_blob_null;
1773                 nt_response = data_blob_null;
1774                 lm_response = data_blob_null;
1775                 SAFE_FREE(full_username);
1776                 SAFE_FREE(username);
1777                 SAFE_FREE(domain);
1778                 SAFE_FREE(plaintext_password);
1779                 ntlm_server_1_user_session_key = False;
1780                 ntlm_server_1_lm_session_key = False;
1781                 x_fprintf(x_stdout, ".\n");
1782
1783                 return;
1784         }
1785
1786         request = buf;
1787
1788         /* Indicates a base64 encoded structure */
1789         parameter = strstr_m(request, ":: ");
1790         if (!parameter) {
1791                 parameter = strstr_m(request, ": ");
1792                 
1793                 if (!parameter) {
1794                         DEBUG(0, ("Parameter not found!\n"));
1795                         x_fprintf(x_stdout, "Error: Parameter not found!\n.\n");
1796                         return;
1797                 }
1798                 
1799                 parameter[0] ='\0';
1800                 parameter++;
1801                 parameter[0] ='\0';
1802                 parameter++;
1803
1804         } else {
1805                 parameter[0] ='\0';
1806                 parameter++;
1807                 parameter[0] ='\0';
1808                 parameter++;
1809                 parameter[0] ='\0';
1810                 parameter++;
1811
1812                 base64_decode_inplace(parameter);
1813         }
1814
1815         if (strequal(request, "LANMAN-Challenge")) {
1816                 challenge = strhex_to_data_blob(NULL, parameter);
1817                 if (challenge.length != 8) {
1818                         x_fprintf(x_stdout, "Error: hex decode of %s failed! (got %d bytes, expected 8)\n.\n", 
1819                                   parameter,
1820                                   (int)challenge.length);
1821                         challenge = data_blob_null;
1822                 }
1823         } else if (strequal(request, "NT-Response")) {
1824                 nt_response = strhex_to_data_blob(NULL, parameter);
1825                 if (nt_response.length < 24) {
1826                         x_fprintf(x_stdout, "Error: hex decode of %s failed! (only got %d bytes, needed at least 24)\n.\n", 
1827                                   parameter,
1828                                   (int)nt_response.length);
1829                         nt_response = data_blob_null;
1830                 }
1831         } else if (strequal(request, "LANMAN-Response")) {
1832                 lm_response = strhex_to_data_blob(NULL, parameter);
1833                 if (lm_response.length != 24) {
1834                         x_fprintf(x_stdout, "Error: hex decode of %s failed! (got %d bytes, expected 24)\n.\n", 
1835                                   parameter,
1836                                   (int)lm_response.length);
1837                         lm_response = data_blob_null;
1838                 }
1839         } else if (strequal(request, "Password")) {
1840                 plaintext_password = smb_xstrdup(parameter);
1841         } else if (strequal(request, "NT-Domain")) {
1842                 domain = smb_xstrdup(parameter);
1843         } else if (strequal(request, "Username")) {
1844                 username = smb_xstrdup(parameter);
1845         } else if (strequal(request, "Full-Username")) {
1846                 full_username = smb_xstrdup(parameter);
1847         } else if (strequal(request, "Request-User-Session-Key")) {
1848                 ntlm_server_1_user_session_key = strequal(parameter, "Yes");
1849         } else if (strequal(request, "Request-LanMan-Session-Key")) {
1850                 ntlm_server_1_lm_session_key = strequal(parameter, "Yes");
1851         } else {
1852                 x_fprintf(x_stdout, "Error: Unknown request %s\n.\n", request);
1853         }
1854 }
1855
1856 static void manage_ntlm_change_password_1_request(enum stdio_helper_mode helper_mode, char *buf, int length)
1857 {
1858         char *request, *parameter;      
1859         static DATA_BLOB new_nt_pswd;
1860         static DATA_BLOB old_nt_hash_enc;
1861         static DATA_BLOB new_lm_pswd;
1862         static DATA_BLOB old_lm_hash_enc;
1863         static char *full_username = NULL;
1864         static char *username = NULL;
1865         static char *domain = NULL;
1866         static char *newpswd =  NULL;
1867         static char *oldpswd = NULL;
1868
1869         if (strequal(buf, ".")) {
1870                 if(newpswd && oldpswd) {
1871                         uchar old_nt_hash[16];
1872                         uchar old_lm_hash[16];
1873                         uchar new_nt_hash[16];
1874                         uchar new_lm_hash[16];
1875
1876                         new_nt_pswd = data_blob(NULL, 516);
1877                         old_nt_hash_enc = data_blob(NULL, 16);
1878                         
1879                         /* Calculate the MD4 hash (NT compatible) of the
1880                          * password */
1881                         E_md4hash(oldpswd, old_nt_hash);
1882                         E_md4hash(newpswd, new_nt_hash);
1883
1884                         /* E_deshash returns false for 'long'
1885                            passwords (> 14 DOS chars).  
1886                            
1887                            Therefore, don't send a buffer
1888                            encrypted with the truncated hash
1889                            (it could allow an even easier
1890                            attack on the password)
1891
1892                            Likewise, obey the admin's restriction
1893                         */
1894
1895                         if (lp_client_lanman_auth() &&
1896                             E_deshash(newpswd, new_lm_hash) &&
1897                             E_deshash(oldpswd, old_lm_hash)) {
1898                                 new_lm_pswd = data_blob(NULL, 516);
1899                                 old_lm_hash_enc = data_blob(NULL, 16);
1900                                 encode_pw_buffer(new_lm_pswd.data, newpswd,
1901                                                  STR_UNICODE);
1902
1903                                 SamOEMhash(new_lm_pswd.data, old_nt_hash, 516);
1904                                 E_old_pw_hash(new_nt_hash, old_lm_hash,
1905                                               old_lm_hash_enc.data);
1906                         } else {
1907                                 new_lm_pswd.data = NULL;
1908                                 new_lm_pswd.length = 0;
1909                                 old_lm_hash_enc.data = NULL;
1910                                 old_lm_hash_enc.length = 0;
1911                         }
1912
1913                         encode_pw_buffer(new_nt_pswd.data, newpswd,
1914                                          STR_UNICODE);
1915         
1916                         SamOEMhash(new_nt_pswd.data, old_nt_hash, 516);
1917                         E_old_pw_hash(new_nt_hash, old_nt_hash,
1918                                       old_nt_hash_enc.data);
1919                 }
1920                 
1921                 if (!full_username && !username) {      
1922                         x_fprintf(x_stdout, "Error: No username supplied!\n");
1923                 } else if ((!new_nt_pswd.data || !old_nt_hash_enc.data) &&
1924                            (!new_lm_pswd.data || old_lm_hash_enc.data) ) {
1925                         x_fprintf(x_stdout, "Error: No NT or LM password "
1926                                   "blobs supplied!\n");
1927                 } else {
1928                         char *error_string = NULL;
1929                         
1930                         if (full_username && !username) {
1931                                 fstring fstr_user;
1932                                 fstring fstr_domain;
1933                                 
1934                                 if (!parse_ntlm_auth_domain_user(full_username,
1935                                                                  fstr_user,
1936                                                                  fstr_domain)) {
1937                                         /* username might be 'tainted', don't
1938                                          * print into our new-line
1939                                          * deleimianted stream */
1940                                         x_fprintf(x_stdout, "Error: Could not "
1941                                                   "parse into domain and "
1942                                                   "username\n");
1943                                         SAFE_FREE(username);
1944                                         username = smb_xstrdup(full_username);
1945                                 } else {
1946                                         SAFE_FREE(username);
1947                                         SAFE_FREE(domain);
1948                                         username = smb_xstrdup(fstr_user);
1949                                         domain = smb_xstrdup(fstr_domain);
1950                                 }
1951                                 
1952                         }
1953
1954                         if(!NT_STATUS_IS_OK(contact_winbind_change_pswd_auth_crap(
1955                                                     username, domain,
1956                                                     new_nt_pswd,
1957                                                     old_nt_hash_enc,
1958                                                     new_lm_pswd,
1959                                                     old_lm_hash_enc,
1960                                                     &error_string))) {
1961                                 x_fprintf(x_stdout, "Password-Change: No\n");
1962                                 x_fprintf(x_stdout, "Password-Change-Error: "
1963                                           "%s\n.\n", error_string);
1964                         } else {
1965                                 x_fprintf(x_stdout, "Password-Change: Yes\n");
1966                         }
1967
1968                         SAFE_FREE(error_string);
1969                 }
1970                 /* clear out the state */
1971                 new_nt_pswd = data_blob_null;
1972                 old_nt_hash_enc = data_blob_null;
1973                 new_lm_pswd = data_blob_null;
1974                 old_nt_hash_enc = data_blob_null;
1975                 SAFE_FREE(full_username);
1976                 SAFE_FREE(username);
1977                 SAFE_FREE(domain);
1978                 SAFE_FREE(newpswd);
1979                 SAFE_FREE(oldpswd);
1980                 x_fprintf(x_stdout, ".\n");
1981
1982                 return;
1983         }
1984
1985         request = buf;
1986
1987         /* Indicates a base64 encoded structure */
1988         parameter = strstr_m(request, ":: ");
1989         if (!parameter) {
1990                 parameter = strstr_m(request, ": ");
1991                 
1992                 if (!parameter) {
1993                         DEBUG(0, ("Parameter not found!\n"));
1994                         x_fprintf(x_stdout, "Error: Parameter not found!\n.\n");
1995                         return;
1996                 }
1997                 
1998                 parameter[0] ='\0';
1999                 parameter++;
2000                 parameter[0] ='\0';
2001                 parameter++;
2002         } else {
2003                 parameter[0] ='\0';
2004                 parameter++;
2005                 parameter[0] ='\0';
2006                 parameter++;
2007                 parameter[0] ='\0';
2008                 parameter++;
2009
2010                 base64_decode_inplace(parameter);
2011         }
2012
2013         if (strequal(request, "new-nt-password-blob")) {
2014                 new_nt_pswd = strhex_to_data_blob(NULL, parameter);
2015                 if (new_nt_pswd.length != 516) {
2016                         x_fprintf(x_stdout, "Error: hex decode of %s failed! "
2017                                   "(got %d bytes, expected 516)\n.\n", 
2018                                   parameter,
2019                                   (int)new_nt_pswd.length);
2020                         new_nt_pswd = data_blob_null;
2021                 }
2022         } else if (strequal(request, "old-nt-hash-blob")) {
2023                 old_nt_hash_enc = strhex_to_data_blob(NULL, parameter);
2024                 if (old_nt_hash_enc.length != 16) {
2025                         x_fprintf(x_stdout, "Error: hex decode of %s failed! "
2026                                   "(got %d bytes, expected 16)\n.\n", 
2027                                   parameter,
2028                                   (int)old_nt_hash_enc.length);
2029                         old_nt_hash_enc = data_blob_null;
2030                 }
2031         } else if (strequal(request, "new-lm-password-blob")) {
2032                 new_lm_pswd = strhex_to_data_blob(NULL, parameter);
2033                 if (new_lm_pswd.length != 516) {
2034                         x_fprintf(x_stdout, "Error: hex decode of %s failed! "
2035                                   "(got %d bytes, expected 516)\n.\n", 
2036                                   parameter,
2037                                   (int)new_lm_pswd.length);
2038                         new_lm_pswd = data_blob_null;
2039                 }
2040         }
2041         else if (strequal(request, "old-lm-hash-blob")) {
2042                 old_lm_hash_enc = strhex_to_data_blob(NULL, parameter);
2043                 if (old_lm_hash_enc.length != 16)
2044                 {
2045                         x_fprintf(x_stdout, "Error: hex decode of %s failed! "
2046                                   "(got %d bytes, expected 16)\n.\n", 
2047                                   parameter,
2048                                   (int)old_lm_hash_enc.length);
2049                         old_lm_hash_enc = data_blob_null;
2050                 }
2051         } else if (strequal(request, "nt-domain")) {
2052                 domain = smb_xstrdup(parameter);
2053         } else if(strequal(request, "username")) {
2054                 username = smb_xstrdup(parameter);
2055         } else if(strequal(request, "full-username")) {
2056                 username = smb_xstrdup(parameter);
2057         } else if(strequal(request, "new-password")) {
2058                 newpswd = smb_xstrdup(parameter);
2059         } else if (strequal(request, "old-password")) {
2060                 oldpswd = smb_xstrdup(parameter);
2061         } else {
2062                 x_fprintf(x_stdout, "Error: Unknown request %s\n.\n", request);
2063         }
2064 }
2065
2066 static void manage_squid_request(enum stdio_helper_mode helper_mode, stdio_helper_function fn) 
2067 {
2068         char buf[SQUID_BUFFER_SIZE+1];
2069         int length;
2070         char *c;
2071         static bool err;
2072
2073         /* this is not a typo - x_fgets doesn't work too well under squid */
2074         if (fgets(buf, sizeof(buf)-1, stdin) == NULL) {
2075                 if (ferror(stdin)) {
2076                         DEBUG(1, ("fgets() failed! dying..... errno=%d (%s)\n", ferror(stdin),
2077                                   strerror(ferror(stdin))));
2078                         
2079                         exit(1);    /* BIIG buffer */
2080                 }
2081                 exit(0);
2082         }
2083     
2084         c=(char *)memchr(buf,'\n',sizeof(buf)-1);
2085         if (c) {
2086                 *c = '\0';
2087                 length = c-buf;
2088         } else {
2089                 err = 1;
2090                 return;
2091         }
2092         if (err) {
2093                 DEBUG(2, ("Oversized message\n"));
2094                 x_fprintf(x_stderr, "ERR\n");
2095                 err = 0;
2096                 return;
2097         }
2098
2099         DEBUG(10, ("Got '%s' from squid (length: %d).\n",buf,length));
2100
2101         if (buf[0] == '\0') {
2102                 DEBUG(2, ("Invalid Request\n"));
2103                 x_fprintf(x_stderr, "ERR\n");
2104                 return;
2105         }
2106         
2107         fn(helper_mode, buf, length);
2108 }
2109
2110
2111 static void squid_stream(enum stdio_helper_mode stdio_mode, stdio_helper_function fn) {
2112         /* initialize FDescs */
2113         x_setbuf(x_stdout, NULL);
2114         x_setbuf(x_stderr, NULL);
2115         while(1) {
2116                 manage_squid_request(stdio_mode, fn);
2117         }
2118 }
2119
2120
2121 /* Authenticate a user with a challenge/response */
2122
2123 static bool check_auth_crap(void)
2124 {
2125         NTSTATUS nt_status;
2126         uint32 flags = 0;
2127         char lm_key[8];
2128         char user_session_key[16];
2129         char *hex_lm_key;
2130         char *hex_user_session_key;
2131         char *error_string;
2132         static uint8 zeros[16];
2133
2134         x_setbuf(x_stdout, NULL);
2135
2136         if (request_lm_key) 
2137                 flags |= WBFLAG_PAM_LMKEY;
2138
2139         if (request_user_session_key) 
2140                 flags |= WBFLAG_PAM_USER_SESSION_KEY;
2141
2142         flags |= WBFLAG_PAM_NT_STATUS_SQUASH;
2143
2144         nt_status = contact_winbind_auth_crap(opt_username, opt_domain, 
2145                                               opt_workstation,
2146                                               &opt_challenge, 
2147                                               &opt_lm_response, 
2148                                               &opt_nt_response, 
2149                                               flags,
2150                                               (unsigned char *)lm_key, 
2151                                               (unsigned char *)user_session_key, 
2152                                               &error_string, NULL);
2153
2154         if (!NT_STATUS_IS_OK(nt_status)) {
2155                 x_fprintf(x_stdout, "%s (0x%x)\n", 
2156                           error_string,
2157                           NT_STATUS_V(nt_status));
2158                 SAFE_FREE(error_string);
2159                 return False;
2160         }
2161
2162         if (request_lm_key 
2163             && (memcmp(zeros, lm_key, 
2164                        sizeof(lm_key)) != 0)) {
2165                 hex_lm_key = hex_encode(NULL, (const unsigned char *)lm_key,
2166                                         sizeof(lm_key));
2167                 x_fprintf(x_stdout, "LM_KEY: %s\n", hex_lm_key);
2168                 TALLOC_FREE(hex_lm_key);
2169         }
2170         if (request_user_session_key 
2171             && (memcmp(zeros, user_session_key, 
2172                        sizeof(user_session_key)) != 0)) {
2173                 hex_user_session_key = hex_encode(NULL, (const unsigned char *)user_session_key, 
2174                                                   sizeof(user_session_key));
2175                 x_fprintf(x_stdout, "NT_KEY: %s\n", hex_user_session_key);
2176                 TALLOC_FREE(hex_user_session_key);
2177         }
2178
2179         return True;
2180 }
2181
2182 /* Main program */
2183
2184 enum {
2185         OPT_USERNAME = 1000,
2186         OPT_DOMAIN,
2187         OPT_WORKSTATION,
2188         OPT_CHALLENGE,
2189         OPT_RESPONSE,
2190         OPT_LM,
2191         OPT_NT,
2192         OPT_PASSWORD,
2193         OPT_LM_KEY,
2194         OPT_USER_SESSION_KEY,
2195         OPT_DIAGNOSTICS,
2196         OPT_REQUIRE_MEMBERSHIP,
2197         OPT_USE_CACHED_CREDS
2198 };
2199
2200  int main(int argc, const char **argv)
2201 {
2202         TALLOC_CTX *frame = talloc_stackframe();
2203         int opt;
2204         static const char *helper_protocol;
2205         static int diagnostics;
2206
2207         static const char *hex_challenge;
2208         static const char *hex_lm_response;
2209         static const char *hex_nt_response;
2210
2211         poptContext pc;
2212
2213         /* NOTE: DO NOT change this interface without considering the implications!
2214            This is an external interface, which other programs will use to interact 
2215            with this helper.
2216         */
2217
2218         /* We do not use single-letter command abbreviations, because they harm future 
2219            interface stability. */
2220
2221         struct poptOption long_options[] = {
2222                 POPT_AUTOHELP
2223                 { "helper-protocol", 0, POPT_ARG_STRING, &helper_protocol, OPT_DOMAIN, "operate as a stdio-based helper", "helper protocol to use"},
2224                 { "username", 0, POPT_ARG_STRING, &opt_username, OPT_USERNAME, "username"},
2225                 { "domain", 0, POPT_ARG_STRING, &opt_domain, OPT_DOMAIN, "domain name"},
2226                 { "workstation", 0, POPT_ARG_STRING, &opt_workstation, OPT_WORKSTATION, "workstation"},
2227                 { "challenge", 0, POPT_ARG_STRING, &hex_challenge, OPT_CHALLENGE, "challenge (HEX encoded)"},
2228                 { "lm-response", 0, POPT_ARG_STRING, &hex_lm_response, OPT_LM, "LM Response to the challenge (HEX encoded)"},
2229                 { "nt-response", 0, POPT_ARG_STRING, &hex_nt_response, OPT_NT, "NT or NTLMv2 Response to the challenge (HEX encoded)"},
2230                 { "password", 0, POPT_ARG_STRING, &opt_password, OPT_PASSWORD, "User's plaintext password"},            
2231                 { "request-lm-key", 0, POPT_ARG_NONE, &request_lm_key, OPT_LM_KEY, "Retrieve LM session key"},
2232                 { "request-nt-key", 0, POPT_ARG_NONE, &request_user_session_key, OPT_USER_SESSION_KEY, "Retrieve User (NT) session key"},
2233                 { "use-cached-creds", 0, POPT_ARG_NONE, &use_cached_creds, OPT_USE_CACHED_CREDS, "Use cached credentials if no password is given"},
2234                 { "diagnostics", 0, POPT_ARG_NONE, &diagnostics, OPT_DIAGNOSTICS, "Perform diagnostics on the authentictaion chain"},
2235                 { "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" },
2236                 POPT_COMMON_SAMBA
2237                 POPT_TABLEEND
2238         };
2239
2240         /* Samba client initialisation */
2241         load_case_tables();
2242
2243         dbf = x_stderr;
2244         
2245         /* Samba client initialisation */
2246
2247         if (!lp_load(get_dyn_CONFIGFILE(), True, False, False, True)) {
2248                 d_fprintf(stderr, "ntlm_auth: error opening config file %s. Error was %s\n",
2249                         get_dyn_CONFIGFILE(), strerror(errno));
2250                 exit(1);
2251         }
2252
2253         /* Parse options */
2254
2255         pc = poptGetContext("ntlm_auth", argc, argv, long_options, 0);
2256
2257         /* Parse command line options */
2258
2259         if (argc == 1) {
2260                 poptPrintHelp(pc, stderr, 0);
2261                 return 1;
2262         }
2263
2264         pc = poptGetContext(NULL, argc, (const char **)argv, long_options, 
2265                             POPT_CONTEXT_KEEP_FIRST);
2266
2267         while((opt = poptGetNextOpt(pc)) != -1) {
2268                 switch (opt) {
2269                 case OPT_CHALLENGE:
2270                         opt_challenge = strhex_to_data_blob(NULL, hex_challenge);
2271                         if (opt_challenge.length != 8) {
2272                                 x_fprintf(x_stderr, "hex decode of %s failed! (only got %d bytes)\n", 
2273                                           hex_challenge,
2274                                           (int)opt_challenge.length);
2275                                 exit(1);
2276                         }
2277                         break;
2278                 case OPT_LM: 
2279                         opt_lm_response = strhex_to_data_blob(NULL, hex_lm_response);
2280                         if (opt_lm_response.length != 24) {
2281                                 x_fprintf(x_stderr, "hex decode of %s failed! (only got %d bytes)\n", 
2282                                           hex_lm_response,
2283                                           (int)opt_lm_response.length);
2284                                 exit(1);
2285                         }
2286                         break;
2287
2288                 case OPT_NT: 
2289                         opt_nt_response = strhex_to_data_blob(NULL, hex_nt_response);
2290                         if (opt_nt_response.length < 24) {
2291                                 x_fprintf(x_stderr, "hex decode of %s failed! (only got %d bytes)\n", 
2292                                           hex_nt_response,
2293                                           (int)opt_nt_response.length);
2294                                 exit(1);
2295                         }
2296                         break;
2297
2298                 case OPT_REQUIRE_MEMBERSHIP:
2299                         if (StrnCaseCmp("S-", require_membership_of, 2) == 0) {
2300                                 require_membership_of_sid = require_membership_of;
2301                         }
2302                         break;
2303                 }
2304         }
2305
2306         if (opt_username) {
2307                 char *domain = SMB_STRDUP(opt_username);
2308                 char *p = strchr_m(domain, *lp_winbind_separator());
2309                 if (p) {
2310                         opt_username = p+1;
2311                         *p = '\0';
2312                         if (opt_domain && !strequal(opt_domain, domain)) {
2313                                 x_fprintf(x_stderr, "Domain specified in username (%s) "
2314                                         "doesn't match specified domain (%s)!\n\n",
2315                                         domain, opt_domain);
2316                                 poptPrintHelp(pc, stderr, 0);
2317                                 exit(1);
2318                         }
2319                         opt_domain = domain;
2320                 } else {
2321                         SAFE_FREE(domain);
2322                 }
2323         }
2324
2325         /* Note: if opt_domain is "" then send no domain */
2326         if (opt_domain == NULL) {
2327                 opt_domain = get_winbind_domain();
2328         }
2329
2330         if (opt_workstation == NULL) {
2331                 opt_workstation = "";
2332         }
2333
2334         if (helper_protocol) {
2335                 int i;
2336                 for (i=0; i<NUM_HELPER_MODES; i++) {
2337                         if (strcmp(helper_protocol, stdio_helper_protocols[i].name) == 0) {
2338                                 squid_stream(stdio_helper_protocols[i].mode, stdio_helper_protocols[i].fn);
2339                                 exit(0);
2340                         }
2341                 }
2342                 x_fprintf(x_stderr, "unknown helper protocol [%s]\n\nValid helper protools:\n\n", helper_protocol);
2343
2344                 for (i=0; i<NUM_HELPER_MODES; i++) {
2345                         x_fprintf(x_stderr, "%s\n", stdio_helper_protocols[i].name);
2346                 }
2347
2348                 exit(1);
2349         }
2350
2351         if (!opt_username || !*opt_username) {
2352                 x_fprintf(x_stderr, "username must be specified!\n\n");
2353                 poptPrintHelp(pc, stderr, 0);
2354                 exit(1);
2355         }
2356
2357         if (opt_challenge.length) {
2358                 if (!check_auth_crap()) {
2359                         exit(1);
2360                 }
2361                 exit(0);
2362         } 
2363
2364         if (!opt_password) {
2365                 opt_password = getpass("password: ");
2366         }
2367
2368         if (diagnostics) {
2369                 if (!diagnose_ntlm_auth()) {
2370                         return 1;
2371                 }
2372         } else {
2373                 fstring user;
2374
2375                 fstr_sprintf(user, "%s%c%s", opt_domain, winbind_separator(), opt_username);
2376                 if (!check_plaintext_auth(user, opt_password, True)) {
2377                         return 1;
2378                 }
2379         }
2380
2381         /* Exit code */
2382
2383         poptFreeContext(pc);
2384         TALLOC_FREE(frame);
2385         return 0;
2386 }