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