s3-util_sid: use shared dom_sid_compare_auth and dom_sid_equal_X functions.
[kai/samba.git] / source3 / utils / sharesec.c
1 /*
2  *  Unix SMB/Netbios implementation.
3  *  Utility for managing share permissions
4  *
5  *  Copyright (C) Tim Potter                    2000
6  *  Copyright (C) Jeremy Allison                2000
7  *  Copyright (C) Jelmer Vernooij               2003
8  *  Copyright (C) Gerald (Jerry) Carter         2005.
9  *
10  *  This program is free software; you can redistribute it and/or modify
11  *  it under the terms of the GNU General Public License as published by
12  *  the Free Software Foundation; either version 3 of the License, or
13  *  (at your option) any later version.
14  *
15  *  This program is distributed in the hope that it will be useful,
16  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
17  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  *  GNU General Public License for more details.
19  *
20  *  You should have received a copy of the GNU General Public License
21  *  along with this program; if not, see <http://www.gnu.org/licenses/>.
22  */
23
24
25 #include "includes.h"
26 #include "popt_common.h"
27 #include "../libcli/security/dom_sid.h"
28
29 static TALLOC_CTX *ctx;
30
31 enum acl_mode { SMB_ACL_DELETE,
32                 SMB_ACL_MODIFY,
33                 SMB_ACL_ADD,
34                 SMB_ACL_SET,
35                 SMB_SD_DELETE,
36                 SMB_ACL_VIEW };
37
38 struct perm_value {
39         const char *perm;
40         uint32 mask;
41 };
42
43 /* These values discovered by inspection */
44
45 static const struct perm_value special_values[] = {
46         { "R", SEC_RIGHTS_FILE_READ },
47         { "W", SEC_RIGHTS_FILE_WRITE },
48         { "X", SEC_RIGHTS_FILE_EXECUTE },
49         { "D", SEC_STD_DELETE },
50         { "P", SEC_STD_WRITE_DAC },
51         { "O", SEC_STD_WRITE_OWNER },
52         { NULL, 0 },
53 };
54
55 #define SEC_RIGHTS_DIR_CHANGE ( SEC_RIGHTS_DIR_READ|SEC_STD_DELETE|\
56                                 SEC_RIGHTS_DIR_WRITE|SEC_DIR_TRAVERSE )
57
58 static const struct perm_value standard_values[] = {
59         { "READ",   SEC_RIGHTS_DIR_READ|SEC_DIR_TRAVERSE },
60         { "CHANGE", SEC_RIGHTS_DIR_CHANGE },
61         { "FULL",   SEC_RIGHTS_DIR_ALL },
62         { NULL, 0 },
63 };
64
65 /********************************************************************
66  print an ACE on a FILE
67 ********************************************************************/
68
69 static void print_ace(FILE *f, struct security_ace *ace)
70 {
71         const struct perm_value *v;
72         int do_print = 0;
73         uint32 got_mask;
74
75         fprintf(f, "%s:", sid_string_tos(&ace->trustee));
76
77         /* Ace type */
78
79         if (ace->type == SEC_ACE_TYPE_ACCESS_ALLOWED) {
80                 fprintf(f, "ALLOWED");
81         } else if (ace->type == SEC_ACE_TYPE_ACCESS_DENIED) {
82                 fprintf(f, "DENIED");
83         } else {
84                 fprintf(f, "%d", ace->type);
85         }
86
87         /* Not sure what flags can be set in a file ACL */
88
89         fprintf(f, "/%d/", ace->flags);
90
91         /* Standard permissions */
92
93         for (v = standard_values; v->perm; v++) {
94                 if (ace->access_mask == v->mask) {
95                         fprintf(f, "%s", v->perm);
96                         return;
97                 }
98         }
99
100         /* Special permissions.  Print out a hex value if we have
101            leftover bits in the mask. */
102
103         got_mask = ace->access_mask;
104
105  again:
106         for (v = special_values; v->perm; v++) {
107                 if ((ace->access_mask & v->mask) == v->mask) {
108                         if (do_print) {
109                                 fprintf(f, "%s", v->perm);
110                         }
111                         got_mask &= ~v->mask;
112                 }
113         }
114
115         if (!do_print) {
116                 if (got_mask != 0) {
117                         fprintf(f, "0x%08x", ace->access_mask);
118                 } else {
119                         do_print = 1;
120                         goto again;
121                 }
122         }
123 }
124
125 /********************************************************************
126  print an ascii version of a security descriptor on a FILE handle
127 ********************************************************************/
128
129 static void sec_desc_print(FILE *f, struct security_descriptor *sd)
130 {
131         uint32 i;
132
133         fprintf(f, "REVISION:%d\n", sd->revision);
134
135         /* Print owner and group sid */
136
137         fprintf(f, "OWNER:%s\n", sid_string_tos(sd->owner_sid));
138
139         fprintf(f, "GROUP:%s\n", sid_string_tos(sd->group_sid));
140
141         /* Print aces */
142         for (i = 0; sd->dacl && i < sd->dacl->num_aces; i++) {
143                 struct security_ace *ace = &sd->dacl->aces[i];
144                 fprintf(f, "ACL:");
145                 print_ace(f, ace);
146                 fprintf(f, "\n");
147         }
148 }
149
150 /********************************************************************
151  parse an ACE in the same format as print_ace()
152 ********************************************************************/
153
154 static bool parse_ace(struct security_ace *ace, const char *orig_str)
155 {
156         char *p;
157         const char *cp;
158         char *tok;
159         unsigned int atype = 0;
160         unsigned int aflags = 0;
161         unsigned int amask = 0;
162         struct dom_sid sid;
163         uint32_t mask;
164         const struct perm_value *v;
165         char *str = SMB_STRDUP(orig_str);
166         TALLOC_CTX *frame = talloc_stackframe();
167
168         if (!str) {
169                 TALLOC_FREE(frame);
170                 return False;
171         }
172
173         ZERO_STRUCTP(ace);
174         p = strchr_m(str,':');
175         if (!p) {
176                 fprintf(stderr, "ACE '%s': missing ':'.\n", orig_str);
177                 SAFE_FREE(str);
178                 TALLOC_FREE(frame);
179                 return False;
180         }
181         *p = '\0';
182         p++;
183         /* Try to parse numeric form */
184
185         if (sscanf(p, "%i/%i/%i", &atype, &aflags, &amask) == 3 &&
186             string_to_sid(&sid, str)) {
187                 goto done;
188         }
189
190         /* Try to parse text form */
191
192         if (!string_to_sid(&sid, str)) {
193                 fprintf(stderr, "ACE '%s': failed to convert '%s' to SID\n",
194                         orig_str, str);
195                 SAFE_FREE(str);
196                 TALLOC_FREE(frame);
197                 return False;
198         }
199
200         cp = p;
201         if (!next_token_talloc(frame, &cp, &tok, "/")) {
202                 fprintf(stderr, "ACE '%s': failed to find '/' character.\n",
203                         orig_str);
204                 SAFE_FREE(str);
205                 TALLOC_FREE(frame);
206                 return False;
207         }
208
209         if (strncmp(tok, "ALLOWED", strlen("ALLOWED")) == 0) {
210                 atype = SEC_ACE_TYPE_ACCESS_ALLOWED;
211         } else if (strncmp(tok, "DENIED", strlen("DENIED")) == 0) {
212                 atype = SEC_ACE_TYPE_ACCESS_DENIED;
213         } else {
214                 fprintf(stderr, "ACE '%s': missing 'ALLOWED' or 'DENIED' "
215                         "entry at '%s'\n", orig_str, tok);
216                 SAFE_FREE(str);
217                 TALLOC_FREE(frame);
218                 return False;
219         }
220
221         /* Only numeric form accepted for flags at present */
222         /* no flags on share permissions */
223
224         if (!(next_token_talloc(frame, &cp, &tok, "/") &&
225               sscanf(tok, "%i", &aflags) && aflags == 0)) {
226                 fprintf(stderr, "ACE '%s': bad integer flags entry at '%s'\n",
227                         orig_str, tok);
228                 SAFE_FREE(str);
229                 TALLOC_FREE(frame);
230                 return False;
231         }
232
233         if (!next_token_talloc(frame, &cp, &tok, "/")) {
234                 fprintf(stderr, "ACE '%s': missing / at '%s'\n",
235                         orig_str, tok);
236                 SAFE_FREE(str);
237                 TALLOC_FREE(frame);
238                 return False;
239         }
240
241         if (strncmp(tok, "0x", 2) == 0) {
242                 if (sscanf(tok, "%i", &amask) != 1) {
243                         fprintf(stderr, "ACE '%s': bad hex number at '%s'\n",
244                                 orig_str, tok);
245                         TALLOC_FREE(frame);
246                         SAFE_FREE(str);
247                         return False;
248                 }
249                 goto done;
250         }
251
252         for (v = standard_values; v->perm; v++) {
253                 if (strcmp(tok, v->perm) == 0) {
254                         amask = v->mask;
255                         goto done;
256                 }
257         }
258
259         p = tok;
260
261         while(*p) {
262                 bool found = False;
263
264                 for (v = special_values; v->perm; v++) {
265                         if (v->perm[0] == *p) {
266                                 amask |= v->mask;
267                                 found = True;
268                         }
269                 }
270
271                 if (!found) {
272                         fprintf(stderr, "ACE '%s': bad permission value at "
273                                 "'%s'\n", orig_str, p);
274                         TALLOC_FREE(frame);
275                         SAFE_FREE(str);
276                         return False;
277                 }
278                 p++;
279         }
280
281         if (*p) {
282                 TALLOC_FREE(frame);
283                 SAFE_FREE(str);
284                 return False;
285         }
286
287  done:
288         mask = amask;
289         init_sec_ace(ace, &sid, atype, mask, aflags);
290         SAFE_FREE(str);
291         TALLOC_FREE(frame);
292         return True;
293 }
294
295
296 /********************************************************************
297 ********************************************************************/
298
299 static struct security_descriptor* parse_acl_string(TALLOC_CTX *mem_ctx, const char *szACL, size_t *sd_size )
300 {
301         struct security_descriptor *sd = NULL;
302         struct security_ace *ace;
303         struct security_acl *theacl;
304         int num_ace;
305         const char *pacl;
306         int i;
307
308         if ( !szACL )
309                 return NULL;
310
311         pacl = szACL;
312         num_ace = count_chars( pacl, ',' ) + 1;
313
314         if ( !(ace = TALLOC_ZERO_ARRAY( mem_ctx, struct security_ace, num_ace )) )
315                 return NULL;
316
317         for ( i=0; i<num_ace; i++ ) {
318                 char *end_acl = strchr_m( pacl, ',' );
319                 fstring acl_string;
320
321                 strncpy( acl_string, pacl, MIN( PTR_DIFF( end_acl, pacl ), sizeof(fstring)-1) );
322                 acl_string[MIN( PTR_DIFF( end_acl, pacl ), sizeof(fstring)-1)] = '\0';
323
324                 if ( !parse_ace( &ace[i], acl_string ) )
325                         return NULL;
326
327                 pacl = end_acl;
328                 pacl++;
329         }
330
331         if ( !(theacl = make_sec_acl( mem_ctx, NT4_ACL_REVISION, num_ace, ace )) )
332                 return NULL;
333
334         sd = make_sec_desc( mem_ctx, SD_REVISION, SEC_DESC_SELF_RELATIVE,
335                 NULL, NULL, NULL, theacl, sd_size);
336
337         return sd;
338 }
339
340 /* add an ACE to a list of ACEs in a struct security_acl */
341 static bool add_ace(TALLOC_CTX *mem_ctx, struct security_acl **the_acl, struct security_ace *ace)
342 {
343         struct security_acl *new_ace;
344         struct security_ace *aces;
345         if (! *the_acl) {
346                 return (((*the_acl) = make_sec_acl(mem_ctx, 3, 1, ace)) != NULL);
347         }
348
349         if (!(aces = SMB_CALLOC_ARRAY(struct security_ace, 1+(*the_acl)->num_aces))) {
350                 return False;
351         }
352         memcpy(aces, (*the_acl)->aces, (*the_acl)->num_aces * sizeof(struct
353         security_ace));
354         memcpy(aces+(*the_acl)->num_aces, ace, sizeof(struct security_ace));
355         new_ace = make_sec_acl(mem_ctx,(*the_acl)->revision,1+(*the_acl)->num_aces, aces);
356         SAFE_FREE(aces);
357         (*the_acl) = new_ace;
358         return True;
359 }
360
361 /* The MSDN is contradictory over the ordering of ACE entries in an ACL.
362    However NT4 gives a "The information may have been modified by a
363    computer running Windows NT 5.0" if denied ACEs do not appear before
364    allowed ACEs. */
365
366 static int ace_compare(struct security_ace *ace1, struct security_ace *ace2)
367 {
368         if (sec_ace_equal(ace1, ace2))
369                 return 0;
370
371         if (ace1->type != ace2->type)
372                 return ace2->type - ace1->type;
373
374         if (dom_sid_compare(&ace1->trustee, &ace2->trustee))
375                 return dom_sid_compare(&ace1->trustee, &ace2->trustee);
376
377         if (ace1->flags != ace2->flags)
378                 return ace1->flags - ace2->flags;
379
380         if (ace1->access_mask != ace2->access_mask)
381                 return ace1->access_mask - ace2->access_mask;
382
383         if (ace1->size != ace2->size)
384                 return ace1->size - ace2->size;
385
386         return memcmp(ace1, ace2, sizeof(struct security_ace));
387 }
388
389 static void sort_acl(struct security_acl *the_acl)
390 {
391         uint32 i;
392         if (!the_acl) return;
393
394         TYPESAFE_QSORT(the_acl->aces, the_acl->num_aces, ace_compare);
395
396         for (i=1;i<the_acl->num_aces;) {
397                 if (sec_ace_equal(&the_acl->aces[i-1], &the_acl->aces[i])) {
398                         int j;
399                         for (j=i; j<the_acl->num_aces-1; j++) {
400                                 the_acl->aces[j] = the_acl->aces[j+1];
401                         }
402                         the_acl->num_aces--;
403                 } else {
404                         i++;
405                 }
406         }
407 }
408
409
410 static int change_share_sec(TALLOC_CTX *mem_ctx, const char *sharename, char *the_acl, enum acl_mode mode)
411 {
412         struct security_descriptor *sd = NULL;
413         struct security_descriptor *old = NULL;
414         size_t sd_size = 0;
415         uint32 i, j;
416
417         if (mode != SMB_ACL_SET && mode != SMB_SD_DELETE) {
418             if (!(old = get_share_security( mem_ctx, sharename, &sd_size )) ) {
419                 fprintf(stderr, "Unable to retrieve permissions for share "
420                         "[%s]\n", sharename);
421                 return -1;
422             }
423         }
424
425         if ( (mode != SMB_ACL_VIEW && mode != SMB_SD_DELETE) &&
426             !(sd = parse_acl_string(mem_ctx, the_acl, &sd_size )) ) {
427                 fprintf( stderr, "Failed to parse acl\n");
428                 return -1;
429         }
430
431         switch (mode) {
432         case SMB_ACL_VIEW:
433                 sec_desc_print( stdout, old);
434                 return 0;
435         case SMB_ACL_DELETE:
436             for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
437                 bool found = False;
438
439                 for (j=0;old->dacl && j<old->dacl->num_aces;j++) {
440                     if (sec_ace_equal(&sd->dacl->aces[i], &old->dacl->aces[j])) {
441                         uint32 k;
442                         for (k=j; k<old->dacl->num_aces-1;k++) {
443                             old->dacl->aces[k] = old->dacl->aces[k+1];
444                         }
445                         old->dacl->num_aces--;
446                         found = True;
447                         break;
448                     }
449                 }
450
451                 if (!found) {
452                 printf("ACL for ACE:");
453                 print_ace(stdout, &sd->dacl->aces[i]);
454                 printf(" not found\n");
455                 }
456             }
457             break;
458         case SMB_ACL_MODIFY:
459             for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
460                 bool found = False;
461
462                 for (j=0;old->dacl && j<old->dacl->num_aces;j++) {
463                     if (dom_sid_equal(&sd->dacl->aces[i].trustee,
464                         &old->dacl->aces[j].trustee)) {
465                         old->dacl->aces[j] = sd->dacl->aces[i];
466                         found = True;
467                     }
468                 }
469
470                 if (!found) {
471                     printf("ACL for SID %s not found\n",
472                            sid_string_tos(&sd->dacl->aces[i].trustee));
473                 }
474             }
475
476             if (sd->owner_sid) {
477                 old->owner_sid = sd->owner_sid;
478             }
479
480             if (sd->group_sid) {
481                 old->group_sid = sd->group_sid;
482             }
483             break;
484         case SMB_ACL_ADD:
485             for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
486                 add_ace(mem_ctx, &old->dacl, &sd->dacl->aces[i]);
487             }
488             break;
489         case SMB_ACL_SET:
490             old = sd;
491             break;
492         case SMB_SD_DELETE:
493             if (!delete_share_security(sharename)) {
494                 fprintf( stderr, "Failed to delete security descriptor for "
495                          "share [%s]\n", sharename );
496                 return -1;
497             }
498             return 0;
499         }
500
501         /* Denied ACE entries must come before allowed ones */
502         sort_acl(old->dacl);
503
504         if ( !set_share_security( sharename, old ) ) {
505             fprintf( stderr, "Failed to store acl for share [%s]\n", sharename );
506             return 2;
507         }
508         return 0;
509 }
510
511 /********************************************************************
512   main program
513 ********************************************************************/
514
515 int main(int argc, const char *argv[])
516 {
517         int opt;
518         int retval = 0;
519         enum acl_mode mode = SMB_ACL_SET;
520         static char *the_acl = NULL;
521         fstring sharename;
522         bool force_acl = False;
523         int snum;
524         poptContext pc;
525         bool initialize_sid = False;
526         struct poptOption long_options[] = {
527                 POPT_AUTOHELP
528                 { "remove", 'r', POPT_ARG_STRING, &the_acl, 'r', "Remove ACEs", "ACL" },
529                 { "modify", 'm', POPT_ARG_STRING, &the_acl, 'm', "Modify existing ACEs", "ACL" },
530                 { "add", 'a', POPT_ARG_STRING, &the_acl, 'a', "Add ACEs", "ACL" },
531                 { "replace", 'R', POPT_ARG_STRING, &the_acl, 'R', "Overwrite share permission ACL", "ACLS" },
532                 { "delete", 'D', POPT_ARG_NONE, NULL, 'D', "Delete the entire security descriptor" },
533                 { "view", 'v', POPT_ARG_NONE, NULL, 'v', "View current share permissions" },
534                 { "machine-sid", 'M', POPT_ARG_NONE, NULL, 'M', "Initialize the machine SID" },
535                 { "force", 'F', POPT_ARG_NONE, NULL, 'F', "Force storing the ACL", "ACLS" },
536                 POPT_COMMON_SAMBA
537                 { NULL }
538         };
539
540         if ( !(ctx = talloc_stackframe()) ) {
541                 fprintf( stderr, "Failed to initialize talloc context!\n");
542                 return -1;
543         }
544
545         /* set default debug level to 1 regardless of what smb.conf sets */
546         setup_logging( "sharesec", True );
547         DEBUGLEVEL_CLASS[DBGC_ALL] = 1;
548         dbf = x_stderr;
549         x_setbuf( x_stderr, NULL );
550
551         pc = poptGetContext("sharesec", argc, argv, long_options, 0);
552
553         poptSetOtherOptionHelp(pc, "sharename\n");
554
555         while ((opt = poptGetNextOpt(pc)) != -1) {
556                 switch (opt) {
557                 case 'r':
558                         the_acl = smb_xstrdup(poptGetOptArg(pc));
559                         mode = SMB_ACL_DELETE;
560                         break;
561
562                 case 'm':
563                         the_acl = smb_xstrdup(poptGetOptArg(pc));
564                         mode = SMB_ACL_MODIFY;
565                         break;
566
567                 case 'a':
568                         the_acl = smb_xstrdup(poptGetOptArg(pc));
569                         mode = SMB_ACL_ADD;
570                         break;
571
572                 case 'R':
573                         the_acl = smb_xstrdup(poptGetOptArg(pc));
574                         mode = SMB_ACL_SET;
575                         break;
576
577                 case 'D':
578                         mode = SMB_SD_DELETE;
579                         break;
580
581                 case 'v':
582                         mode = SMB_ACL_VIEW;
583                         break;
584
585                 case 'F':
586                         force_acl = True;
587                         break;
588
589                 case 'M':
590                         initialize_sid = True;
591                         break;
592                 }
593         }
594
595         setlinebuf(stdout);
596
597         load_case_tables();
598
599         lp_load( get_dyn_CONFIGFILE(), False, False, False, True );
600
601         /* check for initializing secrets.tdb first */
602
603         if ( initialize_sid ) {
604                 struct dom_sid *sid = get_global_sam_sid();
605
606                 if ( !sid ) {
607                         fprintf( stderr, "Failed to retrieve Machine SID!\n");
608                         return 3;
609                 }
610
611                 printf ("%s\n", sid_string_tos( sid ) );
612                 return 0;
613         }
614
615         if ( mode == SMB_ACL_VIEW && force_acl ) {
616                 fprintf( stderr, "Invalid combination of -F and -v\n");
617                 return -1;
618         }
619
620         /* get the sharename */
621
622         if(!poptPeekArg(pc)) {
623                 poptPrintUsage(pc, stderr, 0);
624                 return -1;
625         }
626
627         fstrcpy(sharename, poptGetArg(pc));
628
629         snum = lp_servicenumber( sharename );
630
631         if ( snum == -1 && !force_acl ) {
632                 fprintf( stderr, "Invalid sharename: %s\n", sharename);
633                 return -1;
634         }
635
636         retval = change_share_sec(ctx, sharename, the_acl, mode);
637
638         talloc_destroy(ctx);
639
640         return retval;
641 }