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