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