de45220de8ed42211749c51f0c92587e772f4c7f
[metze/samba/wip.git] / auth / credentials / credentials.c
1 /* 
2    Unix SMB/CIFS implementation.
3
4    User credentials handling
5
6    Copyright (C) Jelmer Vernooij 2005
7    Copyright (C) Tim Potter 2001
8    Copyright (C) Andrew Bartlett <abartlet@samba.org> 2005
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 "librpc/gen_ndr/samr.h" /* for struct samrPassword */
26 #include "auth/credentials/credentials.h"
27 #include "auth/credentials/credentials_internal.h"
28 #include "auth/gensec/gensec.h"
29 #include "libcli/auth/libcli_auth.h"
30 #include "tevent.h"
31 #include "param/param.h"
32 #include "system/filesys.h"
33
34 /**
35  * Create a new credentials structure
36  * @param mem_ctx TALLOC_CTX parent for credentials structure 
37  */
38 _PUBLIC_ struct cli_credentials *cli_credentials_init(TALLOC_CTX *mem_ctx) 
39 {
40         struct cli_credentials *cred = talloc_zero(mem_ctx, struct cli_credentials);
41         if (cred == NULL) {
42                 return cred;
43         }
44
45         cred->winbind_separator = '\\';
46
47         return cred;
48 }
49
50 _PUBLIC_ void cli_credentials_set_callback_data(struct cli_credentials *cred,
51                                                 void *callback_data)
52 {
53         cred->priv_data = callback_data;
54 }
55
56 _PUBLIC_ void *_cli_credentials_callback_data(struct cli_credentials *cred)
57 {
58         return cred->priv_data;
59 }
60
61 /**
62  * Create a new anonymous credential
63  * @param mem_ctx TALLOC_CTX parent for credentials structure 
64  */
65 _PUBLIC_ struct cli_credentials *cli_credentials_init_anon(TALLOC_CTX *mem_ctx)
66 {
67         struct cli_credentials *anon_credentials;
68
69         anon_credentials = cli_credentials_init(mem_ctx);
70         cli_credentials_set_anonymous(anon_credentials);
71
72         return anon_credentials;
73 }
74
75 _PUBLIC_ void cli_credentials_set_kerberos_state(struct cli_credentials *creds, 
76                                         enum credentials_use_kerberos use_kerberos)
77 {
78         creds->use_kerberos = use_kerberos;
79 }
80
81 _PUBLIC_ void cli_credentials_set_forced_sasl_mech(struct cli_credentials *creds,
82                                                    const char *sasl_mech)
83 {
84         TALLOC_FREE(creds->forced_sasl_mech);
85         creds->forced_sasl_mech = talloc_strdup(creds, sasl_mech);
86 }
87
88 _PUBLIC_ void cli_credentials_set_krb_forwardable(struct cli_credentials *creds,
89                                                   enum credentials_krb_forwardable krb_forwardable)
90 {
91         creds->krb_forwardable = krb_forwardable;
92 }
93
94 _PUBLIC_ enum credentials_use_kerberos cli_credentials_get_kerberos_state(struct cli_credentials *creds)
95 {
96         return creds->use_kerberos;
97 }
98
99 _PUBLIC_ const char *cli_credentials_get_forced_sasl_mech(struct cli_credentials *creds)
100 {
101         return creds->forced_sasl_mech;
102 }
103
104 _PUBLIC_ enum credentials_krb_forwardable cli_credentials_get_krb_forwardable(struct cli_credentials *creds)
105 {
106         return creds->krb_forwardable;
107 }
108
109 _PUBLIC_ void cli_credentials_set_gensec_features(struct cli_credentials *creds, uint32_t gensec_features)
110 {
111         creds->gensec_features = gensec_features;
112 }
113
114 _PUBLIC_ uint32_t cli_credentials_get_gensec_features(struct cli_credentials *creds)
115 {
116         return creds->gensec_features;
117 }
118
119
120 /**
121  * Obtain the username for this credentials context.
122  * @param cred credentials context
123  * @retval The username set on this context.
124  * @note Return value will never be NULL except by programmer error.
125  */
126 _PUBLIC_ const char *cli_credentials_get_username(struct cli_credentials *cred)
127 {
128         if (cred->machine_account_pending) {
129                 cli_credentials_set_machine_account(cred, 
130                                         cred->machine_account_pending_lp_ctx);
131         }
132
133         if (cred->username_obtained == CRED_CALLBACK && 
134             !cred->callback_running) {
135                 cred->callback_running = true;
136                 cred->username = cred->username_cb(cred);
137                 cred->callback_running = false;
138                 if (cred->username_obtained == CRED_CALLBACK) {
139                         cred->username_obtained = CRED_CALLBACK_RESULT;
140                         cli_credentials_invalidate_ccache(cred, cred->username_obtained);
141                 }
142         }
143
144         return cred->username;
145 }
146
147 _PUBLIC_ bool cli_credentials_set_username(struct cli_credentials *cred, 
148                                   const char *val, enum credentials_obtained obtained)
149 {
150         if (obtained >= cred->username_obtained) {
151                 cred->username = talloc_strdup(cred, val);
152                 cred->username_obtained = obtained;
153                 cli_credentials_invalidate_ccache(cred, cred->username_obtained);
154                 return true;
155         }
156
157         return false;
158 }
159
160 _PUBLIC_ bool cli_credentials_set_username_callback(struct cli_credentials *cred,
161                                   const char *(*username_cb) (struct cli_credentials *))
162 {
163         if (cred->username_obtained < CRED_CALLBACK) {
164                 cred->username_cb = username_cb;
165                 cred->username_obtained = CRED_CALLBACK;
166                 return true;
167         }
168
169         return false;
170 }
171
172 _PUBLIC_ bool cli_credentials_set_bind_dn(struct cli_credentials *cred, 
173                                  const char *bind_dn)
174 {
175         cred->bind_dn = talloc_strdup(cred, bind_dn);
176         return true;
177 }
178
179 /**
180  * Obtain the BIND DN for this credentials context.
181  * @param cred credentials context
182  * @retval The username set on this context.
183  * @note Return value will be NULL if not specified explictly
184  */
185 _PUBLIC_ const char *cli_credentials_get_bind_dn(struct cli_credentials *cred)
186 {
187         return cred->bind_dn;
188 }
189
190
191 /**
192  * Obtain the client principal for this credentials context.
193  * @param cred credentials context
194  * @retval The username set on this context.
195  * @note Return value will never be NULL except by programmer error.
196  */
197 _PUBLIC_ char *cli_credentials_get_principal_and_obtained(struct cli_credentials *cred, TALLOC_CTX *mem_ctx, enum credentials_obtained *obtained)
198 {
199         if (cred->machine_account_pending) {
200                 cli_credentials_set_machine_account(cred,
201                                         cred->machine_account_pending_lp_ctx);
202         }
203
204         if (cred->principal_obtained == CRED_CALLBACK && 
205             !cred->callback_running) {
206                 cred->callback_running = true;
207                 cred->principal = cred->principal_cb(cred);
208                 cred->callback_running = false;
209                 if (cred->principal_obtained == CRED_CALLBACK) {
210                         cred->principal_obtained = CRED_CALLBACK_RESULT;
211                         cli_credentials_invalidate_ccache(cred, cred->principal_obtained);
212                 }
213         }
214
215         if (cred->principal_obtained < cred->username_obtained
216             || cred->principal_obtained < MAX(cred->domain_obtained, cred->realm_obtained)) {
217                 const char *effective_username = NULL;
218                 const char *effective_realm = NULL;
219                 enum credentials_obtained effective_obtained;
220
221                 effective_username = cli_credentials_get_username(cred);
222                 if (effective_username == NULL || strlen(effective_username) == 0) {
223                         *obtained = cred->username_obtained;
224                         return NULL;
225                 }
226
227                 if (cred->domain_obtained > cred->realm_obtained) {
228                         effective_realm = cli_credentials_get_domain(cred);
229                         effective_obtained = MIN(cred->domain_obtained,
230                                                  cred->username_obtained);
231                 } else {
232                         effective_realm = cli_credentials_get_realm(cred);
233                         effective_obtained = MIN(cred->realm_obtained,
234                                                  cred->username_obtained);
235                 }
236
237                 if (effective_realm == NULL || strlen(effective_realm) == 0) {
238                         effective_realm = cli_credentials_get_domain(cred);
239                         effective_obtained = MIN(cred->domain_obtained,
240                                                  cred->username_obtained);
241                 }
242
243                 if (effective_realm != NULL && strlen(effective_realm) != 0) {
244                         *obtained = effective_obtained;
245                         return talloc_asprintf(mem_ctx, "%s@%s", 
246                                                effective_username,
247                                                effective_realm);
248                 }
249         }
250         *obtained = cred->principal_obtained;
251         return talloc_strdup(mem_ctx, cred->principal);
252 }
253
254 /**
255  * Obtain the client principal for this credentials context.
256  * @param cred credentials context
257  * @retval The username set on this context.
258  * @note Return value will never be NULL except by programmer error.
259  */
260 _PUBLIC_ char *cli_credentials_get_principal(struct cli_credentials *cred, TALLOC_CTX *mem_ctx)
261 {
262         enum credentials_obtained obtained;
263         return cli_credentials_get_principal_and_obtained(cred, mem_ctx, &obtained);
264 }
265
266 _PUBLIC_ bool cli_credentials_set_principal(struct cli_credentials *cred, 
267                                    const char *val, 
268                                    enum credentials_obtained obtained)
269 {
270         if (obtained >= cred->principal_obtained) {
271                 struct loadparm_context *lp_ctx;
272                 bool ok;
273
274                 cred->principal = talloc_strdup(cred, val);
275                 if (cred->principal == NULL) {
276                         return false;
277                 }
278                 cred->principal_obtained = obtained;
279
280                 cli_credentials_invalidate_ccache(cred, cred->principal_obtained);
281
282                 lp_ctx = loadparm_init_s3(cred, loadparm_s3_helpers());
283                 if (lp_ctx == NULL) {
284                         return false;
285                 }
286                 ok = cli_credentials_ccache_reinit(cred, lp_ctx);
287                 talloc_free(lp_ctx);
288
289                 return ok;
290         }
291
292         return false;
293 }
294
295 /* Set a callback to get the principal.  This could be a popup dialog,
296  * a terminal prompt or similar.  */
297 _PUBLIC_ bool cli_credentials_set_principal_callback(struct cli_credentials *cred,
298                                   const char *(*principal_cb) (struct cli_credentials *))
299 {
300         if (cred->principal_obtained < CRED_CALLBACK) {
301                 cred->principal_cb = principal_cb;
302                 cred->principal_obtained = CRED_CALLBACK;
303                 return true;
304         }
305
306         return false;
307 }
308
309 /* Some of our tools are 'anonymous by default'.  This is a single
310  * function to determine if authentication has been explicitly
311  * requested */
312
313 _PUBLIC_ bool cli_credentials_authentication_requested(struct cli_credentials *cred) 
314 {
315         uint32_t gensec_features = 0;
316
317         if (cred->bind_dn) {
318                 return true;
319         }
320
321         /*
322          * If we forced the mech we clearly want authentication. E.g. to use
323          * SASL/EXTERNAL which has no credentials.
324          */
325         if (cred->forced_sasl_mech) {
326                 return true;
327         }
328
329         if (cli_credentials_is_anonymous(cred)){
330                 return false;
331         }
332
333         if (cred->principal_obtained >= CRED_SPECIFIED) {
334                 return true;
335         }
336         if (cred->username_obtained >= CRED_SPECIFIED) {
337                 return true;
338         }
339
340         if (cli_credentials_get_kerberos_state(cred) == CRED_MUST_USE_KERBEROS) {
341                 return true;
342         }
343
344         gensec_features = cli_credentials_get_gensec_features(cred);
345         if (gensec_features & GENSEC_FEATURE_NTLM_CCACHE) {
346                 return true;
347         }
348
349         if (gensec_features & GENSEC_FEATURE_SIGN) {
350                 return true;
351         }
352
353         if (gensec_features & GENSEC_FEATURE_SEAL) {
354                 return true;
355         }
356
357         return false;
358 }
359
360 /**
361  * Obtain the password for this credentials context.
362  * @param cred credentials context
363  * @retval If set, the cleartext password, otherwise NULL
364  */
365 _PUBLIC_ const char *cli_credentials_get_password(struct cli_credentials *cred)
366 {
367         if (cred->machine_account_pending) {
368                 cli_credentials_set_machine_account(cred,
369                                                     cred->machine_account_pending_lp_ctx);
370         }
371
372         if (cred->password_obtained == CRED_CALLBACK && 
373             !cred->callback_running &&
374             !cred->password_will_be_nt_hash) {
375                 cred->callback_running = true;
376                 cred->password = cred->password_cb(cred);
377                 cred->callback_running = false;
378                 if (cred->password_obtained == CRED_CALLBACK) {
379                         cred->password_obtained = CRED_CALLBACK_RESULT;
380                         cli_credentials_invalidate_ccache(cred, cred->password_obtained);
381                 }
382         }
383
384         return cred->password;
385 }
386
387 /* Set a password on the credentials context, including an indication
388  * of 'how' the password was obtained */
389
390 _PUBLIC_ bool cli_credentials_set_password(struct cli_credentials *cred, 
391                                   const char *val, 
392                                   enum credentials_obtained obtained)
393 {
394         if (obtained >= cred->password_obtained) {
395
396                 cred->lm_response = data_blob_null;
397                 cred->nt_response = data_blob_null;
398                 cred->nt_hash = NULL;
399                 cred->password = NULL;
400
401                 cli_credentials_invalidate_ccache(cred, obtained);
402
403                 cred->password_tries = 0;
404
405                 if (val == NULL) {
406                         cred->password_obtained = obtained;
407                         return true;
408                 }
409
410                 if (cred->password_will_be_nt_hash) {
411                         struct samr_Password *nt_hash = NULL;
412                         size_t val_len = strlen(val);
413                         size_t converted;
414
415                         nt_hash = talloc(cred, struct samr_Password);
416                         if (nt_hash == NULL) {
417                                 return false;
418                         }
419
420                         converted = strhex_to_str((char *)nt_hash->hash,
421                                                   sizeof(nt_hash->hash),
422                                                   val, val_len);
423                         if (converted != sizeof(nt_hash->hash)) {
424                                 TALLOC_FREE(nt_hash);
425                                 return false;
426                         }
427
428                         cred->nt_hash = nt_hash;
429                         cred->password_obtained = obtained;
430                         return true;
431                 }
432
433                 cred->password = talloc_strdup(cred, val);
434                 if (cred->password == NULL) {
435                         return false;
436                 }
437
438                 /* Don't print the actual password in talloc memory dumps */
439                 talloc_set_name_const(cred->password,
440                         "password set via cli_credentials_set_password");
441                 cred->password_obtained = obtained;
442
443                 return true;
444         }
445
446         return false;
447 }
448
449 _PUBLIC_ bool cli_credentials_set_password_callback(struct cli_credentials *cred,
450                                            const char *(*password_cb) (struct cli_credentials *))
451 {
452         if (cred->password_obtained < CRED_CALLBACK) {
453                 cred->password_tries = 3;
454                 cred->password_cb = password_cb;
455                 cred->password_obtained = CRED_CALLBACK;
456                 cli_credentials_invalidate_ccache(cred, cred->password_obtained);
457                 return true;
458         }
459
460         return false;
461 }
462
463 /**
464  * Obtain the 'old' password for this credentials context (used for join accounts).
465  * @param cred credentials context
466  * @retval If set, the cleartext password, otherwise NULL
467  */
468 _PUBLIC_ const char *cli_credentials_get_old_password(struct cli_credentials *cred)
469 {
470         if (cred->machine_account_pending) {
471                 cli_credentials_set_machine_account(cred,
472                                                     cred->machine_account_pending_lp_ctx);
473         }
474
475         return cred->old_password;
476 }
477
478 _PUBLIC_ bool cli_credentials_set_old_password(struct cli_credentials *cred, 
479                                       const char *val, 
480                                       enum credentials_obtained obtained)
481 {
482         cred->old_password = talloc_strdup(cred, val);
483         if (cred->old_password) {
484                 /* Don't print the actual password in talloc memory dumps */
485                 talloc_set_name_const(cred->old_password, "password set via cli_credentials_set_old_password");
486         }
487         cred->old_nt_hash = NULL;
488         return true;
489 }
490
491 /**
492  * Obtain the password, in the form MD4(unicode(password)) for this credentials context.
493  *
494  * Sometimes we only have this much of the password, while the rest of
495  * the time this call avoids calling E_md4hash themselves.
496  *
497  * @param cred credentials context
498  * @retval If set, the cleartext password, otherwise NULL
499  */
500 _PUBLIC_ struct samr_Password *cli_credentials_get_nt_hash(struct cli_credentials *cred,
501                                                            TALLOC_CTX *mem_ctx)
502 {
503         enum credentials_obtained password_obtained;
504         enum credentials_obtained ccache_threshold;
505         enum credentials_obtained client_gss_creds_threshold;
506         bool password_is_nt_hash;
507         const char *password = NULL;
508         struct samr_Password *nt_hash = NULL;
509
510         if (cred->nt_hash != NULL) {
511                 /*
512                  * If we already have a hash it's easy.
513                  */
514                 goto return_hash;
515         }
516
517         /*
518          * This is a bit tricky, with password_will_be_nt_hash
519          * we still need to get the value via the password_callback
520          * but if we did that we should not remember it's state
521          * in the long run so we need to undo it.
522          */
523
524         password_obtained = cred->password_obtained;
525         ccache_threshold = cred->ccache_threshold;
526         client_gss_creds_threshold = cred->client_gss_creds_threshold;
527         password_is_nt_hash = cred->password_will_be_nt_hash;
528
529         cred->password_will_be_nt_hash = false;
530         password = cli_credentials_get_password(cred);
531
532         cred->password_will_be_nt_hash = password_is_nt_hash;
533         if (password_is_nt_hash && password_obtained == CRED_CALLBACK) {
534                 /*
535                  * We got the nt_hash as string via the callback,
536                  * so we need to undo the state change.
537                  *
538                  * And also don't remember it as plaintext password.
539                  */
540                 cred->client_gss_creds_threshold = client_gss_creds_threshold;
541                 cred->ccache_threshold = ccache_threshold;
542                 cred->password_obtained = password_obtained;
543                 cred->password = NULL;
544         }
545
546         if (password == NULL) {
547                 return NULL;
548         }
549
550         nt_hash = talloc(cred, struct samr_Password);
551         if (nt_hash == NULL) {
552                 return NULL;
553         }
554
555         if (password_is_nt_hash) {
556                 size_t password_len = strlen(password);
557                 size_t converted;
558
559                 converted = strhex_to_str((char *)nt_hash->hash,
560                                           sizeof(nt_hash->hash),
561                                           password, password_len);
562                 if (converted != sizeof(nt_hash->hash)) {
563                         TALLOC_FREE(nt_hash);
564                         return NULL;
565                 }
566         } else {
567                 E_md4hash(password, nt_hash->hash);
568         }
569
570         cred->nt_hash = nt_hash;
571         nt_hash = NULL;
572
573 return_hash:
574         nt_hash = talloc(mem_ctx, struct samr_Password);
575         if (nt_hash == NULL) {
576                 return NULL;
577         }
578
579         *nt_hash = *cred->nt_hash;
580
581         return nt_hash;
582 }
583
584 /**
585  * Obtain the old password, in the form MD4(unicode(password)) for this credentials context.
586  *
587  * Sometimes we only have this much of the password, while the rest of
588  * the time this call avoids calling E_md4hash themselves.
589  *
590  * @param cred credentials context
591  * @retval If set, the cleartext password, otherwise NULL
592  */
593 _PUBLIC_ struct samr_Password *cli_credentials_get_old_nt_hash(struct cli_credentials *cred,
594                                                                TALLOC_CTX *mem_ctx)
595 {
596         const char *old_password = NULL;
597
598         if (cred->old_nt_hash != NULL) {
599                 struct samr_Password *nt_hash = talloc(mem_ctx, struct samr_Password);
600                 if (!nt_hash) {
601                         return NULL;
602                 }
603
604                 *nt_hash = *cred->old_nt_hash;
605
606                 return nt_hash;
607         }
608
609         old_password = cli_credentials_get_old_password(cred);
610         if (old_password) {
611                 struct samr_Password *nt_hash = talloc(mem_ctx, struct samr_Password);
612                 if (!nt_hash) {
613                         return NULL;
614                 }
615
616                 E_md4hash(old_password, nt_hash->hash);
617
618                 return nt_hash;
619         }
620
621         return NULL;
622 }
623
624 /**
625  * Obtain the 'short' or 'NetBIOS' domain for this credentials context.
626  * @param cred credentials context
627  * @retval The domain set on this context. 
628  * @note Return value will never be NULL except by programmer error.
629  */
630 _PUBLIC_ const char *cli_credentials_get_domain(struct cli_credentials *cred)
631 {
632         if (cred->machine_account_pending) {
633                 cli_credentials_set_machine_account(cred,
634                                                     cred->machine_account_pending_lp_ctx);
635         }
636
637         if (cred->domain_obtained == CRED_CALLBACK && 
638             !cred->callback_running) {
639                 cred->callback_running = true;
640                 cred->domain = cred->domain_cb(cred);
641                 cred->callback_running = false;
642                 if (cred->domain_obtained == CRED_CALLBACK) {
643                         cred->domain_obtained = CRED_CALLBACK_RESULT;
644                         cli_credentials_invalidate_ccache(cred, cred->domain_obtained);
645                 }
646         }
647
648         return cred->domain;
649 }
650
651
652 _PUBLIC_ bool cli_credentials_set_domain(struct cli_credentials *cred, 
653                                 const char *val, 
654                                 enum credentials_obtained obtained)
655 {
656         if (obtained >= cred->domain_obtained) {
657                 /* it is important that the domain be in upper case,
658                  * particularly for the sensitive NTLMv2
659                  * calculations */
660                 cred->domain = strupper_talloc(cred, val);
661                 cred->domain_obtained = obtained;
662                 /* setting domain does not mean we have to invalidate ccache 
663                  * because domain in not used for Kerberos operations.
664                  * If ccache invalidation is required, one will anyway specify
665                  * a password to kinit, and that will force invalidation of the ccache
666                  */
667                 return true;
668         }
669
670         return false;
671 }
672
673 bool cli_credentials_set_domain_callback(struct cli_credentials *cred,
674                                          const char *(*domain_cb) (struct cli_credentials *))
675 {
676         if (cred->domain_obtained < CRED_CALLBACK) {
677                 cred->domain_cb = domain_cb;
678                 cred->domain_obtained = CRED_CALLBACK;
679                 return true;
680         }
681
682         return false;
683 }
684
685 /**
686  * Obtain the Kerberos realm for this credentials context.
687  * @param cred credentials context
688  * @retval The realm set on this context. 
689  * @note Return value will never be NULL except by programmer error.
690  */
691 _PUBLIC_ const char *cli_credentials_get_realm(struct cli_credentials *cred)
692 {       
693         if (cred->machine_account_pending) {
694                 cli_credentials_set_machine_account(cred,
695                                                     cred->machine_account_pending_lp_ctx);
696         }
697
698         if (cred->realm_obtained == CRED_CALLBACK && 
699             !cred->callback_running) {
700                 cred->callback_running = true;
701                 cred->realm = cred->realm_cb(cred);
702                 cred->callback_running = false;
703                 if (cred->realm_obtained == CRED_CALLBACK) {
704                         cred->realm_obtained = CRED_CALLBACK_RESULT;
705                         cli_credentials_invalidate_ccache(cred, cred->realm_obtained);
706                 }
707         }
708
709         return cred->realm;
710 }
711
712 /**
713  * Set the realm for this credentials context, and force it to
714  * uppercase for the sanity of our local kerberos libraries
715  */
716 _PUBLIC_ bool cli_credentials_set_realm(struct cli_credentials *cred, 
717                                const char *val, 
718                                enum credentials_obtained obtained)
719 {
720         if (obtained >= cred->realm_obtained) {
721                 cred->realm = strupper_talloc(cred, val);
722                 cred->realm_obtained = obtained;
723                 cli_credentials_invalidate_ccache(cred, cred->realm_obtained);
724                 return true;
725         }
726
727         return false;
728 }
729
730 bool cli_credentials_set_realm_callback(struct cli_credentials *cred,
731                                         const char *(*realm_cb) (struct cli_credentials *))
732 {
733         if (cred->realm_obtained < CRED_CALLBACK) {
734                 cred->realm_cb = realm_cb;
735                 cred->realm_obtained = CRED_CALLBACK;
736                 return true;
737         }
738
739         return false;
740 }
741
742 /**
743  * Obtain the 'short' or 'NetBIOS' workstation name for this credentials context.
744  *
745  * @param cred credentials context
746  * @retval The workstation name set on this context. 
747  * @note Return value will never be NULL except by programmer error.
748  */
749 _PUBLIC_ const char *cli_credentials_get_workstation(struct cli_credentials *cred)
750 {
751         if (cred->workstation_obtained == CRED_CALLBACK && 
752             !cred->callback_running) {
753                 cred->callback_running = true;
754                 cred->workstation = cred->workstation_cb(cred);
755                 cred->callback_running = false;
756                 if (cred->workstation_obtained == CRED_CALLBACK) {
757                         cred->workstation_obtained = CRED_CALLBACK_RESULT;
758                 }
759         }
760
761         return cred->workstation;
762 }
763
764 _PUBLIC_ bool cli_credentials_set_workstation(struct cli_credentials *cred, 
765                                      const char *val, 
766                                      enum credentials_obtained obtained)
767 {
768         if (obtained >= cred->workstation_obtained) {
769                 cred->workstation = talloc_strdup(cred, val);
770                 cred->workstation_obtained = obtained;
771                 return true;
772         }
773
774         return false;
775 }
776
777 bool cli_credentials_set_workstation_callback(struct cli_credentials *cred,
778                                               const char *(*workstation_cb) (struct cli_credentials *))
779 {
780         if (cred->workstation_obtained < CRED_CALLBACK) {
781                 cred->workstation_cb = workstation_cb;
782                 cred->workstation_obtained = CRED_CALLBACK;
783                 return true;
784         }
785
786         return false;
787 }
788
789 /**
790  * Given a string, typically obtained from a -U argument, parse it into domain, username, realm and password fields
791  *
792  * The format accepted is [domain\\]user[%password] or user[@realm][%password]
793  *
794  * @param credentials Credentials structure on which to set the password
795  * @param data the string containing the username, password etc
796  * @param obtained This enum describes how 'specified' this password is
797  */
798
799 _PUBLIC_ void cli_credentials_parse_string(struct cli_credentials *credentials, const char *data, enum credentials_obtained obtained)
800 {
801         char *uname, *p;
802
803         if (strcmp("%",data) == 0) {
804                 cli_credentials_set_anonymous(credentials);
805                 return;
806         }
807
808         uname = talloc_strdup(credentials, data); 
809         if ((p = strchr_m(uname,'%'))) {
810                 const char *password;
811
812                 *p = '\0';
813                 password = p + 1;
814                 if (password[0] != '\0') {
815                         cli_credentials_set_password(credentials,
816                                                      password,
817                                                      obtained);
818                 }
819         }
820
821         if ((p = strchr_m(uname,'@'))) {
822                 const char *realm = p + 1;
823
824                 if (realm[0] == '\0') {
825                         *p = 0;
826
827                         /*
828                          * We also need to set username and domain
829                          * in order to undo the effect of
830                          * cli_credentials_guess().
831                          */
832                         cli_credentials_set_username(credentials,
833                                                      uname,
834                                                      obtained);
835                         cli_credentials_set_domain(credentials, "", obtained);
836                 } else {
837                         cli_credentials_set_principal(credentials,
838                                                       uname,
839                                                       obtained);
840                         *p = 0;
841
842                         cli_credentials_set_realm(credentials, realm, obtained);
843                 }
844                 return;
845         } else if ((p = strchr_m(uname,'\\'))
846                    || (p = strchr_m(uname, '/'))
847                    || (p = strchr_m(uname, credentials->winbind_separator)))
848         {
849                 const char *domain = NULL;
850
851                 domain = uname;
852                 *p = 0;
853                 uname = p+1;
854
855                 if (obtained == credentials->realm_obtained &&
856                     !strequal_m(credentials->domain, domain))
857                 {
858                         /*
859                          * We need to undo a former set with the same level
860                          * in order to get the expected result from
861                          * cli_credentials_get_principal().
862                          *
863                          * But we only need to do that if the domain
864                          * actually changes.
865                          */
866                         cli_credentials_set_realm(credentials, domain, obtained);
867                 }
868                 cli_credentials_set_domain(credentials, domain, obtained);
869         }
870         if (obtained == credentials->principal_obtained &&
871             !strequal_m(credentials->username, uname))
872         {
873                 /*
874                  * We need to undo a former set with the same level
875                  * in order to get the expected result from
876                  * cli_credentials_get_principal().
877                  *
878                  * But we only need to do that if the username
879                  * actually changes.
880                  */
881                 credentials->principal_obtained = CRED_UNINITIALISED;
882                 credentials->principal = NULL;
883         }
884         cli_credentials_set_username(credentials, uname, obtained);
885 }
886
887 /**
888  * Given a a credentials structure, print it as a string
889  *
890  * The format output is [domain\\]user[%password] or user[@realm][%password]
891  *
892  * @param credentials Credentials structure on which to set the password
893  * @param mem_ctx The memory context to place the result on
894  */
895
896 _PUBLIC_ char *cli_credentials_get_unparsed_name(struct cli_credentials *credentials, TALLOC_CTX *mem_ctx)
897 {
898         const char *bind_dn = cli_credentials_get_bind_dn(credentials);
899         const char *domain = NULL;
900         const char *username = NULL;
901         char *name = NULL;
902
903         if (bind_dn) {
904                 name = talloc_strdup(mem_ctx, bind_dn);
905         } else {
906                 cli_credentials_get_ntlm_username_domain(credentials, mem_ctx, &username, &domain);
907                 if (domain && domain[0]) {
908                         name = talloc_asprintf(mem_ctx, "%s\\%s", 
909                                                domain, username);
910                 } else {
911                         name = talloc_asprintf(mem_ctx, "%s", 
912                                                username);
913                 }
914         }
915         return name;
916 }
917
918 /**
919  * Specifies default values for domain, workstation and realm
920  * from the smb.conf configuration file
921  *
922  * @param cred Credentials structure to fill in
923  */
924 _PUBLIC_ void cli_credentials_set_conf(struct cli_credentials *cred, 
925                               struct loadparm_context *lp_ctx)
926 {
927         const char *sep = NULL;
928         const char *realm = lpcfg_realm(lp_ctx);
929
930         cli_credentials_set_username(cred, "", CRED_UNINITIALISED);
931         if (lpcfg_parm_is_cmdline(lp_ctx, "workgroup")) {
932                 cli_credentials_set_domain(cred, lpcfg_workgroup(lp_ctx), CRED_SPECIFIED);
933         } else {
934                 cli_credentials_set_domain(cred, lpcfg_workgroup(lp_ctx), CRED_UNINITIALISED);
935         }
936         if (lpcfg_parm_is_cmdline(lp_ctx, "netbios name")) {
937                 cli_credentials_set_workstation(cred, lpcfg_netbios_name(lp_ctx), CRED_SPECIFIED);
938         } else {
939                 cli_credentials_set_workstation(cred, lpcfg_netbios_name(lp_ctx), CRED_UNINITIALISED);
940         }
941         if (realm != NULL && strlen(realm) == 0) {
942                 realm = NULL;
943         }
944         if (lpcfg_parm_is_cmdline(lp_ctx, "realm")) {
945                 cli_credentials_set_realm(cred, realm, CRED_SPECIFIED);
946         } else {
947                 cli_credentials_set_realm(cred, realm, CRED_UNINITIALISED);
948         }
949
950         sep = lpcfg_winbind_separator(lp_ctx);
951         if (sep != NULL && sep[0] != '\0') {
952                 cred->winbind_separator = *lpcfg_winbind_separator(lp_ctx);
953         }
954 }
955
956 /**
957  * Guess defaults for credentials from environment variables, 
958  * and from the configuration file
959  * 
960  * @param cred Credentials structure to fill in
961  */
962 _PUBLIC_ void cli_credentials_guess(struct cli_credentials *cred,
963                            struct loadparm_context *lp_ctx)
964 {
965         char *p;
966         const char *error_string;
967
968         if (lp_ctx != NULL) {
969                 cli_credentials_set_conf(cred, lp_ctx);
970         }
971         
972         if (getenv("LOGNAME")) {
973                 cli_credentials_set_username(cred, getenv("LOGNAME"), CRED_GUESS_ENV);
974         }
975
976         if (getenv("USER")) {
977                 cli_credentials_parse_string(cred, getenv("USER"), CRED_GUESS_ENV);
978                 if ((p = strchr_m(getenv("USER"),'%'))) {
979                         memset(p,0,strlen(cred->password));
980                 }
981         }
982
983         if (getenv("PASSWD")) {
984                 cli_credentials_set_password(cred, getenv("PASSWD"), CRED_GUESS_ENV);
985         }
986
987         if (getenv("PASSWD_FD")) {
988                 cli_credentials_parse_password_fd(cred, atoi(getenv("PASSWD_FD")), 
989                                                   CRED_GUESS_FILE);
990         }
991         
992         p = getenv("PASSWD_FILE");
993         if (p && p[0]) {
994                 cli_credentials_parse_password_file(cred, p, CRED_GUESS_FILE);
995         }
996         
997         if (cli_credentials_get_kerberos_state(cred) != CRED_DONT_USE_KERBEROS) {
998                 cli_credentials_set_ccache(cred, lp_ctx, NULL, CRED_GUESS_FILE,
999                                            &error_string);
1000         }
1001 }
1002
1003 /**
1004  * Attach NETLOGON credentials for use with SCHANNEL
1005  */
1006
1007 _PUBLIC_ void cli_credentials_set_netlogon_creds(
1008         struct cli_credentials *cred,
1009         const struct netlogon_creds_CredentialState *netlogon_creds)
1010 {
1011         TALLOC_FREE(cred->netlogon_creds);
1012         if (netlogon_creds == NULL) {
1013                 return;
1014         }
1015         cred->netlogon_creds = netlogon_creds_copy(cred, netlogon_creds);
1016 }
1017
1018 /**
1019  * Return attached NETLOGON credentials 
1020  */
1021
1022 _PUBLIC_ struct netlogon_creds_CredentialState *cli_credentials_get_netlogon_creds(struct cli_credentials *cred)
1023 {
1024         return cred->netlogon_creds;
1025 }
1026
1027 /** 
1028  * Set NETLOGON secure channel type
1029  */
1030
1031 _PUBLIC_ void cli_credentials_set_secure_channel_type(struct cli_credentials *cred,
1032                                              enum netr_SchannelType secure_channel_type)
1033 {
1034         cred->secure_channel_type = secure_channel_type;
1035 }
1036
1037 /**
1038  * Return NETLOGON secure chanel type
1039  */
1040
1041 _PUBLIC_ time_t cli_credentials_get_password_last_changed_time(struct cli_credentials *cred)
1042 {
1043         return cred->password_last_changed_time;
1044 }
1045
1046 /** 
1047  * Set NETLOGON secure channel type
1048  */
1049
1050 _PUBLIC_ void cli_credentials_set_password_last_changed_time(struct cli_credentials *cred,
1051                                                              time_t last_changed_time)
1052 {
1053         cred->password_last_changed_time = last_changed_time;
1054 }
1055
1056 /**
1057  * Return NETLOGON secure chanel type
1058  */
1059
1060 _PUBLIC_ enum netr_SchannelType cli_credentials_get_secure_channel_type(struct cli_credentials *cred)
1061 {
1062         return cred->secure_channel_type;
1063 }
1064
1065 /**
1066  * Fill in a credentials structure as the anonymous user
1067  */
1068 _PUBLIC_ void cli_credentials_set_anonymous(struct cli_credentials *cred) 
1069 {
1070         cli_credentials_set_username(cred, "", CRED_SPECIFIED);
1071         cli_credentials_set_domain(cred, "", CRED_SPECIFIED);
1072         cli_credentials_set_password(cred, NULL, CRED_SPECIFIED);
1073         cli_credentials_set_principal(cred, NULL, CRED_SPECIFIED);
1074         cli_credentials_set_realm(cred, NULL, CRED_SPECIFIED);
1075         cli_credentials_set_workstation(cred, "", CRED_UNINITIALISED);
1076         cli_credentials_set_kerberos_state(cred, CRED_DONT_USE_KERBEROS);
1077 }
1078
1079 /**
1080  * Describe a credentials context as anonymous or authenticated
1081  * @retval true if anonymous, false if a username is specified
1082  */
1083
1084 _PUBLIC_ bool cli_credentials_is_anonymous(struct cli_credentials *cred)
1085 {
1086         const char *username;
1087         
1088         /* if bind dn is set it's not anonymous */
1089         if (cred->bind_dn) {
1090                 return false;
1091         }
1092
1093         if (cred->machine_account_pending) {
1094                 cli_credentials_set_machine_account(cred,
1095                                                     cred->machine_account_pending_lp_ctx);
1096         }
1097
1098         /* if principal is set, it's not anonymous */
1099         if ((cred->principal != NULL) && cred->principal_obtained >= cred->username_obtained) {
1100                 return false;
1101         }
1102
1103         username = cli_credentials_get_username(cred);
1104         
1105         /* Yes, it is deliberate that we die if we have a NULL pointer
1106          * here - anonymous is "", not NULL, which is 'never specified,
1107          * never guessed', ie programmer bug */
1108         if (!username[0]) {
1109                 return true;
1110         }
1111
1112         return false;
1113 }
1114
1115 /**
1116  * Mark the current password for a credentials struct as wrong. This will 
1117  * cause the password to be prompted again (if a callback is set).
1118  *
1119  * This will decrement the number of times the password can be tried.
1120  *
1121  * @retval whether the credentials struct is finished
1122  */
1123 _PUBLIC_ bool cli_credentials_wrong_password(struct cli_credentials *cred)
1124 {
1125         if (cred->password_obtained != CRED_CALLBACK_RESULT) {
1126                 return false;
1127         }
1128
1129         if (cred->password_tries == 0) {
1130                 return false;
1131         }
1132
1133         cred->password_tries--;
1134
1135         if (cred->password_tries == 0) {
1136                 return false;
1137         }
1138
1139         cred->password_obtained = CRED_CALLBACK;
1140         return true;
1141 }
1142
1143 _PUBLIC_ void cli_credentials_get_ntlm_username_domain(struct cli_credentials *cred, TALLOC_CTX *mem_ctx, 
1144                                               const char **username, 
1145                                               const char **domain) 
1146 {
1147         if (cred->principal_obtained > cred->username_obtained) {
1148                 *domain = talloc_strdup(mem_ctx, "");
1149                 *username = cli_credentials_get_principal(cred, mem_ctx);
1150         } else {
1151                 *domain = cli_credentials_get_domain(cred);
1152                 *username = cli_credentials_get_username(cred);
1153         }
1154 }
1155
1156 /**
1157  * Read a named file, and parse it for username, domain, realm and password
1158  *
1159  * @param credentials Credentials structure on which to set the password
1160  * @param file a named file to read the details from 
1161  * @param obtained This enum describes how 'specified' this password is
1162  */
1163
1164 _PUBLIC_ bool cli_credentials_parse_file(struct cli_credentials *cred, const char *file, enum credentials_obtained obtained) 
1165 {
1166         uint16_t len = 0;
1167         char *ptr, *val, *param;
1168         char **lines;
1169         int i, numlines;
1170         const char *realm = NULL;
1171         const char *domain = NULL;
1172         const char *password = NULL;
1173         const char *username = NULL;
1174
1175         lines = file_lines_load(file, &numlines, 0, NULL);
1176
1177         if (lines == NULL)
1178         {
1179                 /* fail if we can't open the credentials file */
1180                 d_printf("ERROR: Unable to open credentials file!\n");
1181                 return false;
1182         }
1183
1184         for (i = 0; i < numlines; i++) {
1185                 len = strlen(lines[i]);
1186
1187                 if (len == 0)
1188                         continue;
1189
1190                 /* break up the line into parameter & value.
1191                  * will need to eat a little whitespace possibly */
1192                 param = lines[i];
1193                 if (!(ptr = strchr_m (lines[i], '=')))
1194                         continue;
1195
1196                 val = ptr+1;
1197                 *ptr = '\0';
1198
1199                 /* eat leading white space */
1200                 while ((*val!='\0') && ((*val==' ') || (*val=='\t')))
1201                         val++;
1202
1203                 if (strwicmp("password", param) == 0) {
1204                         password = val;
1205                 } else if (strwicmp("username", param) == 0) {
1206                         username = val;
1207                 } else if (strwicmp("domain", param) == 0) {
1208                         domain = val;
1209                 } else if (strwicmp("realm", param) == 0) {
1210                         realm = val;
1211                 }
1212
1213                 /*
1214                  * We need to readd '=' in order to let
1215                  * the strlen() work in the last loop
1216                  * that clears the memory.
1217                  */
1218                 *ptr = '=';
1219         }
1220
1221         if (realm != NULL && strlen(realm) != 0) {
1222                 /*
1223                  * only overwrite with a valid string
1224                  */
1225                 cli_credentials_set_realm(cred, realm, obtained);
1226         }
1227
1228         if (domain != NULL && strlen(domain) != 0) {
1229                 /*
1230                  * only overwrite with a valid string
1231                  */
1232                 cli_credentials_set_domain(cred, domain, obtained);
1233         }
1234
1235         if (password != NULL) {
1236                 /*
1237                  * Here we allow "".
1238                  */
1239                 cli_credentials_set_password(cred, password, obtained);
1240         }
1241
1242         if (username != NULL) {
1243                 /*
1244                  * The last "username" line takes preference
1245                  * if the string also contains domain, realm or
1246                  * password.
1247                  */
1248                 cli_credentials_parse_string(cred, username, obtained);
1249         }
1250
1251         for (i = 0; i < numlines; i++) {
1252                 len = strlen(lines[i]);
1253                 memset(lines[i], 0, len);
1254         }
1255         talloc_free(lines);
1256
1257         return true;
1258 }
1259
1260 /**
1261  * Read a named file, and parse it for a password
1262  *
1263  * @param credentials Credentials structure on which to set the password
1264  * @param file a named file to read the password from 
1265  * @param obtained This enum describes how 'specified' this password is
1266  */
1267
1268 _PUBLIC_ bool cli_credentials_parse_password_file(struct cli_credentials *credentials, const char *file, enum credentials_obtained obtained)
1269 {
1270         int fd = open(file, O_RDONLY, 0);
1271         bool ret;
1272
1273         if (fd < 0) {
1274                 fprintf(stderr, "Error opening password file %s: %s\n",
1275                                 file, strerror(errno));
1276                 return false;
1277         }
1278
1279         ret = cli_credentials_parse_password_fd(credentials, fd, obtained);
1280
1281         close(fd);
1282         
1283         return ret;
1284 }
1285
1286
1287 /**
1288  * Read a file descriptor, and parse it for a password (eg from a file or stdin)
1289  *
1290  * @param credentials Credentials structure on which to set the password
1291  * @param fd open file descriptor to read the password from 
1292  * @param obtained This enum describes how 'specified' this password is
1293  */
1294
1295 _PUBLIC_ bool cli_credentials_parse_password_fd(struct cli_credentials *credentials, 
1296                                        int fd, enum credentials_obtained obtained)
1297 {
1298         char *p;
1299         char pass[128];
1300
1301         for(p = pass, *p = '\0'; /* ensure that pass is null-terminated */
1302                 p && p - pass < sizeof(pass);) {
1303                 switch (read(fd, p, 1)) {
1304                 case 1:
1305                         if (*p != '\n' && *p != '\0') {
1306                                 *++p = '\0'; /* advance p, and null-terminate pass */
1307                                 break;
1308                         }
1309
1310                         FALL_THROUGH;
1311                 case 0:
1312                         if (p - pass) {
1313                                 *p = '\0'; /* null-terminate it, just in case... */
1314                                 p = NULL; /* then force the loop condition to become false */
1315                                 break;
1316                         }
1317
1318                         fprintf(stderr,
1319                                 "Error reading password from file descriptor "
1320                                 "%d: empty password\n",
1321                                 fd);
1322                         return false;
1323
1324                 default:
1325                         fprintf(stderr, "Error reading password from file descriptor %d: %s\n",
1326                                         fd, strerror(errno));
1327                         return false;
1328                 }
1329         }
1330
1331         cli_credentials_set_password(credentials, pass, obtained);
1332         return true;
1333 }
1334
1335
1336 /**
1337  * Encrypt a data blob using the session key and the negotiated encryption
1338  * algorithm
1339  *
1340  * @param state Credential state, contains the session key and algorithm
1341  * @param data Data blob containing the data to be encrypted.
1342  *
1343  */
1344 _PUBLIC_ NTSTATUS netlogon_creds_session_encrypt(
1345         struct netlogon_creds_CredentialState *state,
1346         DATA_BLOB data)
1347 {
1348         if (data.data == NULL || data.length == 0) {
1349                 DBG_ERR("Nothing to encrypt "
1350                         "data.data == NULL or data.length == 0");
1351                 return NT_STATUS_INVALID_PARAMETER;
1352         }
1353         /*
1354          * Don't crypt an all-zero password it will give away the
1355          * NETLOGON pipe session key .
1356          */
1357         if (all_zero(data.data, data.length)) {
1358                 DBG_ERR("Supplied data all zeros, could leak session key");
1359                 return NT_STATUS_INVALID_PARAMETER;
1360         }
1361         if (state->negotiate_flags & NETLOGON_NEG_SUPPORTS_AES) {
1362                 netlogon_creds_aes_encrypt(state,
1363                                            data.data,
1364                                            data.length);
1365         } else if (state->negotiate_flags & NETLOGON_NEG_ARCFOUR) {
1366                 netlogon_creds_arcfour_crypt(state,
1367                                              data.data,
1368                                              data.length);
1369         } else {
1370                 DBG_ERR("Unsupported encryption option negotiated");
1371                 return NT_STATUS_NOT_SUPPORTED;
1372         }
1373         return NT_STATUS_OK;
1374 }
1375