util_str: Don't return memory from talloc_tos(), use mem_ctx instead.
[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(talloc_tos(),
743                                         session_key);
744                         x_fprintf(x_stdout, "GK %s\n", key64?key64:"<NULL>");
745                         TALLOC_FREE(key64);
746                 } else {
747                         x_fprintf(x_stdout, "BH\n");
748                 }
749                         
750                 data_blob_free(&request);
751                 return;
752         } else {
753                 DEBUG(1, ("NTLMSSP query [%s] invalid", buf));
754                 x_fprintf(x_stdout, "BH\n");
755                 return;
756         }
757
758         if (!ntlmssp_state) {
759                 if (!NT_STATUS_IS_OK(nt_status = ntlm_auth_start_ntlmssp_server(&ntlmssp_state))) {
760                         x_fprintf(x_stdout, "BH %s\n", nt_errstr(nt_status));
761                         return;
762                 }
763                 ntlmssp_want_feature_list(ntlmssp_state, want_feature_list);
764         }
765
766         DEBUG(10, ("got NTLMSSP packet:\n"));
767         dump_data(10, request.data, request.length);
768
769         nt_status = ntlmssp_update(ntlmssp_state, request, &reply);
770         
771         if (NT_STATUS_EQUAL(nt_status, NT_STATUS_MORE_PROCESSING_REQUIRED)) {
772                 char *reply_base64 = base64_encode_data_blob(talloc_tos(),
773                                 reply);
774                 x_fprintf(x_stdout, "TT %s\n", reply_base64);
775                 TALLOC_FREE(reply_base64);
776                 data_blob_free(&reply);
777                 DEBUG(10, ("NTLMSSP challenge\n"));
778         } else if (NT_STATUS_EQUAL(nt_status, NT_STATUS_ACCESS_DENIED)) {
779                 x_fprintf(x_stdout, "BH %s\n", nt_errstr(nt_status));
780                 DEBUG(0, ("NTLMSSP BH: %s\n", nt_errstr(nt_status)));
781
782                 ntlmssp_end(&ntlmssp_state);
783         } else if (!NT_STATUS_IS_OK(nt_status)) {
784                 x_fprintf(x_stdout, "NA %s\n", nt_errstr(nt_status));
785                 DEBUG(10, ("NTLMSSP %s\n", nt_errstr(nt_status)));
786         } else {
787                 x_fprintf(x_stdout, "AF %s\n", (char *)ntlmssp_state->auth_context);
788                 DEBUG(10, ("NTLMSSP OK!\n"));
789                 
790                 if(have_session_key)
791                         data_blob_free(&session_key);
792                 session_key = data_blob(ntlmssp_state->session_key.data, 
793                                 ntlmssp_state->session_key.length);
794                 neg_flags = ntlmssp_state->neg_flags;
795                 have_session_key = True;
796         }
797
798         data_blob_free(&request);
799 }
800
801 static void manage_client_ntlmssp_request(enum stdio_helper_mode stdio_helper_mode, 
802                                          char *buf, int length) 
803 {
804         /* The statics here are *HORRIBLE* and this entire concept
805            needs to be rewritten. Essentially it's using these statics
806            as the state in a state machine. BLEEEGH ! JRA. */
807
808         static NTLMSSP_STATE *ntlmssp_state = NULL;
809         static DATA_BLOB initial_message;
810         static char* want_feature_list = NULL;
811         static uint32 neg_flags = 0;
812         static bool have_session_key = False;
813         static DATA_BLOB session_key;
814         DATA_BLOB request, reply;
815         NTSTATUS nt_status;
816         bool first = False;
817         
818         if (!opt_username || !*opt_username) {
819                 x_fprintf(x_stderr, "username must be specified!\n\n");
820                 exit(1);
821         }
822
823         if (strlen(buf) < 2) {
824                 DEBUG(1, ("NTLMSSP query [%s] invalid", buf));
825                 x_fprintf(x_stdout, "BH\n");
826                 return;
827         }
828
829         if (strlen(buf) > 3) {
830                 if(strncmp(buf, "SF ", 3) == 0) {
831                         DEBUG(10, ("Looking for flags to negotiate\n"));
832                         SAFE_FREE(want_feature_list);
833                         want_feature_list = SMB_STRNDUP(buf+3, strlen(buf)-3);
834                         x_fprintf(x_stdout, "OK\n");
835                         return;
836                 }
837                 request = base64_decode_data_blob(buf + 3);
838         } else {
839                 request = data_blob_null;
840         }
841
842         if (strncmp(buf, "PW ", 3) == 0) {
843                 /* We asked for a password and obviously got it :-) */
844
845                 opt_password = SMB_STRNDUP((const char *)request.data, request.length);
846
847                 if (opt_password == NULL) {
848                         DEBUG(1, ("Out of memory\n"));
849                         x_fprintf(x_stdout, "BH\n");
850                         data_blob_free(&request);
851                         return;
852                 }
853
854                 x_fprintf(x_stdout, "OK\n");
855                 data_blob_free(&request);
856                 return;
857         }
858
859         if (!ntlmssp_state && use_cached_creds) {
860                 /* check whether credentials are usable. */
861                 DATA_BLOB empty_blob = data_blob_null;
862
863                 nt_status = do_ccache_ntlm_auth(empty_blob, empty_blob, NULL);
864                 if (!NT_STATUS_EQUAL(nt_status, NT_STATUS_MORE_PROCESSING_REQUIRED)) {
865                         /* failed to use cached creds */
866                         use_cached_creds = False;
867                 }
868         }
869
870         if (opt_password == NULL && !use_cached_creds) {
871                 
872                 /* Request a password from the calling process.  After
873                    sending it, the calling process should retry asking for the negotiate. */
874                 
875                 DEBUG(10, ("Requesting password\n"));
876                 x_fprintf(x_stdout, "PW\n");
877                 return;
878         }
879
880         if (strncmp(buf, "YR", 2) == 0) {
881                 if (ntlmssp_state)
882                         ntlmssp_end(&ntlmssp_state);
883         } else if (strncmp(buf, "TT", 2) == 0) {
884                 
885         } else if (strncmp(buf, "GF", 2) == 0) {
886                 DEBUG(10, ("Requested negotiated NTLMSSP flags\n"));
887                 x_fprintf(x_stdout, "GF 0x%08lx\n", have_session_key?neg_flags:0l);
888                 data_blob_free(&request);
889                 return;
890         } else if (strncmp(buf, "GK", 2) == 0 ) {
891                 DEBUG(10, ("Requested session key\n"));
892
893                 if(have_session_key) {
894                         char *key64 = base64_encode_data_blob(talloc_tos(),
895                                         session_key);
896                         x_fprintf(x_stdout, "GK %s\n", key64?key64:"<NULL>");
897                         TALLOC_FREE(key64);
898                 }
899                 else {
900                         x_fprintf(x_stdout, "BH\n");
901                 }
902
903                 data_blob_free(&request);
904                 return;
905         } else {
906                 DEBUG(1, ("NTLMSSP query [%s] invalid", buf));
907                 x_fprintf(x_stdout, "BH\n");
908                 return;
909         }
910
911         if (!ntlmssp_state) {
912                 if (!NT_STATUS_IS_OK(nt_status = ntlm_auth_start_ntlmssp_client(&ntlmssp_state))) {
913                         x_fprintf(x_stdout, "BH %s\n", nt_errstr(nt_status));
914                         return;
915                 }
916                 ntlmssp_want_feature_list(ntlmssp_state, want_feature_list);
917                 first = True;
918                 initial_message = data_blob_null;
919         }
920
921         DEBUG(10, ("got NTLMSSP packet:\n"));
922         dump_data(10, request.data, request.length);
923
924         if (use_cached_creds && !opt_password && !first) {
925                 nt_status = do_ccache_ntlm_auth(initial_message, request, &reply);
926         } else {
927                 nt_status = ntlmssp_update(ntlmssp_state, request, &reply);
928         }
929         
930         if (NT_STATUS_EQUAL(nt_status, NT_STATUS_MORE_PROCESSING_REQUIRED)) {
931                 char *reply_base64 = base64_encode_data_blob(talloc_tos(),
932                                 reply);
933                 if (first) {
934                         x_fprintf(x_stdout, "YR %s\n", reply_base64);
935                 } else { 
936                         x_fprintf(x_stdout, "KK %s\n", reply_base64);
937                 }
938                 TALLOC_FREE(reply_base64);
939                 if (first) {
940                         initial_message = reply;
941                 } else {
942                         data_blob_free(&reply);
943                 }
944                 DEBUG(10, ("NTLMSSP challenge\n"));
945         } else if (NT_STATUS_IS_OK(nt_status)) {
946                 char *reply_base64 = base64_encode_data_blob(talloc_tos(),
947                                 reply);
948                 x_fprintf(x_stdout, "AF %s\n", reply_base64);
949                 TALLOC_FREE(reply_base64);
950
951                 if(have_session_key)
952                         data_blob_free(&session_key);
953
954                 session_key = data_blob(ntlmssp_state->session_key.data, 
955                                 ntlmssp_state->session_key.length);
956                 neg_flags = ntlmssp_state->neg_flags;
957                 have_session_key = True;
958
959                 DEBUG(10, ("NTLMSSP OK!\n"));
960                 if (ntlmssp_state)
961                         ntlmssp_end(&ntlmssp_state);
962         } else {
963                 x_fprintf(x_stdout, "BH %s\n", nt_errstr(nt_status));
964                 DEBUG(0, ("NTLMSSP BH: %s\n", nt_errstr(nt_status)));
965                 if (ntlmssp_state)
966                         ntlmssp_end(&ntlmssp_state);
967         }
968
969         data_blob_free(&request);
970 }
971
972 static void manage_squid_basic_request(enum stdio_helper_mode stdio_helper_mode, 
973                                        char *buf, int length) 
974 {
975         char *user, *pass;      
976         user=buf;
977         
978         pass=(char *)memchr(buf,' ',length);
979         if (!pass) {
980                 DEBUG(2, ("Password not found. Denying access\n"));
981                 x_fprintf(x_stdout, "ERR\n");
982                 return;
983         }
984         *pass='\0';
985         pass++;
986         
987         if (stdio_helper_mode == SQUID_2_5_BASIC) {
988                 rfc1738_unescape(user);
989                 rfc1738_unescape(pass);
990         }
991         
992         if (check_plaintext_auth(user, pass, False)) {
993                 x_fprintf(x_stdout, "OK\n");
994         } else {
995                 x_fprintf(x_stdout, "ERR\n");
996         }
997 }
998
999 static void offer_gss_spnego_mechs(void) {
1000
1001         DATA_BLOB token;
1002         SPNEGO_DATA spnego;
1003         ssize_t len;
1004         char *reply_base64;
1005         TALLOC_CTX *ctx = talloc_tos();
1006         char *principal;
1007         char *myname_lower;
1008
1009         ZERO_STRUCT(spnego);
1010
1011         myname_lower = talloc_strdup(ctx, global_myname());
1012         if (!myname_lower) {
1013                 return;
1014         }
1015         strlower_m(myname_lower);
1016
1017         principal = talloc_asprintf(ctx, "%s$@%s", myname_lower, lp_realm());
1018         if (!principal) {
1019                 return;
1020         }
1021
1022         /* Server negTokenInit (mech offerings) */
1023         spnego.type = SPNEGO_NEG_TOKEN_INIT;
1024         spnego.negTokenInit.mechTypes = SMB_XMALLOC_ARRAY(const char *, 2);
1025 #ifdef HAVE_KRB5
1026         spnego.negTokenInit.mechTypes[0] = smb_xstrdup(OID_KERBEROS5_OLD);
1027         spnego.negTokenInit.mechTypes[1] = smb_xstrdup(OID_NTLMSSP);
1028         spnego.negTokenInit.mechTypes[2] = NULL;
1029 #else
1030         spnego.negTokenInit.mechTypes[0] = smb_xstrdup(OID_NTLMSSP);
1031         spnego.negTokenInit.mechTypes[1] = NULL;
1032 #endif
1033
1034
1035         spnego.negTokenInit.mechListMIC = data_blob(principal,
1036                                                     strlen(principal));
1037
1038         len = write_spnego_data(&token, &spnego);
1039         free_spnego_data(&spnego);
1040
1041         if (len == -1) {
1042                 DEBUG(1, ("Could not write SPNEGO data blob\n"));
1043                 x_fprintf(x_stdout, "BH\n");
1044                 return;
1045         }
1046
1047         reply_base64 = base64_encode_data_blob(talloc_tos(), token);
1048         x_fprintf(x_stdout, "TT %s *\n", reply_base64);
1049
1050         TALLOC_FREE(reply_base64);
1051         data_blob_free(&token);
1052         DEBUG(10, ("sent SPNEGO negTokenInit\n"));
1053         return;
1054 }
1055
1056 static void manage_gss_spnego_request(enum stdio_helper_mode stdio_helper_mode, 
1057                                       char *buf, int length) 
1058 {
1059         static NTLMSSP_STATE *ntlmssp_state = NULL;
1060         SPNEGO_DATA request, response;
1061         DATA_BLOB token;
1062         NTSTATUS status;
1063         ssize_t len;
1064         TALLOC_CTX *ctx = talloc_tos();
1065
1066         char *user = NULL;
1067         char *domain = NULL;
1068
1069         const char *reply_code;
1070         char       *reply_base64;
1071         char *reply_argument = NULL;
1072
1073         if (strlen(buf) < 2) {
1074                 DEBUG(1, ("SPENGO query [%s] invalid", buf));
1075                 x_fprintf(x_stdout, "BH\n");
1076                 return;
1077         }
1078
1079         if (strncmp(buf, "YR", 2) == 0) {
1080                 if (ntlmssp_state)
1081                         ntlmssp_end(&ntlmssp_state);
1082         } else if (strncmp(buf, "KK", 2) == 0) {
1083                 ;
1084         } else {
1085                 DEBUG(1, ("SPENGO query [%s] invalid", buf));
1086                 x_fprintf(x_stdout, "BH\n");
1087                 return;
1088         }
1089
1090         if ( (strlen(buf) == 2)) {
1091
1092                 /* no client data, get the negTokenInit offering
1093                    mechanisms */
1094
1095                 offer_gss_spnego_mechs();
1096                 return;
1097         }
1098
1099         /* All subsequent requests have a blob. This might be negTokenInit or negTokenTarg */
1100
1101         if (strlen(buf) <= 3) {
1102                 DEBUG(1, ("GSS-SPNEGO query [%s] invalid\n", buf));
1103                 x_fprintf(x_stdout, "BH\n");
1104                 return;
1105         }
1106
1107         token = base64_decode_data_blob(buf + 3);
1108         len = read_spnego_data(token, &request);
1109         data_blob_free(&token);
1110
1111         if (len == -1) {
1112                 DEBUG(1, ("GSS-SPNEGO query [%s] invalid", buf));
1113                 x_fprintf(x_stdout, "BH\n");
1114                 return;
1115         }
1116
1117         if (request.type == SPNEGO_NEG_TOKEN_INIT) {
1118
1119                 /* Second request from Client. This is where the
1120                    client offers its mechanism to use. */
1121
1122                 if ( (request.negTokenInit.mechTypes == NULL) ||
1123                      (request.negTokenInit.mechTypes[0] == NULL) ) {
1124                         DEBUG(1, ("Client did not offer any mechanism"));
1125                         x_fprintf(x_stdout, "BH\n");
1126                         return;
1127                 }
1128
1129                 status = NT_STATUS_UNSUCCESSFUL;
1130                 if (strcmp(request.negTokenInit.mechTypes[0], OID_NTLMSSP) == 0) {
1131
1132                         if ( request.negTokenInit.mechToken.data == NULL ) {
1133                                 DEBUG(1, ("Client did not provide  NTLMSSP data\n"));
1134                                 x_fprintf(x_stdout, "BH\n");
1135                                 return;
1136                         }
1137
1138                         if ( ntlmssp_state != NULL ) {
1139                                 DEBUG(1, ("Client wants a new NTLMSSP challenge, but "
1140                                           "already got one\n"));
1141                                 x_fprintf(x_stdout, "BH\n");
1142                                 ntlmssp_end(&ntlmssp_state);
1143                                 return;
1144                         }
1145
1146                         if (!NT_STATUS_IS_OK(status = ntlm_auth_start_ntlmssp_server(&ntlmssp_state))) {
1147                                 x_fprintf(x_stdout, "BH %s\n", nt_errstr(status));
1148                                 return;
1149                         }
1150
1151                         DEBUG(10, ("got NTLMSSP packet:\n"));
1152                         dump_data(10, request.negTokenInit.mechToken.data,
1153                                   request.negTokenInit.mechToken.length);
1154
1155                         response.type = SPNEGO_NEG_TOKEN_TARG;
1156                         response.negTokenTarg.supportedMech = SMB_STRDUP(OID_NTLMSSP);
1157                         response.negTokenTarg.mechListMIC = data_blob_null;
1158
1159                         status = ntlmssp_update(ntlmssp_state,
1160                                                        request.negTokenInit.mechToken,
1161                                                        &response.negTokenTarg.responseToken);
1162                 }
1163
1164 #ifdef HAVE_KRB5
1165                 if (strcmp(request.negTokenInit.mechTypes[0], OID_KERBEROS5_OLD) == 0) {
1166
1167                         TALLOC_CTX *mem_ctx = talloc_init("manage_gss_spnego_request");
1168                         char *principal;
1169                         DATA_BLOB ap_rep;
1170                         DATA_BLOB session_key;
1171                         PAC_DATA *pac_data = NULL;
1172
1173                         if ( request.negTokenInit.mechToken.data == NULL ) {
1174                                 DEBUG(1, ("Client did not provide Kerberos data\n"));
1175                                 x_fprintf(x_stdout, "BH\n");
1176                                 return;
1177                         }
1178
1179                         response.type = SPNEGO_NEG_TOKEN_TARG;
1180                         response.negTokenTarg.supportedMech = SMB_STRDUP(OID_KERBEROS5_OLD);
1181                         response.negTokenTarg.mechListMIC = data_blob_null;
1182                         response.negTokenTarg.responseToken = data_blob_null;
1183
1184                         status = ads_verify_ticket(mem_ctx, lp_realm(), 0,
1185                                                    &request.negTokenInit.mechToken,
1186                                                    &principal, &pac_data, &ap_rep,
1187                                                    &session_key, True);
1188
1189                         talloc_destroy(mem_ctx);
1190
1191                         /* Now in "principal" we have the name we are
1192                            authenticated as. */
1193
1194                         if (NT_STATUS_IS_OK(status)) {
1195
1196                                 domain = strchr_m(principal, '@');
1197
1198                                 if (domain == NULL) {
1199                                         DEBUG(1, ("Did not get a valid principal "
1200                                                   "from ads_verify_ticket\n"));
1201                                         x_fprintf(x_stdout, "BH\n");
1202                                         return;
1203                                 }
1204
1205                                 *domain++ = '\0';
1206                                 domain = SMB_STRDUP(domain);
1207                                 user = SMB_STRDUP(principal);
1208
1209                                 data_blob_free(&ap_rep);
1210
1211                                 SAFE_FREE(principal);
1212                         }
1213                 }
1214 #endif
1215
1216         } else {
1217
1218                 if ( (request.negTokenTarg.supportedMech == NULL) ||
1219                      ( strcmp(request.negTokenTarg.supportedMech, OID_NTLMSSP) != 0 ) ) {
1220                         /* Kerberos should never send a negTokenTarg, OID_NTLMSSP
1221                            is the only one we support that sends this stuff */
1222                         DEBUG(1, ("Got a negTokenTarg for something non-NTLMSSP: %s\n",
1223                                   request.negTokenTarg.supportedMech));
1224                         x_fprintf(x_stdout, "BH\n");
1225                         return;
1226                 }
1227
1228                 if (request.negTokenTarg.responseToken.data == NULL) {
1229                         DEBUG(1, ("Got a negTokenTarg without a responseToken!\n"));
1230                         x_fprintf(x_stdout, "BH\n");
1231                         return;
1232                 }
1233
1234                 status = ntlmssp_update(ntlmssp_state,
1235                                                request.negTokenTarg.responseToken,
1236                                                &response.negTokenTarg.responseToken);
1237
1238                 response.type = SPNEGO_NEG_TOKEN_TARG;
1239                 response.negTokenTarg.supportedMech = SMB_STRDUP(OID_NTLMSSP);
1240                 response.negTokenTarg.mechListMIC = data_blob_null;
1241
1242                 if (NT_STATUS_IS_OK(status)) {
1243                         user = SMB_STRDUP(ntlmssp_state->user);
1244                         domain = SMB_STRDUP(ntlmssp_state->domain);
1245                         ntlmssp_end(&ntlmssp_state);
1246                 }
1247         }
1248
1249         free_spnego_data(&request);
1250
1251         if (NT_STATUS_IS_OK(status)) {
1252                 response.negTokenTarg.negResult = SPNEGO_ACCEPT_COMPLETED;
1253                 reply_code = "AF";
1254                 reply_argument = talloc_asprintf(ctx, "%s\\%s", domain, user);
1255         } else if (NT_STATUS_EQUAL(status,
1256                                    NT_STATUS_MORE_PROCESSING_REQUIRED)) {
1257                 response.negTokenTarg.negResult = SPNEGO_ACCEPT_INCOMPLETE;
1258                 reply_code = "TT";
1259                 reply_argument = talloc_strdup(ctx, "*");
1260         } else {
1261                 response.negTokenTarg.negResult = SPNEGO_REJECT;
1262                 reply_code = "NA";
1263                 reply_argument = talloc_strdup(ctx, nt_errstr(status));
1264         }
1265
1266         if (!reply_argument) {
1267                 DEBUG(1, ("Could not write SPNEGO data blob\n"));
1268                 x_fprintf(x_stdout, "BH\n");
1269                 return;
1270         }
1271
1272         SAFE_FREE(user);
1273         SAFE_FREE(domain);
1274
1275         len = write_spnego_data(&token, &response);
1276         free_spnego_data(&response);
1277
1278         if (len == -1) {
1279                 DEBUG(1, ("Could not write SPNEGO data blob\n"));
1280                 x_fprintf(x_stdout, "BH\n");
1281                 return;
1282         }
1283
1284         reply_base64 = base64_encode_data_blob(talloc_tos(), token);
1285
1286         x_fprintf(x_stdout, "%s %s %s\n",
1287                   reply_code, reply_base64, reply_argument);
1288
1289         TALLOC_FREE(reply_base64);
1290         data_blob_free(&token);
1291
1292         return;
1293 }
1294
1295 static NTLMSSP_STATE *client_ntlmssp_state = NULL;
1296
1297 static bool manage_client_ntlmssp_init(SPNEGO_DATA spnego)
1298 {
1299         NTSTATUS status;
1300         DATA_BLOB null_blob = data_blob_null;
1301         DATA_BLOB to_server;
1302         char *to_server_base64;
1303         const char *my_mechs[] = {OID_NTLMSSP, NULL};
1304
1305         DEBUG(10, ("Got spnego negTokenInit with NTLMSSP\n"));
1306
1307         if (client_ntlmssp_state != NULL) {
1308                 DEBUG(1, ("Request for initial SPNEGO request where "
1309                           "we already have a state\n"));
1310                 return False;
1311         }
1312
1313         if (!client_ntlmssp_state) {
1314                 if (!NT_STATUS_IS_OK(status = ntlm_auth_start_ntlmssp_client(&client_ntlmssp_state))) {
1315                         x_fprintf(x_stdout, "BH %s\n", nt_errstr(status));
1316                         return False;
1317                 }
1318         }
1319
1320
1321         if (opt_password == NULL) {
1322
1323                 /* Request a password from the calling process.  After
1324                    sending it, the calling process should retry with
1325                    the negTokenInit. */
1326
1327                 DEBUG(10, ("Requesting password\n"));
1328                 x_fprintf(x_stdout, "PW\n");
1329                 return True;
1330         }
1331
1332         spnego.type = SPNEGO_NEG_TOKEN_INIT;
1333         spnego.negTokenInit.mechTypes = my_mechs;
1334         spnego.negTokenInit.reqFlags = 0;
1335         spnego.negTokenInit.mechListMIC = null_blob;
1336
1337         status = ntlmssp_update(client_ntlmssp_state, null_blob,
1338                                        &spnego.negTokenInit.mechToken);
1339
1340         if ( !(NT_STATUS_EQUAL(status, NT_STATUS_MORE_PROCESSING_REQUIRED) ||
1341                         NT_STATUS_IS_OK(status)) ) {
1342                 DEBUG(1, ("Expected OK or MORE_PROCESSING_REQUIRED, got: %s\n",
1343                           nt_errstr(status)));
1344                 ntlmssp_end(&client_ntlmssp_state);
1345                 return False;
1346         }
1347
1348         write_spnego_data(&to_server, &spnego);
1349         data_blob_free(&spnego.negTokenInit.mechToken);
1350
1351         to_server_base64 = base64_encode_data_blob(talloc_tos(), to_server);
1352         data_blob_free(&to_server);
1353         x_fprintf(x_stdout, "KK %s\n", to_server_base64);
1354         TALLOC_FREE(to_server_base64);
1355         return True;
1356 }
1357
1358 static void manage_client_ntlmssp_targ(SPNEGO_DATA spnego)
1359 {
1360         NTSTATUS status;
1361         DATA_BLOB null_blob = data_blob_null;
1362         DATA_BLOB request;
1363         DATA_BLOB to_server;
1364         char *to_server_base64;
1365
1366         DEBUG(10, ("Got spnego negTokenTarg with NTLMSSP\n"));
1367
1368         if (client_ntlmssp_state == NULL) {
1369                 DEBUG(1, ("Got NTLMSSP tArg without a client state\n"));
1370                 x_fprintf(x_stdout, "BH\n");
1371                 return;
1372         }
1373
1374         if (spnego.negTokenTarg.negResult == SPNEGO_REJECT) {
1375                 x_fprintf(x_stdout, "NA\n");
1376                 ntlmssp_end(&client_ntlmssp_state);
1377                 return;
1378         }
1379
1380         if (spnego.negTokenTarg.negResult == SPNEGO_ACCEPT_COMPLETED) {
1381                 x_fprintf(x_stdout, "AF\n");
1382                 ntlmssp_end(&client_ntlmssp_state);
1383                 return;
1384         }
1385
1386         status = ntlmssp_update(client_ntlmssp_state,
1387                                        spnego.negTokenTarg.responseToken,
1388                                        &request);
1389                 
1390         if (!NT_STATUS_EQUAL(status, NT_STATUS_MORE_PROCESSING_REQUIRED)) {
1391                 DEBUG(1, ("Expected MORE_PROCESSING_REQUIRED from "
1392                           "ntlmssp_client_update, got: %s\n",
1393                           nt_errstr(status)));
1394                 x_fprintf(x_stdout, "BH\n");
1395                 data_blob_free(&request);
1396                 ntlmssp_end(&client_ntlmssp_state);
1397                 return;
1398         }
1399
1400         spnego.type = SPNEGO_NEG_TOKEN_TARG;
1401         spnego.negTokenTarg.negResult = SPNEGO_ACCEPT_INCOMPLETE;
1402         spnego.negTokenTarg.supportedMech = (char *)OID_NTLMSSP;
1403         spnego.negTokenTarg.responseToken = request;
1404         spnego.negTokenTarg.mechListMIC = null_blob;
1405         
1406         write_spnego_data(&to_server, &spnego);
1407         data_blob_free(&request);
1408
1409         to_server_base64 = base64_encode_data_blob(talloc_tos(), to_server);
1410         data_blob_free(&to_server);
1411         x_fprintf(x_stdout, "KK %s\n", to_server_base64);
1412         TALLOC_FREE(to_server_base64);
1413         return;
1414 }
1415
1416 #ifdef HAVE_KRB5
1417
1418 static bool manage_client_krb5_init(SPNEGO_DATA spnego)
1419 {
1420         char *principal;
1421         DATA_BLOB tkt, to_server;
1422         DATA_BLOB session_key_krb5 = data_blob_null;
1423         SPNEGO_DATA reply;
1424         char *reply_base64;
1425         int retval;
1426
1427         const char *my_mechs[] = {OID_KERBEROS5_OLD, NULL};
1428         ssize_t len;
1429
1430         if ( (spnego.negTokenInit.mechListMIC.data == NULL) ||
1431              (spnego.negTokenInit.mechListMIC.length == 0) ) {
1432                 DEBUG(1, ("Did not get a principal for krb5\n"));
1433                 return False;
1434         }
1435
1436         principal = (char *)SMB_MALLOC(
1437                 spnego.negTokenInit.mechListMIC.length+1);
1438
1439         if (principal == NULL) {
1440                 DEBUG(1, ("Could not malloc principal\n"));
1441                 return False;
1442         }
1443
1444         memcpy(principal, spnego.negTokenInit.mechListMIC.data,
1445                spnego.negTokenInit.mechListMIC.length);
1446         principal[spnego.negTokenInit.mechListMIC.length] = '\0';
1447
1448         retval = cli_krb5_get_ticket(principal, 0, &tkt, &session_key_krb5, 0, NULL, NULL);
1449
1450         if (retval) {
1451                 char *user = NULL;
1452
1453                 /* Let's try to first get the TGT, for that we need a
1454                    password. */
1455
1456                 if (opt_password == NULL) {
1457                         DEBUG(10, ("Requesting password\n"));
1458                         x_fprintf(x_stdout, "PW\n");
1459                         return True;
1460                 }
1461
1462                 user = talloc_asprintf(talloc_tos(), "%s@%s", opt_username, opt_domain);
1463                 if (!user) {
1464                         return false;
1465                 }
1466
1467                 if ((retval = kerberos_kinit_password(user, opt_password, 0, NULL))) {
1468                         DEBUG(10, ("Requesting TGT failed: %s\n", error_message(retval)));
1469                         return False;
1470                 }
1471
1472                 retval = cli_krb5_get_ticket(principal, 0, &tkt, &session_key_krb5, 0, NULL, NULL);
1473
1474                 if (retval) {
1475                         DEBUG(10, ("Kinit suceeded, but getting a ticket failed: %s\n", error_message(retval)));
1476                         return False;
1477                 }
1478         }
1479
1480         data_blob_free(&session_key_krb5);
1481
1482         ZERO_STRUCT(reply);
1483
1484         reply.type = SPNEGO_NEG_TOKEN_INIT;
1485         reply.negTokenInit.mechTypes = my_mechs;
1486         reply.negTokenInit.reqFlags = 0;
1487         reply.negTokenInit.mechToken = tkt;
1488         reply.negTokenInit.mechListMIC = data_blob_null;
1489
1490         len = write_spnego_data(&to_server, &reply);
1491         data_blob_free(&tkt);
1492
1493         if (len == -1) {
1494                 DEBUG(1, ("Could not write SPNEGO data blob\n"));
1495                 return False;
1496         }
1497
1498         reply_base64 = base64_encode_data_blob(talloc_tos(), to_server);
1499         x_fprintf(x_stdout, "KK %s *\n", reply_base64);
1500
1501         TALLOC_FREE(reply_base64);
1502         data_blob_free(&to_server);
1503         DEBUG(10, ("sent GSS-SPNEGO KERBEROS5 negTokenInit\n"));
1504         return True;
1505 }
1506
1507 static void manage_client_krb5_targ(SPNEGO_DATA spnego)
1508 {
1509         switch (spnego.negTokenTarg.negResult) {
1510         case SPNEGO_ACCEPT_INCOMPLETE:
1511                 DEBUG(1, ("Got a Kerberos negTokenTarg with ACCEPT_INCOMPLETE\n"));
1512                 x_fprintf(x_stdout, "BH\n");
1513                 break;
1514         case SPNEGO_ACCEPT_COMPLETED:
1515                 DEBUG(10, ("Accept completed\n"));
1516                 x_fprintf(x_stdout, "AF\n");
1517                 break;
1518         case SPNEGO_REJECT:
1519                 DEBUG(10, ("Rejected\n"));
1520                 x_fprintf(x_stdout, "NA\n");
1521                 break;
1522         default:
1523                 DEBUG(1, ("Got an invalid negTokenTarg\n"));
1524                 x_fprintf(x_stdout, "AF\n");
1525         }
1526 }
1527
1528 #endif
1529
1530 static void manage_gss_spnego_client_request(enum stdio_helper_mode stdio_helper_mode, 
1531                                              char *buf, int length) 
1532 {
1533         DATA_BLOB request;
1534         SPNEGO_DATA spnego;
1535         ssize_t len;
1536
1537         if (!opt_username || !*opt_username) {
1538                 x_fprintf(x_stderr, "username must be specified!\n\n");
1539                 exit(1);
1540         }
1541
1542         if (strlen(buf) <= 3) {
1543                 DEBUG(1, ("SPNEGO query [%s] too short\n", buf));
1544                 x_fprintf(x_stdout, "BH\n");
1545                 return;
1546         }
1547
1548         request = base64_decode_data_blob(buf+3);
1549
1550         if (strncmp(buf, "PW ", 3) == 0) {
1551
1552                 /* We asked for a password and obviously got it :-) */
1553
1554                 opt_password = SMB_STRNDUP((const char *)request.data, request.length);
1555                 
1556                 if (opt_password == NULL) {
1557                         DEBUG(1, ("Out of memory\n"));
1558                         x_fprintf(x_stdout, "BH\n");
1559                         data_blob_free(&request);
1560                         return;
1561                 }
1562
1563                 x_fprintf(x_stdout, "OK\n");
1564                 data_blob_free(&request);
1565                 return;
1566         }
1567
1568         if ( (strncmp(buf, "TT ", 3) != 0) &&
1569              (strncmp(buf, "AF ", 3) != 0) &&
1570              (strncmp(buf, "NA ", 3) != 0) ) {
1571                 DEBUG(1, ("SPNEGO request [%s] invalid\n", buf));
1572                 x_fprintf(x_stdout, "BH\n");
1573                 data_blob_free(&request);
1574                 return;
1575         }
1576
1577         /* So we got a server challenge to generate a SPNEGO
1578            client-to-server request... */
1579
1580         len = read_spnego_data(request, &spnego);
1581         data_blob_free(&request);
1582
1583         if (len == -1) {
1584                 DEBUG(1, ("Could not read SPNEGO data for [%s]\n", buf));
1585                 x_fprintf(x_stdout, "BH\n");
1586                 return;
1587         }
1588
1589         if (spnego.type == SPNEGO_NEG_TOKEN_INIT) {
1590
1591                 /* The server offers a list of mechanisms */
1592
1593                 const char **mechType = (const char **)spnego.negTokenInit.mechTypes;
1594
1595                 while (*mechType != NULL) {
1596
1597 #ifdef HAVE_KRB5
1598                         if ( (strcmp(*mechType, OID_KERBEROS5_OLD) == 0) ||
1599                              (strcmp(*mechType, OID_KERBEROS5) == 0) ) {
1600                                 if (manage_client_krb5_init(spnego))
1601                                         goto out;
1602                         }
1603 #endif
1604
1605                         if (strcmp(*mechType, OID_NTLMSSP) == 0) {
1606                                 if (manage_client_ntlmssp_init(spnego))
1607                                         goto out;
1608                         }
1609
1610                         mechType++;
1611                 }
1612
1613                 DEBUG(1, ("Server offered no compatible mechanism\n"));
1614                 x_fprintf(x_stdout, "BH\n");
1615                 return;
1616         }
1617
1618         if (spnego.type == SPNEGO_NEG_TOKEN_TARG) {
1619
1620                 if (spnego.negTokenTarg.supportedMech == NULL) {
1621                         /* On accept/reject Windows does not send the
1622                            mechanism anymore. Handle that here and
1623                            shut down the mechanisms. */
1624
1625                         switch (spnego.negTokenTarg.negResult) {
1626                         case SPNEGO_ACCEPT_COMPLETED:
1627                                 x_fprintf(x_stdout, "AF\n");
1628                                 break;
1629                         case SPNEGO_REJECT:
1630                                 x_fprintf(x_stdout, "NA\n");
1631                                 break;
1632                         default:
1633                                 DEBUG(1, ("Got a negTokenTarg with no mech and an "
1634                                           "unknown negResult: %d\n",
1635                                           spnego.negTokenTarg.negResult));
1636                                 x_fprintf(x_stdout, "BH\n");
1637                         }
1638
1639                         ntlmssp_end(&client_ntlmssp_state);
1640                         goto out;
1641                 }
1642
1643                 if (strcmp(spnego.negTokenTarg.supportedMech,
1644                            OID_NTLMSSP) == 0) {
1645                         manage_client_ntlmssp_targ(spnego);
1646                         goto out;
1647                 }
1648
1649 #if HAVE_KRB5
1650                 if (strcmp(spnego.negTokenTarg.supportedMech,
1651                            OID_KERBEROS5_OLD) == 0) {
1652                         manage_client_krb5_targ(spnego);
1653                         goto out;
1654                 }
1655 #endif
1656
1657         }
1658
1659         DEBUG(1, ("Got an SPNEGO token I could not handle [%s]!\n", buf));
1660         x_fprintf(x_stdout, "BH\n");
1661         return;
1662
1663  out:
1664         free_spnego_data(&spnego);
1665         return;
1666 }
1667
1668 static void manage_ntlm_server_1_request(enum stdio_helper_mode stdio_helper_mode, 
1669                                          char *buf, int length) 
1670 {
1671         char *request, *parameter;      
1672         static DATA_BLOB challenge;
1673         static DATA_BLOB lm_response;
1674         static DATA_BLOB nt_response;
1675         static char *full_username;
1676         static char *username;
1677         static char *domain;
1678         static char *plaintext_password;
1679         static bool ntlm_server_1_user_session_key;
1680         static bool ntlm_server_1_lm_session_key;
1681         
1682         if (strequal(buf, ".")) {
1683                 if (!full_username && !username) {      
1684                         x_fprintf(x_stdout, "Error: No username supplied!\n");
1685                 } else if (plaintext_password) {
1686                         /* handle this request as plaintext */
1687                         if (!full_username) {
1688                                 if (asprintf(&full_username, "%s%c%s", domain, winbind_separator(), username) == -1) {
1689                                         x_fprintf(x_stdout, "Error: Out of memory in asprintf!\n.\n");
1690                                         return;
1691                                 }
1692                         }
1693                         if (check_plaintext_auth(full_username, plaintext_password, False)) {
1694                                 x_fprintf(x_stdout, "Authenticated: Yes\n");
1695                         } else {
1696                                 x_fprintf(x_stdout, "Authenticated: No\n");
1697                         }
1698                 } else if (!lm_response.data && !nt_response.data) {
1699                         x_fprintf(x_stdout, "Error: No password supplied!\n");
1700                 } else if (!challenge.data) {   
1701                         x_fprintf(x_stdout, "Error: No lanman-challenge supplied!\n");
1702                 } else {
1703                         char *error_string = NULL;
1704                         uchar lm_key[8];
1705                         uchar user_session_key[16];
1706                         uint32 flags = 0;
1707
1708                         if (full_username && !username) {
1709                                 fstring fstr_user;
1710                                 fstring fstr_domain;
1711                                 
1712                                 if (!parse_ntlm_auth_domain_user(full_username, fstr_user, fstr_domain)) {
1713                                         /* username might be 'tainted', don't print into our new-line deleimianted stream */
1714                                         x_fprintf(x_stdout, "Error: Could not parse into domain and username\n");
1715                                 }
1716                                 SAFE_FREE(username);
1717                                 SAFE_FREE(domain);
1718                                 username = smb_xstrdup(fstr_user);
1719                                 domain = smb_xstrdup(fstr_domain);
1720                         }
1721
1722                         if (!domain) {
1723                                 domain = smb_xstrdup(get_winbind_domain());
1724                         }
1725
1726                         if (ntlm_server_1_lm_session_key) 
1727                                 flags |= WBFLAG_PAM_LMKEY;
1728                         
1729                         if (ntlm_server_1_user_session_key) 
1730                                 flags |= WBFLAG_PAM_USER_SESSION_KEY;
1731
1732                         if (!NT_STATUS_IS_OK(
1733                                     contact_winbind_auth_crap(username, 
1734                                                               domain, 
1735                                                               global_myname(),
1736                                                               &challenge, 
1737                                                               &lm_response, 
1738                                                               &nt_response, 
1739                                                               flags, 
1740                                                               lm_key, 
1741                                                               user_session_key,
1742                                                               &error_string,
1743                                                               NULL))) {
1744
1745                                 x_fprintf(x_stdout, "Authenticated: No\n");
1746                                 x_fprintf(x_stdout, "Authentication-Error: %s\n.\n", error_string);
1747                                 SAFE_FREE(error_string);
1748                         } else {
1749                                 static char zeros[16];
1750                                 char *hex_lm_key;
1751                                 char *hex_user_session_key;
1752
1753                                 x_fprintf(x_stdout, "Authenticated: Yes\n");
1754
1755                                 if (ntlm_server_1_lm_session_key 
1756                                     && (memcmp(zeros, lm_key, 
1757                                                sizeof(lm_key)) != 0)) {
1758                                         hex_lm_key = hex_encode(NULL,
1759                                                                 (const unsigned char *)lm_key,
1760                                                                 sizeof(lm_key));
1761                                         x_fprintf(x_stdout, "LANMAN-Session-Key: %s\n", hex_lm_key);
1762                                         TALLOC_FREE(hex_lm_key);
1763                                 }
1764
1765                                 if (ntlm_server_1_user_session_key 
1766                                     && (memcmp(zeros, user_session_key, 
1767                                                sizeof(user_session_key)) != 0)) {
1768                                         hex_user_session_key = hex_encode(NULL,
1769                                                                           (const unsigned char *)user_session_key, 
1770                                                                           sizeof(user_session_key));
1771                                         x_fprintf(x_stdout, "User-Session-Key: %s\n", hex_user_session_key);
1772                                         TALLOC_FREE(hex_user_session_key);
1773                                 }
1774                         }
1775                 }
1776                 /* clear out the state */
1777                 challenge = data_blob_null;
1778                 nt_response = data_blob_null;
1779                 lm_response = data_blob_null;
1780                 SAFE_FREE(full_username);
1781                 SAFE_FREE(username);
1782                 SAFE_FREE(domain);
1783                 SAFE_FREE(plaintext_password);
1784                 ntlm_server_1_user_session_key = False;
1785                 ntlm_server_1_lm_session_key = False;
1786                 x_fprintf(x_stdout, ".\n");
1787
1788                 return;
1789         }
1790
1791         request = buf;
1792
1793         /* Indicates a base64 encoded structure */
1794         parameter = strstr_m(request, ":: ");
1795         if (!parameter) {
1796                 parameter = strstr_m(request, ": ");
1797                 
1798                 if (!parameter) {
1799                         DEBUG(0, ("Parameter not found!\n"));
1800                         x_fprintf(x_stdout, "Error: Parameter not found!\n.\n");
1801                         return;
1802                 }
1803                 
1804                 parameter[0] ='\0';
1805                 parameter++;
1806                 parameter[0] ='\0';
1807                 parameter++;
1808
1809         } else {
1810                 parameter[0] ='\0';
1811                 parameter++;
1812                 parameter[0] ='\0';
1813                 parameter++;
1814                 parameter[0] ='\0';
1815                 parameter++;
1816
1817                 base64_decode_inplace(parameter);
1818         }
1819
1820         if (strequal(request, "LANMAN-Challenge")) {
1821                 challenge = strhex_to_data_blob(NULL, parameter);
1822                 if (challenge.length != 8) {
1823                         x_fprintf(x_stdout, "Error: hex decode of %s failed! (got %d bytes, expected 8)\n.\n", 
1824                                   parameter,
1825                                   (int)challenge.length);
1826                         challenge = data_blob_null;
1827                 }
1828         } else if (strequal(request, "NT-Response")) {
1829                 nt_response = strhex_to_data_blob(NULL, parameter);
1830                 if (nt_response.length < 24) {
1831                         x_fprintf(x_stdout, "Error: hex decode of %s failed! (only got %d bytes, needed at least 24)\n.\n", 
1832                                   parameter,
1833                                   (int)nt_response.length);
1834                         nt_response = data_blob_null;
1835                 }
1836         } else if (strequal(request, "LANMAN-Response")) {
1837                 lm_response = strhex_to_data_blob(NULL, parameter);
1838                 if (lm_response.length != 24) {
1839                         x_fprintf(x_stdout, "Error: hex decode of %s failed! (got %d bytes, expected 24)\n.\n", 
1840                                   parameter,
1841                                   (int)lm_response.length);
1842                         lm_response = data_blob_null;
1843                 }
1844         } else if (strequal(request, "Password")) {
1845                 plaintext_password = smb_xstrdup(parameter);
1846         } else if (strequal(request, "NT-Domain")) {
1847                 domain = smb_xstrdup(parameter);
1848         } else if (strequal(request, "Username")) {
1849                 username = smb_xstrdup(parameter);
1850         } else if (strequal(request, "Full-Username")) {
1851                 full_username = smb_xstrdup(parameter);
1852         } else if (strequal(request, "Request-User-Session-Key")) {
1853                 ntlm_server_1_user_session_key = strequal(parameter, "Yes");
1854         } else if (strequal(request, "Request-LanMan-Session-Key")) {
1855                 ntlm_server_1_lm_session_key = strequal(parameter, "Yes");
1856         } else {
1857                 x_fprintf(x_stdout, "Error: Unknown request %s\n.\n", request);
1858         }
1859 }
1860
1861 static void manage_ntlm_change_password_1_request(enum stdio_helper_mode helper_mode, char *buf, int length)
1862 {
1863         char *request, *parameter;      
1864         static DATA_BLOB new_nt_pswd;
1865         static DATA_BLOB old_nt_hash_enc;
1866         static DATA_BLOB new_lm_pswd;
1867         static DATA_BLOB old_lm_hash_enc;
1868         static char *full_username = NULL;
1869         static char *username = NULL;
1870         static char *domain = NULL;
1871         static char *newpswd =  NULL;
1872         static char *oldpswd = NULL;
1873
1874         if (strequal(buf, ".")) {
1875                 if(newpswd && oldpswd) {
1876                         uchar old_nt_hash[16];
1877                         uchar old_lm_hash[16];
1878                         uchar new_nt_hash[16];
1879                         uchar new_lm_hash[16];
1880
1881                         new_nt_pswd = data_blob(NULL, 516);
1882                         old_nt_hash_enc = data_blob(NULL, 16);
1883                         
1884                         /* Calculate the MD4 hash (NT compatible) of the
1885                          * password */
1886                         E_md4hash(oldpswd, old_nt_hash);
1887                         E_md4hash(newpswd, new_nt_hash);
1888
1889                         /* E_deshash returns false for 'long'
1890                            passwords (> 14 DOS chars).  
1891                            
1892                            Therefore, don't send a buffer
1893                            encrypted with the truncated hash
1894                            (it could allow an even easier
1895                            attack on the password)
1896
1897                            Likewise, obey the admin's restriction
1898                         */
1899
1900                         if (lp_client_lanman_auth() &&
1901                             E_deshash(newpswd, new_lm_hash) &&
1902                             E_deshash(oldpswd, old_lm_hash)) {
1903                                 new_lm_pswd = data_blob(NULL, 516);
1904                                 old_lm_hash_enc = data_blob(NULL, 16);
1905                                 encode_pw_buffer(new_lm_pswd.data, newpswd,
1906                                                  STR_UNICODE);
1907
1908                                 SamOEMhash(new_lm_pswd.data, old_nt_hash, 516);
1909                                 E_old_pw_hash(new_nt_hash, old_lm_hash,
1910                                               old_lm_hash_enc.data);
1911                         } else {
1912                                 new_lm_pswd.data = NULL;
1913                                 new_lm_pswd.length = 0;
1914                                 old_lm_hash_enc.data = NULL;
1915                                 old_lm_hash_enc.length = 0;
1916                         }
1917
1918                         encode_pw_buffer(new_nt_pswd.data, newpswd,
1919                                          STR_UNICODE);
1920         
1921                         SamOEMhash(new_nt_pswd.data, old_nt_hash, 516);
1922                         E_old_pw_hash(new_nt_hash, old_nt_hash,
1923                                       old_nt_hash_enc.data);
1924                 }
1925                 
1926                 if (!full_username && !username) {      
1927                         x_fprintf(x_stdout, "Error: No username supplied!\n");
1928                 } else if ((!new_nt_pswd.data || !old_nt_hash_enc.data) &&
1929                            (!new_lm_pswd.data || old_lm_hash_enc.data) ) {
1930                         x_fprintf(x_stdout, "Error: No NT or LM password "
1931                                   "blobs supplied!\n");
1932                 } else {
1933                         char *error_string = NULL;
1934                         
1935                         if (full_username && !username) {
1936                                 fstring fstr_user;
1937                                 fstring fstr_domain;
1938                                 
1939                                 if (!parse_ntlm_auth_domain_user(full_username,
1940                                                                  fstr_user,
1941                                                                  fstr_domain)) {
1942                                         /* username might be 'tainted', don't
1943                                          * print into our new-line
1944                                          * deleimianted stream */
1945                                         x_fprintf(x_stdout, "Error: Could not "
1946                                                   "parse into domain and "
1947                                                   "username\n");
1948                                         SAFE_FREE(username);
1949                                         username = smb_xstrdup(full_username);
1950                                 } else {
1951                                         SAFE_FREE(username);
1952                                         SAFE_FREE(domain);
1953                                         username = smb_xstrdup(fstr_user);
1954                                         domain = smb_xstrdup(fstr_domain);
1955                                 }
1956                                 
1957                         }
1958
1959                         if(!NT_STATUS_IS_OK(contact_winbind_change_pswd_auth_crap(
1960                                                     username, domain,
1961                                                     new_nt_pswd,
1962                                                     old_nt_hash_enc,
1963                                                     new_lm_pswd,
1964                                                     old_lm_hash_enc,
1965                                                     &error_string))) {
1966                                 x_fprintf(x_stdout, "Password-Change: No\n");
1967                                 x_fprintf(x_stdout, "Password-Change-Error: "
1968                                           "%s\n.\n", error_string);
1969                         } else {
1970                                 x_fprintf(x_stdout, "Password-Change: Yes\n");
1971                         }
1972
1973                         SAFE_FREE(error_string);
1974                 }
1975                 /* clear out the state */
1976                 new_nt_pswd = data_blob_null;
1977                 old_nt_hash_enc = data_blob_null;
1978                 new_lm_pswd = data_blob_null;
1979                 old_nt_hash_enc = data_blob_null;
1980                 SAFE_FREE(full_username);
1981                 SAFE_FREE(username);
1982                 SAFE_FREE(domain);
1983                 SAFE_FREE(newpswd);
1984                 SAFE_FREE(oldpswd);
1985                 x_fprintf(x_stdout, ".\n");
1986
1987                 return;
1988         }
1989
1990         request = buf;
1991
1992         /* Indicates a base64 encoded structure */
1993         parameter = strstr_m(request, ":: ");
1994         if (!parameter) {
1995                 parameter = strstr_m(request, ": ");
1996                 
1997                 if (!parameter) {
1998                         DEBUG(0, ("Parameter not found!\n"));
1999                         x_fprintf(x_stdout, "Error: Parameter not found!\n.\n");
2000                         return;
2001                 }
2002                 
2003                 parameter[0] ='\0';
2004                 parameter++;
2005                 parameter[0] ='\0';
2006                 parameter++;
2007         } else {
2008                 parameter[0] ='\0';
2009                 parameter++;
2010                 parameter[0] ='\0';
2011                 parameter++;
2012                 parameter[0] ='\0';
2013                 parameter++;
2014
2015                 base64_decode_inplace(parameter);
2016         }
2017
2018         if (strequal(request, "new-nt-password-blob")) {
2019                 new_nt_pswd = strhex_to_data_blob(NULL, parameter);
2020                 if (new_nt_pswd.length != 516) {
2021                         x_fprintf(x_stdout, "Error: hex decode of %s failed! "
2022                                   "(got %d bytes, expected 516)\n.\n", 
2023                                   parameter,
2024                                   (int)new_nt_pswd.length);
2025                         new_nt_pswd = data_blob_null;
2026                 }
2027         } else if (strequal(request, "old-nt-hash-blob")) {
2028                 old_nt_hash_enc = strhex_to_data_blob(NULL, parameter);
2029                 if (old_nt_hash_enc.length != 16) {
2030                         x_fprintf(x_stdout, "Error: hex decode of %s failed! "
2031                                   "(got %d bytes, expected 16)\n.\n", 
2032                                   parameter,
2033                                   (int)old_nt_hash_enc.length);
2034                         old_nt_hash_enc = data_blob_null;
2035                 }
2036         } else if (strequal(request, "new-lm-password-blob")) {
2037                 new_lm_pswd = strhex_to_data_blob(NULL, parameter);
2038                 if (new_lm_pswd.length != 516) {
2039                         x_fprintf(x_stdout, "Error: hex decode of %s failed! "
2040                                   "(got %d bytes, expected 516)\n.\n", 
2041                                   parameter,
2042                                   (int)new_lm_pswd.length);
2043                         new_lm_pswd = data_blob_null;
2044                 }
2045         }
2046         else if (strequal(request, "old-lm-hash-blob")) {
2047                 old_lm_hash_enc = strhex_to_data_blob(NULL, parameter);
2048                 if (old_lm_hash_enc.length != 16)
2049                 {
2050                         x_fprintf(x_stdout, "Error: hex decode of %s failed! "
2051                                   "(got %d bytes, expected 16)\n.\n", 
2052                                   parameter,
2053                                   (int)old_lm_hash_enc.length);
2054                         old_lm_hash_enc = data_blob_null;
2055                 }
2056         } else if (strequal(request, "nt-domain")) {
2057                 domain = smb_xstrdup(parameter);
2058         } else if(strequal(request, "username")) {
2059                 username = smb_xstrdup(parameter);
2060         } else if(strequal(request, "full-username")) {
2061                 username = smb_xstrdup(parameter);
2062         } else if(strequal(request, "new-password")) {
2063                 newpswd = smb_xstrdup(parameter);
2064         } else if (strequal(request, "old-password")) {
2065                 oldpswd = smb_xstrdup(parameter);
2066         } else {
2067                 x_fprintf(x_stdout, "Error: Unknown request %s\n.\n", request);
2068         }
2069 }
2070
2071 static void manage_squid_request(enum stdio_helper_mode helper_mode, stdio_helper_function fn) 
2072 {
2073         char buf[SQUID_BUFFER_SIZE+1];
2074         int length;
2075         char *c;
2076         static bool err;
2077
2078         /* this is not a typo - x_fgets doesn't work too well under squid */
2079         if (fgets(buf, sizeof(buf)-1, stdin) == NULL) {
2080                 if (ferror(stdin)) {
2081                         DEBUG(1, ("fgets() failed! dying..... errno=%d (%s)\n", ferror(stdin),
2082                                   strerror(ferror(stdin))));
2083                         
2084                         exit(1);    /* BIIG buffer */
2085                 }
2086                 exit(0);
2087         }
2088     
2089         c=(char *)memchr(buf,'\n',sizeof(buf)-1);
2090         if (c) {
2091                 *c = '\0';
2092                 length = c-buf;
2093         } else {
2094                 err = 1;
2095                 return;
2096         }
2097         if (err) {
2098                 DEBUG(2, ("Oversized message\n"));
2099                 x_fprintf(x_stderr, "ERR\n");
2100                 err = 0;
2101                 return;
2102         }
2103
2104         DEBUG(10, ("Got '%s' from squid (length: %d).\n",buf,length));
2105
2106         if (buf[0] == '\0') {
2107                 DEBUG(2, ("Invalid Request\n"));
2108                 x_fprintf(x_stderr, "ERR\n");
2109                 return;
2110         }
2111         
2112         fn(helper_mode, buf, length);
2113 }
2114
2115
2116 static void squid_stream(enum stdio_helper_mode stdio_mode, stdio_helper_function fn) {
2117         /* initialize FDescs */
2118         x_setbuf(x_stdout, NULL);
2119         x_setbuf(x_stderr, NULL);
2120         while(1) {
2121                 manage_squid_request(stdio_mode, fn);
2122         }
2123 }
2124
2125
2126 /* Authenticate a user with a challenge/response */
2127
2128 static bool check_auth_crap(void)
2129 {
2130         NTSTATUS nt_status;
2131         uint32 flags = 0;
2132         char lm_key[8];
2133         char user_session_key[16];
2134         char *hex_lm_key;
2135         char *hex_user_session_key;
2136         char *error_string;
2137         static uint8 zeros[16];
2138
2139         x_setbuf(x_stdout, NULL);
2140
2141         if (request_lm_key) 
2142                 flags |= WBFLAG_PAM_LMKEY;
2143
2144         if (request_user_session_key) 
2145                 flags |= WBFLAG_PAM_USER_SESSION_KEY;
2146
2147         flags |= WBFLAG_PAM_NT_STATUS_SQUASH;
2148
2149         nt_status = contact_winbind_auth_crap(opt_username, opt_domain, 
2150                                               opt_workstation,
2151                                               &opt_challenge, 
2152                                               &opt_lm_response, 
2153                                               &opt_nt_response, 
2154                                               flags,
2155                                               (unsigned char *)lm_key, 
2156                                               (unsigned char *)user_session_key, 
2157                                               &error_string, NULL);
2158
2159         if (!NT_STATUS_IS_OK(nt_status)) {
2160                 x_fprintf(x_stdout, "%s (0x%x)\n", 
2161                           error_string,
2162                           NT_STATUS_V(nt_status));
2163                 SAFE_FREE(error_string);
2164                 return False;
2165         }
2166
2167         if (request_lm_key 
2168             && (memcmp(zeros, lm_key, 
2169                        sizeof(lm_key)) != 0)) {
2170                 hex_lm_key = hex_encode(NULL, (const unsigned char *)lm_key,
2171                                         sizeof(lm_key));
2172                 x_fprintf(x_stdout, "LM_KEY: %s\n", hex_lm_key);
2173                 TALLOC_FREE(hex_lm_key);
2174         }
2175         if (request_user_session_key 
2176             && (memcmp(zeros, user_session_key, 
2177                        sizeof(user_session_key)) != 0)) {
2178                 hex_user_session_key = hex_encode(NULL, (const unsigned char *)user_session_key, 
2179                                                   sizeof(user_session_key));
2180                 x_fprintf(x_stdout, "NT_KEY: %s\n", hex_user_session_key);
2181                 TALLOC_FREE(hex_user_session_key);
2182         }
2183
2184         return True;
2185 }
2186
2187 /* Main program */
2188
2189 enum {
2190         OPT_USERNAME = 1000,
2191         OPT_DOMAIN,
2192         OPT_WORKSTATION,
2193         OPT_CHALLENGE,
2194         OPT_RESPONSE,
2195         OPT_LM,
2196         OPT_NT,
2197         OPT_PASSWORD,
2198         OPT_LM_KEY,
2199         OPT_USER_SESSION_KEY,
2200         OPT_DIAGNOSTICS,
2201         OPT_REQUIRE_MEMBERSHIP,
2202         OPT_USE_CACHED_CREDS
2203 };
2204
2205  int main(int argc, const char **argv)
2206 {
2207         TALLOC_CTX *frame = talloc_stackframe();
2208         int opt;
2209         static const char *helper_protocol;
2210         static int diagnostics;
2211
2212         static const char *hex_challenge;
2213         static const char *hex_lm_response;
2214         static const char *hex_nt_response;
2215
2216         poptContext pc;
2217
2218         /* NOTE: DO NOT change this interface without considering the implications!
2219            This is an external interface, which other programs will use to interact 
2220            with this helper.
2221         */
2222
2223         /* We do not use single-letter command abbreviations, because they harm future 
2224            interface stability. */
2225
2226         struct poptOption long_options[] = {
2227                 POPT_AUTOHELP
2228                 { "helper-protocol", 0, POPT_ARG_STRING, &helper_protocol, OPT_DOMAIN, "operate as a stdio-based helper", "helper protocol to use"},
2229                 { "username", 0, POPT_ARG_STRING, &opt_username, OPT_USERNAME, "username"},
2230                 { "domain", 0, POPT_ARG_STRING, &opt_domain, OPT_DOMAIN, "domain name"},
2231                 { "workstation", 0, POPT_ARG_STRING, &opt_workstation, OPT_WORKSTATION, "workstation"},
2232                 { "challenge", 0, POPT_ARG_STRING, &hex_challenge, OPT_CHALLENGE, "challenge (HEX encoded)"},
2233                 { "lm-response", 0, POPT_ARG_STRING, &hex_lm_response, OPT_LM, "LM Response to the challenge (HEX encoded)"},
2234                 { "nt-response", 0, POPT_ARG_STRING, &hex_nt_response, OPT_NT, "NT or NTLMv2 Response to the challenge (HEX encoded)"},
2235                 { "password", 0, POPT_ARG_STRING, &opt_password, OPT_PASSWORD, "User's plaintext password"},            
2236                 { "request-lm-key", 0, POPT_ARG_NONE, &request_lm_key, OPT_LM_KEY, "Retrieve LM session key"},
2237                 { "request-nt-key", 0, POPT_ARG_NONE, &request_user_session_key, OPT_USER_SESSION_KEY, "Retrieve User (NT) session key"},
2238                 { "use-cached-creds", 0, POPT_ARG_NONE, &use_cached_creds, OPT_USE_CACHED_CREDS, "Use cached credentials if no password is given"},
2239                 { "diagnostics", 0, POPT_ARG_NONE, &diagnostics, OPT_DIAGNOSTICS, "Perform diagnostics on the authentictaion chain"},
2240                 { "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" },
2241                 POPT_COMMON_SAMBA
2242                 POPT_TABLEEND
2243         };
2244
2245         /* Samba client initialisation */
2246         load_case_tables();
2247
2248         dbf = x_stderr;
2249         
2250         /* Samba client initialisation */
2251
2252         if (!lp_load(get_dyn_CONFIGFILE(), True, False, False, True)) {
2253                 d_fprintf(stderr, "ntlm_auth: error opening config file %s. Error was %s\n",
2254                         get_dyn_CONFIGFILE(), strerror(errno));
2255                 exit(1);
2256         }
2257
2258         /* Parse options */
2259
2260         pc = poptGetContext("ntlm_auth", argc, argv, long_options, 0);
2261
2262         /* Parse command line options */
2263
2264         if (argc == 1) {
2265                 poptPrintHelp(pc, stderr, 0);
2266                 return 1;
2267         }
2268
2269         pc = poptGetContext(NULL, argc, (const char **)argv, long_options, 
2270                             POPT_CONTEXT_KEEP_FIRST);
2271
2272         while((opt = poptGetNextOpt(pc)) != -1) {
2273                 switch (opt) {
2274                 case OPT_CHALLENGE:
2275                         opt_challenge = strhex_to_data_blob(NULL, hex_challenge);
2276                         if (opt_challenge.length != 8) {
2277                                 x_fprintf(x_stderr, "hex decode of %s failed! (only got %d bytes)\n", 
2278                                           hex_challenge,
2279                                           (int)opt_challenge.length);
2280                                 exit(1);
2281                         }
2282                         break;
2283                 case OPT_LM: 
2284                         opt_lm_response = strhex_to_data_blob(NULL, hex_lm_response);
2285                         if (opt_lm_response.length != 24) {
2286                                 x_fprintf(x_stderr, "hex decode of %s failed! (only got %d bytes)\n", 
2287                                           hex_lm_response,
2288                                           (int)opt_lm_response.length);
2289                                 exit(1);
2290                         }
2291                         break;
2292
2293                 case OPT_NT: 
2294                         opt_nt_response = strhex_to_data_blob(NULL, hex_nt_response);
2295                         if (opt_nt_response.length < 24) {
2296                                 x_fprintf(x_stderr, "hex decode of %s failed! (only got %d bytes)\n", 
2297                                           hex_nt_response,
2298                                           (int)opt_nt_response.length);
2299                                 exit(1);
2300                         }
2301                         break;
2302
2303                 case OPT_REQUIRE_MEMBERSHIP:
2304                         if (StrnCaseCmp("S-", require_membership_of, 2) == 0) {
2305                                 require_membership_of_sid = require_membership_of;
2306                         }
2307                         break;
2308                 }
2309         }
2310
2311         if (opt_username) {
2312                 char *domain = SMB_STRDUP(opt_username);
2313                 char *p = strchr_m(domain, *lp_winbind_separator());
2314                 if (p) {
2315                         opt_username = p+1;
2316                         *p = '\0';
2317                         if (opt_domain && !strequal(opt_domain, domain)) {
2318                                 x_fprintf(x_stderr, "Domain specified in username (%s) "
2319                                         "doesn't match specified domain (%s)!\n\n",
2320                                         domain, opt_domain);
2321                                 poptPrintHelp(pc, stderr, 0);
2322                                 exit(1);
2323                         }
2324                         opt_domain = domain;
2325                 } else {
2326                         SAFE_FREE(domain);
2327                 }
2328         }
2329
2330         /* Note: if opt_domain is "" then send no domain */
2331         if (opt_domain == NULL) {
2332                 opt_domain = get_winbind_domain();
2333         }
2334
2335         if (opt_workstation == NULL) {
2336                 opt_workstation = "";
2337         }
2338
2339         if (helper_protocol) {
2340                 int i;
2341                 for (i=0; i<NUM_HELPER_MODES; i++) {
2342                         if (strcmp(helper_protocol, stdio_helper_protocols[i].name) == 0) {
2343                                 squid_stream(stdio_helper_protocols[i].mode, stdio_helper_protocols[i].fn);
2344                                 exit(0);
2345                         }
2346                 }
2347                 x_fprintf(x_stderr, "unknown helper protocol [%s]\n\nValid helper protools:\n\n", helper_protocol);
2348
2349                 for (i=0; i<NUM_HELPER_MODES; i++) {
2350                         x_fprintf(x_stderr, "%s\n", stdio_helper_protocols[i].name);
2351                 }
2352
2353                 exit(1);
2354         }
2355
2356         if (!opt_username || !*opt_username) {
2357                 x_fprintf(x_stderr, "username must be specified!\n\n");
2358                 poptPrintHelp(pc, stderr, 0);
2359                 exit(1);
2360         }
2361
2362         if (opt_challenge.length) {
2363                 if (!check_auth_crap()) {
2364                         exit(1);
2365                 }
2366                 exit(0);
2367         } 
2368
2369         if (!opt_password) {
2370                 opt_password = getpass("password: ");
2371         }
2372
2373         if (diagnostics) {
2374                 if (!diagnose_ntlm_auth()) {
2375                         return 1;
2376                 }
2377         } else {
2378                 fstring user;
2379
2380                 fstr_sprintf(user, "%s%c%s", opt_domain, winbind_separator(), opt_username);
2381                 if (!check_plaintext_auth(user, opt_password, True)) {
2382                         return 1;
2383                 }
2384         }
2385
2386         /* Exit code */
2387
2388         poptFreeContext(pc);
2389         TALLOC_FREE(frame);
2390         return 0;
2391 }