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