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