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