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