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