r19832: better prototypes for the linearization functions:
[samba.git] / source4 / auth / credentials / credentials_files.c
1 /* 
2    Unix SMB/CIFS implementation.
3
4    User credentials handling (as regards on-disk files)
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 2 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, write to the Free Software
22    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
23 */
24
25 #include "includes.h"
26 #include "lib/ldb/include/ldb.h"
27 #include "librpc/gen_ndr/samr.h" /* for struct samrPassword */
28 #include "param/secrets.h"
29 #include "system/filesys.h"
30 #include "db_wrap.h"
31 #include "auth/credentials/credentials.h"
32 #include "auth/credentials/credentials_krb5.h"
33
34 /**
35  * Read a file descriptor, and parse it for a password (eg from a file or stdin)
36  *
37  * @param credentials Credentials structure on which to set the password
38  * @param fd open file descriptor to read the password from 
39  * @param obtained This enum describes how 'specified' this password is
40  */
41
42 BOOL cli_credentials_parse_password_fd(struct cli_credentials *credentials, 
43                                        int fd, enum credentials_obtained obtained)
44 {
45         char *p;
46         char pass[128];
47
48         for(p = pass, *p = '\0'; /* ensure that pass is null-terminated */
49                 p && p - pass < sizeof(pass);) {
50                 switch (read(fd, p, 1)) {
51                 case 1:
52                         if (*p != '\n' && *p != '\0') {
53                                 *++p = '\0'; /* advance p, and null-terminate pass */
54                                 break;
55                         }
56                         /* fall through */
57                 case 0:
58                         if (p - pass) {
59                                 *p = '\0'; /* null-terminate it, just in case... */
60                                 p = NULL; /* then force the loop condition to become false */
61                                 break;
62                         } else {
63                                 fprintf(stderr, "Error reading password from file descriptor %d: %s\n", fd, "empty password\n");
64                                 return False;
65                         }
66
67                 default:
68                         fprintf(stderr, "Error reading password from file descriptor %d: %s\n",
69                                         fd, strerror(errno));
70                         return False;
71                 }
72         }
73
74         cli_credentials_set_password(credentials, pass, obtained);
75         return True;
76 }
77
78 /**
79  * Read a named file, and parse it for a password
80  *
81  * @param credentials Credentials structure on which to set the password
82  * @param file a named file to read the password from 
83  * @param obtained This enum describes how 'specified' this password is
84  */
85
86 BOOL cli_credentials_parse_password_file(struct cli_credentials *credentials, const char *file, enum credentials_obtained obtained)
87 {
88         int fd = open(file, O_RDONLY, 0);
89         BOOL ret;
90
91         if (fd < 0) {
92                 fprintf(stderr, "Error opening PASSWD_FILE %s: %s\n",
93                                 file, strerror(errno));
94                 return False;
95         }
96
97         ret = cli_credentials_parse_password_fd(credentials, fd, obtained);
98
99         close(fd);
100         
101         return ret;
102 }
103
104 /**
105  * Read a named file, and parse it for username, domain, realm and password
106  *
107  * @param credentials Credentials structure on which to set the password
108  * @param file a named file to read the details from 
109  * @param obtained This enum describes how 'specified' this password is
110  */
111
112 BOOL cli_credentials_parse_file(struct cli_credentials *cred, const char *file, enum credentials_obtained obtained) 
113 {
114         uint16_t len = 0;
115         char *ptr, *val, *param;
116         char **lines;
117         int i, numlines;
118
119         lines = file_lines_load(file, &numlines, NULL);
120
121         if (lines == NULL)
122         {
123                 /* fail if we can't open the credentials file */
124                 d_printf("ERROR: Unable to open credentials file!\n");
125                 return False;
126         }
127
128         for (i = 0; i < numlines; i++) {
129                 len = strlen(lines[i]);
130
131                 if (len == 0)
132                         continue;
133
134                 /* break up the line into parameter & value.
135                  * will need to eat a little whitespace possibly */
136                 param = lines[i];
137                 if (!(ptr = strchr_m (lines[i], '=')))
138                         continue;
139
140                 val = ptr+1;
141                 *ptr = '\0';
142
143                 /* eat leading white space */
144                 while ((*val!='\0') && ((*val==' ') || (*val=='\t')))
145                         val++;
146
147                 if (strwicmp("password", param) == 0) {
148                         cli_credentials_set_password(cred, val, obtained);
149                 } else if (strwicmp("username", param) == 0) {
150                         cli_credentials_set_username(cred, val, obtained);
151                 } else if (strwicmp("domain", param) == 0) {
152                         cli_credentials_set_domain(cred, val, obtained);
153                 } else if (strwicmp("realm", param) == 0) {
154                         cli_credentials_set_realm(cred, val, obtained);
155                 }
156                 memset(lines[i], 0, len);
157         }
158
159         talloc_free(lines);
160
161         return True;
162 }
163
164
165 /**
166  * Fill in credentials for the machine trust account, from the secrets database.
167  * 
168  * @param cred Credentials structure to fill in
169  * @retval NTSTATUS error detailing any failure
170  */
171 NTSTATUS cli_credentials_set_secrets(struct cli_credentials *cred, 
172                                      const char *base,
173                                      const char *filter)
174 {
175         TALLOC_CTX *mem_ctx;
176         
177         struct ldb_context *ldb;
178         int ldb_ret;
179         struct ldb_message **msgs;
180         const char *attrs[] = {
181                 "secret",
182                 "priorSecret",
183                 "samAccountName",
184                 "flatname",
185                 "realm",
186                 "secureChannelType",
187                 "ntPwdHash",
188                 "msDS-KeyVersionNumber",
189                 "saltPrincipal",
190                 "privateKeytab",
191                 "krb5Keytab",
192                 NULL
193         };
194         
195         const char *machine_account;
196         const char *password;
197         const char *old_password;
198         const char *domain;
199         const char *realm;
200         enum netr_SchannelType sct;
201         const char *salt_principal;
202         const char *keytab;
203         
204         /* ok, we are going to get it now, don't recurse back here */
205         cred->machine_account_pending = False;
206
207         /* some other parts of the system will key off this */
208         cred->machine_account = True;
209
210         mem_ctx = talloc_named(cred, 0, "cli_credentials fetch machine password");
211
212         /* Local secrets are stored in secrets.ldb */
213         ldb = secrets_db_connect(mem_ctx);
214         if (!ldb) {
215                 /* set anonymous as the fallback, if the machine account won't work */
216                 cli_credentials_set_anonymous(cred);
217                 DEBUG(1, ("Could not open secrets.ldb\n"));
218                 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
219         }
220
221         /* search for the secret record */
222         ldb_ret = gendb_search(ldb,
223                                mem_ctx, ldb_dn_new(mem_ctx, ldb, base), 
224                                &msgs, attrs,
225                                "%s", filter);
226         if (ldb_ret == 0) {
227                 DEBUG(1, ("Could not find entry to match filter: %s\n",
228                           filter));
229                 /* set anonymous as the fallback, if the machine account won't work */
230                 cli_credentials_set_anonymous(cred);
231                 talloc_free(mem_ctx);
232                 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
233         } else if (ldb_ret != 1) {
234                 DEBUG(1, ("Found more than one (%d) entry to match filter: %s\n",
235                           ldb_ret, filter));
236                 /* set anonymous as the fallback, if the machine account won't work */
237                 cli_credentials_set_anonymous(cred);
238                 talloc_free(mem_ctx);
239                 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
240         }
241         
242         password = ldb_msg_find_attr_as_string(msgs[0], "secret", NULL);
243         old_password = ldb_msg_find_attr_as_string(msgs[0], "priorSecret", NULL);
244
245         machine_account = ldb_msg_find_attr_as_string(msgs[0], "samAccountName", NULL);
246
247         if (!machine_account) {
248                 DEBUG(1, ("Could not find 'samAccountName' in join record to domain: %s\n",
249                           cli_credentials_get_domain(cred)));
250                 /* set anonymous as the fallback, if the machine account won't work */
251                 cli_credentials_set_anonymous(cred);
252                 talloc_free(mem_ctx);
253                 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
254         }
255
256         salt_principal = ldb_msg_find_attr_as_string(msgs[0], "saltPrincipal", NULL);
257         cli_credentials_set_salt_principal(cred, salt_principal);
258         
259         sct = ldb_msg_find_attr_as_int(msgs[0], "secureChannelType", 0);
260         if (sct) { 
261                 cli_credentials_set_secure_channel_type(cred, sct);
262         }
263         
264         if (!password) {
265                 const struct ldb_val *nt_password_hash = ldb_msg_find_ldb_val(msgs[0], "ntPwdHash");
266                 struct samr_Password hash;
267                 ZERO_STRUCT(hash);
268                 if (nt_password_hash) {
269                         memcpy(hash.hash, nt_password_hash->data, 
270                                MIN(nt_password_hash->length, sizeof(hash.hash)));
271                 
272                         cli_credentials_set_nt_hash(cred, &hash, CRED_SPECIFIED);
273                 } else {
274                         cli_credentials_set_password(cred, NULL, CRED_SPECIFIED);
275                 }
276         } else {
277                 cli_credentials_set_password(cred, password, CRED_SPECIFIED);
278         }
279
280         
281         domain = ldb_msg_find_attr_as_string(msgs[0], "flatname", NULL);
282         if (domain) {
283                 cli_credentials_set_domain(cred, domain, CRED_SPECIFIED);
284         }
285
286         realm = ldb_msg_find_attr_as_string(msgs[0], "realm", NULL);
287         if (realm) {
288                 cli_credentials_set_realm(cred, realm, CRED_SPECIFIED);
289         }
290
291         cli_credentials_set_username(cred, machine_account, CRED_SPECIFIED);
292
293         cli_credentials_set_kvno(cred, ldb_msg_find_attr_as_int(msgs[0], "msDS-KeyVersionNumber", 0));
294
295         /* If there was an external keytab specified by reference in
296          * the LDB, then use this.  Otherwise we will make one up
297          * (chewing CPU time) from the password */
298         keytab = ldb_msg_find_attr_as_string(msgs[0], "krb5Keytab", NULL);
299         if (keytab) {
300                 cli_credentials_set_keytab_name(cred, keytab, CRED_SPECIFIED);
301         } else {
302                 keytab = ldb_msg_find_attr_as_string(msgs[0], "privateKeytab", NULL);
303                 if (keytab) {
304                         keytab = talloc_asprintf(mem_ctx, "FILE:%s", private_path(mem_ctx, keytab));
305                         if (keytab) {
306                                 cli_credentials_set_keytab_name(cred, keytab, CRED_SPECIFIED);
307                         }
308                 }
309         }
310         talloc_free(mem_ctx);
311         
312         return NT_STATUS_OK;
313 }
314
315 /**
316  * Fill in credentials for the machine trust account, from the secrets database.
317  * 
318  * @param cred Credentials structure to fill in
319  * @retval NTSTATUS error detailing any failure
320  */
321 NTSTATUS cli_credentials_set_machine_account(struct cli_credentials *cred)
322 {
323         char *filter;
324         /* Bleh, nasty recursion issues: We are setting a machine
325          * account here, so we don't want the 'pending' flag around
326          * any more */
327         cred->machine_account_pending = False;
328         filter = talloc_asprintf(cred, SECRETS_PRIMARY_DOMAIN_FILTER, 
329                                        cli_credentials_get_domain(cred));
330         return cli_credentials_set_secrets(cred, SECRETS_PRIMARY_DOMAIN_DN,
331                                            filter);
332 }
333
334 /**
335  * Fill in credentials for the machine trust account, from the secrets database.
336  * 
337  * @param cred Credentials structure to fill in
338  * @retval NTSTATUS error detailing any failure
339  */
340 NTSTATUS cli_credentials_set_krbtgt(struct cli_credentials *cred)
341 {
342         char *filter;
343         /* Bleh, nasty recursion issues: We are setting a machine
344          * account here, so we don't want the 'pending' flag around
345          * any more */
346         cred->machine_account_pending = False;
347         filter = talloc_asprintf(cred, SECRETS_KRBTGT_SEARCH,
348                                        cli_credentials_get_realm(cred),
349                                        cli_credentials_get_domain(cred));
350         return cli_credentials_set_secrets(cred, SECRETS_PRINCIPALS_DN,
351                                            filter);
352 }
353
354 /**
355  * Fill in credentials for the machine trust account, from the secrets database.
356  * 
357  * @param cred Credentials structure to fill in
358  * @retval NTSTATUS error detailing any failure
359  */
360 NTSTATUS cli_credentials_set_stored_principal(struct cli_credentials *cred,
361                                               const char *serviceprincipal)
362 {
363         char *filter;
364         /* Bleh, nasty recursion issues: We are setting a machine
365          * account here, so we don't want the 'pending' flag around
366          * any more */
367         cred->machine_account_pending = False;
368         filter = talloc_asprintf(cred, SECRETS_PRINCIPAL_SEARCH,
369                                  cli_credentials_get_realm(cred),
370                                  cli_credentials_get_domain(cred),
371                                  serviceprincipal);
372         return cli_credentials_set_secrets(cred, SECRETS_PRINCIPALS_DN,
373                                            filter);
374 }
375
376 /**
377  * Ask that when required, the credentials system will be filled with
378  * machine trust account, from the secrets database.
379  * 
380  * @param cred Credentials structure to fill in
381  * @note This function is used to call the above function after, rather 
382  *       than during, popt processing.
383  *
384  */
385 void cli_credentials_set_machine_account_pending(struct cli_credentials *cred)
386 {
387         cred->machine_account_pending = True;
388 }
389
390
391 NTSTATUS cli_credentials_update_all_keytabs(TALLOC_CTX *parent_ctx)
392 {
393         TALLOC_CTX *mem_ctx;
394         int ldb_ret;
395         struct ldb_context *ldb;
396         struct ldb_message **msgs;
397         const char *attrs[] = { NULL };
398         struct cli_credentials *creds;
399         const char *filter;
400         NTSTATUS status;
401         int i, ret;
402
403         mem_ctx = talloc_new(parent_ctx);
404         if (!mem_ctx) {
405                 return NT_STATUS_NO_MEMORY;
406         }
407
408         /* Local secrets are stored in secrets.ldb */
409         ldb = secrets_db_connect(mem_ctx);
410         if (!ldb) {
411                 DEBUG(1, ("Could not open secrets.ldb\n"));
412                 talloc_free(mem_ctx);
413                 return NT_STATUS_ACCESS_DENIED;
414         }
415
416         /* search for the secret record, but only of things we can
417          * actually update */
418         ldb_ret = gendb_search(ldb,
419                                mem_ctx, NULL,
420                                &msgs, attrs,
421                                "(&(objectClass=kerberosSecret)(|(secret=*)(ntPwdHash=*)))");
422         if (ldb_ret == -1) {
423                 DEBUG(1, ("Error looking for kerberos type secrets to push into a keytab:: %s", ldb_errstring(ldb)));
424                 talloc_free(mem_ctx);
425                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
426         }
427
428         for (i=0; i < ldb_ret; i++) {
429                 /* Make a credentials structure from it */
430                 creds = cli_credentials_init(mem_ctx);
431                 if (!creds) {
432                         DEBUG(1, ("cli_credentials_init failed!"));
433                         talloc_free(mem_ctx);
434                         return NT_STATUS_NO_MEMORY;
435                 }
436                 cli_credentials_set_conf(creds);
437                 filter = talloc_asprintf(mem_ctx, "dn=%s", ldb_dn_get_linearized(msgs[i]->dn));
438                 status = cli_credentials_set_secrets(creds, NULL, filter);
439                 if (!NT_STATUS_IS_OK(status)) {
440                         DEBUG(1, ("Failed to read secrets for keytab update for %s\n", 
441                                   filter));
442                         continue;
443                 } 
444                 ret = cli_credentials_update_keytab(creds);
445                 if (ret != 0) {
446                         DEBUG(1, ("Failed to update keytab for %s\n", 
447                                   filter));
448                         continue;
449                 }
450         }
451         return NT_STATUS_OK;
452 }
453