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