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