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