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