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