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