r6079: Add inline documentation on the credentials context API.
[jra/samba/.git] / source4 / lib / credentials.c
1 /* 
2    Unix SMB/CIFS implementation.
3
4    Copyright (C) Jelmer Vernooij 2005
5    Copyright (C) Tim Potter 2001
6    Copyright (C) Andrew Bartlett <abartlet@samba.org> 2005
7    
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 2 of the License, or
11    (at your option) any later version.
12    
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17    
18    You should have received a copy of the GNU General Public License
19    along with this program; if not, write to the Free Software
20    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
21 */
22
23 #include "includes.h"
24 #include "system/filesys.h"
25 #include "lib/cmdline/popt_common.h"
26 #include "include/secrets.h"
27 #include "lib/ldb/include/ldb.h"
28
29 /**
30  * Create a new credentials structure
31  * @param mem_ctx TALLOC_CTX parent for credentials structure 
32  */
33 struct cli_credentials *cli_credentials_init(TALLOC_CTX *mem_ctx) 
34 {
35         struct cli_credentials *cred = talloc_zero(mem_ctx, struct cli_credentials);
36         if (!cred) {
37                 return cred;
38         }
39
40         return cred;
41 }
42
43 /**
44  * Obtain the username for this credentials context.
45  * @param cred credentials context
46  * @retval The username set on this context.
47  * @note Return value will never be NULL except by programmer error.
48  */
49 const char *cli_credentials_get_username(struct cli_credentials *cred)
50 {
51         if (cred->machine_account_pending) {
52                 cli_credentials_set_machine_account(cred);
53         }
54
55         if (cred->username_obtained == CRED_CALLBACK) {
56                 cred->username = cred->username_cb(cred);
57                 cred->username_obtained = CRED_SPECIFIED;
58         }
59
60         return cred->username;
61 }
62
63 BOOL cli_credentials_set_username(struct cli_credentials *cred, const char *val, enum credentials_obtained obtained)
64 {
65         if (obtained >= cred->username_obtained) {
66                 cred->username = talloc_strdup(cred, val);
67                 cred->username_obtained = obtained;
68                 return True;
69         }
70
71         return False;
72 }
73
74 /**
75  * Obtain the password for this credentials context.
76  * @param cred credentials context
77  * @retval If set, the cleartext password, otherwise NULL
78  */
79 const char *cli_credentials_get_password(struct cli_credentials *cred)
80 {
81         if (cred->machine_account_pending) {
82                 cli_credentials_set_machine_account(cred);
83         }
84
85         if (cred->password_obtained == CRED_CALLBACK) {
86                 cred->password = cred->password_cb(cred);
87                 cred->password_obtained = CRED_SPECIFIED;
88         }
89
90         return cred->password;
91 }
92
93 BOOL cli_credentials_set_password(struct cli_credentials *cred, const char *val, enum credentials_obtained obtained)
94 {
95         if (obtained >= cred->password_obtained) {
96                 cred->password = talloc_strdup(cred, val);
97                 cred->password_obtained = obtained;
98                 return True;
99         }
100
101         return False;
102 }
103
104 /**
105  * Obtain the 'short' or 'NetBIOS' domain for this credentials context.
106  * @param cred credentials context
107  * @retval The domain set on this context. 
108  * @note Return value will never be NULL except by programmer error.
109  */
110 const char *cli_credentials_get_domain(struct cli_credentials *cred)
111 {
112         if (cred->machine_account_pending) {
113                 cli_credentials_set_machine_account(cred);
114         }
115
116         if (cred->domain_obtained == CRED_CALLBACK) {
117                 cred->domain = cred->domain_cb(cred);
118                 cred->domain_obtained = CRED_SPECIFIED;
119         }
120
121         return cred->domain;
122 }
123
124
125 BOOL cli_credentials_set_domain(struct cli_credentials *cred, const char *val, enum credentials_obtained obtained)
126 {
127         if (obtained >= cred->domain_obtained) {
128                 cred->domain = talloc_strdup(cred, val);
129                 cred->domain_obtained = obtained;
130                 return True;
131         }
132
133         return False;
134 }
135
136 /**
137  * Obtain the Kerberos realm for this credentials context.
138  * @param cred credentials context
139  * @retval The realm set on this context. 
140  * @note Return value will never be NULL except by programmer error.
141  */
142 const char *cli_credentials_get_realm(struct cli_credentials *cred)
143 {       
144         if (cred->machine_account_pending) {
145                 cli_credentials_set_machine_account(cred);
146         }
147
148         if (cred->realm_obtained == CRED_CALLBACK) {
149                 cred->realm = cred->realm_cb(cred);
150                 cred->realm_obtained = CRED_SPECIFIED;
151         }
152
153         return cred->realm;
154 }
155
156 /**
157  * Obtain the user's Kerberos principal for this credentials context.
158  * @param cred credentials context
159  * @param mem_ctx A talloc context to return the prinipal name on.
160  * @retval The user's Kerberos principal
161  * @note Return value may be NULL due to out-of memeory or invalid mem_ctx
162  */
163 char *cli_credentials_get_principal(struct cli_credentials *cred,
164                                     TALLOC_CTX *mem_ctx)
165 {
166         return talloc_asprintf(mem_ctx, "%s@%s", 
167                                cli_credentials_get_username(cred),
168                                cli_credentials_get_realm(cred));
169 }
170
171 BOOL cli_credentials_set_realm(struct cli_credentials *cred, const char *val, enum credentials_obtained obtained)
172 {
173         if (obtained >= cred->realm_obtained) {
174                 cred->realm = talloc_strdup(cred, val);
175                 cred->realm_obtained = obtained;
176                 return True;
177         }
178
179         return False;
180 }
181
182 /**
183  * Obtain the 'short' or 'NetBIOS' workstation name for this credentials context.
184  *
185  * @param cred credentials context
186  * @retval The workstation name set on this context. 
187  * @note Return value will never be NULL except by programmer error.
188  */
189 const char *cli_credentials_get_workstation(struct cli_credentials *cred)
190 {
191         if (cred->workstation_obtained == CRED_CALLBACK) {
192                 cred->workstation = cred->workstation_cb(cred);
193                 cred->workstation_obtained = CRED_SPECIFIED;
194         }
195
196         return cred->workstation;
197 }
198
199 BOOL cli_credentials_set_workstation(struct cli_credentials *cred, const char *val, enum credentials_obtained obtained)
200 {
201         if (obtained >= cred->workstation_obtained) {
202                 cred->workstation = talloc_strdup(cred, val);
203                 cred->workstation_obtained = obtained;
204                 return True;
205         }
206
207         return False;
208 }
209
210 /**
211  * Read a file descriptor, and parse it for a password (eg from a file or stdin)
212  *
213  * @param credentials Credentials structure on which to set the password
214  * @param fd open file descriptor to read the password from 
215  * @param obtained This enum describes how 'specified' this password is
216  */
217
218 BOOL cli_credentials_parse_password_fd(struct cli_credentials *credentials, int fd, enum credentials_obtained obtained)
219 {
220         char *p;
221         char pass[128];
222
223         for(p = pass, *p = '\0'; /* ensure that pass is null-terminated */
224                 p && p - pass < sizeof(pass);) {
225                 switch (read(fd, p, 1)) {
226                 case 1:
227                         if (*p != '\n' && *p != '\0') {
228                                 *++p = '\0'; /* advance p, and null-terminate pass */
229                                 break;
230                         }
231                 case 0:
232                         if (p - pass) {
233                                 *p = '\0'; /* null-terminate it, just in case... */
234                                 p = NULL; /* then force the loop condition to become false */
235                                 break;
236                         } else {
237                                 fprintf(stderr, "Error reading password from file descriptor %d: %s\n", fd, "empty password\n");
238                                 return False;
239                         }
240
241                 default:
242                         fprintf(stderr, "Error reading password from file descriptor %d: %s\n",
243                                         fd, strerror(errno));
244                         return False;
245                 }
246         }
247
248         cli_credentials_set_password(credentials, pass, obtained);
249         return True;
250 }
251
252 /**
253  * Read a named file, and parse it for a password
254  *
255  * @param credentials Credentials structure on which to set the password
256  * @param file a named file to read the password from 
257  * @param obtained This enum describes how 'specified' this password is
258  */
259
260 BOOL cli_credentials_parse_password_file(struct cli_credentials *credentials, const char *file, enum credentials_obtained obtained)
261 {
262         int fd = open(file, O_RDONLY, 0);
263         BOOL ret;
264
265         if (fd < 0) {
266                 fprintf(stderr, "Error opening PASSWD_FILE %s: %s\n",
267                                 file, strerror(errno));
268                 return False;
269         }
270
271         ret = cli_credentials_parse_password_fd(credentials, fd, obtained);
272
273         close(fd);
274         
275         return ret;
276 }
277
278 /**
279  * Read a named file, and parse it for username, domain, realm and password
280  *
281  * @param credentials Credentials structure on which to set the password
282  * @param file a named file to read the details from 
283  * @param obtained This enum describes how 'specified' this password is
284  */
285
286 BOOL cli_credentials_parse_file(struct cli_credentials *cred, const char *file, enum credentials_obtained obtained) 
287 {
288         XFILE *auth;
289         char buf[128];
290         uint16_t len = 0;
291         char *ptr, *val, *param;
292
293         if ((auth=x_fopen(file, O_RDONLY, 0)) == NULL)
294         {
295                 /* fail if we can't open the credentials file */
296                 d_printf("ERROR: Unable to open credentials file!\n");
297                 return False;
298         }
299
300         while (!x_feof(auth))
301         {
302                 /* get a line from the file */
303                 if (!x_fgets(buf, sizeof(buf), auth))
304                         continue;
305                 len = strlen(buf);
306
307                 if ((len) && (buf[len-1]=='\n'))
308                 {
309                         buf[len-1] = '\0';
310                         len--;
311                 }
312                 if (len == 0)
313                         continue;
314
315                 /* break up the line into parameter & value.
316                  * will need to eat a little whitespace possibly */
317                 param = buf;
318                 if (!(ptr = strchr_m (buf, '=')))
319                         continue;
320
321                 val = ptr+1;
322                 *ptr = '\0';
323
324                 /* eat leading white space */
325                 while ((*val!='\0') && ((*val==' ') || (*val=='\t')))
326                         val++;
327
328                 if (strwicmp("password", param) == 0) {
329                         cli_credentials_set_password(cred, val, obtained);
330                 } else if (strwicmp("username", param) == 0) {
331                         cli_credentials_set_username(cred, val, obtained);
332                 } else if (strwicmp("domain", param) == 0) {
333                         cli_credentials_set_domain(cred, val, obtained);
334                 } else if (strwicmp("realm", param) == 0) {
335                         cli_credentials_set_realm(cred, val, obtained);
336                 }
337                 memset(buf, 0, sizeof(buf));
338         }
339
340         x_fclose(auth);
341         return True;
342 }
343
344
345 /**
346  * Given a string, typically obtained from a -U argument, parse it into domain, username, realm and password fields
347  *
348  * The format accepted is [domain\\]user[%password] or user[@realm][%password]
349  *
350  * @param credentials Credentials structure on which to set the password
351  * @param data the string containing the username, password etc
352  * @param obtained This enum describes how 'specified' this password is
353  */
354
355 void cli_credentials_parse_string(struct cli_credentials *credentials, const char *data, enum credentials_obtained obtained)
356 {
357         char *uname, *p;
358
359         uname = talloc_strdup(credentials, data); 
360         if ((p = strchr_m(uname,'%'))) {
361                 *p = 0;
362                 cli_credentials_set_password(credentials, p+1, obtained);
363         }
364
365         if ((p = strchr_m(uname,'@'))) {
366                 *p = 0;
367                 cli_credentials_set_realm(credentials, p+1, obtained);
368         } else if ((p = strchr_m(uname,'\\')) || (p = strchr_m(uname, '/'))) {
369                 *p = 0;
370                 cli_credentials_set_domain(credentials, uname, obtained);
371                 uname = p+1;
372         }
373         cli_credentials_set_username(credentials, uname, obtained);
374 }
375
376 /**
377  * Specifies default values for domain, workstation and realm
378  * from the smb.conf configuration file
379  *
380  * @param cred Credentials structure to fill in
381  */
382 void cli_credentials_set_conf(struct cli_credentials *cred)
383 {
384         cli_credentials_set_domain(cred, lp_workgroup(), CRED_GUESSED);
385         cli_credentials_set_workstation(cred, lp_netbios_name(), CRED_GUESSED);
386         cli_credentials_set_realm(cred, lp_realm(), CRED_GUESSED);
387 }
388
389 /**
390  * Guess defaults for credentials from environment variables, 
391  * and from the configuration file
392  * 
393  * @param cred Credentials structure to fill in
394  */
395 void cli_credentials_guess(struct cli_credentials *cred)
396 {
397         char *p;
398
399         cli_credentials_set_username(cred, "", CRED_GUESSED);
400         cli_credentials_set_conf(cred);
401         
402         if (getenv("LOGNAME")) {
403                 cli_credentials_set_username(cred, getenv("LOGNAME"), CRED_GUESSED);
404         }
405
406         if (getenv("USER")) {
407                 cli_credentials_parse_string(cred, getenv("USER"), CRED_GUESSED);
408                 if ((p = strchr_m(getenv("USER"),'%'))) {
409                         memset(p,0,strlen(cred->password));
410                 }
411         }
412
413         if (getenv("DOMAIN")) {
414                 cli_credentials_set_domain(cred, getenv("DOMAIN"), CRED_GUESSED);
415         }
416
417         if (getenv("PASSWD")) {
418                 cli_credentials_set_password(cred, getenv("PASSWD"), CRED_GUESSED);
419         }
420
421         if (getenv("PASSWD_FD")) {
422                 cli_credentials_parse_password_fd(cred, atoi(getenv("PASSWD_FD")), CRED_GUESSED);
423         }
424         
425         if (getenv("PASSWD_FILE")) {
426                 cli_credentials_parse_password_file(cred, getenv("PASSWD_FILE"), CRED_GUESSED);
427         }
428 }
429
430 /**
431  * Fill in credentials for the machine trust account, from the secrets database.
432  * 
433  * @param cred Credentials structure to fill in
434  * @retval NTSTATUS error detailing any failure
435  */
436 NTSTATUS cli_credentials_set_machine_account(struct cli_credentials *cred)
437 {
438         TALLOC_CTX *mem_ctx;
439         
440         struct ldb_context *ldb;
441         int ldb_ret;
442         struct ldb_message **msgs;
443         const char *base_dn = SECRETS_PRIMARY_DOMAIN_DN;
444         const char *attrs[] = {
445                 "secret",
446                 "samAccountName",
447                 "flatname",
448                 "realm",
449                 NULL
450         };
451         
452         const char *machine_account;
453         const char *password;
454         const char *domain;
455         const char *realm;
456         
457         /* ok, we are going to get it now, don't recurse back here */
458         cred->machine_account_pending = False;
459
460         mem_ctx = talloc_named(cred, 0, "cli_credentials fetch machine password");
461         /* Local secrets are stored in secrets.ldb */
462         ldb = secrets_db_connect(mem_ctx);
463         if (!ldb) {
464                 DEBUG(1, ("Could not open secrets.ldb\n"));
465                 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
466         }
467
468         /* search for the secret record */
469         ldb_ret = gendb_search(ldb,
470                                mem_ctx, base_dn, &msgs, attrs,
471                                SECRETS_PRIMARY_DOMAIN_FILTER, 
472                                cli_credentials_get_domain(cred));
473         if (ldb_ret == 0) {
474                 DEBUG(1, ("Could not find join record to domain: %s\n",
475                           cli_credentials_get_domain(cred)));
476                 talloc_free(mem_ctx);
477                 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
478         } else if (ldb_ret != 1) {
479                 DEBUG(1, ("Found more than one (%d) join records to domain: %s\n",
480                           ldb_ret, cli_credentials_get_domain(cred)));
481                 talloc_free(mem_ctx);
482                 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
483         }
484         
485         password = ldb_msg_find_string(msgs[0], "secret", NULL);
486         if (!password) {
487                 DEBUG(1, ("Could not find 'secret' in join record to domain: %s\n",
488                           cli_credentials_get_domain(cred)));
489                 talloc_free(mem_ctx);
490                 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
491         }
492         
493         machine_account = ldb_msg_find_string(msgs[0], "samAccountName", NULL);
494         if (!machine_account) {
495                 DEBUG(1, ("Could not find 'samAccountName' in join record to domain: %s\n",
496                           cli_credentials_get_domain(cred)));
497                 talloc_free(mem_ctx);
498                 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
499         }
500         
501         domain = ldb_msg_find_string(msgs[0], "flatname", NULL);
502         if (domain) {
503                 cli_credentials_set_domain(cred, domain, CRED_SPECIFIED);
504         }
505
506         realm = ldb_msg_find_string(msgs[0], "realm", NULL);
507         if (realm) {
508                 cli_credentials_set_realm(cred, realm, CRED_SPECIFIED);
509         }
510         
511         cli_credentials_set_username(cred, machine_account, CRED_SPECIFIED);
512         cli_credentials_set_password(cred, password, CRED_SPECIFIED);
513         talloc_free(mem_ctx);
514         
515         return NT_STATUS_OK;
516 }
517
518 /**
519  * Ask that when required, the credentials system will be filled with
520  * machine trust account, from the secrets database.
521  * 
522  * @param cred Credentials structure to fill in
523  * @note This function is used to call the above function after, rather 
524  *       than during, popt processing.
525  *
526  */
527 void cli_credentials_set_machine_account_pending(struct cli_credentials *cred)
528 {
529         cred->machine_account_pending = True;
530 }
531
532 /**
533  * Attach NETLOGON credentials for use with SCHANNEL
534  */
535
536 void cli_credentials_set_netlogon_creds(struct cli_credentials *cred, 
537                                         struct creds_CredentialState *netlogon_creds)
538 {
539         cred->netlogon_creds = talloc_reference(cred, netlogon_creds);
540 }
541
542 /**
543  * Return attached NETLOGON credentials 
544  */
545
546 struct creds_CredentialState *cli_credentials_get_netlogon_creds(struct cli_credentials *cred)
547 {
548         return cred->netlogon_creds;
549 }
550
551 /**
552  * Fill in a credentials structure as the anonymous user
553  */
554 void cli_credentials_set_anonymous(struct cli_credentials *cred) 
555 {
556         cli_credentials_set_username(cred, "", CRED_SPECIFIED);
557         cli_credentials_set_domain(cred, "", CRED_SPECIFIED);
558         cli_credentials_set_password(cred, NULL, CRED_SPECIFIED);
559 }
560
561 /**
562  * Describe a credentials context as anonymous or authenticated
563  * @retval True if anonymous, False if a username is specified
564  */
565
566 BOOL cli_credentials_is_anonymous(struct cli_credentials *cred)
567 {
568         const char *username = cli_credentials_get_username(cred);
569
570         /* Yes, it is deliberate that we die if we have a NULL pointer
571          * here - anonymous is "", not NULL, which is 'never specified,
572          * never guessed', ie programmer bug */
573         if (!username[0]) 
574                 return True;
575
576         return False;
577 }