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