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