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