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