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