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