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