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