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