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