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