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