don't return 0 on error - bad for scripts
[ab/samba.git/.git] / source3 / utils / smbcacls.c
1 /* 
2    Unix SMB/CIFS implementation.
3    ACL get/set utility
4    
5    Copyright (C) Andrew Tridgell 2000
6    Copyright (C) Tim Potter      2000
7    Copyright (C) Jeremy Allison  2000
8    Copyright (C) Jelmer Vernooij 2003
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 #include "includes.h"
25
26 static int test_args;
27
28 #define CREATE_ACCESS_READ READ_CONTROL_ACCESS
29
30 /* numeric is set when the user wants numeric SIDs and ACEs rather
31    than going via LSA calls to resolve them */
32 static int numeric;
33
34 enum acl_mode {SMB_ACL_SET, SMB_ACL_DELETE, SMB_ACL_MODIFY, SMB_ACL_ADD };
35 enum chown_mode {REQUEST_NONE, REQUEST_CHOWN, REQUEST_CHGRP};
36 enum exit_values {EXIT_OK, EXIT_FAILED, EXIT_PARSE_ERROR};
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", 0x00120089 },
47         { "W", 0x00120116 },
48         { "X", 0x001200a0 },
49         { "D", 0x00010000 },
50         { "P", 0x00040000 },
51         { "O", 0x00080000 },
52         { NULL, 0 },
53 };
54
55 static const struct perm_value standard_values[] = {
56         { "READ",   0x001200a9 },
57         { "CHANGE", 0x001301bf },
58         { "FULL",   0x001f01ff },
59         { NULL, 0 },
60 };
61
62 /* Open cli connection and policy handle */
63
64 static NTSTATUS cli_lsa_lookup_sid(struct cli_state *cli,
65                                    const DOM_SID *sid,
66                                    TALLOC_CTX *mem_ctx,
67                                    enum lsa_SidType *type,
68                                    char **domain, char **name)
69 {
70         uint16 orig_cnum = cli->cnum;
71         struct rpc_pipe_client *p;
72         struct policy_handle handle;
73         NTSTATUS status;
74         TALLOC_CTX *frame = talloc_stackframe();
75         enum lsa_SidType *types;
76         char **domains;
77         char **names;
78
79         if (!cli_send_tconX(cli, "IPC$", "?????", "", 0)) {
80                 return cli_nt_error(cli);
81         }
82
83         status = cli_rpc_pipe_open_noauth(cli, &ndr_table_lsarpc.syntax_id,
84                                           &p);
85         if (!NT_STATUS_IS_OK(status)) {
86                 goto fail;
87         }
88
89         status = rpccli_lsa_open_policy(p, talloc_tos(), True,
90                                         GENERIC_EXECUTE_ACCESS, &handle);
91         if (!NT_STATUS_IS_OK(status)) {
92                 goto fail;
93         }
94
95         status = rpccli_lsa_lookup_sids(p, talloc_tos(), &handle, 1, sid,
96                                         &domains, &names, &types);
97         if (!NT_STATUS_IS_OK(status)) {
98                 goto fail;
99         }
100
101         *type = types[0];
102         *domain = talloc_move(mem_ctx, &domains[0]);
103         *name = talloc_move(mem_ctx, &names[0]);
104
105         status = NT_STATUS_OK;
106  fail:
107         TALLOC_FREE(p);
108         cli_tdis(cli);
109         cli->cnum = orig_cnum;
110         TALLOC_FREE(frame);
111         return status;
112 }
113
114 static NTSTATUS cli_lsa_lookup_name(struct cli_state *cli,
115                                     const char *name,
116                                     enum lsa_SidType *type,
117                                     DOM_SID *sid)
118 {
119         uint16 orig_cnum = cli->cnum;
120         struct rpc_pipe_client *p;
121         struct policy_handle handle;
122         NTSTATUS status;
123         TALLOC_CTX *frame = talloc_stackframe();
124         DOM_SID *sids;
125         enum lsa_SidType *types;
126
127         if (!cli_send_tconX(cli, "IPC$", "?????", "", 0)) {
128                 return cli_nt_error(cli);
129         }
130
131         status = cli_rpc_pipe_open_noauth(cli, &ndr_table_lsarpc.syntax_id,
132                                           &p);
133         if (!NT_STATUS_IS_OK(status)) {
134                 goto fail;
135         }
136
137         status = rpccli_lsa_open_policy(p, talloc_tos(), True,
138                                         GENERIC_EXECUTE_ACCESS, &handle);
139         if (!NT_STATUS_IS_OK(status)) {
140                 goto fail;
141         }
142
143         status = rpccli_lsa_lookup_names(p, talloc_tos(), &handle, 1, &name,
144                                          NULL, 1, &sids, &types);
145         if (!NT_STATUS_IS_OK(status)) {
146                 goto fail;
147         }
148
149         *type = types[0];
150         *sid = sids[0];
151
152         status = NT_STATUS_OK;
153  fail:
154         TALLOC_FREE(p);
155         cli_tdis(cli);
156         cli->cnum = orig_cnum;
157         TALLOC_FREE(frame);
158         return status;
159 }
160
161 /* convert a SID to a string, either numeric or username/group */
162 static void SidToString(struct cli_state *cli, fstring str, const DOM_SID *sid)
163 {
164         char *domain = NULL;
165         char *name = NULL;
166         enum lsa_SidType type;
167         NTSTATUS status;
168
169         sid_to_fstring(str, sid);
170
171         if (numeric) {
172                 return;
173         }
174
175         status = cli_lsa_lookup_sid(cli, sid, talloc_tos(), &type,
176                                     &domain, &name);
177
178         if (!NT_STATUS_IS_OK(status)) {
179                 return;
180         }
181
182         if (*domain) {
183                 slprintf(str, sizeof(fstring) - 1, "%s%s%s",
184                         domain, lp_winbind_separator(), name);
185         } else {
186                 fstrcpy(str, name);
187         }
188 }
189
190 /* convert a string to a SID, either numeric or username/group */
191 static bool StringToSid(struct cli_state *cli, DOM_SID *sid, const char *str)
192 {
193         enum lsa_SidType type;
194
195         if (strncmp(str, "S-", 2) == 0) {
196                 return string_to_sid(sid, str);
197         }
198
199         return NT_STATUS_IS_OK(cli_lsa_lookup_name(cli, str, &type, sid));
200 }
201
202 static void print_ace_flags(FILE *f, uint8_t flags)
203 {
204         char *str = talloc_strdup(NULL, "");
205
206         if (!str) {
207                 goto out;
208         }
209
210         if (flags & SEC_ACE_FLAG_OBJECT_INHERIT) {
211                 str = talloc_asprintf(str, "%s%s",
212                                 str, "OI|");
213                 if (!str) {
214                         goto out;
215                 }
216         }
217         if (flags & SEC_ACE_FLAG_CONTAINER_INHERIT) {
218                 str = talloc_asprintf(str, "%s%s",
219                                 str, "CI|");
220                 if (!str) {
221                         goto out;
222                 }
223         }
224         if (flags & SEC_ACE_FLAG_NO_PROPAGATE_INHERIT) {
225                 str = talloc_asprintf(str, "%s%s",
226                                 str, "NP|");
227                 if (!str) {
228                         goto out;
229                 }
230         }
231         if (flags & SEC_ACE_FLAG_INHERIT_ONLY) {
232                 str = talloc_asprintf(str, "%s%s",
233                                 str, "IO|");
234                 if (!str) {
235                         goto out;
236                 }
237         }
238         if (flags & SEC_ACE_FLAG_INHERITED_ACE) {
239                 str = talloc_asprintf(str, "%s%s",
240                                 str, "I|");
241                 if (!str) {
242                         goto out;
243                 }
244         }
245         /* Ignore define SEC_ACE_FLAG_SUCCESSFUL_ACCESS ( 0x40 )
246            and SEC_ACE_FLAG_FAILED_ACCESS ( 0x80 ) as they're
247            audit ace flags. */
248
249         if (str[strlen(str)-1] == '|') {
250                 str[strlen(str)-1] = '\0';
251                 fprintf(f, "/%s/", str);
252         } else {
253                 fprintf(f, "/0x%x/", flags);
254         }
255         TALLOC_FREE(str);
256         return;
257
258   out:
259         fprintf(f, "/0x%x/", flags);
260 }
261
262 /* print an ACE on a FILE, using either numeric or ascii representation */
263 static void print_ace(struct cli_state *cli, FILE *f, SEC_ACE *ace)
264 {
265         const struct perm_value *v;
266         fstring sidstr;
267         int do_print = 0;
268         uint32 got_mask;
269
270         SidToString(cli, sidstr, &ace->trustee);
271
272         fprintf(f, "%s:", sidstr);
273
274         if (numeric) {
275                 fprintf(f, "%d/0x%x/0x%08x",
276                         ace->type, ace->flags, ace->access_mask);
277                 return;
278         }
279
280         /* Ace type */
281
282         if (ace->type == SEC_ACE_TYPE_ACCESS_ALLOWED) {
283                 fprintf(f, "ALLOWED");
284         } else if (ace->type == SEC_ACE_TYPE_ACCESS_DENIED) {
285                 fprintf(f, "DENIED");
286         } else {
287                 fprintf(f, "%d", ace->type);
288         }
289
290         print_ace_flags(f, ace->flags);
291
292         /* Standard permissions */
293
294         for (v = standard_values; v->perm; v++) {
295                 if (ace->access_mask == v->mask) {
296                         fprintf(f, "%s", v->perm);
297                         return;
298                 }
299         }
300
301         /* Special permissions.  Print out a hex value if we have
302            leftover bits in the mask. */
303
304         got_mask = ace->access_mask;
305
306  again:
307         for (v = special_values; v->perm; v++) {
308                 if ((ace->access_mask & v->mask) == v->mask) {
309                         if (do_print) {
310                                 fprintf(f, "%s", v->perm);
311                         }
312                         got_mask &= ~v->mask;
313                 }
314         }
315
316         if (!do_print) {
317                 if (got_mask != 0) {
318                         fprintf(f, "0x%08x", ace->access_mask);
319                 } else {
320                         do_print = 1;
321                         goto again;
322                 }
323         }
324 }
325
326 static bool parse_ace_flags(const char *str, unsigned int *pflags)
327 {
328         const char *p = str;
329         *pflags = 0;
330
331         while (*p) {
332                 if (strnequal(p, "OI", 2)) {
333                         *pflags |= SEC_ACE_FLAG_OBJECT_INHERIT;
334                         p += 2;
335                 } else if (strnequal(p, "CI", 2)) {
336                         *pflags |= SEC_ACE_FLAG_CONTAINER_INHERIT;
337                         p += 2;
338                 } else if (strnequal(p, "NP", 2)) {
339                         *pflags |= SEC_ACE_FLAG_NO_PROPAGATE_INHERIT;
340                         p += 2;
341                 } else if (strnequal(p, "IO", 2)) {
342                         *pflags |= SEC_ACE_FLAG_INHERIT_ONLY;
343                         p += 2;
344                 } else if (*p == 'I') {
345                         *pflags |= SEC_ACE_FLAG_INHERITED_ACE;
346                         p += 1;
347                 } else if (*p) {
348                         return false;
349                 }
350
351                 if (*p != '|' && *p != '\0') {
352                         return false;
353                 }
354         }
355         return true;
356 }
357
358 /* parse an ACE in the same format as print_ace() */
359 static bool parse_ace(struct cli_state *cli, SEC_ACE *ace,
360                       const char *orig_str)
361 {
362         char *p;
363         const char *cp;
364         char *tok;
365         unsigned int atype = 0;
366         unsigned int aflags = 0;
367         unsigned int amask = 0;
368         DOM_SID sid;
369         uint32_t mask;
370         const struct perm_value *v;
371         char *str = SMB_STRDUP(orig_str);
372         TALLOC_CTX *frame = talloc_stackframe();
373
374         if (!str) {
375                 TALLOC_FREE(frame);
376                 return False;
377         }
378
379         ZERO_STRUCTP(ace);
380         p = strchr_m(str,':');
381         if (!p) {
382                 printf("ACE '%s': missing ':'.\n", orig_str);
383                 SAFE_FREE(str);
384                 TALLOC_FREE(frame);
385                 return False;
386         }
387         *p = '\0';
388         p++;
389         /* Try to parse numeric form */
390
391         if (sscanf(p, "%i/%i/%i", &atype, &aflags, &amask) == 3 &&
392             StringToSid(cli, &sid, str)) {
393                 goto done;
394         }
395
396         /* Try to parse text form */
397
398         if (!StringToSid(cli, &sid, str)) {
399                 printf("ACE '%s': failed to convert '%s' to SID\n",
400                         orig_str, str);
401                 SAFE_FREE(str);
402                 TALLOC_FREE(frame);
403                 return False;
404         }
405
406         cp = p;
407         if (!next_token_talloc(frame, &cp, &tok, "/")) {
408                 printf("ACE '%s': failed to find '/' character.\n",
409                         orig_str);
410                 SAFE_FREE(str);
411                 TALLOC_FREE(frame);
412                 return False;
413         }
414
415         if (strncmp(tok, "ALLOWED", strlen("ALLOWED")) == 0) {
416                 atype = SEC_ACE_TYPE_ACCESS_ALLOWED;
417         } else if (strncmp(tok, "DENIED", strlen("DENIED")) == 0) {
418                 atype = SEC_ACE_TYPE_ACCESS_DENIED;
419         } else {
420                 printf("ACE '%s': missing 'ALLOWED' or 'DENIED' entry at '%s'\n",
421                         orig_str, tok);
422                 SAFE_FREE(str);
423                 TALLOC_FREE(frame);
424                 return False;
425         }
426
427         /* Only numeric form accepted for flags at present */
428
429         if (!next_token_talloc(frame, &cp, &tok, "/")) {
430                 printf("ACE '%s': bad flags entry at '%s'\n",
431                         orig_str, tok);
432                 SAFE_FREE(str);
433                 TALLOC_FREE(frame);
434                 return False;
435         }
436
437         if (tok[0] < '0' || tok[0] > '9') {
438                 if (!parse_ace_flags(tok, &aflags)) {
439                         printf("ACE '%s': bad named flags entry at '%s'\n",
440                                 orig_str, tok);
441                         SAFE_FREE(str);
442                         TALLOC_FREE(frame);
443                         return False;
444                 }
445         } else if (strnequal(tok, "0x", 2)) {
446                 if (!sscanf(tok, "%x", &aflags)) {
447                         printf("ACE '%s': bad hex flags entry at '%s'\n",
448                                 orig_str, tok);
449                         SAFE_FREE(str);
450                         TALLOC_FREE(frame);
451                         return False;
452                 }
453         } else {
454                 if (!sscanf(tok, "%i", &aflags)) {
455                         printf("ACE '%s': bad integer flags entry at '%s'\n",
456                                 orig_str, tok);
457                         SAFE_FREE(str);
458                         TALLOC_FREE(frame);
459                         return False;
460                 }
461         }
462
463         if (!next_token_talloc(frame, &cp, &tok, "/")) {
464                 printf("ACE '%s': missing / at '%s'\n",
465                         orig_str, tok);
466                 SAFE_FREE(str);
467                 TALLOC_FREE(frame);
468                 return False;
469         }
470
471         if (strncmp(tok, "0x", 2) == 0) {
472                 if (sscanf(tok, "%i", &amask) != 1) {
473                         printf("ACE '%s': bad hex number at '%s'\n",
474                                 orig_str, tok);
475                         SAFE_FREE(str);
476                         TALLOC_FREE(frame);
477                         return False;
478                 }
479                 goto done;
480         }
481
482         for (v = standard_values; v->perm; v++) {
483                 if (strcmp(tok, v->perm) == 0) {
484                         amask = v->mask;
485                         goto done;
486                 }
487         }
488
489         p = tok;
490
491         while(*p) {
492                 bool found = False;
493
494                 for (v = special_values; v->perm; v++) {
495                         if (v->perm[0] == *p) {
496                                 amask |= v->mask;
497                                 found = True;
498                         }
499                 }
500
501                 if (!found) {
502                         printf("ACE '%s': bad permission value at '%s'\n",
503                                 orig_str, p);
504                         SAFE_FREE(str);
505                         TALLOC_FREE(frame);
506                         return False;
507                 }
508                 p++;
509         }
510
511         if (*p) {
512                 TALLOC_FREE(frame);
513                 SAFE_FREE(str);
514                 return False;
515         }
516
517  done:
518         mask = amask;
519         init_sec_ace(ace, &sid, atype, mask, aflags);
520         TALLOC_FREE(frame);
521         SAFE_FREE(str);
522         return True;
523 }
524
525 /* add an ACE to a list of ACEs in a SEC_ACL */
526 static bool add_ace(SEC_ACL **the_acl, SEC_ACE *ace)
527 {
528         SEC_ACL *new_ace;
529         SEC_ACE *aces;
530         if (! *the_acl) {
531                 return (((*the_acl) = make_sec_acl(talloc_tos(), 3, 1, ace))
532                         != NULL);
533         }
534
535         if (!(aces = SMB_CALLOC_ARRAY(SEC_ACE, 1+(*the_acl)->num_aces))) {
536                 return False;
537         }
538         memcpy(aces, (*the_acl)->aces, (*the_acl)->num_aces * sizeof(SEC_ACE));
539         memcpy(aces+(*the_acl)->num_aces, ace, sizeof(SEC_ACE));
540         new_ace = make_sec_acl(talloc_tos(),(*the_acl)->revision,1+(*the_acl)->num_aces, aces);
541         SAFE_FREE(aces);
542         (*the_acl) = new_ace;
543         return True;
544 }
545
546 /* parse a ascii version of a security descriptor */
547 static SEC_DESC *sec_desc_parse(TALLOC_CTX *ctx, struct cli_state *cli, char *str)
548 {
549         const char *p = str;
550         char *tok;
551         SEC_DESC *ret = NULL;
552         size_t sd_size;
553         DOM_SID *grp_sid=NULL, *owner_sid=NULL;
554         SEC_ACL *dacl=NULL;
555         int revision=1;
556
557         while (next_token_talloc(ctx, &p, &tok, "\t,\r\n")) {
558                 if (strncmp(tok,"REVISION:", 9) == 0) {
559                         revision = strtol(tok+9, NULL, 16);
560                         continue;
561                 }
562
563                 if (strncmp(tok,"OWNER:", 6) == 0) {
564                         if (owner_sid) {
565                                 printf("Only specify owner once\n");
566                                 goto done;
567                         }
568                         owner_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
569                         if (!owner_sid ||
570                             !StringToSid(cli, owner_sid, tok+6)) {
571                                 printf("Failed to parse owner sid\n");
572                                 goto done;
573                         }
574                         continue;
575                 }
576
577                 if (strncmp(tok,"GROUP:", 6) == 0) {
578                         if (grp_sid) {
579                                 printf("Only specify group once\n");
580                                 goto done;
581                         }
582                         grp_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
583                         if (!grp_sid ||
584                             !StringToSid(cli, grp_sid, tok+6)) {
585                                 printf("Failed to parse group sid\n");
586                                 goto done;
587                         }
588                         continue;
589                 }
590
591                 if (strncmp(tok,"ACL:", 4) == 0) {
592                         SEC_ACE ace;
593                         if (!parse_ace(cli, &ace, tok+4)) {
594                                 goto done;
595                         }
596                         if(!add_ace(&dacl, &ace)) {
597                                 printf("Failed to add ACL %s\n", tok);
598                                 goto done;
599                         }
600                         continue;
601                 }
602
603                 printf("Failed to parse token '%s' in security descriptor,\n", tok);
604                 goto done;
605         }
606
607         ret = make_sec_desc(ctx,revision, SEC_DESC_SELF_RELATIVE, owner_sid, grp_sid,
608                             NULL, dacl, &sd_size);
609
610   done:
611         SAFE_FREE(grp_sid);
612         SAFE_FREE(owner_sid);
613
614         return ret;
615 }
616
617
618 /* print a ascii version of a security descriptor on a FILE handle */
619 static void sec_desc_print(struct cli_state *cli, FILE *f, SEC_DESC *sd)
620 {
621         fstring sidstr;
622         uint32 i;
623
624         fprintf(f, "REVISION:%d\n", sd->revision);
625         fprintf(f, "CONTROL:0x%x\n", sd->type);
626
627         /* Print owner and group sid */
628
629         if (sd->owner_sid) {
630                 SidToString(cli, sidstr, sd->owner_sid);
631         } else {
632                 fstrcpy(sidstr, "");
633         }
634
635         fprintf(f, "OWNER:%s\n", sidstr);
636
637         if (sd->group_sid) {
638                 SidToString(cli, sidstr, sd->group_sid);
639         } else {
640                 fstrcpy(sidstr, "");
641         }
642
643         fprintf(f, "GROUP:%s\n", sidstr);
644
645         /* Print aces */
646         for (i = 0; sd->dacl && i < sd->dacl->num_aces; i++) {
647                 SEC_ACE *ace = &sd->dacl->aces[i];
648                 fprintf(f, "ACL:");
649                 print_ace(cli, f, ace);
650                 fprintf(f, "\n");
651         }
652
653 }
654
655 /***************************************************** 
656 dump the acls for a file
657 *******************************************************/
658 static int cacl_dump(struct cli_state *cli, char *filename)
659 {
660         int result = EXIT_FAILED;
661         int fnum = -1;
662         SEC_DESC *sd;
663
664         if (test_args) 
665                 return EXIT_OK;
666
667         fnum = cli_nt_create(cli, filename, CREATE_ACCESS_READ);
668
669         if (fnum == -1) {
670                 printf("Failed to open %s: %s\n", filename, cli_errstr(cli));
671                 goto done;
672         }
673
674         sd = cli_query_secdesc(cli, fnum, talloc_tos());
675
676         if (!sd) {
677                 printf("ERROR: secdesc query failed: %s\n", cli_errstr(cli));
678                 goto done;
679         }
680
681         sec_desc_print(cli, stdout, sd);
682
683         result = EXIT_OK;
684
685 done:
686         if (fnum != -1)
687                 cli_close(cli, fnum);
688
689         return result;
690 }
691
692 /***************************************************** 
693 Change the ownership or group ownership of a file. Just
694 because the NT docs say this can't be done :-). JRA.
695 *******************************************************/
696
697 static int owner_set(struct cli_state *cli, enum chown_mode change_mode, 
698                         const char *filename, const char *new_username)
699 {
700         int fnum;
701         DOM_SID sid;
702         SEC_DESC *sd, *old;
703         size_t sd_size;
704
705         fnum = cli_nt_create(cli, filename, CREATE_ACCESS_READ);
706
707         if (fnum == -1) {
708                 printf("Failed to open %s: %s\n", filename, cli_errstr(cli));
709                 return EXIT_FAILED;
710         }
711
712         if (!StringToSid(cli, &sid, new_username))
713                 return EXIT_PARSE_ERROR;
714
715         old = cli_query_secdesc(cli, fnum, talloc_tos());
716
717         cli_close(cli, fnum);
718
719         if (!old) {
720                 printf("owner_set: Failed to query old descriptor\n");
721                 return EXIT_FAILED;
722         }
723
724         sd = make_sec_desc(talloc_tos(),old->revision, old->type,
725                                 (change_mode == REQUEST_CHOWN) ? &sid : NULL,
726                                 (change_mode == REQUEST_CHGRP) ? &sid : NULL,
727                            NULL, NULL, &sd_size);
728
729         fnum = cli_nt_create(cli, filename, WRITE_OWNER_ACCESS);
730
731         if (fnum == -1) {
732                 printf("Failed to open %s: %s\n", filename, cli_errstr(cli));
733                 return EXIT_FAILED;
734         }
735
736         if (!cli_set_secdesc(cli, fnum, sd)) {
737                 printf("ERROR: secdesc set failed: %s\n", cli_errstr(cli));
738                 cli_close(cli, fnum);
739                 return EXIT_FAILED;
740         }
741
742         cli_close(cli, fnum);
743
744         return EXIT_OK;
745 }
746
747
748 /* The MSDN is contradictory over the ordering of ACE entries in an
749    ACL.  However NT4 gives a "The information may have been modified
750    by a computer running Windows NT 5.0" if denied ACEs do not appear
751    before allowed ACEs. At
752    http://technet.microsoft.com/en-us/library/cc781716.aspx the
753    canonical order is specified as "Explicit Deny, Explicit Allow,
754    Inherited ACEs unchanged" */
755
756 static int ace_compare(SEC_ACE *ace1, SEC_ACE *ace2)
757 {
758         if (sec_ace_equal(ace1, ace2))
759                 return 0;
760
761         if ((ace1->flags & SEC_ACE_FLAG_INHERITED_ACE) &&
762                         !(ace2->flags & SEC_ACE_FLAG_INHERITED_ACE))
763                 return 1;
764         if (!(ace1->flags & SEC_ACE_FLAG_INHERITED_ACE) &&
765                         (ace2->flags & SEC_ACE_FLAG_INHERITED_ACE))
766                 return -1;
767         if ((ace1->flags & SEC_ACE_FLAG_INHERITED_ACE) &&
768                         (ace2->flags & SEC_ACE_FLAG_INHERITED_ACE))
769                 return ace1 - ace2;
770
771         if (ace1->type != ace2->type)
772                 return ace2->type - ace1->type;
773
774         if (sid_compare(&ace1->trustee, &ace2->trustee))
775                 return sid_compare(&ace1->trustee, &ace2->trustee);
776
777         if (ace1->flags != ace2->flags)
778                 return ace1->flags - ace2->flags;
779
780         if (ace1->access_mask != ace2->access_mask)
781                 return ace1->access_mask - ace2->access_mask;
782
783         if (ace1->size != ace2->size)
784                 return ace1->size - ace2->size;
785
786         return memcmp(ace1, ace2, sizeof(SEC_ACE));
787 }
788
789 static void sort_acl(SEC_ACL *the_acl)
790 {
791         uint32 i;
792         if (!the_acl) return;
793
794         qsort(the_acl->aces, the_acl->num_aces, sizeof(the_acl->aces[0]), QSORT_CAST ace_compare);
795
796         for (i=1;i<the_acl->num_aces;) {
797                 if (sec_ace_equal(&the_acl->aces[i-1], &the_acl->aces[i])) {
798                         int j;
799                         for (j=i; j<the_acl->num_aces-1; j++) {
800                                 the_acl->aces[j] = the_acl->aces[j+1];
801                         }
802                         the_acl->num_aces--;
803                 } else {
804                         i++;
805                 }
806         }
807 }
808
809 /***************************************************** 
810 set the ACLs on a file given an ascii description
811 *******************************************************/
812
813 static int cacl_set(struct cli_state *cli, char *filename, 
814                     char *the_acl, enum acl_mode mode)
815 {
816         int fnum;
817         SEC_DESC *sd, *old;
818         uint32 i, j;
819         size_t sd_size;
820         int result = EXIT_OK;
821
822         sd = sec_desc_parse(talloc_tos(), cli, the_acl);
823
824         if (!sd) return EXIT_PARSE_ERROR;
825         if (test_args) return EXIT_OK;
826
827         /* The desired access below is the only one I could find that works
828            with NT4, W2KP and Samba */
829
830         fnum = cli_nt_create(cli, filename, CREATE_ACCESS_READ);
831
832         if (fnum == -1) {
833                 printf("cacl_set failed to open %s: %s\n", filename, cli_errstr(cli));
834                 return EXIT_FAILED;
835         }
836
837         old = cli_query_secdesc(cli, fnum, talloc_tos());
838
839         if (!old) {
840                 printf("calc_set: Failed to query old descriptor\n");
841                 return EXIT_FAILED;
842         }
843
844         cli_close(cli, fnum);
845
846         /* the logic here is rather more complex than I would like */
847         switch (mode) {
848         case SMB_ACL_DELETE:
849                 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
850                         bool found = False;
851
852                         for (j=0;old->dacl && j<old->dacl->num_aces;j++) {
853                                 if (sec_ace_equal(&sd->dacl->aces[i],
854                                                   &old->dacl->aces[j])) {
855                                         uint32 k;
856                                         for (k=j; k<old->dacl->num_aces-1;k++) {
857                                                 old->dacl->aces[k] = old->dacl->aces[k+1];
858                                         }
859                                         old->dacl->num_aces--;
860                                         found = True;
861                                         break;
862                                 }
863                         }
864
865                         if (!found) {
866                                 printf("ACL for ACE:");
867                                 print_ace(cli, stdout, &sd->dacl->aces[i]);
868                                 printf(" not found\n");
869                         }
870                 }
871                 break;
872
873         case SMB_ACL_MODIFY:
874                 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
875                         bool found = False;
876
877                         for (j=0;old->dacl && j<old->dacl->num_aces;j++) {
878                                 if (sid_equal(&sd->dacl->aces[i].trustee,
879                                               &old->dacl->aces[j].trustee)) {
880                                         old->dacl->aces[j] = sd->dacl->aces[i];
881                                         found = True;
882                                 }
883                         }
884
885                         if (!found) {
886                                 fstring str;
887
888                                 SidToString(cli, str,
889                                             &sd->dacl->aces[i].trustee);
890                                 printf("ACL for SID %s not found\n", str);
891                         }
892                 }
893
894                 if (sd->owner_sid) {
895                         old->owner_sid = sd->owner_sid;
896                 }
897
898                 if (sd->group_sid) {
899                         old->group_sid = sd->group_sid;
900                 }
901
902                 break;
903
904         case SMB_ACL_ADD:
905                 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
906                         add_ace(&old->dacl, &sd->dacl->aces[i]);
907                 }
908                 break;
909
910         case SMB_ACL_SET:
911                 old = sd;
912                 break;
913         }
914
915         /* Denied ACE entries must come before allowed ones */
916         sort_acl(old->dacl);
917
918         /* Create new security descriptor and set it */
919
920         /* We used to just have "WRITE_DAC_ACCESS" without WRITE_OWNER.
921            But if we're sending an owner, even if it's the same as the one
922            that already exists then W2K3 insists we open with WRITE_OWNER access.
923            I need to check that setting a SD with no owner set works against WNT
924            and W2K. JRA.
925         */
926
927         sd = make_sec_desc(talloc_tos(),old->revision, old->type,
928                            old->owner_sid, old->group_sid,
929                            NULL, old->dacl, &sd_size);
930
931         fnum = cli_nt_create(cli, filename, WRITE_DAC_ACCESS|WRITE_OWNER_ACCESS);
932
933         if (fnum == -1) {
934                 printf("cacl_set failed to open %s: %s\n", filename, cli_errstr(cli));
935                 return EXIT_FAILED;
936         }
937
938         if (!cli_set_secdesc(cli, fnum, sd)) {
939                 printf("ERROR: secdesc set failed: %s\n", cli_errstr(cli));
940                 result = EXIT_FAILED;
941         }
942
943         /* Clean up */
944
945         cli_close(cli, fnum);
946
947         return result;
948 }
949
950
951 /*****************************************************
952  Return a connection to a server.
953 *******************************************************/
954 static struct cli_state *connect_one(const char *server, const char *share)
955 {
956         struct cli_state *c = NULL;
957         struct sockaddr_storage ss;
958         NTSTATUS nt_status;
959         uint32_t flags = 0;
960
961         zero_sockaddr(&ss);
962
963         if (get_cmdline_auth_info_use_kerberos()) {
964                 flags |= CLI_FULL_CONNECTION_USE_KERBEROS |
965                          CLI_FULL_CONNECTION_FALLBACK_AFTER_KERBEROS;
966         }
967
968         if (get_cmdline_auth_info_use_machine_account() &&
969             !set_cmdline_auth_info_machine_account_creds()) {
970                 return NULL;
971         }
972
973         if (!get_cmdline_auth_info_got_pass()) {
974                 char *pass = getpass("Password: ");
975                 if (pass) {
976                         set_cmdline_auth_info_password(pass);
977                 }
978         }
979
980         nt_status = cli_full_connection(&c, global_myname(), server, 
981                                 &ss, 0,
982                                 share, "?????",
983                                 get_cmdline_auth_info_username(),
984                                 lp_workgroup(),
985                                 get_cmdline_auth_info_password(),
986                                 flags,
987                                 get_cmdline_auth_info_signing_state(),
988                                 NULL);
989         if (!NT_STATUS_IS_OK(nt_status)) {
990                 DEBUG(0,("cli_full_connection failed! (%s)\n", nt_errstr(nt_status)));
991                 return NULL;
992         }
993
994         if (get_cmdline_auth_info_smb_encrypt()) {
995                 nt_status = cli_cm_force_encryption(c,
996                                         get_cmdline_auth_info_username(),
997                                         get_cmdline_auth_info_password(),
998                                         lp_workgroup(),
999                                         share);
1000                 if (!NT_STATUS_IS_OK(nt_status)) {
1001                         cli_shutdown(c);
1002                         c = NULL;
1003                 }
1004         }
1005
1006         return c;
1007 }
1008
1009 /****************************************************************************
1010   main program
1011 ****************************************************************************/
1012  int main(int argc, const char *argv[])
1013 {
1014         char *share;
1015         int opt;
1016         enum acl_mode mode = SMB_ACL_SET;
1017         static char *the_acl = NULL;
1018         enum chown_mode change_mode = REQUEST_NONE;
1019         int result;
1020         char *path;
1021         char *filename = NULL;
1022         poptContext pc;
1023         struct poptOption long_options[] = {
1024                 POPT_AUTOHELP
1025                 { "delete", 'D', POPT_ARG_STRING, NULL, 'D', "Delete an acl", "ACL" },
1026                 { "modify", 'M', POPT_ARG_STRING, NULL, 'M', "Modify an acl", "ACL" },
1027                 { "add", 'a', POPT_ARG_STRING, NULL, 'a', "Add an acl", "ACL" },
1028                 { "set", 'S', POPT_ARG_STRING, NULL, 'S', "Set acls", "ACLS" },
1029                 { "chown", 'C', POPT_ARG_STRING, NULL, 'C', "Change ownership of a file", "USERNAME" },
1030                 { "chgrp", 'G', POPT_ARG_STRING, NULL, 'G', "Change group ownership of a file", "GROUPNAME" },
1031                 { "numeric", 0, POPT_ARG_NONE, &numeric, 1, "Don't resolve sids or masks to names" },
1032                 { "test-args", 't', POPT_ARG_NONE, &test_args, 1, "Test arguments"},
1033                 POPT_COMMON_SAMBA
1034                 POPT_COMMON_CONNECTION
1035                 POPT_COMMON_CREDENTIALS
1036                 POPT_TABLEEND
1037         };
1038
1039         struct cli_state *cli;
1040         TALLOC_CTX *frame = talloc_stackframe();
1041         const char *owner_username = "";
1042         char *server;
1043
1044         load_case_tables();
1045
1046
1047         /* set default debug level to 1 regardless of what smb.conf sets */
1048         setup_logging( "smbcacls", True );
1049         DEBUGLEVEL_CLASS[DBGC_ALL] = 1;
1050         dbf = x_stderr;
1051         x_setbuf( x_stderr, NULL );
1052
1053         setlinebuf(stdout);
1054
1055         lp_load(get_dyn_CONFIGFILE(),True,False,False,True);
1056         load_interfaces();
1057
1058         pc = poptGetContext("smbcacls", argc, argv, long_options, 0);
1059
1060         poptSetOtherOptionHelp(pc, "//server1/share1 filename\nACLs look like: "
1061                 "'ACL:user:[ALLOWED|DENIED]/flags/permissions'");
1062
1063         while ((opt = poptGetNextOpt(pc)) != -1) {
1064                 switch (opt) {
1065                 case 'S':
1066                         the_acl = smb_xstrdup(poptGetOptArg(pc));
1067                         mode = SMB_ACL_SET;
1068                         break;
1069
1070                 case 'D':
1071                         the_acl = smb_xstrdup(poptGetOptArg(pc));
1072                         mode = SMB_ACL_DELETE;
1073                         break;
1074
1075                 case 'M':
1076                         the_acl = smb_xstrdup(poptGetOptArg(pc));
1077                         mode = SMB_ACL_MODIFY;
1078                         break;
1079
1080                 case 'a':
1081                         the_acl = smb_xstrdup(poptGetOptArg(pc));
1082                         mode = SMB_ACL_ADD;
1083                         break;
1084
1085                 case 'C':
1086                         owner_username = poptGetOptArg(pc);
1087                         change_mode = REQUEST_CHOWN;
1088                         break;
1089
1090                 case 'G':
1091                         owner_username = poptGetOptArg(pc);
1092                         change_mode = REQUEST_CHGRP;
1093                         break;
1094                 }
1095         }
1096
1097         /* Make connection to server */
1098         if(!poptPeekArg(pc)) {
1099                 poptPrintUsage(pc, stderr, 0);
1100                 return -1;
1101         }
1102
1103         path = talloc_strdup(frame, poptGetArg(pc));
1104         if (!path) {
1105                 return -1;
1106         }
1107
1108         if(!poptPeekArg(pc)) {
1109                 poptPrintUsage(pc, stderr, 0);
1110                 return -1;
1111         }
1112
1113         filename = talloc_strdup(frame, poptGetArg(pc));
1114         if (!filename) {
1115                 return -1;
1116         }
1117
1118         string_replace(path,'/','\\');
1119
1120         server = talloc_strdup(frame, path+2);
1121         if (!server) {
1122                 return -1;
1123         }
1124         share = strchr_m(server,'\\');
1125         if (!share) {
1126                 printf("Invalid argument: %s\n", share);
1127                 return -1;
1128         }
1129
1130         *share = 0;
1131         share++;
1132
1133         if (!test_args) {
1134                 cli = connect_one(server, share);
1135                 if (!cli) {
1136                         exit(EXIT_FAILED);
1137                 }
1138         } else {
1139                 exit(0);
1140         }
1141
1142         string_replace(filename, '/', '\\');
1143         if (filename[0] != '\\') {
1144                 filename = talloc_asprintf(frame,
1145                                 "\\%s",
1146                                 filename);
1147                 if (!filename) {
1148                         return -1;
1149                 }
1150         }
1151
1152         /* Perform requested action */
1153
1154         if (change_mode != REQUEST_NONE) {
1155                 result = owner_set(cli, change_mode, filename, owner_username);
1156         } else if (the_acl) {
1157                 result = cacl_set(cli, filename, the_acl, mode);
1158         } else {
1159                 result = cacl_dump(cli, filename);
1160         }
1161
1162         TALLOC_FREE(frame);
1163
1164         return result;
1165 }