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