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