Merge branch 'master' of /home/tridge/samba/git/combined
[samba.git] / source3 / utils / ntlm_auth.c
1 /*
2    Unix SMB/CIFS implementation.
3
4    Winbind status program.
5
6    Copyright (C) Tim Potter      2000-2003
7    Copyright (C) Andrew Bartlett <abartlet@samba.org> 2003-2004
8    Copyright (C) Francesco Chemolli <kinkie@kame.usr.dsi.unimi.it> 2000
9    Copyright (C) Robert O'Callahan 2006 (added cached credential code).
10    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 = data_blob_null;
1458         spnego.negTokenInit.reqFlagsPadding = 0;
1459         spnego.negTokenInit.mechListMIC = null_blob;
1460
1461         status = ntlmssp_update(client_ntlmssp_state, null_blob,
1462                                        &spnego.negTokenInit.mechToken);
1463
1464         if ( !(NT_STATUS_EQUAL(status, NT_STATUS_MORE_PROCESSING_REQUIRED) ||
1465                         NT_STATUS_IS_OK(status)) ) {
1466                 DEBUG(1, ("Expected OK or MORE_PROCESSING_REQUIRED, got: %s\n",
1467                           nt_errstr(status)));
1468                 ntlmssp_end(&client_ntlmssp_state);
1469                 return False;
1470         }
1471
1472         spnego_write_data(ctx, &to_server, &spnego);
1473         data_blob_free(&spnego.negTokenInit.mechToken);
1474
1475         to_server_base64 = base64_encode_data_blob(talloc_tos(), to_server);
1476         data_blob_free(&to_server);
1477         x_fprintf(x_stdout, "KK %s\n", to_server_base64);
1478         TALLOC_FREE(to_server_base64);
1479         return True;
1480 }
1481
1482 static void manage_client_ntlmssp_targ(struct spnego_data spnego)
1483 {
1484         NTSTATUS status;
1485         DATA_BLOB null_blob = data_blob_null;
1486         DATA_BLOB request;
1487         DATA_BLOB to_server;
1488         char *to_server_base64;
1489         TALLOC_CTX *ctx = talloc_tos();
1490
1491         DEBUG(10, ("Got spnego negTokenTarg with NTLMSSP\n"));
1492
1493         if (client_ntlmssp_state == NULL) {
1494                 DEBUG(1, ("Got NTLMSSP tArg without a client state\n"));
1495                 x_fprintf(x_stdout, "BH Got NTLMSSP tArg without a client state\n");
1496                 return;
1497         }
1498
1499         if (spnego.negTokenTarg.negResult == SPNEGO_REJECT) {
1500                 x_fprintf(x_stdout, "NA\n");
1501                 ntlmssp_end(&client_ntlmssp_state);
1502                 return;
1503         }
1504
1505         if (spnego.negTokenTarg.negResult == SPNEGO_ACCEPT_COMPLETED) {
1506                 x_fprintf(x_stdout, "AF\n");
1507                 ntlmssp_end(&client_ntlmssp_state);
1508                 return;
1509         }
1510
1511         status = ntlmssp_update(client_ntlmssp_state,
1512                                        spnego.negTokenTarg.responseToken,
1513                                        &request);
1514                 
1515         if (!NT_STATUS_EQUAL(status, NT_STATUS_MORE_PROCESSING_REQUIRED)) {
1516                 DEBUG(1, ("Expected MORE_PROCESSING_REQUIRED from "
1517                           "ntlmssp_client_update, got: %s\n",
1518                           nt_errstr(status)));
1519                 x_fprintf(x_stdout, "BH Expected MORE_PROCESSING_REQUIRED from "
1520                                     "ntlmssp_client_update\n");
1521                 data_blob_free(&request);
1522                 ntlmssp_end(&client_ntlmssp_state);
1523                 return;
1524         }
1525
1526         spnego.type = SPNEGO_NEG_TOKEN_TARG;
1527         spnego.negTokenTarg.negResult = SPNEGO_ACCEPT_INCOMPLETE;
1528         spnego.negTokenTarg.supportedMech = (char *)OID_NTLMSSP;
1529         spnego.negTokenTarg.responseToken = request;
1530         spnego.negTokenTarg.mechListMIC = null_blob;
1531         
1532         spnego_write_data(ctx, &to_server, &spnego);
1533         data_blob_free(&request);
1534
1535         to_server_base64 = base64_encode_data_blob(talloc_tos(), to_server);
1536         data_blob_free(&to_server);
1537         x_fprintf(x_stdout, "KK %s\n", to_server_base64);
1538         TALLOC_FREE(to_server_base64);
1539         return;
1540 }
1541
1542 #ifdef HAVE_KRB5
1543
1544 static bool manage_client_krb5_init(struct spnego_data spnego)
1545 {
1546         char *principal;
1547         DATA_BLOB tkt, to_server;
1548         DATA_BLOB session_key_krb5 = data_blob_null;
1549         struct spnego_data reply;
1550         char *reply_base64;
1551         int retval;
1552
1553         const char *my_mechs[] = {OID_KERBEROS5_OLD, NULL};
1554         ssize_t len;
1555         TALLOC_CTX *ctx = talloc_tos();
1556
1557         if ( (spnego.negTokenInit.mechListMIC.data == NULL) ||
1558              (spnego.negTokenInit.mechListMIC.length == 0) ) {
1559                 DEBUG(1, ("Did not get a principal for krb5\n"));
1560                 return False;
1561         }
1562
1563         principal = (char *)SMB_MALLOC(
1564                 spnego.negTokenInit.mechListMIC.length+1);
1565
1566         if (principal == NULL) {
1567                 DEBUG(1, ("Could not malloc principal\n"));
1568                 return False;
1569         }
1570
1571         memcpy(principal, spnego.negTokenInit.mechListMIC.data,
1572                spnego.negTokenInit.mechListMIC.length);
1573         principal[spnego.negTokenInit.mechListMIC.length] = '\0';
1574
1575         retval = cli_krb5_get_ticket(principal, 0, &tkt, &session_key_krb5, 0, NULL, NULL);
1576
1577         if (retval) {
1578                 char *user = NULL;
1579
1580                 /* Let's try to first get the TGT, for that we need a
1581                    password. */
1582
1583                 if (opt_password == NULL) {
1584                         DEBUG(10, ("Requesting password\n"));
1585                         x_fprintf(x_stdout, "PW\n");
1586                         return True;
1587                 }
1588
1589                 user = talloc_asprintf(talloc_tos(), "%s@%s", opt_username, opt_domain);
1590                 if (!user) {
1591                         return false;
1592                 }
1593
1594                 if ((retval = kerberos_kinit_password(user, opt_password, 0, NULL))) {
1595                         DEBUG(10, ("Requesting TGT failed: %s\n", error_message(retval)));
1596                         return False;
1597                 }
1598
1599                 retval = cli_krb5_get_ticket(principal, 0, &tkt, &session_key_krb5, 0, NULL, NULL);
1600
1601                 if (retval) {
1602                         DEBUG(10, ("Kinit suceeded, but getting a ticket failed: %s\n", error_message(retval)));
1603                         return False;
1604                 }
1605         }
1606
1607         data_blob_free(&session_key_krb5);
1608
1609         ZERO_STRUCT(reply);
1610
1611         reply.type = SPNEGO_NEG_TOKEN_INIT;
1612         reply.negTokenInit.mechTypes = my_mechs;
1613         reply.negTokenInit.reqFlags = data_blob_null;
1614         reply.negTokenInit.reqFlagsPadding = 0;
1615         reply.negTokenInit.mechToken = tkt;
1616         reply.negTokenInit.mechListMIC = data_blob_null;
1617
1618         len = spnego_write_data(ctx, &to_server, &reply);
1619         data_blob_free(&tkt);
1620
1621         if (len == -1) {
1622                 DEBUG(1, ("Could not write SPNEGO data blob\n"));
1623                 return False;
1624         }
1625
1626         reply_base64 = base64_encode_data_blob(talloc_tos(), to_server);
1627         x_fprintf(x_stdout, "KK %s *\n", reply_base64);
1628
1629         TALLOC_FREE(reply_base64);
1630         data_blob_free(&to_server);
1631         DEBUG(10, ("sent GSS-SPNEGO KERBEROS5 negTokenInit\n"));
1632         return True;
1633 }
1634
1635 static void manage_client_krb5_targ(struct spnego_data spnego)
1636 {
1637         switch (spnego.negTokenTarg.negResult) {
1638         case SPNEGO_ACCEPT_INCOMPLETE:
1639                 DEBUG(1, ("Got a Kerberos negTokenTarg with ACCEPT_INCOMPLETE\n"));
1640                 x_fprintf(x_stdout, "BH Got a Kerberos negTokenTarg with "
1641                                     "ACCEPT_INCOMPLETE\n");
1642                 break;
1643         case SPNEGO_ACCEPT_COMPLETED:
1644                 DEBUG(10, ("Accept completed\n"));
1645                 x_fprintf(x_stdout, "AF\n");
1646                 break;
1647         case SPNEGO_REJECT:
1648                 DEBUG(10, ("Rejected\n"));
1649                 x_fprintf(x_stdout, "NA\n");
1650                 break;
1651         default:
1652                 DEBUG(1, ("Got an invalid negTokenTarg\n"));
1653                 x_fprintf(x_stdout, "AF\n");
1654         }
1655 }
1656
1657 #endif
1658
1659 static void manage_gss_spnego_client_request(struct ntlm_auth_state *state,
1660                                                 char *buf, int length)
1661 {
1662         DATA_BLOB request;
1663         struct spnego_data spnego;
1664         ssize_t len;
1665         TALLOC_CTX *ctx = talloc_tos();
1666
1667         if (!opt_username || !*opt_username) {
1668                 x_fprintf(x_stderr, "username must be specified!\n\n");
1669                 exit(1);
1670         }
1671
1672         if (strlen(buf) <= 3) {
1673                 DEBUG(1, ("SPNEGO query [%s] too short\n", buf));
1674                 x_fprintf(x_stdout, "BH SPNEGO query too short\n");
1675                 return;
1676         }
1677
1678         request = base64_decode_data_blob(buf+3);
1679
1680         if (strncmp(buf, "PW ", 3) == 0) {
1681
1682                 /* We asked for a password and obviously got it :-) */
1683
1684                 opt_password = SMB_STRNDUP((const char *)request.data, request.length);
1685                 
1686                 if (opt_password == NULL) {
1687                         DEBUG(1, ("Out of memory\n"));
1688                         x_fprintf(x_stdout, "BH Out of memory\n");
1689                         data_blob_free(&request);
1690                         return;
1691                 }
1692
1693                 x_fprintf(x_stdout, "OK\n");
1694                 data_blob_free(&request);
1695                 return;
1696         }
1697
1698         if ( (strncmp(buf, "TT ", 3) != 0) &&
1699              (strncmp(buf, "AF ", 3) != 0) &&
1700              (strncmp(buf, "NA ", 3) != 0) ) {
1701                 DEBUG(1, ("SPNEGO request [%s] invalid\n", buf));
1702                 x_fprintf(x_stdout, "BH SPNEGO request invalid\n");
1703                 data_blob_free(&request);
1704                 return;
1705         }
1706
1707         /* So we got a server challenge to generate a SPNEGO
1708            client-to-server request... */
1709
1710         len = spnego_read_data(ctx, request, &spnego);
1711         data_blob_free(&request);
1712
1713         if (len == -1) {
1714                 DEBUG(1, ("Could not read SPNEGO data for [%s]\n", buf));
1715                 x_fprintf(x_stdout, "BH Could not read SPNEGO data\n");
1716                 return;
1717         }
1718
1719         if (spnego.type == SPNEGO_NEG_TOKEN_INIT) {
1720
1721                 /* The server offers a list of mechanisms */
1722
1723                 const char **mechType = (const char **)spnego.negTokenInit.mechTypes;
1724
1725                 while (*mechType != NULL) {
1726
1727 #ifdef HAVE_KRB5
1728                         if ( (strcmp(*mechType, OID_KERBEROS5_OLD) == 0) ||
1729                              (strcmp(*mechType, OID_KERBEROS5) == 0) ) {
1730                                 if (manage_client_krb5_init(spnego))
1731                                         goto out;
1732                         }
1733 #endif
1734
1735                         if (strcmp(*mechType, OID_NTLMSSP) == 0) {
1736                                 if (manage_client_ntlmssp_init(spnego))
1737                                         goto out;
1738                         }
1739
1740                         mechType++;
1741                 }
1742
1743                 DEBUG(1, ("Server offered no compatible mechanism\n"));
1744                 x_fprintf(x_stdout, "BH Server offered no compatible mechanism\n");
1745                 return;
1746         }
1747
1748         if (spnego.type == SPNEGO_NEG_TOKEN_TARG) {
1749
1750                 if (spnego.negTokenTarg.supportedMech == NULL) {
1751                         /* On accept/reject Windows does not send the
1752                            mechanism anymore. Handle that here and
1753                            shut down the mechanisms. */
1754
1755                         switch (spnego.negTokenTarg.negResult) {
1756                         case SPNEGO_ACCEPT_COMPLETED:
1757                                 x_fprintf(x_stdout, "AF\n");
1758                                 break;
1759                         case SPNEGO_REJECT:
1760                                 x_fprintf(x_stdout, "NA\n");
1761                                 break;
1762                         default:
1763                                 DEBUG(1, ("Got a negTokenTarg with no mech and an "
1764                                           "unknown negResult: %d\n",
1765                                           spnego.negTokenTarg.negResult));
1766                                 x_fprintf(x_stdout, "BH Got a negTokenTarg with"
1767                                                     " no mech and an unknown "
1768                                                     "negResult\n");
1769                         }
1770
1771                         ntlmssp_end(&client_ntlmssp_state);
1772                         goto out;
1773                 }
1774
1775                 if (strcmp(spnego.negTokenTarg.supportedMech,
1776                            OID_NTLMSSP) == 0) {
1777                         manage_client_ntlmssp_targ(spnego);
1778                         goto out;
1779                 }
1780
1781 #if HAVE_KRB5
1782                 if (strcmp(spnego.negTokenTarg.supportedMech,
1783                            OID_KERBEROS5_OLD) == 0) {
1784                         manage_client_krb5_targ(spnego);
1785                         goto out;
1786                 }
1787 #endif
1788
1789         }
1790
1791         DEBUG(1, ("Got an SPNEGO token I could not handle [%s]!\n", buf));
1792         x_fprintf(x_stdout, "BH Got an SPNEGO token I could not handle\n");
1793         return;
1794
1795  out:
1796         spnego_free_data(&spnego);
1797         return;
1798 }
1799
1800 static void manage_ntlm_server_1_request(struct ntlm_auth_state *state,
1801                                                 char *buf, int length)
1802 {
1803         char *request, *parameter;      
1804         static DATA_BLOB challenge;
1805         static DATA_BLOB lm_response;
1806         static DATA_BLOB nt_response;
1807         static char *full_username;
1808         static char *username;
1809         static char *domain;
1810         static char *plaintext_password;
1811         static bool ntlm_server_1_user_session_key;
1812         static bool ntlm_server_1_lm_session_key;
1813         
1814         if (strequal(buf, ".")) {
1815                 if (!full_username && !username) {      
1816                         x_fprintf(x_stdout, "Error: No username supplied!\n");
1817                 } else if (plaintext_password) {
1818                         /* handle this request as plaintext */
1819                         if (!full_username) {
1820                                 if (asprintf(&full_username, "%s%c%s", domain, winbind_separator(), username) == -1) {
1821                                         x_fprintf(x_stdout, "Error: Out of memory in asprintf!\n.\n");
1822                                         return;
1823                                 }
1824                         }
1825                         if (check_plaintext_auth(full_username, plaintext_password, False)) {
1826                                 x_fprintf(x_stdout, "Authenticated: Yes\n");
1827                         } else {
1828                                 x_fprintf(x_stdout, "Authenticated: No\n");
1829                         }
1830                 } else if (!lm_response.data && !nt_response.data) {
1831                         x_fprintf(x_stdout, "Error: No password supplied!\n");
1832                 } else if (!challenge.data) {   
1833                         x_fprintf(x_stdout, "Error: No lanman-challenge supplied!\n");
1834                 } else {
1835                         char *error_string = NULL;
1836                         uchar lm_key[8];
1837                         uchar user_session_key[16];
1838                         uint32 flags = 0;
1839
1840                         if (full_username && !username) {
1841                                 fstring fstr_user;
1842                                 fstring fstr_domain;
1843                                 
1844                                 if (!parse_ntlm_auth_domain_user(full_username, fstr_user, fstr_domain)) {
1845                                         /* username might be 'tainted', don't print into our new-line deleimianted stream */
1846                                         x_fprintf(x_stdout, "Error: Could not parse into domain and username\n");
1847                                 }
1848                                 SAFE_FREE(username);
1849                                 SAFE_FREE(domain);
1850                                 username = smb_xstrdup(fstr_user);
1851                                 domain = smb_xstrdup(fstr_domain);
1852                         }
1853
1854                         if (!domain) {
1855                                 domain = smb_xstrdup(get_winbind_domain());
1856                         }
1857
1858                         if (ntlm_server_1_lm_session_key) 
1859                                 flags |= WBFLAG_PAM_LMKEY;
1860                         
1861                         if (ntlm_server_1_user_session_key) 
1862                                 flags |= WBFLAG_PAM_USER_SESSION_KEY;
1863
1864                         if (!NT_STATUS_IS_OK(
1865                                     contact_winbind_auth_crap(username, 
1866                                                               domain, 
1867                                                               global_myname(),
1868                                                               &challenge, 
1869                                                               &lm_response, 
1870                                                               &nt_response, 
1871                                                               flags, 
1872                                                               lm_key, 
1873                                                               user_session_key,
1874                                                               &error_string,
1875                                                               NULL))) {
1876
1877                                 x_fprintf(x_stdout, "Authenticated: No\n");
1878                                 x_fprintf(x_stdout, "Authentication-Error: %s\n.\n", error_string);
1879                         } else {
1880                                 static char zeros[16];
1881                                 char *hex_lm_key;
1882                                 char *hex_user_session_key;
1883
1884                                 x_fprintf(x_stdout, "Authenticated: Yes\n");
1885
1886                                 if (ntlm_server_1_lm_session_key 
1887                                     && (memcmp(zeros, lm_key, 
1888                                                sizeof(lm_key)) != 0)) {
1889                                         hex_lm_key = hex_encode_talloc(NULL,
1890                                                                 (const unsigned char *)lm_key,
1891                                                                 sizeof(lm_key));
1892                                         x_fprintf(x_stdout, "LANMAN-Session-Key: %s\n", hex_lm_key);
1893                                         TALLOC_FREE(hex_lm_key);
1894                                 }
1895
1896                                 if (ntlm_server_1_user_session_key 
1897                                     && (memcmp(zeros, user_session_key, 
1898                                                sizeof(user_session_key)) != 0)) {
1899                                         hex_user_session_key = hex_encode_talloc(NULL,
1900                                                                           (const unsigned char *)user_session_key, 
1901                                                                           sizeof(user_session_key));
1902                                         x_fprintf(x_stdout, "User-Session-Key: %s\n", hex_user_session_key);
1903                                         TALLOC_FREE(hex_user_session_key);
1904                                 }
1905                         }
1906                         SAFE_FREE(error_string);
1907                 }
1908                 /* clear out the state */
1909                 challenge = data_blob_null;
1910                 nt_response = data_blob_null;
1911                 lm_response = data_blob_null;
1912                 SAFE_FREE(full_username);
1913                 SAFE_FREE(username);
1914                 SAFE_FREE(domain);
1915                 SAFE_FREE(plaintext_password);
1916                 ntlm_server_1_user_session_key = False;
1917                 ntlm_server_1_lm_session_key = False;
1918                 x_fprintf(x_stdout, ".\n");
1919
1920                 return;
1921         }
1922
1923         request = buf;
1924
1925         /* Indicates a base64 encoded structure */
1926         parameter = strstr_m(request, ":: ");
1927         if (!parameter) {
1928                 parameter = strstr_m(request, ": ");
1929                 
1930                 if (!parameter) {
1931                         DEBUG(0, ("Parameter not found!\n"));
1932                         x_fprintf(x_stdout, "Error: Parameter not found!\n.\n");
1933                         return;
1934                 }
1935                 
1936                 parameter[0] ='\0';
1937                 parameter++;
1938                 parameter[0] ='\0';
1939                 parameter++;
1940
1941         } else {
1942                 parameter[0] ='\0';
1943                 parameter++;
1944                 parameter[0] ='\0';
1945                 parameter++;
1946                 parameter[0] ='\0';
1947                 parameter++;
1948
1949                 base64_decode_inplace(parameter);
1950         }
1951
1952         if (strequal(request, "LANMAN-Challenge")) {
1953                 challenge = strhex_to_data_blob(NULL, parameter);
1954                 if (challenge.length != 8) {
1955                         x_fprintf(x_stdout, "Error: hex decode of %s failed! (got %d bytes, expected 8)\n.\n", 
1956                                   parameter,
1957                                   (int)challenge.length);
1958                         challenge = data_blob_null;
1959                 }
1960         } else if (strequal(request, "NT-Response")) {
1961                 nt_response = strhex_to_data_blob(NULL, parameter);
1962                 if (nt_response.length < 24) {
1963                         x_fprintf(x_stdout, "Error: hex decode of %s failed! (only got %d bytes, needed at least 24)\n.\n", 
1964                                   parameter,
1965                                   (int)nt_response.length);
1966                         nt_response = data_blob_null;
1967                 }
1968         } else if (strequal(request, "LANMAN-Response")) {
1969                 lm_response = strhex_to_data_blob(NULL, parameter);
1970                 if (lm_response.length != 24) {
1971                         x_fprintf(x_stdout, "Error: hex decode of %s failed! (got %d bytes, expected 24)\n.\n", 
1972                                   parameter,
1973                                   (int)lm_response.length);
1974                         lm_response = data_blob_null;
1975                 }
1976         } else if (strequal(request, "Password")) {
1977                 plaintext_password = smb_xstrdup(parameter);
1978         } else if (strequal(request, "NT-Domain")) {
1979                 domain = smb_xstrdup(parameter);
1980         } else if (strequal(request, "Username")) {
1981                 username = smb_xstrdup(parameter);
1982         } else if (strequal(request, "Full-Username")) {
1983                 full_username = smb_xstrdup(parameter);
1984         } else if (strequal(request, "Request-User-Session-Key")) {
1985                 ntlm_server_1_user_session_key = strequal(parameter, "Yes");
1986         } else if (strequal(request, "Request-LanMan-Session-Key")) {
1987                 ntlm_server_1_lm_session_key = strequal(parameter, "Yes");
1988         } else {
1989                 x_fprintf(x_stdout, "Error: Unknown request %s\n.\n", request);
1990         }
1991 }
1992
1993 static void manage_ntlm_change_password_1_request(struct ntlm_auth_state *state,
1994                                                         char *buf, int length)
1995 {
1996         char *request, *parameter;      
1997         static DATA_BLOB new_nt_pswd;
1998         static DATA_BLOB old_nt_hash_enc;
1999         static DATA_BLOB new_lm_pswd;
2000         static DATA_BLOB old_lm_hash_enc;
2001         static char *full_username = NULL;
2002         static char *username = NULL;
2003         static char *domain = NULL;
2004         static char *newpswd =  NULL;
2005         static char *oldpswd = NULL;
2006
2007         if (strequal(buf, ".")) {
2008                 if(newpswd && oldpswd) {
2009                         uchar old_nt_hash[16];
2010                         uchar old_lm_hash[16];
2011                         uchar new_nt_hash[16];
2012                         uchar new_lm_hash[16];
2013
2014                         new_nt_pswd = data_blob(NULL, 516);
2015                         old_nt_hash_enc = data_blob(NULL, 16);
2016                         
2017                         /* Calculate the MD4 hash (NT compatible) of the
2018                          * password */
2019                         E_md4hash(oldpswd, old_nt_hash);
2020                         E_md4hash(newpswd, new_nt_hash);
2021
2022                         /* E_deshash returns false for 'long'
2023                            passwords (> 14 DOS chars).  
2024                            
2025                            Therefore, don't send a buffer
2026                            encrypted with the truncated hash
2027                            (it could allow an even easier
2028                            attack on the password)
2029
2030                            Likewise, obey the admin's restriction
2031                         */
2032
2033                         if (lp_client_lanman_auth() &&
2034                             E_deshash(newpswd, new_lm_hash) &&
2035                             E_deshash(oldpswd, old_lm_hash)) {
2036                                 new_lm_pswd = data_blob(NULL, 516);
2037                                 old_lm_hash_enc = data_blob(NULL, 16);
2038                                 encode_pw_buffer(new_lm_pswd.data, newpswd,
2039                                                  STR_UNICODE);
2040
2041                                 arcfour_crypt(new_lm_pswd.data, old_nt_hash, 516);
2042                                 E_old_pw_hash(new_nt_hash, old_lm_hash,
2043                                               old_lm_hash_enc.data);
2044                         } else {
2045                                 new_lm_pswd.data = NULL;
2046                                 new_lm_pswd.length = 0;
2047                                 old_lm_hash_enc.data = NULL;
2048                                 old_lm_hash_enc.length = 0;
2049                         }
2050
2051                         encode_pw_buffer(new_nt_pswd.data, newpswd,
2052                                          STR_UNICODE);
2053         
2054                         arcfour_crypt(new_nt_pswd.data, old_nt_hash, 516);
2055                         E_old_pw_hash(new_nt_hash, old_nt_hash,
2056                                       old_nt_hash_enc.data);
2057                 }
2058                 
2059                 if (!full_username && !username) {      
2060                         x_fprintf(x_stdout, "Error: No username supplied!\n");
2061                 } else if ((!new_nt_pswd.data || !old_nt_hash_enc.data) &&
2062                            (!new_lm_pswd.data || old_lm_hash_enc.data) ) {
2063                         x_fprintf(x_stdout, "Error: No NT or LM password "
2064                                   "blobs supplied!\n");
2065                 } else {
2066                         char *error_string = NULL;
2067                         
2068                         if (full_username && !username) {
2069                                 fstring fstr_user;
2070                                 fstring fstr_domain;
2071                                 
2072                                 if (!parse_ntlm_auth_domain_user(full_username,
2073                                                                  fstr_user,
2074                                                                  fstr_domain)) {
2075                                         /* username might be 'tainted', don't
2076                                          * print into our new-line
2077                                          * deleimianted stream */
2078                                         x_fprintf(x_stdout, "Error: Could not "
2079                                                   "parse into domain and "
2080                                                   "username\n");
2081                                         SAFE_FREE(username);
2082                                         username = smb_xstrdup(full_username);
2083                                 } else {
2084                                         SAFE_FREE(username);
2085                                         SAFE_FREE(domain);
2086                                         username = smb_xstrdup(fstr_user);
2087                                         domain = smb_xstrdup(fstr_domain);
2088                                 }
2089                                 
2090                         }
2091
2092                         if(!NT_STATUS_IS_OK(contact_winbind_change_pswd_auth_crap(
2093                                                     username, domain,
2094                                                     new_nt_pswd,
2095                                                     old_nt_hash_enc,
2096                                                     new_lm_pswd,
2097                                                     old_lm_hash_enc,
2098                                                     &error_string))) {
2099                                 x_fprintf(x_stdout, "Password-Change: No\n");
2100                                 x_fprintf(x_stdout, "Password-Change-Error: "
2101                                           "%s\n.\n", error_string);
2102                         } else {
2103                                 x_fprintf(x_stdout, "Password-Change: Yes\n");
2104                         }
2105
2106                         SAFE_FREE(error_string);
2107                 }
2108                 /* clear out the state */
2109                 new_nt_pswd = data_blob_null;
2110                 old_nt_hash_enc = data_blob_null;
2111                 new_lm_pswd = data_blob_null;
2112                 old_nt_hash_enc = data_blob_null;
2113                 SAFE_FREE(full_username);
2114                 SAFE_FREE(username);
2115                 SAFE_FREE(domain);
2116                 SAFE_FREE(newpswd);
2117                 SAFE_FREE(oldpswd);
2118                 x_fprintf(x_stdout, ".\n");
2119
2120                 return;
2121         }
2122
2123         request = buf;
2124
2125         /* Indicates a base64 encoded structure */
2126         parameter = strstr_m(request, ":: ");
2127         if (!parameter) {
2128                 parameter = strstr_m(request, ": ");
2129                 
2130                 if (!parameter) {
2131                         DEBUG(0, ("Parameter not found!\n"));
2132                         x_fprintf(x_stdout, "Error: Parameter not found!\n.\n");
2133                         return;
2134                 }
2135                 
2136                 parameter[0] ='\0';
2137                 parameter++;
2138                 parameter[0] ='\0';
2139                 parameter++;
2140         } else {
2141                 parameter[0] ='\0';
2142                 parameter++;
2143                 parameter[0] ='\0';
2144                 parameter++;
2145                 parameter[0] ='\0';
2146                 parameter++;
2147
2148                 base64_decode_inplace(parameter);
2149         }
2150
2151         if (strequal(request, "new-nt-password-blob")) {
2152                 new_nt_pswd = strhex_to_data_blob(NULL, parameter);
2153                 if (new_nt_pswd.length != 516) {
2154                         x_fprintf(x_stdout, "Error: hex decode of %s failed! "
2155                                   "(got %d bytes, expected 516)\n.\n", 
2156                                   parameter,
2157                                   (int)new_nt_pswd.length);
2158                         new_nt_pswd = data_blob_null;
2159                 }
2160         } else if (strequal(request, "old-nt-hash-blob")) {
2161                 old_nt_hash_enc = strhex_to_data_blob(NULL, parameter);
2162                 if (old_nt_hash_enc.length != 16) {
2163                         x_fprintf(x_stdout, "Error: hex decode of %s failed! "
2164                                   "(got %d bytes, expected 16)\n.\n", 
2165                                   parameter,
2166                                   (int)old_nt_hash_enc.length);
2167                         old_nt_hash_enc = data_blob_null;
2168                 }
2169         } else if (strequal(request, "new-lm-password-blob")) {
2170                 new_lm_pswd = strhex_to_data_blob(NULL, parameter);
2171                 if (new_lm_pswd.length != 516) {
2172                         x_fprintf(x_stdout, "Error: hex decode of %s failed! "
2173                                   "(got %d bytes, expected 516)\n.\n", 
2174                                   parameter,
2175                                   (int)new_lm_pswd.length);
2176                         new_lm_pswd = data_blob_null;
2177                 }
2178         }
2179         else if (strequal(request, "old-lm-hash-blob")) {
2180                 old_lm_hash_enc = strhex_to_data_blob(NULL, parameter);
2181                 if (old_lm_hash_enc.length != 16)
2182                 {
2183                         x_fprintf(x_stdout, "Error: hex decode of %s failed! "
2184                                   "(got %d bytes, expected 16)\n.\n", 
2185                                   parameter,
2186                                   (int)old_lm_hash_enc.length);
2187                         old_lm_hash_enc = data_blob_null;
2188                 }
2189         } else if (strequal(request, "nt-domain")) {
2190                 domain = smb_xstrdup(parameter);
2191         } else if(strequal(request, "username")) {
2192                 username = smb_xstrdup(parameter);
2193         } else if(strequal(request, "full-username")) {
2194                 username = smb_xstrdup(parameter);
2195         } else if(strequal(request, "new-password")) {
2196                 newpswd = smb_xstrdup(parameter);
2197         } else if (strequal(request, "old-password")) {
2198                 oldpswd = smb_xstrdup(parameter);
2199         } else {
2200                 x_fprintf(x_stdout, "Error: Unknown request %s\n.\n", request);
2201         }
2202 }
2203
2204 static void manage_squid_request(struct ntlm_auth_state *state,
2205                 stdio_helper_function fn)
2206 {
2207         char *buf;
2208         char tmp[INITIAL_BUFFER_SIZE+1];
2209         int length, buf_size = 0;
2210         char *c;
2211
2212         buf = talloc_strdup(state->mem_ctx, "");
2213         if (!buf) {
2214                 DEBUG(0, ("Failed to allocate input buffer.\n"));
2215                 x_fprintf(x_stderr, "ERR\n");
2216                 exit(1);
2217         }
2218
2219         do {
2220
2221                 /* this is not a typo - x_fgets doesn't work too well under
2222                  * squid */
2223                 if (fgets(tmp, sizeof(tmp)-1, stdin) == NULL) {
2224                         if (ferror(stdin)) {
2225                                 DEBUG(1, ("fgets() failed! dying..... errno=%d "
2226                                           "(%s)\n", ferror(stdin),
2227                                           strerror(ferror(stdin))));
2228
2229                                 exit(1);
2230                         }
2231                         exit(0);
2232                 }
2233
2234                 buf = talloc_strdup_append_buffer(buf, tmp);
2235                 buf_size += INITIAL_BUFFER_SIZE;
2236
2237                 if (buf_size > MAX_BUFFER_SIZE) {
2238                         DEBUG(2, ("Oversized message\n"));
2239                         x_fprintf(x_stderr, "ERR\n");
2240                         talloc_free(buf);
2241                         return;
2242                 }
2243
2244                 c = strchr(buf, '\n');
2245         } while (c == NULL);
2246
2247         *c = '\0';
2248         length = c-buf;
2249
2250         DEBUG(10, ("Got '%s' from squid (length: %d).\n",buf,length));
2251
2252         if (buf[0] == '\0') {
2253                 DEBUG(2, ("Invalid Request\n"));
2254                 x_fprintf(x_stderr, "ERR\n");
2255                 talloc_free(buf);
2256                 return;
2257         }
2258
2259         fn(state, buf, length);
2260         talloc_free(buf);
2261 }
2262
2263
2264 static void squid_stream(enum stdio_helper_mode stdio_mode, stdio_helper_function fn) {
2265         TALLOC_CTX *mem_ctx;
2266         struct ntlm_auth_state *state;
2267
2268         /* initialize FDescs */
2269         x_setbuf(x_stdout, NULL);
2270         x_setbuf(x_stderr, NULL);
2271
2272         mem_ctx = talloc_init("ntlm_auth");
2273         if (!mem_ctx) {
2274                 DEBUG(0, ("squid_stream: Failed to create talloc context\n"));
2275                 x_fprintf(x_stderr, "ERR\n");
2276                 exit(1);
2277         }
2278
2279         state = talloc_zero(mem_ctx, struct ntlm_auth_state);
2280         if (!state) {
2281                 DEBUG(0, ("squid_stream: Failed to talloc ntlm_auth_state\n"));
2282                 x_fprintf(x_stderr, "ERR\n");
2283                 exit(1);
2284         }
2285
2286         state->mem_ctx = mem_ctx;
2287         state->helper_mode = stdio_mode;
2288
2289         while(1) {
2290                 manage_squid_request(state, fn);
2291         }
2292 }
2293
2294
2295 /* Authenticate a user with a challenge/response */
2296
2297 static bool check_auth_crap(void)
2298 {
2299         NTSTATUS nt_status;
2300         uint32 flags = 0;
2301         char lm_key[8];
2302         char user_session_key[16];
2303         char *hex_lm_key;
2304         char *hex_user_session_key;
2305         char *error_string;
2306         static uint8 zeros[16];
2307
2308         x_setbuf(x_stdout, NULL);
2309
2310         if (request_lm_key) 
2311                 flags |= WBFLAG_PAM_LMKEY;
2312
2313         if (request_user_session_key) 
2314                 flags |= WBFLAG_PAM_USER_SESSION_KEY;
2315
2316         flags |= WBFLAG_PAM_NT_STATUS_SQUASH;
2317
2318         nt_status = contact_winbind_auth_crap(opt_username, opt_domain, 
2319                                               opt_workstation,
2320                                               &opt_challenge, 
2321                                               &opt_lm_response, 
2322                                               &opt_nt_response, 
2323                                               flags,
2324                                               (unsigned char *)lm_key, 
2325                                               (unsigned char *)user_session_key, 
2326                                               &error_string, NULL);
2327
2328         if (!NT_STATUS_IS_OK(nt_status)) {
2329                 x_fprintf(x_stdout, "%s (0x%x)\n", 
2330                           error_string,
2331                           NT_STATUS_V(nt_status));
2332                 SAFE_FREE(error_string);
2333                 return False;
2334         }
2335
2336         if (request_lm_key 
2337             && (memcmp(zeros, lm_key, 
2338                        sizeof(lm_key)) != 0)) {
2339                 hex_lm_key = hex_encode_talloc(talloc_tos(), (const unsigned char *)lm_key,
2340                                         sizeof(lm_key));
2341                 x_fprintf(x_stdout, "LM_KEY: %s\n", hex_lm_key);
2342                 TALLOC_FREE(hex_lm_key);
2343         }
2344         if (request_user_session_key 
2345             && (memcmp(zeros, user_session_key, 
2346                        sizeof(user_session_key)) != 0)) {
2347                 hex_user_session_key = hex_encode_talloc(talloc_tos(), (const unsigned char *)user_session_key, 
2348                                                   sizeof(user_session_key));
2349                 x_fprintf(x_stdout, "NT_KEY: %s\n", hex_user_session_key);
2350                 TALLOC_FREE(hex_user_session_key);
2351         }
2352
2353         return True;
2354 }
2355
2356 /* Main program */
2357
2358 enum {
2359         OPT_USERNAME = 1000,
2360         OPT_DOMAIN,
2361         OPT_WORKSTATION,
2362         OPT_CHALLENGE,
2363         OPT_RESPONSE,
2364         OPT_LM,
2365         OPT_NT,
2366         OPT_PASSWORD,
2367         OPT_LM_KEY,
2368         OPT_USER_SESSION_KEY,
2369         OPT_DIAGNOSTICS,
2370         OPT_REQUIRE_MEMBERSHIP,
2371         OPT_USE_CACHED_CREDS,
2372         OPT_PAM_WINBIND_CONF
2373 };
2374
2375  int main(int argc, const char **argv)
2376 {
2377         TALLOC_CTX *frame = talloc_stackframe();
2378         int opt;
2379         static const char *helper_protocol;
2380         static int diagnostics;
2381
2382         static const char *hex_challenge;
2383         static const char *hex_lm_response;
2384         static const char *hex_nt_response;
2385
2386         poptContext pc;
2387
2388         /* NOTE: DO NOT change this interface without considering the implications!
2389            This is an external interface, which other programs will use to interact 
2390            with this helper.
2391         */
2392
2393         /* We do not use single-letter command abbreviations, because they harm future 
2394            interface stability. */
2395
2396         struct poptOption long_options[] = {
2397                 POPT_AUTOHELP
2398                 { "helper-protocol", 0, POPT_ARG_STRING, &helper_protocol, OPT_DOMAIN, "operate as a stdio-based helper", "helper protocol to use"},
2399                 { "username", 0, POPT_ARG_STRING, &opt_username, OPT_USERNAME, "username"},
2400                 { "domain", 0, POPT_ARG_STRING, &opt_domain, OPT_DOMAIN, "domain name"},
2401                 { "workstation", 0, POPT_ARG_STRING, &opt_workstation, OPT_WORKSTATION, "workstation"},
2402                 { "challenge", 0, POPT_ARG_STRING, &hex_challenge, OPT_CHALLENGE, "challenge (HEX encoded)"},
2403                 { "lm-response", 0, POPT_ARG_STRING, &hex_lm_response, OPT_LM, "LM Response to the challenge (HEX encoded)"},
2404                 { "nt-response", 0, POPT_ARG_STRING, &hex_nt_response, OPT_NT, "NT or NTLMv2 Response to the challenge (HEX encoded)"},
2405                 { "password", 0, POPT_ARG_STRING, &opt_password, OPT_PASSWORD, "User's plaintext password"},            
2406                 { "request-lm-key", 0, POPT_ARG_NONE, &request_lm_key, OPT_LM_KEY, "Retrieve LM session key"},
2407                 { "request-nt-key", 0, POPT_ARG_NONE, &request_user_session_key, OPT_USER_SESSION_KEY, "Retrieve User (NT) session key"},
2408                 { "use-cached-creds", 0, POPT_ARG_NONE, &use_cached_creds, OPT_USE_CACHED_CREDS, "Use cached credentials if no password is given"},
2409                 { "diagnostics", 0, POPT_ARG_NONE, &diagnostics, OPT_DIAGNOSTICS, "Perform diagnostics on the authentictaion chain"},
2410                 { "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" },
2411                 { "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" },
2412                 POPT_COMMON_CONFIGFILE
2413                 POPT_COMMON_VERSION
2414                 POPT_TABLEEND
2415         };
2416
2417         /* Samba client initialisation */
2418         load_case_tables();
2419
2420         dbf = x_stderr;
2421
2422         /* Parse options */
2423
2424         pc = poptGetContext("ntlm_auth", argc, argv, long_options, 0);
2425
2426         /* Parse command line options */
2427
2428         if (argc == 1) {
2429                 poptPrintHelp(pc, stderr, 0);
2430                 return 1;
2431         }
2432
2433         while((opt = poptGetNextOpt(pc)) != -1) {
2434                 /* Get generic config options like --configfile */
2435         }
2436
2437         poptFreeContext(pc);
2438
2439         if (!lp_load(get_dyn_CONFIGFILE(), True, False, False, True)) {
2440                 d_fprintf(stderr, "ntlm_auth: error opening config file %s. Error was %s\n",
2441                         get_dyn_CONFIGFILE(), strerror(errno));
2442                 exit(1);
2443         }
2444
2445         pc = poptGetContext(NULL, argc, (const char **)argv, long_options, 
2446                             POPT_CONTEXT_KEEP_FIRST);
2447
2448         while((opt = poptGetNextOpt(pc)) != -1) {
2449                 switch (opt) {
2450                 case OPT_CHALLENGE:
2451                         opt_challenge = strhex_to_data_blob(NULL, hex_challenge);
2452                         if (opt_challenge.length != 8) {
2453                                 x_fprintf(x_stderr, "hex decode of %s failed! (only got %d bytes)\n", 
2454                                           hex_challenge,
2455                                           (int)opt_challenge.length);
2456                                 exit(1);
2457                         }
2458                         break;
2459                 case OPT_LM: 
2460                         opt_lm_response = strhex_to_data_blob(NULL, hex_lm_response);
2461                         if (opt_lm_response.length != 24) {
2462                                 x_fprintf(x_stderr, "hex decode of %s failed! (only got %d bytes)\n", 
2463                                           hex_lm_response,
2464                                           (int)opt_lm_response.length);
2465                                 exit(1);
2466                         }
2467                         break;
2468
2469                 case OPT_NT: 
2470                         opt_nt_response = strhex_to_data_blob(NULL, hex_nt_response);
2471                         if (opt_nt_response.length < 24) {
2472                                 x_fprintf(x_stderr, "hex decode of %s failed! (only got %d bytes)\n", 
2473                                           hex_nt_response,
2474                                           (int)opt_nt_response.length);
2475                                 exit(1);
2476                         }
2477                         break;
2478
2479                 case OPT_REQUIRE_MEMBERSHIP:
2480                         if (StrnCaseCmp("S-", require_membership_of, 2) == 0) {
2481                                 require_membership_of_sid = require_membership_of;
2482                         }
2483                         break;
2484                 }
2485         }
2486
2487         if (opt_username) {
2488                 char *domain = SMB_STRDUP(opt_username);
2489                 char *p = strchr_m(domain, *lp_winbind_separator());
2490                 if (p) {
2491                         opt_username = p+1;
2492                         *p = '\0';
2493                         if (opt_domain && !strequal(opt_domain, domain)) {
2494                                 x_fprintf(x_stderr, "Domain specified in username (%s) "
2495                                         "doesn't match specified domain (%s)!\n\n",
2496                                         domain, opt_domain);
2497                                 poptPrintHelp(pc, stderr, 0);
2498                                 exit(1);
2499                         }
2500                         opt_domain = domain;
2501                 } else {
2502                         SAFE_FREE(domain);
2503                 }
2504         }
2505
2506         /* Note: if opt_domain is "" then send no domain */
2507         if (opt_domain == NULL) {
2508                 opt_domain = get_winbind_domain();
2509         }
2510
2511         if (opt_workstation == NULL) {
2512                 opt_workstation = "";
2513         }
2514
2515         if (helper_protocol) {
2516                 int i;
2517                 for (i=0; i<NUM_HELPER_MODES; i++) {
2518                         if (strcmp(helper_protocol, stdio_helper_protocols[i].name) == 0) {
2519                                 squid_stream(stdio_helper_protocols[i].mode, stdio_helper_protocols[i].fn);
2520                                 exit(0);
2521                         }
2522                 }
2523                 x_fprintf(x_stderr, "unknown helper protocol [%s]\n\nValid helper protools:\n\n", helper_protocol);
2524
2525                 for (i=0; i<NUM_HELPER_MODES; i++) {
2526                         x_fprintf(x_stderr, "%s\n", stdio_helper_protocols[i].name);
2527                 }
2528
2529                 exit(1);
2530         }
2531
2532         if (!opt_username || !*opt_username) {
2533                 x_fprintf(x_stderr, "username must be specified!\n\n");
2534                 poptPrintHelp(pc, stderr, 0);
2535                 exit(1);
2536         }
2537
2538         if (opt_challenge.length) {
2539                 if (!check_auth_crap()) {
2540                         exit(1);
2541                 }
2542                 exit(0);
2543         } 
2544
2545         if (!opt_password) {
2546                 opt_password = getpass("password: ");
2547         }
2548
2549         if (diagnostics) {
2550                 if (!diagnose_ntlm_auth()) {
2551                         return 1;
2552                 }
2553         } else {
2554                 fstring user;
2555
2556                 fstr_sprintf(user, "%s%c%s", opt_domain, winbind_separator(), opt_username);
2557                 if (!check_plaintext_auth(user, opt_password, True)) {
2558                         return 1;
2559                 }
2560         }
2561
2562         /* Exit code */
2563
2564         poptFreeContext(pc);
2565         TALLOC_FREE(frame);
2566         return 0;
2567 }