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