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