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