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