r4147: converted from NT_USER_TOKEN to struct security_token
[abartlet/samba.git/.git] / source4 / 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
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 #include "dynconfig.h"
27 #include "system/passwd.h"
28 #include "lib/cmdline/popt_common.h"
29 #include "auth/auth.h"
30
31 #undef DBGC_CLASS
32 #define DBGC_CLASS DBGC_WINBIND
33
34 #define SQUID_BUFFER_SIZE 2010
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_CLIENT,
42         GSS_SPNEGO_SERVER,
43         NTLM_SERVER_1,
44         NUM_HELPER_MODES
45 };
46
47 #define NTLM_AUTH_FLAG_USER_SESSION_KEY     0x0004
48 #define NTLM_AUTH_FLAG_LMKEY                0x0008
49
50
51 typedef void (*stdio_helper_function)(enum stdio_helper_mode stdio_helper_mode, 
52                                       char *buf, int length, void **private,
53                                       unsigned int mux_id);
54
55 static void manage_squid_basic_request (enum stdio_helper_mode stdio_helper_mode, 
56                                         char *buf, int length, void **private,
57                                         unsigned int mux_id);
58
59 static void manage_gensec_request (enum stdio_helper_mode stdio_helper_mode, 
60                                    char *buf, int length, void **private,
61                                    unsigned int mux_id);
62
63 static void manage_ntlm_server_1_request (enum stdio_helper_mode stdio_helper_mode, 
64                                           char *buf, int length, void **private,
65                                           unsigned int mux_id);
66
67 static void manage_squid_request(enum stdio_helper_mode helper_mode, 
68                                  stdio_helper_function fn);
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_gensec_request},
78         { GSS_SPNEGO_CLIENT, "gss-spnego-client", manage_gensec_request},
79         { GSS_SPNEGO_SERVER, "gss-spnego", manage_gensec_request},
80         { NTLMSSP_CLIENT_1, "ntlmssp-client-1", manage_gensec_request},
81         { NTLM_SERVER_1, "ntlm-server-1", manage_ntlm_server_1_request},
82         { NUM_HELPER_MODES, NULL, NULL}
83 };
84
85 extern int winbindd_fd;
86
87 const char *opt_username;
88 const char *opt_domain;
89 const char *opt_workstation;
90 const char *opt_password;
91 int opt_multiplex;
92
93
94 static void mux_printf(unsigned int mux_id, const char *format, ...) PRINTF_ATTRIBUTE(2, 3);
95
96 static void mux_printf(unsigned int mux_id, const char *format, ...)
97 {
98         va_list ap;
99
100         if (opt_multiplex) {
101                 x_fprintf(x_stdout, "%d ", mux_id);
102         }
103
104         va_start(ap, format);
105         x_vfprintf(x_stdout, format, ap);
106         va_end(ap);
107 }
108
109
110
111 /* Copy of parse_domain_user from winbindd_util.c.  Parse a string of the
112    form DOMAIN/user into a domain and a user */
113
114 static BOOL parse_ntlm_auth_domain_user(const char *domuser, fstring domain, 
115                                         fstring user)
116 {
117
118         char *p = strchr(domuser,*lp_winbind_separator());
119
120         if (!p) {
121                 return False;
122         }
123         
124         fstrcpy(user, p+1);
125         fstrcpy(domain, domuser);
126         domain[PTR_DIFF(p, domuser)] = 0;
127
128         return True;
129 }
130
131 /* Authenticate a user with a plaintext password */
132
133 static BOOL check_plaintext_auth(const char *user, const char *pass, 
134                                  BOOL stdout_diagnostics)
135 {
136         return (strcmp(pass, opt_password) == 0);
137 }
138
139 /* authenticate a user with an encrypted username/password */
140
141 static NTSTATUS local_pw_check_specified(const char *username, 
142                                          const char *domain, 
143                                          const char *workstation,
144                                          const DATA_BLOB *challenge, 
145                                          const DATA_BLOB *lm_response, 
146                                          const DATA_BLOB *nt_response, 
147                                          uint32 flags, 
148                                          DATA_BLOB *lm_session_key, 
149                                          DATA_BLOB *user_session_key, 
150                                          char **error_string, 
151                                          char **unix_name) 
152 {
153         NTSTATUS nt_status;
154         uint8_t lm_pw[16], nt_pw[16];
155         uint8_t *lm_pwd, *nt_pwd;
156         TALLOC_CTX *mem_ctx = talloc_init("local_pw_check_specified");
157         if (!mem_ctx) {
158                 nt_status = NT_STATUS_NO_MEMORY;
159         } else {
160                 
161                 E_md4hash(opt_password, nt_pw);
162                 if (E_deshash(opt_password, lm_pw)) {
163                         lm_pwd = lm_pw;
164                 } else {
165                         lm_pwd = NULL;
166                 }
167                 nt_pwd = nt_pw;
168                 
169                 
170                 nt_status = ntlm_password_check(mem_ctx, 
171                                                 challenge,
172                                                 lm_response,
173                                                 nt_response,
174                                                 NULL, NULL,
175                                                 username,
176                                                 username,
177                                                 domain,
178                                                 lm_pwd, nt_pwd, user_session_key, lm_session_key);
179                 
180                 if (NT_STATUS_IS_OK(nt_status)) {
181                         if (unix_name) {
182                                 asprintf(unix_name, 
183                                          "%s%c%s", domain,
184                                          *lp_winbind_separator(), 
185                                          username);
186                         }
187                 } else {
188                         DEBUG(3, ("Login for user [%s]\\[%s]@[%s] failed due to [%s]\n", 
189                                   domain, username, workstation, 
190                                   nt_errstr(nt_status)));
191                 }
192                 talloc_destroy(mem_ctx);
193         }
194         if (error_string) {
195                 *error_string = strdup(nt_errstr(nt_status));
196         }
197         return nt_status;
198         
199         
200 }
201
202 static void manage_squid_basic_request(enum stdio_helper_mode stdio_helper_mode, 
203                                        char *buf, int length, void **private,
204                                        unsigned int mux_id) 
205 {
206         char *user, *pass;      
207         user=buf;
208         
209         pass=memchr(buf,' ',length);
210         if (!pass) {
211                 DEBUG(2, ("Password not found. Denying access\n"));
212                 mux_printf(mux_id, "ERR\n");
213                 return;
214         }
215         *pass='\0';
216         pass++;
217         
218         if (stdio_helper_mode == SQUID_2_5_BASIC) {
219                 rfc1738_unescape(user);
220                 rfc1738_unescape(pass);
221         }
222         
223         if (check_plaintext_auth(user, pass, False)) {
224                 mux_printf(mux_id, "OK\n");
225         } else {
226                 mux_printf(mux_id, "ERR\n");
227         }
228 }
229
230 /* This is a bit hairy, but the basic idea is to do a password callback
231    to the calling application.  The callback comes from within gensec */
232
233 static void manage_gensec_get_pw_request(enum stdio_helper_mode stdio_helper_mode, 
234                                          char *buf, int length, void **private,
235                                          unsigned int mux_id)  
236 {
237         DATA_BLOB in;
238         struct gensec_security **gensec_state = (struct gensec_security **)private;
239         if (strlen(buf) < 2) {
240                 DEBUG(1, ("query [%s] invalid", buf));
241                 mux_printf(mux_id, "BH\n");
242                 return;
243         }
244
245         if (strlen(buf) > 3) {
246                 in = base64_decode_data_blob(buf + 3);
247         } else {
248                 in = data_blob(NULL, 0);
249         }
250
251         if (strncmp(buf, "PW ", 3) == 0) {
252
253                 (*gensec_state)->password_callback_private = talloc_strndup((*gensec_state), 
254                                                                             (const char *)in.data, in.length);
255                 
256                 if ((*gensec_state)->password_callback_private == NULL) {
257                         DEBUG(1, ("Out of memory\n"));
258                         mux_printf(mux_id, "BH\n");
259                         data_blob_free(&in);
260                         return;
261                 }
262
263                 mux_printf(mux_id, "OK\n");
264                 data_blob_free(&in);
265                 return;
266         }
267         DEBUG(1, ("Asked for (and expected) a password\n"));
268         mux_printf(mux_id, "BH\n");
269         data_blob_free(&in);
270 }
271
272 /* 
273  * Callback for gensec, to ask the calling application for a password.  Uses the above function
274  * for the stdio part of this.
275  */
276
277 static NTSTATUS get_password(struct gensec_security *gensec_security, 
278                              TALLOC_CTX *mem_ctx, 
279                              char **password) 
280 {
281         *password = NULL;
282         
283         /* Ask for a password */
284         mux_printf((unsigned int)gensec_security->password_callback_private, "PW\n");
285         gensec_security->password_callback_private = NULL;
286
287         manage_squid_request(NUM_HELPER_MODES /* bogus */, manage_gensec_get_pw_request);
288         *password = (char *)gensec_security->password_callback_private;
289         if (*password) {
290                 return NT_STATUS_OK;
291         } else {
292                 return NT_STATUS_INVALID_PARAMETER;
293         }
294 }
295
296 static void manage_gensec_request(enum stdio_helper_mode stdio_helper_mode, 
297                                   char *buf, int length, void **private,
298                                   unsigned int mux_id) 
299 {
300         DATA_BLOB in;
301         DATA_BLOB out = data_blob(NULL, 0);
302         char *out_base64 = NULL;
303         const char *reply_arg = NULL;
304         struct gensec_security **gensec_state = (struct gensec_security **)private;
305         NTSTATUS nt_status;
306         BOOL first = False;
307         const char *reply_code;
308         
309         if (strlen(buf) < 2) {
310                 DEBUG(1, ("query [%s] invalid", buf));
311                 mux_printf(mux_id, "BH\n");
312                 return;
313         }
314
315         if (strlen(buf) > 3) {
316                 in = base64_decode_data_blob(buf + 3);
317         } else {
318                 in = data_blob(NULL, 0);
319         }
320
321         if (strncmp(buf, "YR", 2) == 0) {
322                 if (gensec_state && *gensec_state) {
323                         gensec_end(gensec_state);
324                         *gensec_state = NULL;
325                 }
326         } else if ( (strncmp(buf, "OK", 2) == 0)) {
327                 /* do nothing */
328                 data_blob_free(&in);
329                 return;
330         } else if ( (strncmp(buf, "TT ", 3) != 0) &&
331                     (strncmp(buf, "KK ", 3) != 0) &&
332                     (strncmp(buf, "AF ", 3) != 0) &&
333                     (strncmp(buf, "NA ", 3) != 0) && 
334                     (strncmp(buf, "UG", 2) != 0) && 
335                     (strncmp(buf, "PW ", 3) != 0)) {
336                 DEBUG(1, ("SPNEGO request [%s] invalid\n", buf));
337                 mux_printf(mux_id, "BH\n");
338                 data_blob_free(&in);
339                 return;
340         }
341
342         /* setup gensec */
343         if (!(gensec_state && *gensec_state)) {
344                 switch (stdio_helper_mode) {
345                 case GSS_SPNEGO_CLIENT:
346                 case NTLMSSP_CLIENT_1:
347                         /* setup the client side */
348                         
349                         if (!NT_STATUS_IS_OK(gensec_client_start(NULL, gensec_state))) {
350                                 exit(1);
351                         }
352                         gensec_set_username(*gensec_state, opt_username);
353                         gensec_set_domain(*gensec_state, opt_domain);           
354                         if (opt_password) {
355                                 if (!NT_STATUS_IS_OK(gensec_set_password(*gensec_state, opt_password))) {
356                                         DEBUG(1, ("Out of memory\n"));
357                                         mux_printf(mux_id, "BH\n");
358                                         data_blob_free(&in);
359                                         return;
360                                 }
361                         } else {
362                                 gensec_set_password_callback(*gensec_state, get_password, (void*)mux_id);
363                         }
364                         
365                         break;
366                 case GSS_SPNEGO_SERVER:
367                 case SQUID_2_5_NTLMSSP:
368                         if (!NT_STATUS_IS_OK(gensec_server_start(NULL, gensec_state))) {
369                                 exit(1);
370                         }
371                         break;
372                 default:
373                         abort();
374                 }
375
376                 switch (stdio_helper_mode) {
377                 case GSS_SPNEGO_CLIENT:
378                 case GSS_SPNEGO_SERVER:
379                         nt_status = gensec_start_mech_by_oid(*gensec_state, GENSEC_OID_SPNEGO);
380                         if (!in.length) {
381                                 first = True;
382                         }
383                         break;
384                 case NTLMSSP_CLIENT_1:
385                         if (!in.length) {
386                                 first = True;
387                         }
388                 case SQUID_2_5_NTLMSSP:
389                         nt_status = gensec_start_mech_by_oid(*gensec_state, GENSEC_OID_NTLMSSP);
390                         break;
391                 default:
392                         abort();
393                 }
394
395                 if (!NT_STATUS_IS_OK(nt_status)) {
396                         DEBUG(1, ("SPENGO login failed to initialise: %s\n", nt_errstr(nt_status)));
397                         mux_printf(mux_id, "BH\n");
398                         return;
399                 }
400         }
401         
402         if (strncmp(buf, "PW ", 3) == 0) {
403
404                 if (!NT_STATUS_IS_OK(gensec_set_password(*gensec_state, 
405                                                          talloc_strndup((*gensec_state), 
406                                                                         (const char *)in.data, 
407                                                                         in.length)))) {
408                         DEBUG(1, ("gensec_set_password failed: %s\n", nt_errstr(nt_status)));
409                         mux_printf(mux_id, "BH %s\n", nt_errstr(nt_status));
410                         data_blob_free(&in);
411                         return;
412                 }
413
414                 mux_printf(mux_id, "OK\n");
415                 data_blob_free(&in);
416                 return;
417         }
418
419         if (strncmp(buf, "UG", 2) == 0) {
420                 int i;
421                 char *grouplist = NULL;
422                 struct auth_session_info *session_info;
423
424                 if (!NT_STATUS_IS_OK(gensec_session_info(*gensec_state, &session_info))) { 
425                         DEBUG(1, ("gensec_session_info failed: %s\n", nt_errstr(nt_status)));
426                         mux_printf(mux_id, "BH %s\n", nt_errstr(nt_status));
427                         data_blob_free(&in);
428                         return;
429                 }
430                 
431                 /* get the string onto the context */
432                 grouplist = talloc_strdup(session_info, "");
433                 
434                 for (i=0; i<session_info->security_token->num_sids; i++) {
435                         struct security_token *token = session_info->security_token; 
436                         const char *sidstr = dom_sid_string(session_info, 
437                                                             token->sids[i]);
438                         grouplist = talloc_asprintf_append(grouplist, "%s,", sidstr);
439                 }
440
441                 mux_printf(mux_id, "GL %s\n", grouplist);
442                 free_session_info(&session_info);
443                 data_blob_free(&in);
444                 return;
445         }
446
447         /* update */
448
449         nt_status = gensec_update(*gensec_state, NULL, in, &out);
450         
451         /* don't leak 'bad password'/'no such user' info to the network client */
452         nt_status = nt_status_squash(nt_status);
453
454         if (out.length) {
455                 out_base64 = base64_encode_data_blob(out);
456         } else {
457                 out_base64 = NULL;
458         }
459         if (NT_STATUS_EQUAL(nt_status, NT_STATUS_MORE_PROCESSING_REQUIRED)) {
460                 reply_arg = "*";
461                 if (first) {
462                         reply_code = "YR";
463                 } else if ((*gensec_state)->gensec_role == GENSEC_CLIENT) { 
464                         reply_code = "KK";
465                 } else if ((*gensec_state)->gensec_role == GENSEC_SERVER) { 
466                         reply_code = "TT";
467                 } else {
468                         abort();
469                 }
470
471
472         } else if (NT_STATUS_EQUAL(nt_status, NT_STATUS_ACCESS_DENIED)) {
473                 reply_code = "BH";
474                 reply_arg = nt_errstr(nt_status);
475                 DEBUG(1, ("GENSEC login failed: %s\n", nt_errstr(nt_status)));
476         } else if (NT_STATUS_EQUAL(nt_status, NT_STATUS_UNSUCCESSFUL)) {
477                 reply_code = "BH";
478                 reply_arg = nt_errstr(nt_status);
479                 DEBUG(1, ("GENSEC login failed: %s\n", nt_errstr(nt_status)));
480         } else if (!NT_STATUS_IS_OK(nt_status)) {
481                 reply_code = "NA";
482                 reply_arg = nt_errstr(nt_status);
483                 DEBUG(1, ("GENSEC login failed: %s\n", nt_errstr(nt_status)));
484         } else if /* OK */ ((*gensec_state)->gensec_role == GENSEC_SERVER) {
485                 struct auth_session_info *session_info;
486
487                 nt_status = gensec_session_info(*gensec_state, &session_info);
488                 if (!NT_STATUS_IS_OK(nt_status)) {
489                         reply_code = "BH";
490                         reply_arg = nt_errstr(nt_status);
491                         DEBUG(1, ("GENSEC failed to retreive the session info: %s\n", nt_errstr(nt_status)));
492                 } else {
493
494                         reply_code = "AF";
495                         reply_arg = talloc_asprintf(*gensec_state, 
496                                                     "%s%s%s", session_info->server_info->domain, 
497                                                     lp_winbind_separator(), session_info->server_info->account_name);
498                         talloc_free(session_info);
499                 }
500         } else if ((*gensec_state)->gensec_role == GENSEC_CLIENT) {
501                 reply_code = "AF";
502                 reply_arg = NULL;
503         } else {
504                 abort();
505         }
506
507         switch (stdio_helper_mode) {
508         case GSS_SPNEGO_SERVER:
509                 mux_printf(mux_id, "%s %s %s\n", reply_code, 
510                           out_base64 ? out_base64 : "*", 
511                           reply_arg ? reply_arg : "*");
512                 break;
513         default:
514                 if (out_base64) {
515                         mux_printf(mux_id, "%s %s\n", reply_code, out_base64);
516                 } else if (reply_arg) {
517                         mux_printf(mux_id, "%s %s\n", reply_code, reply_arg);
518                 } else {
519                         mux_printf(mux_id, "%s\n", reply_code);
520                 }
521         }
522
523         SAFE_FREE(out_base64);
524         return;
525 }
526
527 static void manage_ntlm_server_1_request(enum stdio_helper_mode stdio_helper_mode, 
528                                          char *buf, int length, void **private,
529                                          unsigned int mux_id) 
530 {
531         char *request, *parameter;      
532         static DATA_BLOB challenge;
533         static DATA_BLOB lm_response;
534         static DATA_BLOB nt_response;
535         static char *full_username;
536         static char *username;
537         static char *domain;
538         static char *plaintext_password;
539         static BOOL ntlm_server_1_user_session_key;
540         static BOOL ntlm_server_1_lm_session_key;
541         
542         if (strequal(buf, ".")) {
543                 if (!full_username && !username) {      
544                         mux_printf(mux_id, "Error: No username supplied!\n");
545                 } else if (plaintext_password) {
546                         /* handle this request as plaintext */
547                         if (!full_username) {
548                                 if (asprintf(&full_username, "%s%c%s", domain, *lp_winbind_separator(), username) == -1) {
549                                         mux_printf(mux_id, "Error: Out of memory in asprintf!\n.\n");
550                                         return;
551                                 }
552                         }
553                         if (check_plaintext_auth(full_username, plaintext_password, False)) {
554                                 mux_printf(mux_id, "Authenticated: Yes\n");
555                         } else {
556                                 mux_printf(mux_id, "Authenticated: No\n");
557                         }
558                 } else if (!lm_response.data && !nt_response.data) {
559                         mux_printf(mux_id, "Error: No password supplied!\n");
560                 } else if (!challenge.data) {   
561                         mux_printf(mux_id, "Error: No lanman-challenge supplied!\n");
562                 } else {
563                         char *error_string = NULL;
564                         DATA_BLOB lm_key;
565                         DATA_BLOB user_session_key;
566                         uint32 flags = 0;
567
568                         if (full_username && !username) {
569                                 fstring fstr_user;
570                                 fstring fstr_domain;
571                                 
572                                 if (!parse_ntlm_auth_domain_user(full_username, fstr_user, fstr_domain)) {
573                                         /* username might be 'tainted', don't print into our new-line deleimianted stream */
574                                         mux_printf(mux_id, "Error: Could not parse into domain and username\n");
575                                 }
576                                 SAFE_FREE(username);
577                                 SAFE_FREE(domain);
578                                 username = smb_xstrdup(fstr_user);
579                                 domain = smb_xstrdup(fstr_domain);
580                         }
581
582                         if (!domain) {
583                                 domain = smb_xstrdup(lp_workgroup());
584                         }
585
586                         if (ntlm_server_1_lm_session_key) 
587                                 flags |= NTLM_AUTH_FLAG_LMKEY;
588                         
589                         if (ntlm_server_1_user_session_key) 
590                                 flags |= NTLM_AUTH_FLAG_USER_SESSION_KEY;
591
592                         if (!NT_STATUS_IS_OK(
593                                     local_pw_check_specified(username, 
594                                                               domain, 
595                                                               lp_netbios_name(),
596                                                               &challenge, 
597                                                               &lm_response, 
598                                                               &nt_response, 
599                                                               flags, 
600                                                               &lm_key, 
601                                                               &user_session_key,
602                                                               &error_string,
603                                                               NULL))) {
604
605                                 mux_printf(mux_id, "Authenticated: No\n");
606                                 mux_printf(mux_id, "Authentication-Error: %s\n.\n", error_string);
607                                 SAFE_FREE(error_string);
608                         } else {
609                                 static char zeros[16];
610                                 char *hex_lm_key;
611                                 char *hex_user_session_key;
612
613                                 mux_printf(mux_id, "Authenticated: Yes\n");
614
615                                 if (ntlm_server_1_lm_session_key 
616                                     && lm_key.length 
617                                     && (memcmp(zeros, lm_key.data, 
618                                                                 lm_key.length) != 0)) {
619                                         hex_encode(lm_key.data,
620                                                    lm_key.length,
621                                                    &hex_lm_key);
622                                         mux_printf(mux_id, "LANMAN-Session-Key: %s\n", hex_lm_key);
623                                         SAFE_FREE(hex_lm_key);
624                                 }
625
626                                 if (ntlm_server_1_user_session_key 
627                                     && user_session_key.length 
628                                     && (memcmp(zeros, user_session_key.data, 
629                                                user_session_key.length) != 0)) {
630                                         hex_encode(user_session_key.data, 
631                                                    user_session_key.length, 
632                                                    &hex_user_session_key);
633                                         mux_printf(mux_id, "User-Session-Key: %s\n", hex_user_session_key);
634                                         SAFE_FREE(hex_user_session_key);
635                                 }
636                         }
637                 }
638                 /* clear out the state */
639                 challenge = data_blob(NULL, 0);
640                 nt_response = data_blob(NULL, 0);
641                 lm_response = data_blob(NULL, 0);
642                 SAFE_FREE(full_username);
643                 SAFE_FREE(username);
644                 SAFE_FREE(domain);
645                 SAFE_FREE(plaintext_password);
646                 ntlm_server_1_user_session_key = False;
647                 ntlm_server_1_lm_session_key = False;
648                 mux_printf(mux_id, ".\n");
649
650                 return;
651         }
652
653         request = buf;
654
655         /* Indicates a base64 encoded structure */
656         parameter = strstr(request, ":: ");
657         if (!parameter) {
658                 parameter = strstr(request, ": ");
659                 
660                 if (!parameter) {
661                         DEBUG(0, ("Parameter not found!\n"));
662                         mux_printf(mux_id, "Error: Parameter not found!\n.\n");
663                         return;
664                 }
665                 
666                 parameter[0] ='\0';
667                 parameter++;
668                 parameter[0] ='\0';
669                 parameter++;
670
671         } else {
672                 parameter[0] ='\0';
673                 parameter++;
674                 parameter[0] ='\0';
675                 parameter++;
676                 parameter[0] ='\0';
677                 parameter++;
678
679                 base64_decode_inplace(parameter);
680         }
681
682         if (strequal(request, "LANMAN-Challenge")) {
683                 challenge = strhex_to_data_blob(parameter);
684                 if (challenge.length != 8) {
685                         mux_printf(mux_id, "Error: hex decode of %s failed! (got %d bytes, expected 8)\n.\n", 
686                                   parameter,
687                                   (int)challenge.length);
688                         challenge = data_blob(NULL, 0);
689                 }
690         } else if (strequal(request, "NT-Response")) {
691                 nt_response = strhex_to_data_blob(parameter);
692                 if (nt_response.length < 24) {
693                         mux_printf(mux_id, "Error: hex decode of %s failed! (only got %d bytes, needed at least 24)\n.\n", 
694                                   parameter,
695                                   (int)nt_response.length);
696                         nt_response = data_blob(NULL, 0);
697                 }
698         } else if (strequal(request, "LANMAN-Response")) {
699                 lm_response = strhex_to_data_blob(parameter);
700                 if (lm_response.length != 24) {
701                         mux_printf(mux_id, "Error: hex decode of %s failed! (got %d bytes, expected 24)\n.\n", 
702                                   parameter,
703                                   (int)lm_response.length);
704                         lm_response = data_blob(NULL, 0);
705                 }
706         } else if (strequal(request, "Password")) {
707                 plaintext_password = smb_xstrdup(parameter);
708         } else if (strequal(request, "NT-Domain")) {
709                 domain = smb_xstrdup(parameter);
710         } else if (strequal(request, "Username")) {
711                 username = smb_xstrdup(parameter);
712         } else if (strequal(request, "Full-Username")) {
713                 full_username = smb_xstrdup(parameter);
714         } else if (strequal(request, "Request-User-Session-Key")) {
715                 ntlm_server_1_user_session_key = strequal(parameter, "Yes");
716         } else if (strequal(request, "Request-LanMan-Session-Key")) {
717                 ntlm_server_1_lm_session_key = strequal(parameter, "Yes");
718         } else {
719                 mux_printf(mux_id, "Error: Unknown request %s\n.\n", request);
720         }
721 }
722
723 static void manage_squid_request(enum stdio_helper_mode helper_mode, 
724                                  stdio_helper_function fn) 
725 {
726         char buf[SQUID_BUFFER_SIZE+1];
727         unsigned int mux_id;
728         int length;
729         char *c;
730         static BOOL err;
731         struct mux_private {
732                 unsigned int max_mux;
733                 void **private_pointers;
734         };
735         
736         static struct mux_private *mux_private;
737         static void *normal_private;
738         void **private;
739
740         /* this is not a typo - x_fgets doesn't work too well under squid */
741         if (fgets(buf, sizeof(buf)-1, stdin) == NULL) {
742                 if (ferror(stdin)) {
743                         DEBUG(1, ("fgets() failed! dying..... errno=%d (%s)\n", ferror(stdin),
744                                   strerror(ferror(stdin))));
745                         
746                         exit(1);    /* BIIG buffer */
747                 }
748                 exit(0);
749         }
750     
751         c=memchr(buf,'\n',sizeof(buf)-1);
752         if (c) {
753                 *c = '\0';
754                 length = c-buf;
755         } else {
756                 err = 1;
757                 return;
758         }
759         if (err) {
760                 DEBUG(0, ("Oversized message\n"));
761                 x_fprintf(x_stdout, "ERR\n");
762                 err = 0;
763                 return;
764         }
765
766         DEBUG(10, ("Got '%s' from squid (length: %d).\n",buf,length));
767
768         if (buf[0] == '\0') {
769                 DEBUG(0, ("Invalid Request (empty)\n"));
770                 x_fprintf(x_stdout, "ERR\n");
771                 return;
772         }
773
774         if (opt_multiplex) {
775                 if (sscanf(buf, "%u ", &mux_id) != 1) {
776                         DEBUG(0, ("Invalid Request - no multiplex id\n"));
777                         x_fprintf(x_stdout, "ERR\n");
778                         return;
779                 }
780                 if (!mux_private) {
781                         mux_private = talloc_p(NULL, struct mux_private);
782                         mux_private->max_mux = 0;
783                         mux_private->private_pointers = NULL;
784                 }
785                 
786                 c=memchr(buf,' ',sizeof(buf)-1);
787                 c++;
788                 if (mux_id >= mux_private->max_mux) {
789                         unsigned int prev_max = mux_private->max_mux;
790                         mux_private->max_mux = mux_id + 1;
791                         mux_private->private_pointers
792                                 = talloc_realloc_p(mux_private, 
793                                                    mux_private->private_pointers, 
794                                                    void *, mux_private->max_mux);
795                         memset(&mux_private->private_pointers[prev_max], '\0',  
796                                (sizeof(*mux_private->private_pointers) * (mux_private->max_mux - prev_max))); 
797                 };
798
799                 private = &mux_private->private_pointers[mux_id];
800         } else {
801                 c = buf;
802                 private = &normal_private;
803         }
804         
805         fn(helper_mode, c, length, private, mux_id);
806 }
807
808 static void squid_stream(enum stdio_helper_mode stdio_mode, 
809                          stdio_helper_function fn) {
810         /* initialize FDescs */
811         x_setbuf(x_stdout, NULL);
812         x_setbuf(x_stderr, NULL);
813         while(1) {
814                 manage_squid_request(stdio_mode, fn);
815         }
816 }
817
818
819 /* Main program */
820
821 enum {
822         OPT_USERNAME = 1000,
823         OPT_DOMAIN,
824         OPT_WORKSTATION,
825         OPT_CHALLENGE,
826         OPT_RESPONSE,
827         OPT_LM,
828         OPT_NT,
829         OPT_PASSWORD,
830         OPT_LM_KEY,
831         OPT_USER_SESSION_KEY,
832         OPT_DIAGNOSTICS,
833         OPT_REQUIRE_MEMBERSHIP,
834         OPT_MULTIPLEX,
835 };
836
837  int main(int argc, const char **argv)
838 {
839         static const char *helper_protocol;
840         int opt;
841
842         poptContext pc;
843
844         /* NOTE: DO NOT change this interface without considering the implications!
845            This is an external interface, which other programs will use to interact 
846            with this helper.
847         */
848
849         /* We do not use single-letter command abbreviations, because they harm future 
850            interface stability. */
851
852         struct poptOption long_options[] = {
853                 POPT_AUTOHELP
854                 { "helper-protocol", 0, POPT_ARG_STRING, &helper_protocol, OPT_DOMAIN, "operate as a stdio-based helper", "helper protocol to use"},
855                 { "domain", 0, POPT_ARG_STRING, &opt_domain, OPT_DOMAIN, "domain name"},
856                 { "workstation", 0, POPT_ARG_STRING, &opt_workstation, OPT_WORKSTATION, "workstation"},
857                 { "username", 0, POPT_ARG_STRING, &opt_username, OPT_PASSWORD, "Username"},             
858                 { "password", 0, POPT_ARG_STRING, &opt_password, OPT_PASSWORD, "User's plaintext password"},            
859                 { "multiplex", 0, POPT_ARG_NONE, &opt_multiplex, OPT_MULTIPLEX, "Multiplex Mode"},
860                 POPT_COMMON_SAMBA
861                 POPT_TABLEEND
862         };
863
864         /* Samba client initialisation */
865
866         setup_logging("ntlm_auth", DEBUG_STDERR);
867
868         if (!lp_load(dyn_CONFIGFILE, True, False, False)) {
869                 d_fprintf(stderr, "wbinfo: error opening config file %s. Error was %s\n",
870                         dyn_CONFIGFILE, strerror(errno));
871                 exit(1);
872         }
873
874         /* Parse options */
875
876         pc = poptGetContext("ntlm_auth", argc, argv, long_options, 0);
877
878         /* Parse command line options */
879
880         if (argc == 1) {
881                 poptPrintHelp(pc, stderr, 0);
882                 return 1;
883         }
884
885         pc = poptGetContext(NULL, argc, (const char **)argv, long_options, 
886                             POPT_CONTEXT_KEEP_FIRST);
887
888         while((opt = poptGetNextOpt(pc)) != -1) {
889                 if (opt < -1) {
890                         break;
891                 }
892         }
893         if (opt < -1) {
894                 fprintf(stderr, "%s: %s\n",
895                         poptBadOption(pc, POPT_BADOPTION_NOALIAS),
896                         poptStrerror(opt));
897                 return 1;
898         }
899
900         ntlm_auth_init_subsystems;
901
902
903         if (opt_domain == NULL) {
904                 opt_domain = lp_workgroup();
905         }
906
907         if (helper_protocol) {
908                 int i;
909                 for (i=0; i<NUM_HELPER_MODES; i++) {
910                         if (strcmp(helper_protocol, stdio_helper_protocols[i].name) == 0) {
911                                 squid_stream(stdio_helper_protocols[i].mode, stdio_helper_protocols[i].fn);
912                                 exit(0);
913                         }
914                 }
915                 x_fprintf(x_stderr, "unknown helper protocol [%s]\n\nValid helper protools:\n\n", helper_protocol);
916
917                 for (i=0; i<NUM_HELPER_MODES; i++) {
918                         x_fprintf(x_stderr, "%s\n", stdio_helper_protocols[i].name);
919                 }
920
921                 exit(1);
922         }
923
924         if (!opt_username) {
925                 x_fprintf(x_stderr, "username must be specified!\n\n");
926                 poptPrintHelp(pc, stderr, 0);
927                 exit(1);
928         }
929
930         if (opt_workstation == NULL) {
931                 opt_workstation = lp_netbios_name();
932         }
933
934         if (!opt_password) {
935                 opt_password = getpass("password: ");
936         }
937
938         {
939                 char *user;
940
941                 asprintf(&user, "%s%c%s", opt_domain, *lp_winbind_separator(), opt_username);
942                 if (!check_plaintext_auth(user, opt_password, True)) {
943                         return 1;
944                 }
945         }
946
947         /* Exit code */
948
949         poptFreeContext(pc);
950         return 0;
951 }