c2494e2293a1501783c8a1e5c6f6713a8e05c20c
[samba.git] / source3 / lib / sharesec.c
1 /* 
2  *  Unix SMB/Netbios implementation.
3  *  SEC_DESC handling functions
4  *  Copyright (C) Jeremy R. Allison            1995-2003.
5  *  
6  *  This program is free software; you can redistribute it and/or modify
7  *  it under the terms of the GNU General Public License as published by
8  *  the Free Software Foundation; either version 3 of the License, or
9  *  (at your option) any later version.
10  *  
11  *  This program is distributed in the hope that it will be useful,
12  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  *  GNU General Public License for more details.
15  *  
16  *  You should have received a copy of the GNU General Public License
17  *  along with this program; if not, see <http://www.gnu.org/licenses/>.
18  */
19
20 #include "includes.h"
21 #include "system/filesys.h"
22 #include "../libcli/security/security.h"
23 #include "../librpc/gen_ndr/ndr_security.h"
24 #include "dbwrap.h"
25 #include "util_tdb.h"
26
27 /*******************************************************************
28  Create the share security tdb.
29  ********************************************************************/
30
31 static struct db_context *share_db; /* used for share security descriptors */
32 #define SHARE_DATABASE_VERSION_V1 1
33 #define SHARE_DATABASE_VERSION_V2 2 /* version id in little endian. */
34 #define SHARE_DATABASE_VERSION_V3 3 /* canonicalized sharenames as lower case */
35
36 #define SHARE_SECURITY_DB_KEY_PREFIX_STR "SECDESC/"
37 /* Map generic permissions to file object specific permissions */
38
39 extern const struct generic_mapping file_generic_mapping;
40
41 static int delete_fn(struct db_record *rec, void *priv)
42 {
43         rec->delete_rec(rec);
44         return 0;
45 }
46
47 /*****************************************************
48  Looking for keys of the form: SHARE_SECURITY_DB_KEY_PREFIX_STR + "non lower case str".
49  If we find one re-write it into a canonical case form.
50 *****************************************************/
51
52 static int upgrade_v2_to_v3(struct db_record *rec, void *priv)
53 {
54         size_t prefix_len = strlen(SHARE_SECURITY_DB_KEY_PREFIX_STR);
55         const char *servicename = NULL;
56         char *c_servicename = NULL;
57         char *newkey = NULL;
58         bool *p_upgrade_ok = (bool *)priv;
59         NTSTATUS status;
60
61         /* Is there space for a one character sharename ? */
62         if (rec->key.dsize <= prefix_len+2) {
63                 return 0;
64         }
65
66         /* Does it start with the share key prefix ? */
67         if (memcmp(rec->key.dptr, SHARE_SECURITY_DB_KEY_PREFIX_STR,
68                         prefix_len) != 0) {
69                 return 0;
70         }
71
72         /* Is it a null terminated string as a key ? */
73         if (rec->key.dptr[rec->key.dsize-1] != '\0') {
74                 return 0;
75         }
76
77         /* Bytes after the prefix are the sharename string. */
78         servicename = (char *)&rec->key.dptr[prefix_len];
79         c_servicename = canonicalize_servicename(talloc_tos(), servicename);
80         if (!c_servicename) {
81                 smb_panic("out of memory upgrading share security db from v2 -> v3");
82         }
83
84         if (strcmp(servicename, c_servicename) == 0) {
85                 /* Old and new names match. No canonicalization needed. */
86                 TALLOC_FREE(c_servicename);
87                 return 0;
88         }
89
90         /* Oops. Need to canonicalize name, delete old then store new. */
91         status = rec->delete_rec(rec);
92         if (!NT_STATUS_IS_OK(status)) {
93                 DEBUG(1, ("upgrade_v2_to_v3: Failed to delete secdesc for "
94                           "%s: %s\n", rec->key.dptr, nt_errstr(status)));
95                 TALLOC_FREE(c_servicename);
96                 *p_upgrade_ok = false;
97                 return -1;
98         } else {
99                 DEBUG(10, ("upgrade_v2_to_v3: deleted secdesc for "
100                           "%s\n", rec->key.dptr ));
101         }
102
103         if (!(newkey = talloc_asprintf(talloc_tos(),
104                         SHARE_SECURITY_DB_KEY_PREFIX_STR "%s",
105                         c_servicename))) {
106                 smb_panic("out of memory upgrading share security db from v2 -> v3");
107         }
108
109         status = dbwrap_store(share_db,
110                                 string_term_tdb_data(newkey),
111                                 rec->value,
112                                 TDB_REPLACE);
113
114         if (!NT_STATUS_IS_OK(status)) {
115                 DEBUG(1, ("upgrade_v2_to_v3: Failed to store secdesc for "
116                           "%s: %s\n", c_servicename, nt_errstr(status)));
117                 TALLOC_FREE(c_servicename);
118                 TALLOC_FREE(newkey);
119                 *p_upgrade_ok = false;
120                 return -1;
121         } else {
122                 DEBUG(10, ("upgrade_v2_to_v3: stored secdesc for "
123                           "%s\n", newkey ));
124         }
125
126         TALLOC_FREE(newkey);
127         TALLOC_FREE(c_servicename);
128
129         return 0;
130 }
131
132 bool share_info_db_init(void)
133 {
134         const char *vstring = "INFO/version";
135         int32 vers_id;
136         int ret;
137         bool upgrade_ok = true;
138
139         if (share_db != NULL) {
140                 return True;
141         }
142
143         share_db = db_open(NULL, state_path("share_info.tdb"), 0,
144                                  TDB_DEFAULT, O_RDWR|O_CREAT, 0600);
145         if (share_db == NULL) {
146                 DEBUG(0,("Failed to open share info database %s (%s)\n",
147                         state_path("share_info.tdb"), strerror(errno) ));
148                 return False;
149         }
150
151         vers_id = dbwrap_fetch_int32(share_db, vstring);
152         if (vers_id == SHARE_DATABASE_VERSION_V3) {
153                 return true;
154         }
155
156         if (share_db->transaction_start(share_db) != 0) {
157                 DEBUG(0, ("transaction_start failed\n"));
158                 TALLOC_FREE(share_db);
159                 return false;
160         }
161
162         vers_id = dbwrap_fetch_int32(share_db, vstring);
163         if (vers_id == SHARE_DATABASE_VERSION_V3) {
164                 /*
165                  * Race condition
166                  */
167                 if (share_db->transaction_cancel(share_db)) {
168                         smb_panic("transaction_cancel failed");
169                 }
170                 return true;
171         }
172
173         /* Move to at least V2. */
174
175         /* Cope with byte-reversed older versions of the db. */
176         if ((vers_id == SHARE_DATABASE_VERSION_V1) || (IREV(vers_id) == SHARE_DATABASE_VERSION_V1)) {
177                 /* Written on a bigendian machine with old fetch_int code. Save as le. */
178
179                 if (dbwrap_store_int32(share_db, vstring,
180                                        SHARE_DATABASE_VERSION_V2) != 0) {
181                         DEBUG(0, ("dbwrap_store_int32 failed\n"));
182                         goto cancel;
183                 }
184                 vers_id = SHARE_DATABASE_VERSION_V2;
185         }
186
187         if (vers_id != SHARE_DATABASE_VERSION_V2) {
188                 ret = share_db->traverse(share_db, delete_fn, NULL);
189                 if (ret < 0) {
190                         DEBUG(0, ("traverse failed\n"));
191                         goto cancel;
192                 }
193                 if (dbwrap_store_int32(share_db, vstring,
194                                        SHARE_DATABASE_VERSION_V2) != 0) {
195                         DEBUG(0, ("dbwrap_store_int32 failed\n"));
196                         goto cancel;
197                 }
198         }
199
200         /* Finally upgrade to version 3, with canonicalized sharenames. */
201
202         ret = share_db->traverse(share_db, upgrade_v2_to_v3, &upgrade_ok);
203         if (ret < 0 || upgrade_ok == false) {
204                 DEBUG(0, ("traverse failed\n"));
205                 goto cancel;
206         }
207         if (dbwrap_store_int32(share_db, vstring,
208                                SHARE_DATABASE_VERSION_V3) != 0) {
209                 DEBUG(0, ("dbwrap_store_int32 failed\n"));
210                 goto cancel;
211         }
212
213         if (share_db->transaction_commit(share_db) != 0) {
214                 DEBUG(0, ("transaction_commit failed\n"));
215                 return false;
216         }
217
218         return true;
219
220  cancel:
221         if (share_db->transaction_cancel(share_db)) {
222                 smb_panic("transaction_cancel failed");
223         }
224
225         return false;
226 }
227
228 /*******************************************************************
229  Fake up a Everyone, default access as a default.
230  def_access is a GENERIC_XXX access mode.
231  ********************************************************************/
232
233 struct security_descriptor *get_share_security_default( TALLOC_CTX *ctx, size_t *psize, uint32 def_access)
234 {
235         uint32_t sa;
236         struct security_ace ace;
237         struct security_acl *psa = NULL;
238         struct security_descriptor *psd = NULL;
239         uint32 spec_access = def_access;
240
241         se_map_generic(&spec_access, &file_generic_mapping);
242
243         sa = (def_access | spec_access );
244         init_sec_ace(&ace, &global_sid_World, SEC_ACE_TYPE_ACCESS_ALLOWED, sa, 0);
245
246         if ((psa = make_sec_acl(ctx, NT4_ACL_REVISION, 1, &ace)) != NULL) {
247                 psd = make_sec_desc(ctx, SECURITY_DESCRIPTOR_REVISION_1,
248                                     SEC_DESC_SELF_RELATIVE, NULL, NULL, NULL,
249                                     psa, psize);
250         }
251
252         if (!psd) {
253                 DEBUG(0,("get_share_security: Failed to make SEC_DESC.\n"));
254                 return NULL;
255         }
256
257         return psd;
258 }
259
260 /*******************************************************************
261  Pull a security descriptor from the share tdb.
262  ********************************************************************/
263
264 struct security_descriptor *get_share_security( TALLOC_CTX *ctx, const char *servicename,
265                               size_t *psize)
266 {
267         char *key;
268         struct security_descriptor *psd = NULL;
269         TDB_DATA data;
270         char *c_servicename = canonicalize_servicename(talloc_tos(), servicename);
271         NTSTATUS status;
272
273         if (!c_servicename) {
274                 return NULL;
275         }
276
277         if (!share_info_db_init()) {
278                 TALLOC_FREE(c_servicename);
279                 return NULL;
280         }
281
282         if (!(key = talloc_asprintf(ctx, SHARE_SECURITY_DB_KEY_PREFIX_STR "%s", c_servicename))) {
283                 TALLOC_FREE(c_servicename);
284                 DEBUG(0, ("talloc_asprintf failed\n"));
285                 return NULL;
286         }
287
288         TALLOC_FREE(c_servicename);
289
290         data = dbwrap_fetch_bystring(share_db, talloc_tos(), key);
291
292         TALLOC_FREE(key);
293
294         if (data.dptr == NULL) {
295                 return get_share_security_default(ctx, psize,
296                                                   GENERIC_ALL_ACCESS);
297         }
298
299         status = unmarshall_sec_desc(ctx, data.dptr, data.dsize, &psd);
300
301         TALLOC_FREE(data.dptr);
302
303         if (!NT_STATUS_IS_OK(status)) {
304                 DEBUG(0, ("unmarshall_sec_desc failed: %s\n",
305                           nt_errstr(status)));
306                 return get_share_security_default(ctx, psize,
307                                                   GENERIC_ALL_ACCESS);
308         }
309
310         if (psd) {
311                 *psize = ndr_size_security_descriptor(psd, 0);
312         } else {
313                 return get_share_security_default(ctx, psize,
314                                                   GENERIC_ALL_ACCESS);
315         }
316
317         return psd;
318 }
319
320 /*******************************************************************
321  Store a security descriptor in the share db.
322  ********************************************************************/
323
324 bool set_share_security(const char *share_name, struct security_descriptor *psd)
325 {
326         TALLOC_CTX *frame = talloc_stackframe();
327         char *key;
328         bool ret = False;
329         TDB_DATA blob;
330         NTSTATUS status;
331         char *c_share_name = canonicalize_servicename(frame, share_name);
332
333         if (!c_share_name) {
334                 goto out;
335         }
336
337         if (!share_info_db_init()) {
338                 goto out;
339         }
340
341         status = marshall_sec_desc(frame, psd, &blob.dptr, &blob.dsize);
342
343         if (!NT_STATUS_IS_OK(status)) {
344                 DEBUG(0, ("marshall_sec_desc failed: %s\n",
345                           nt_errstr(status)));
346                 goto out;
347         }
348
349         if (!(key = talloc_asprintf(frame, SHARE_SECURITY_DB_KEY_PREFIX_STR "%s", c_share_name))) {
350                 DEBUG(0, ("talloc_asprintf failed\n"));
351                 goto out;
352         }
353
354         status = dbwrap_trans_store(share_db, string_term_tdb_data(key), blob,
355                                     TDB_REPLACE);
356         if (!NT_STATUS_IS_OK(status)) {
357                 DEBUG(1, ("set_share_security: Failed to store secdesc for "
358                           "%s: %s\n", share_name, nt_errstr(status)));
359                 goto out;
360         }
361
362         DEBUG(5,("set_share_security: stored secdesc for %s\n", share_name ));
363         ret = True;
364
365  out:
366         TALLOC_FREE(frame);
367         return ret;
368 }
369
370 /*******************************************************************
371  Delete a security descriptor.
372 ********************************************************************/
373
374 bool delete_share_security(const char *servicename)
375 {
376         TDB_DATA kbuf;
377         char *key;
378         NTSTATUS status;
379         char *c_servicename = canonicalize_servicename(talloc_tos(), servicename);
380
381         if (!c_servicename) {
382                 return NULL;
383         }
384
385         if (!share_info_db_init()) {
386                 TALLOC_FREE(c_servicename);
387                 return False;
388         }
389
390         if (!(key = talloc_asprintf(talloc_tos(), SHARE_SECURITY_DB_KEY_PREFIX_STR "%s",
391                                     c_servicename))) {
392                 TALLOC_FREE(c_servicename);
393                 return False;
394         }
395         kbuf = string_term_tdb_data(key);
396
397         status = dbwrap_trans_delete(share_db, kbuf);
398         if (!NT_STATUS_IS_OK(status)) {
399                 DEBUG(0, ("delete_share_security: Failed to delete entry for "
400                           "share %s: %s\n", c_servicename, nt_errstr(status)));
401                 TALLOC_FREE(c_servicename);
402                 return False;
403         }
404
405         TALLOC_FREE(c_servicename);
406         return True;
407 }
408
409 /*******************************************************************
410  Can this user access with share with the required permissions ?
411 ********************************************************************/
412
413 bool share_access_check(const struct security_token *token, const char *sharename,
414                         uint32 desired_access)
415 {
416         uint32 granted;
417         NTSTATUS status;
418         struct security_descriptor *psd = NULL;
419         size_t sd_size;
420
421         psd = get_share_security(talloc_tos(), sharename, &sd_size);
422
423         if (!psd) {
424                 return True;
425         }
426
427         status = se_access_check(psd, token, desired_access, &granted);
428
429         TALLOC_FREE(psd);
430
431         return NT_STATUS_IS_OK(status);
432 }
433
434 /***************************************************************************
435  Parse the contents of an acl string from a usershare file.
436 ***************************************************************************/
437
438 bool parse_usershare_acl(TALLOC_CTX *ctx, const char *acl_str, struct security_descriptor **ppsd)
439 {
440         size_t s_size = 0;
441         const char *pacl = acl_str;
442         int num_aces = 0;
443         struct security_ace *ace_list = NULL;
444         struct security_acl *psa = NULL;
445         struct security_descriptor *psd = NULL;
446         size_t sd_size = 0;
447         int i;
448
449         *ppsd = NULL;
450
451         /* If the acl string is blank return "Everyone:R" */
452         if (!*acl_str) {
453                 struct security_descriptor *default_psd = get_share_security_default(ctx, &s_size, GENERIC_READ_ACCESS);
454                 if (!default_psd) {
455                         return False;
456                 }
457                 *ppsd = default_psd;
458                 return True;
459         }
460
461         num_aces = 1;
462
463         /* Add the number of ',' characters to get the number of aces. */
464         num_aces += count_chars(pacl,',');
465
466         ace_list = TALLOC_ARRAY(ctx, struct security_ace, num_aces);
467         if (!ace_list) {
468                 return False;
469         }
470
471         for (i = 0; i < num_aces; i++) {
472                 uint32_t sa;
473                 uint32 g_access;
474                 uint32 s_access;
475                 struct dom_sid sid;
476                 char *sidstr;
477                 enum security_ace_type type = SEC_ACE_TYPE_ACCESS_ALLOWED;
478
479                 if (!next_token_talloc(ctx, &pacl, &sidstr, ":")) {
480                         DEBUG(0,("parse_usershare_acl: malformed usershare acl looking "
481                                 "for ':' in string '%s'\n", pacl));
482                         return False;
483                 }
484
485                 if (!string_to_sid(&sid, sidstr)) {
486                         DEBUG(0,("parse_usershare_acl: failed to convert %s to sid.\n",
487                                 sidstr ));
488                         return False;
489                 }
490
491                 switch (*pacl) {
492                         case 'F': /* Full Control, ie. R+W */
493                         case 'f': /* Full Control, ie. R+W */
494                                 s_access = g_access = GENERIC_ALL_ACCESS;
495                                 break;
496                         case 'R': /* Read only. */
497                         case 'r': /* Read only. */
498                                 s_access = g_access = GENERIC_READ_ACCESS;
499                                 break;
500                         case 'D': /* Deny all to this SID. */
501                         case 'd': /* Deny all to this SID. */
502                                 type = SEC_ACE_TYPE_ACCESS_DENIED;
503                                 s_access = g_access = GENERIC_ALL_ACCESS;
504                                 break;
505                         default:
506                                 DEBUG(0,("parse_usershare_acl: unknown acl type at %s.\n",
507                                         pacl ));
508                                 return False;
509                 }
510
511                 pacl++;
512                 if (*pacl && *pacl != ',') {
513                         DEBUG(0,("parse_usershare_acl: bad acl string at %s.\n",
514                                 pacl ));
515                         return False;
516                 }
517                 pacl++; /* Go past any ',' */
518
519                 se_map_generic(&s_access, &file_generic_mapping);
520                 sa = (g_access | s_access);
521                 init_sec_ace(&ace_list[i], &sid, type, sa, 0);
522         }
523
524         if ((psa = make_sec_acl(ctx, NT4_ACL_REVISION, num_aces, ace_list)) != NULL) {
525                 psd = make_sec_desc(ctx, SECURITY_DESCRIPTOR_REVISION_1,
526                                     SEC_DESC_SELF_RELATIVE, NULL, NULL, NULL,
527                                     psa, &sd_size);
528         }
529
530         if (!psd) {
531                 DEBUG(0,("parse_usershare_acl: Failed to make SEC_DESC.\n"));
532                 return False;
533         }
534
535         *ppsd = psd;
536         return True;
537 }