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