s3-rpc_client: Move client pipe functions to own header.
[samba.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 "rpc_client/cli_pipe.h"
27 #include "../librpc/gen_ndr/ndr_lsa.h"
28 #include "rpc_client/cli_lsarpc.h"
29 #include "../libcli/security/security.h"
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 (string_to_sid(sid, str)) {
205                 return true;
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 = 0;
672         NTSTATUS status;
673
674         /* The desired access below is the only one I could find that works
675            with NT4, W2KP and Samba */
676
677         status = cli_ntcreate(cli, filename, 0, CREATE_ACCESS_READ,
678                               0, FILE_SHARE_READ|FILE_SHARE_WRITE,
679                               FILE_OPEN, 0x0, 0x0, &fnum);
680         if (!NT_STATUS_IS_OK(status)) {
681                 printf("Failed to open %s: %s\n", filename, nt_errstr(status));
682                 return 0;
683         }
684
685         status = cli_qfileinfo_basic(cli, fnum, &mode, NULL, NULL, NULL,
686                                      NULL, NULL, NULL);
687         if (!NT_STATUS_IS_OK(status)) {
688                 printf("Failed to file info %s: %s\n", filename,
689                        nt_errstr(status));
690         }
691
692         cli_close(cli, fnum);
693
694         return mode;
695 }
696
697 /*****************************************************
698 get sec desc for filename
699 *******************************************************/
700 static struct security_descriptor *get_secdesc(struct cli_state *cli, const char *filename)
701 {
702         uint16_t fnum = (uint16_t)-1;
703         struct security_descriptor *sd;
704         NTSTATUS status;
705
706         /* The desired access below is the only one I could find that works
707            with NT4, W2KP and Samba */
708
709         status = cli_ntcreate(cli, filename, 0, CREATE_ACCESS_READ,
710                               0, FILE_SHARE_READ|FILE_SHARE_WRITE,
711                               FILE_OPEN, 0x0, 0x0, &fnum);
712         if (!NT_STATUS_IS_OK(status)) {
713                 printf("Failed to open %s: %s\n", filename, nt_errstr(status));
714                 return NULL;
715         }
716
717         sd = cli_query_secdesc(cli, fnum, talloc_tos());
718
719         cli_close(cli, fnum);
720
721         if (!sd) {
722                 printf("Failed to get security descriptor\n");
723                 return NULL;
724         }
725         return sd;
726 }
727
728 /*****************************************************
729 set sec desc for filename
730 *******************************************************/
731 static bool set_secdesc(struct cli_state *cli, const char *filename,
732                         struct security_descriptor *sd)
733 {
734         uint16_t fnum = (uint16_t)-1;
735         bool result=true;
736         NTSTATUS status;
737
738         /* The desired access below is the only one I could find that works
739            with NT4, W2KP and Samba */
740
741         status = cli_ntcreate(cli, filename, 0,
742                               WRITE_DAC_ACCESS|WRITE_OWNER_ACCESS,
743                               0, FILE_SHARE_READ|FILE_SHARE_WRITE,
744                               FILE_OPEN, 0x0, 0x0, &fnum);
745         if (!NT_STATUS_IS_OK(status)) {
746                 printf("Failed to open %s: %s\n", filename, nt_errstr(status));
747                 return false;
748         }
749
750         status = cli_set_secdesc(cli, fnum, sd);
751         if (!NT_STATUS_IS_OK(status)) {
752                 printf("ERROR: security description set failed: %s\n",
753                        nt_errstr(status));
754                 result=false;
755         }
756
757         cli_close(cli, fnum);
758         return result;
759 }
760
761 /*****************************************************
762 dump the acls for a file
763 *******************************************************/
764 static int cacl_dump(struct cli_state *cli, const char *filename)
765 {
766         int result = EXIT_FAILED;
767         struct security_descriptor *sd;
768
769         if (test_args)
770                 return EXIT_OK;
771
772         sd = get_secdesc(cli, filename);
773
774         if (sd) {
775                 if (sddl) {
776                         printf("%s\n", sddl_encode(talloc_tos(), sd,
777                                            get_global_sam_sid()));
778                 } else {
779                         sec_desc_print(cli, stdout, sd);
780                 }
781                 result = EXIT_OK;
782         }
783
784         return result;
785 }
786
787 /***************************************************** 
788 Change the ownership or group ownership of a file. Just
789 because the NT docs say this can't be done :-). JRA.
790 *******************************************************/
791
792 static int owner_set(struct cli_state *cli, enum chown_mode change_mode, 
793                         const char *filename, const char *new_username)
794 {
795         struct dom_sid sid;
796         struct security_descriptor *sd, *old;
797         size_t sd_size;
798
799         if (!StringToSid(cli, &sid, new_username))
800                 return EXIT_PARSE_ERROR;
801
802         old = get_secdesc(cli, filename);
803
804         if (!old) {
805                 return EXIT_FAILED;
806         }
807
808         sd = make_sec_desc(talloc_tos(),old->revision, old->type,
809                                 (change_mode == REQUEST_CHOWN) ? &sid : NULL,
810                                 (change_mode == REQUEST_CHGRP) ? &sid : NULL,
811                            NULL, NULL, &sd_size);
812
813         if (!set_secdesc(cli, filename, sd)) {
814                 return EXIT_FAILED;
815         }
816
817         return EXIT_OK;
818 }
819
820
821 /* The MSDN is contradictory over the ordering of ACE entries in an
822    ACL.  However NT4 gives a "The information may have been modified
823    by a computer running Windows NT 5.0" if denied ACEs do not appear
824    before allowed ACEs. At
825    http://technet.microsoft.com/en-us/library/cc781716.aspx the
826    canonical order is specified as "Explicit Deny, Explicit Allow,
827    Inherited ACEs unchanged" */
828
829 static int ace_compare(struct security_ace *ace1, struct security_ace *ace2)
830 {
831         if (sec_ace_equal(ace1, ace2))
832                 return 0;
833
834         if ((ace1->flags & SEC_ACE_FLAG_INHERITED_ACE) &&
835                         !(ace2->flags & SEC_ACE_FLAG_INHERITED_ACE))
836                 return 1;
837         if (!(ace1->flags & SEC_ACE_FLAG_INHERITED_ACE) &&
838                         (ace2->flags & SEC_ACE_FLAG_INHERITED_ACE))
839                 return -1;
840         if ((ace1->flags & SEC_ACE_FLAG_INHERITED_ACE) &&
841                         (ace2->flags & SEC_ACE_FLAG_INHERITED_ACE))
842                 return ace1 - ace2;
843
844         if (ace1->type != ace2->type)
845                 return ace2->type - ace1->type;
846
847         if (dom_sid_compare(&ace1->trustee, &ace2->trustee))
848                 return dom_sid_compare(&ace1->trustee, &ace2->trustee);
849
850         if (ace1->flags != ace2->flags)
851                 return ace1->flags - ace2->flags;
852
853         if (ace1->access_mask != ace2->access_mask)
854                 return ace1->access_mask - ace2->access_mask;
855
856         if (ace1->size != ace2->size)
857                 return ace1->size - ace2->size;
858
859         return memcmp(ace1, ace2, sizeof(struct security_ace));
860 }
861
862 static void sort_acl(struct security_acl *the_acl)
863 {
864         uint32 i;
865         if (!the_acl) return;
866
867         TYPESAFE_QSORT(the_acl->aces, the_acl->num_aces, ace_compare);
868
869         for (i=1;i<the_acl->num_aces;) {
870                 if (sec_ace_equal(&the_acl->aces[i-1], &the_acl->aces[i])) {
871                         int j;
872                         for (j=i; j<the_acl->num_aces-1; j++) {
873                                 the_acl->aces[j] = the_acl->aces[j+1];
874                         }
875                         the_acl->num_aces--;
876                 } else {
877                         i++;
878                 }
879         }
880 }
881
882 /***************************************************** 
883 set the ACLs on a file given an ascii description
884 *******************************************************/
885
886 static int cacl_set(struct cli_state *cli, const char *filename,
887                     char *the_acl, enum acl_mode mode)
888 {
889         struct security_descriptor *sd, *old;
890         uint32 i, j;
891         size_t sd_size;
892         int result = EXIT_OK;
893
894         if (sddl) {
895                 sd = sddl_decode(talloc_tos(), the_acl, get_global_sam_sid());
896         } else {
897                 sd = sec_desc_parse(talloc_tos(), cli, the_acl);
898         }
899
900         if (!sd) return EXIT_PARSE_ERROR;
901         if (test_args) return EXIT_OK;
902
903         old = get_secdesc(cli, filename);
904
905         if (!old) {
906                 return EXIT_FAILED;
907         }
908
909         /* the logic here is rather more complex than I would like */
910         switch (mode) {
911         case SMB_ACL_DELETE:
912                 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
913                         bool found = False;
914
915                         for (j=0;old->dacl && j<old->dacl->num_aces;j++) {
916                                 if (sec_ace_equal(&sd->dacl->aces[i],
917                                                   &old->dacl->aces[j])) {
918                                         uint32 k;
919                                         for (k=j; k<old->dacl->num_aces-1;k++) {
920                                                 old->dacl->aces[k] = old->dacl->aces[k+1];
921                                         }
922                                         old->dacl->num_aces--;
923                                         found = True;
924                                         break;
925                                 }
926                         }
927
928                         if (!found) {
929                                 printf("ACL for ACE:");
930                                 print_ace(cli, stdout, &sd->dacl->aces[i]);
931                                 printf(" not found\n");
932                         }
933                 }
934                 break;
935
936         case SMB_ACL_MODIFY:
937                 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
938                         bool found = False;
939
940                         for (j=0;old->dacl && j<old->dacl->num_aces;j++) {
941                                 if (dom_sid_equal(&sd->dacl->aces[i].trustee,
942                                               &old->dacl->aces[j].trustee)) {
943                                         old->dacl->aces[j] = sd->dacl->aces[i];
944                                         found = True;
945                                 }
946                         }
947
948                         if (!found) {
949                                 fstring str;
950
951                                 SidToString(cli, str,
952                                             &sd->dacl->aces[i].trustee);
953                                 printf("ACL for SID %s not found\n", str);
954                         }
955                 }
956
957                 if (sd->owner_sid) {
958                         old->owner_sid = sd->owner_sid;
959                 }
960
961                 if (sd->group_sid) {
962                         old->group_sid = sd->group_sid;
963                 }
964
965                 break;
966
967         case SMB_ACL_ADD:
968                 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
969                         add_ace(&old->dacl, &sd->dacl->aces[i]);
970                 }
971                 break;
972
973         case SMB_ACL_SET:
974                 old = sd;
975                 break;
976         }
977
978         /* Denied ACE entries must come before allowed ones */
979         sort_acl(old->dacl);
980
981         /* Create new security descriptor and set it */
982
983         /* We used to just have "WRITE_DAC_ACCESS" without WRITE_OWNER.
984            But if we're sending an owner, even if it's the same as the one
985            that already exists then W2K3 insists we open with WRITE_OWNER access.
986            I need to check that setting a SD with no owner set works against WNT
987            and W2K. JRA.
988         */
989
990         sd = make_sec_desc(talloc_tos(),old->revision, old->type,
991                            old->owner_sid, old->group_sid,
992                            NULL, old->dacl, &sd_size);
993
994         if (!set_secdesc(cli, filename, sd)) {
995                 result = EXIT_FAILED;
996         }
997
998         return result;
999 }
1000
1001 /*****************************************************
1002 set the inherit on a file
1003 *******************************************************/
1004 static int inherit(struct cli_state *cli, const char *filename,
1005                    const char *type)
1006 {
1007         struct security_descriptor *old,*sd;
1008         uint32 oldattr;
1009         size_t sd_size;
1010         int result = EXIT_OK;
1011
1012         old = get_secdesc(cli, filename);
1013
1014         if (!old) {
1015                 return EXIT_FAILED;
1016         }
1017
1018         oldattr = get_fileinfo(cli,filename);
1019
1020         if (strcmp(type,"allow")==0) {
1021                 if ((old->type & SEC_DESC_DACL_PROTECTED) ==
1022                     SEC_DESC_DACL_PROTECTED) {
1023                         int i;
1024                         char *parentname,*temp;
1025                         struct security_descriptor *parent;
1026                         temp = talloc_strdup(talloc_tos(), filename);
1027
1028                         old->type=old->type & (~SEC_DESC_DACL_PROTECTED);
1029
1030                         /* look at parent and copy in all its inheritable ACL's. */
1031                         string_replace(temp, '\\', '/');
1032                         if (!parent_dirname(talloc_tos(),temp,&parentname,NULL)) {
1033                                 return EXIT_FAILED;
1034                         }
1035                         string_replace(parentname, '/', '\\');
1036                         parent = get_secdesc(cli,parentname);
1037                         for (i=0;i<parent->dacl->num_aces;i++) {
1038                                 struct security_ace *ace=&parent->dacl->aces[i];
1039                                 /* Add inherited flag to all aces */
1040                                 ace->flags=ace->flags|
1041                                            SEC_ACE_FLAG_INHERITED_ACE;
1042                                 if ((oldattr & aDIR) == aDIR) {
1043                                         if ((ace->flags & SEC_ACE_FLAG_CONTAINER_INHERIT) ==
1044                                             SEC_ACE_FLAG_CONTAINER_INHERIT) {
1045                                                 add_ace(&old->dacl, ace);
1046                                         }
1047                                 } else {
1048                                         if ((ace->flags & SEC_ACE_FLAG_OBJECT_INHERIT) ==
1049                                             SEC_ACE_FLAG_OBJECT_INHERIT) {
1050                                                 /* clear flags for files */
1051                                                 ace->flags=0;
1052                                                 add_ace(&old->dacl, ace);
1053                                         }
1054                                 }
1055                         }
1056                 } else {
1057                         printf("Already set to inheritable permissions.\n");
1058                         return EXIT_FAILED;
1059                 }
1060         } else if (strcmp(type,"remove")==0) {
1061                 if ((old->type & SEC_DESC_DACL_PROTECTED) !=
1062                     SEC_DESC_DACL_PROTECTED) {
1063                         old->type=old->type | SEC_DESC_DACL_PROTECTED;
1064
1065                         /* remove all inherited ACL's. */
1066                         if (old->dacl) {
1067                                 int i;
1068                                 struct security_acl *temp=old->dacl;
1069                                 old->dacl=make_sec_acl(talloc_tos(), 3, 0, NULL);
1070                                 for (i=temp->num_aces-1;i>=0;i--) {
1071                                         struct security_ace *ace=&temp->aces[i];
1072                                         /* Remove all ace with INHERITED flag set */
1073                                         if ((ace->flags & SEC_ACE_FLAG_INHERITED_ACE) !=
1074                                             SEC_ACE_FLAG_INHERITED_ACE) {
1075                                                 add_ace(&old->dacl,ace);
1076                                         }
1077                                 }
1078                         }
1079                 } else {
1080                         printf("Already set to no inheritable permissions.\n");
1081                         return EXIT_FAILED;
1082                 }
1083         } else if (strcmp(type,"copy")==0) {
1084                 if ((old->type & SEC_DESC_DACL_PROTECTED) !=
1085                     SEC_DESC_DACL_PROTECTED) {
1086                         old->type=old->type | SEC_DESC_DACL_PROTECTED;
1087
1088                         /* convert all inherited ACL's to non inherated ACL's. */
1089                         if (old->dacl) {
1090                                 int i;
1091                                 for (i=0;i<old->dacl->num_aces;i++) {
1092                                         struct security_ace *ace=&old->dacl->aces[i];
1093                                         /* Remove INHERITED FLAG from all aces */
1094                                         ace->flags=ace->flags&(~SEC_ACE_FLAG_INHERITED_ACE);
1095                                 }
1096                         }
1097                 } else {
1098                         printf("Already set to no inheritable permissions.\n");
1099                         return EXIT_FAILED;
1100                 }
1101         }
1102
1103         /* Denied ACE entries must come before allowed ones */
1104         sort_acl(old->dacl);
1105
1106         sd = make_sec_desc(talloc_tos(),old->revision, old->type,
1107                            old->owner_sid, old->group_sid,
1108                            NULL, old->dacl, &sd_size);
1109
1110         if (!set_secdesc(cli, filename, sd)) {
1111                 result = EXIT_FAILED;
1112         }
1113
1114         return result;
1115 }
1116
1117 /*****************************************************
1118  Return a connection to a server.
1119 *******************************************************/
1120 static struct cli_state *connect_one(struct user_auth_info *auth_info,
1121                                      const char *server, const char *share)
1122 {
1123         struct cli_state *c = NULL;
1124         struct sockaddr_storage ss;
1125         NTSTATUS nt_status;
1126         uint32_t flags = 0;
1127
1128         zero_sockaddr(&ss);
1129
1130         if (get_cmdline_auth_info_use_kerberos(auth_info)) {
1131                 flags |= CLI_FULL_CONNECTION_USE_KERBEROS |
1132                          CLI_FULL_CONNECTION_FALLBACK_AFTER_KERBEROS;
1133         }
1134
1135         if (get_cmdline_auth_info_use_machine_account(auth_info) &&
1136             !set_cmdline_auth_info_machine_account_creds(auth_info)) {
1137                 return NULL;
1138         }
1139
1140         set_cmdline_auth_info_getpass(auth_info);
1141
1142         nt_status = cli_full_connection(&c, global_myname(), server, 
1143                                 &ss, 0,
1144                                 share, "?????",
1145                                 get_cmdline_auth_info_username(auth_info),
1146                                 lp_workgroup(),
1147                                 get_cmdline_auth_info_password(auth_info),
1148                                 flags,
1149                                 get_cmdline_auth_info_signing_state(auth_info));
1150         if (!NT_STATUS_IS_OK(nt_status)) {
1151                 DEBUG(0,("cli_full_connection failed! (%s)\n", nt_errstr(nt_status)));
1152                 return NULL;
1153         }
1154
1155         if (get_cmdline_auth_info_smb_encrypt(auth_info)) {
1156                 nt_status = cli_cm_force_encryption(c,
1157                                         get_cmdline_auth_info_username(auth_info),
1158                                         get_cmdline_auth_info_password(auth_info),
1159                                         lp_workgroup(),
1160                                         share);
1161                 if (!NT_STATUS_IS_OK(nt_status)) {
1162                         cli_shutdown(c);
1163                         c = NULL;
1164                 }
1165         }
1166
1167         return c;
1168 }
1169
1170 /****************************************************************************
1171   main program
1172 ****************************************************************************/
1173  int main(int argc, const char *argv[])
1174 {
1175         char *share;
1176         int opt;
1177         enum acl_mode mode = SMB_ACL_SET;
1178         static char *the_acl = NULL;
1179         enum chown_mode change_mode = REQUEST_NONE;
1180         int result;
1181         char *path;
1182         char *filename = NULL;
1183         poptContext pc;
1184         struct poptOption long_options[] = {
1185                 POPT_AUTOHELP
1186                 { "delete", 'D', POPT_ARG_STRING, NULL, 'D', "Delete an acl", "ACL" },
1187                 { "modify", 'M', POPT_ARG_STRING, NULL, 'M', "Modify an acl", "ACL" },
1188                 { "add", 'a', POPT_ARG_STRING, NULL, 'a', "Add an acl", "ACL" },
1189                 { "set", 'S', POPT_ARG_STRING, NULL, 'S', "Set acls", "ACLS" },
1190                 { "chown", 'C', POPT_ARG_STRING, NULL, 'C', "Change ownership of a file", "USERNAME" },
1191                 { "chgrp", 'G', POPT_ARG_STRING, NULL, 'G', "Change group ownership of a file", "GROUPNAME" },
1192                 { "inherit", 'I', POPT_ARG_STRING, NULL, 'I', "Inherit allow|remove|copy" },
1193                 { "numeric", 0, POPT_ARG_NONE, &numeric, 1, "Don't resolve sids or masks to names" },
1194                 { "sddl", 0, POPT_ARG_NONE, &sddl, 1, "Output and input acls in sddl format" },
1195                 { "test-args", 't', POPT_ARG_NONE, &test_args, 1, "Test arguments"},
1196                 POPT_COMMON_SAMBA
1197                 POPT_COMMON_CONNECTION
1198                 POPT_COMMON_CREDENTIALS
1199                 POPT_TABLEEND
1200         };
1201
1202         struct cli_state *cli;
1203         TALLOC_CTX *frame = talloc_stackframe();
1204         const char *owner_username = "";
1205         char *server;
1206         struct user_auth_info *auth_info;
1207
1208         load_case_tables();
1209
1210         /* set default debug level to 1 regardless of what smb.conf sets */
1211         setup_logging( "smbcacls", DEBUG_STDERR);
1212         lp_set_cmdline("log level", "1");
1213
1214         setlinebuf(stdout);
1215
1216         lp_load(get_dyn_CONFIGFILE(),True,False,False,True);
1217         load_interfaces();
1218
1219         auth_info = user_auth_info_init(frame);
1220         if (auth_info == NULL) {
1221                 exit(1);
1222         }
1223         popt_common_set_auth_info(auth_info);
1224
1225         pc = poptGetContext("smbcacls", argc, argv, long_options, 0);
1226
1227         poptSetOtherOptionHelp(pc, "//server1/share1 filename\nACLs look like: "
1228                 "'ACL:user:[ALLOWED|DENIED]/flags/permissions'");
1229
1230         while ((opt = poptGetNextOpt(pc)) != -1) {
1231                 switch (opt) {
1232                 case 'S':
1233                         the_acl = smb_xstrdup(poptGetOptArg(pc));
1234                         mode = SMB_ACL_SET;
1235                         break;
1236
1237                 case 'D':
1238                         the_acl = smb_xstrdup(poptGetOptArg(pc));
1239                         mode = SMB_ACL_DELETE;
1240                         break;
1241
1242                 case 'M':
1243                         the_acl = smb_xstrdup(poptGetOptArg(pc));
1244                         mode = SMB_ACL_MODIFY;
1245                         break;
1246
1247                 case 'a':
1248                         the_acl = smb_xstrdup(poptGetOptArg(pc));
1249                         mode = SMB_ACL_ADD;
1250                         break;
1251
1252                 case 'C':
1253                         owner_username = poptGetOptArg(pc);
1254                         change_mode = REQUEST_CHOWN;
1255                         break;
1256
1257                 case 'G':
1258                         owner_username = poptGetOptArg(pc);
1259                         change_mode = REQUEST_CHGRP;
1260                         break;
1261
1262                 case 'I':
1263                         owner_username = poptGetOptArg(pc);
1264                         change_mode = REQUEST_INHERIT;
1265                         break;
1266                 }
1267         }
1268
1269         /* Make connection to server */
1270         if(!poptPeekArg(pc)) {
1271                 poptPrintUsage(pc, stderr, 0);
1272                 return -1;
1273         }
1274
1275         path = talloc_strdup(frame, poptGetArg(pc));
1276         if (!path) {
1277                 return -1;
1278         }
1279
1280         if(!poptPeekArg(pc)) {
1281                 poptPrintUsage(pc, stderr, 0);
1282                 return -1;
1283         }
1284
1285         filename = talloc_strdup(frame, poptGetArg(pc));
1286         if (!filename) {
1287                 return -1;
1288         }
1289
1290         string_replace(path,'/','\\');
1291
1292         server = talloc_strdup(frame, path+2);
1293         if (!server) {
1294                 return -1;
1295         }
1296         share = strchr_m(server,'\\');
1297         if (!share) {
1298                 printf("Invalid argument: %s\n", share);
1299                 return -1;
1300         }
1301
1302         *share = 0;
1303         share++;
1304
1305         if (!test_args) {
1306                 cli = connect_one(auth_info, server, share);
1307                 if (!cli) {
1308                         exit(EXIT_FAILED);
1309                 }
1310         } else {
1311                 exit(0);
1312         }
1313
1314         string_replace(filename, '/', '\\');
1315         if (filename[0] != '\\') {
1316                 filename = talloc_asprintf(frame,
1317                                 "\\%s",
1318                                 filename);
1319                 if (!filename) {
1320                         return -1;
1321                 }
1322         }
1323
1324         /* Perform requested action */
1325
1326         if (change_mode == REQUEST_INHERIT) {
1327                 result = inherit(cli, filename, owner_username);
1328         } else if (change_mode != REQUEST_NONE) {
1329                 result = owner_set(cli, change_mode, filename, owner_username);
1330         } else if (the_acl) {
1331                 result = cacl_set(cli, filename, the_acl, mode);
1332         } else {
1333                 result = cacl_dump(cli, filename);
1334         }
1335
1336         TALLOC_FREE(frame);
1337
1338         return result;
1339 }