smbcacls: Move print_ace and parse_ace to common file
[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 #include "util_sd.h"
35
36 static int test_args;
37
38 #define CREATE_ACCESS_READ READ_CONTROL_ACCESS
39
40 static int sddl;
41 static int query_sec_info = -1;
42 static int set_sec_info = -1;
43
44 static const char *domain_sid = NULL;
45
46 enum acl_mode {SMB_ACL_SET, SMB_ACL_DELETE, SMB_ACL_MODIFY, SMB_ACL_ADD };
47 enum chown_mode {REQUEST_NONE, REQUEST_CHOWN, REQUEST_CHGRP, REQUEST_INHERIT};
48 enum exit_values {EXIT_OK, EXIT_FAILED, EXIT_PARSE_ERROR};
49
50 static NTSTATUS cli_lsa_lookup_domain_sid(struct cli_state *cli,
51                                           struct dom_sid *sid)
52 {
53         union lsa_PolicyInformation *info = NULL;
54         uint16 orig_cnum = cli_state_get_tid(cli);
55         struct rpc_pipe_client *rpc_pipe = NULL;
56         struct policy_handle handle;
57         NTSTATUS status, result;
58         TALLOC_CTX *frame = talloc_stackframe();
59
60         status = cli_tree_connect(cli, "IPC$", "?????", "", 0);
61         if (!NT_STATUS_IS_OK(status)) {
62                 goto done;
63         }
64
65         status = cli_rpc_pipe_open_noauth(cli, &ndr_table_lsarpc, &rpc_pipe);
66         if (!NT_STATUS_IS_OK(status)) {
67                 goto tdis;
68         }
69
70         status = rpccli_lsa_open_policy(rpc_pipe, frame, True,
71                                         GENERIC_EXECUTE_ACCESS, &handle);
72         if (!NT_STATUS_IS_OK(status)) {
73                 goto tdis;
74         }
75
76         status = dcerpc_lsa_QueryInfoPolicy2(rpc_pipe->binding_handle,
77                                              frame, &handle,
78                                              LSA_POLICY_INFO_DOMAIN,
79                                              &info, &result);
80
81         if (any_nt_status_not_ok(status, result, &status)) {
82                 goto tdis;
83         }
84
85         *sid = *info->domain.sid;
86
87 tdis:
88         TALLOC_FREE(rpc_pipe);
89         cli_tdis(cli);
90 done:
91         cli_state_set_tid(cli, orig_cnum);
92         TALLOC_FREE(frame);
93         return status;
94 }
95
96 static struct dom_sid *get_domain_sid(struct cli_state *cli)
97 {
98         NTSTATUS status;
99
100         struct dom_sid *sid = talloc(talloc_tos(), struct dom_sid);
101         if (sid == NULL) {
102                 DEBUG(0, ("Out of memory\n"));
103                 return NULL;
104         }
105
106         if (domain_sid) {
107                 if (!dom_sid_parse(domain_sid, sid)) {
108                         DEBUG(0,("failed to parse domain sid\n"));
109                         TALLOC_FREE(sid);
110                 }
111         } else {
112                 status = cli_lsa_lookup_domain_sid(cli, sid);
113
114                 if (!NT_STATUS_IS_OK(status)) {
115                         DEBUG(0,("failed to lookup domain sid: %s\n", nt_errstr(status)));
116                         TALLOC_FREE(sid);
117                 }
118
119         }
120
121         DEBUG(2,("Domain SID: %s\n", sid_string_dbg(sid)));
122         return sid;
123 }
124
125 /* add an ACE to a list of ACEs in a struct security_acl */
126 static bool add_ace(struct security_acl **the_acl, struct security_ace *ace)
127 {
128         struct security_acl *new_ace;
129         struct security_ace *aces;
130         if (! *the_acl) {
131                 return (((*the_acl) = make_sec_acl(talloc_tos(), 3, 1, ace))
132                         != NULL);
133         }
134
135         if (!(aces = SMB_CALLOC_ARRAY(struct security_ace, 1+(*the_acl)->num_aces))) {
136                 return False;
137         }
138         memcpy(aces, (*the_acl)->aces, (*the_acl)->num_aces * sizeof(struct
139         security_ace));
140         memcpy(aces+(*the_acl)->num_aces, ace, sizeof(struct security_ace));
141         new_ace = make_sec_acl(talloc_tos(),(*the_acl)->revision,1+(*the_acl)->num_aces, aces);
142         SAFE_FREE(aces);
143         (*the_acl) = new_ace;
144         return True;
145 }
146
147 /* parse a ascii version of a security descriptor */
148 static struct security_descriptor *sec_desc_parse(TALLOC_CTX *ctx, struct cli_state *cli, char *str)
149 {
150         const char *p = str;
151         char *tok;
152         struct security_descriptor *ret = NULL;
153         size_t sd_size;
154         struct dom_sid *grp_sid=NULL, *owner_sid=NULL;
155         struct security_acl *dacl=NULL;
156         int revision=1;
157
158         while (next_token_talloc(ctx, &p, &tok, "\t,\r\n")) {
159                 if (strncmp(tok,"REVISION:", 9) == 0) {
160                         revision = strtol(tok+9, NULL, 16);
161                         continue;
162                 }
163
164                 if (strncmp(tok,"OWNER:", 6) == 0) {
165                         if (owner_sid) {
166                                 printf("Only specify owner once\n");
167                                 goto done;
168                         }
169                         owner_sid = SMB_CALLOC_ARRAY(struct dom_sid, 1);
170                         if (!owner_sid ||
171                             !StringToSid(cli, owner_sid, tok+6)) {
172                                 printf("Failed to parse owner sid\n");
173                                 goto done;
174                         }
175                         continue;
176                 }
177
178                 if (strncmp(tok,"GROUP:", 6) == 0) {
179                         if (grp_sid) {
180                                 printf("Only specify group once\n");
181                                 goto done;
182                         }
183                         grp_sid = SMB_CALLOC_ARRAY(struct dom_sid, 1);
184                         if (!grp_sid ||
185                             !StringToSid(cli, grp_sid, tok+6)) {
186                                 printf("Failed to parse group sid\n");
187                                 goto done;
188                         }
189                         continue;
190                 }
191
192                 if (strncmp(tok,"ACL:", 4) == 0) {
193                         struct security_ace ace;
194                         if (!parse_ace(cli, &ace, tok+4)) {
195                                 goto done;
196                         }
197                         if(!add_ace(&dacl, &ace)) {
198                                 printf("Failed to add ACL %s\n", tok);
199                                 goto done;
200                         }
201                         continue;
202                 }
203
204                 printf("Failed to parse token '%s' in security descriptor,\n", tok);
205                 goto done;
206         }
207
208         ret = make_sec_desc(ctx,revision, SEC_DESC_SELF_RELATIVE, owner_sid, grp_sid,
209                             NULL, dacl, &sd_size);
210
211   done:
212         SAFE_FREE(grp_sid);
213         SAFE_FREE(owner_sid);
214
215         return ret;
216 }
217
218 static const struct {
219         uint16_t mask;
220         const char *str;
221         const char *desc;
222 } sec_desc_ctrl_bits[] = {
223         {SEC_DESC_OWNER_DEFAULTED,       "OD", "Owner Defaulted"},
224         {SEC_DESC_GROUP_DEFAULTED,       "GD", "Group Defaulted"},
225         {SEC_DESC_DACL_PRESENT,          "DP", "DACL Present"},
226         {SEC_DESC_DACL_DEFAULTED,        "DD", "DACL Defaulted"},
227         {SEC_DESC_SACL_PRESENT,          "SP", "SACL Present"},
228         {SEC_DESC_SACL_DEFAULTED,        "SD", "SACL Defaulted"},
229         {SEC_DESC_DACL_TRUSTED,          "DT", "DACL Trusted"},
230         {SEC_DESC_SERVER_SECURITY,       "SS", "Server Security"},
231         {SEC_DESC_DACL_AUTO_INHERIT_REQ, "DR", "DACL Inheritance Required"},
232         {SEC_DESC_SACL_AUTO_INHERIT_REQ, "SR", "SACL Inheritance Required"},
233         {SEC_DESC_DACL_AUTO_INHERITED,   "DI", "DACL Auto Inherited"},
234         {SEC_DESC_SACL_AUTO_INHERITED,   "SI", "SACL Auto Inherited"},
235         {SEC_DESC_DACL_PROTECTED,        "PD", "DACL Protected"},
236         {SEC_DESC_SACL_PROTECTED,        "PS", "SACL Protected"},
237         {SEC_DESC_RM_CONTROL_VALID,      "RM", "RM Control Valid"},
238         {SEC_DESC_SELF_RELATIVE ,        "SR", "Self Relative"},
239 };
240
241 static void print_acl_ctrl(FILE *file, uint16_t ctrl, bool numeric)
242 {
243         int i;
244         const char* separator = "";
245
246         fprintf(file, "CONTROL:");
247         if (numeric) {
248                 fprintf(file, "0x%x\n", ctrl);
249                 return;
250         }
251
252         for (i = ARRAY_SIZE(sec_desc_ctrl_bits) - 1; i >= 0; i--) {
253                 if (ctrl & sec_desc_ctrl_bits[i].mask) {
254                         fprintf(file, "%s%s", separator, sec_desc_ctrl_bits[i].str);
255                         separator = "|";
256                 }
257         }
258         fputc('\n', file);
259 }
260
261 /* print a ascii version of a security descriptor on a FILE handle */
262 static void sec_desc_print(struct cli_state *cli, FILE *f,
263                            struct security_descriptor *sd, bool numeric)
264 {
265         fstring sidstr;
266         uint32 i;
267
268         fprintf(f, "REVISION:%d\n", sd->revision);
269         print_acl_ctrl(f, sd->type, numeric);
270
271         /* Print owner and group sid */
272
273         if (sd->owner_sid) {
274                 SidToString(cli, sidstr, sd->owner_sid, numeric);
275         } else {
276                 fstrcpy(sidstr, "");
277         }
278
279         fprintf(f, "OWNER:%s\n", sidstr);
280
281         if (sd->group_sid) {
282                 SidToString(cli, sidstr, sd->group_sid, numeric);
283         } else {
284                 fstrcpy(sidstr, "");
285         }
286
287         fprintf(f, "GROUP:%s\n", sidstr);
288
289         /* Print aces */
290         for (i = 0; sd->dacl && i < sd->dacl->num_aces; i++) {
291                 struct security_ace *ace = &sd->dacl->aces[i];
292                 fprintf(f, "ACL:");
293                 print_ace(cli, f, ace, numeric);
294                 fprintf(f, "\n");
295         }
296
297 }
298
299 /*****************************************************
300 get fileinfo for filename
301 *******************************************************/
302 static uint16 get_fileinfo(struct cli_state *cli, const char *filename)
303 {
304         uint16_t fnum = (uint16_t)-1;
305         uint16 mode = 0;
306         NTSTATUS status;
307
308         /* The desired access below is the only one I could find that works
309            with NT4, W2KP and Samba */
310
311         status = cli_ntcreate(cli, filename, 0, CREATE_ACCESS_READ,
312                               0, FILE_SHARE_READ|FILE_SHARE_WRITE,
313                               FILE_OPEN, 0x0, 0x0, &fnum, NULL);
314         if (!NT_STATUS_IS_OK(status)) {
315                 printf("Failed to open %s: %s\n", filename, nt_errstr(status));
316                 return 0;
317         }
318
319         status = cli_qfileinfo_basic(cli, fnum, &mode, NULL, NULL, NULL,
320                                      NULL, NULL, NULL);
321         if (!NT_STATUS_IS_OK(status)) {
322                 printf("Failed to file info %s: %s\n", filename,
323                        nt_errstr(status));
324         }
325
326         cli_close(cli, fnum);
327
328         return mode;
329 }
330
331 /*****************************************************
332 get sec desc for filename
333 *******************************************************/
334 static struct security_descriptor *get_secdesc(struct cli_state *cli, const char *filename)
335 {
336         uint16_t fnum = (uint16_t)-1;
337         struct security_descriptor *sd;
338         NTSTATUS status;
339         uint32_t sec_info;
340         uint32_t desired_access = 0;
341
342         if (query_sec_info == -1) {
343                 sec_info = SECINFO_OWNER | SECINFO_GROUP | SECINFO_DACL;
344         } else {
345                 sec_info = query_sec_info;
346         }
347
348         if (sec_info & (SECINFO_OWNER | SECINFO_GROUP | SECINFO_DACL)) {
349                 desired_access |= SEC_STD_READ_CONTROL;
350         }
351         if (sec_info & SECINFO_SACL) {
352                 desired_access |= SEC_FLAG_SYSTEM_SECURITY;
353         }
354
355         if (desired_access == 0) {
356                 desired_access |= SEC_STD_READ_CONTROL;
357         }
358
359         status = cli_ntcreate(cli, filename, 0, desired_access,
360                               0, FILE_SHARE_READ|FILE_SHARE_WRITE,
361                               FILE_OPEN, 0x0, 0x0, &fnum, NULL);
362         if (!NT_STATUS_IS_OK(status)) {
363                 printf("Failed to open %s: %s\n", filename, nt_errstr(status));
364                 return NULL;
365         }
366
367         status = cli_query_security_descriptor(cli, fnum, sec_info,
368                                                talloc_tos(), &sd);
369
370         cli_close(cli, fnum);
371
372         if (!NT_STATUS_IS_OK(status)) {
373                 printf("Failed to get security descriptor: %s\n",
374                        nt_errstr(status));
375                 return NULL;
376         }
377         return sd;
378 }
379
380 /*****************************************************
381 set sec desc for filename
382 *******************************************************/
383 static bool set_secdesc(struct cli_state *cli, const char *filename,
384                         struct security_descriptor *sd)
385 {
386         uint16_t fnum = (uint16_t)-1;
387         bool result=true;
388         NTSTATUS status;
389         uint32_t desired_access = 0;
390         uint32_t sec_info;
391
392         if (set_sec_info == -1) {
393                 sec_info = 0;
394
395                 if (sd->dacl || (sd->type & SEC_DESC_DACL_PRESENT)) {
396                         sec_info |= SECINFO_DACL;
397                 }
398                 if (sd->sacl || (sd->type & SEC_DESC_SACL_PRESENT)) {
399                         sec_info |= SECINFO_SACL;
400                 }
401                 if (sd->owner_sid) {
402                         sec_info |= SECINFO_OWNER;
403                 }
404                 if (sd->group_sid) {
405                         sec_info |= SECINFO_GROUP;
406                 }
407         } else {
408                 sec_info = set_sec_info;
409         }
410
411         /* Make the desired_access more specific. */
412         if (sec_info & SECINFO_DACL) {
413                 desired_access |= SEC_STD_WRITE_DAC;
414         }
415         if (sec_info & SECINFO_SACL) {
416                 desired_access |= SEC_FLAG_SYSTEM_SECURITY;
417         }
418         if (sec_info & (SECINFO_OWNER | SECINFO_GROUP)) {
419                 desired_access |= SEC_STD_WRITE_OWNER;
420         }
421
422         status = cli_ntcreate(cli, filename, 0,
423                               desired_access,
424                               0, FILE_SHARE_READ|FILE_SHARE_WRITE,
425                               FILE_OPEN, 0x0, 0x0, &fnum, NULL);
426         if (!NT_STATUS_IS_OK(status)) {
427                 printf("Failed to open %s: %s\n", filename, nt_errstr(status));
428                 return false;
429         }
430
431         status = cli_set_security_descriptor(cli, fnum, sec_info, sd);
432         if (!NT_STATUS_IS_OK(status)) {
433                 printf("ERROR: security description set failed: %s\n",
434                        nt_errstr(status));
435                 result=false;
436         }
437
438         cli_close(cli, fnum);
439         return result;
440 }
441
442 /*****************************************************
443 dump the acls for a file
444 *******************************************************/
445 static int cacl_dump(struct cli_state *cli, const char *filename, bool numeric)
446 {
447         struct security_descriptor *sd;
448
449         if (test_args) {
450                 return EXIT_OK;
451         }
452
453         sd = get_secdesc(cli, filename);
454         if (sd == NULL) {
455                 return EXIT_FAILED;
456         }
457
458         if (sddl) {
459                 char *str = sddl_encode(talloc_tos(), sd, get_domain_sid(cli));
460                 if (str == NULL) {
461                         return EXIT_FAILED;
462                 }
463                 printf("%s\n", str);
464                 TALLOC_FREE(str);
465         } else {
466                 sec_desc_print(cli, stdout, sd, numeric);
467         }
468
469         return EXIT_OK;
470 }
471
472 /***************************************************** 
473 Change the ownership or group ownership of a file. Just
474 because the NT docs say this can't be done :-). JRA.
475 *******************************************************/
476
477 static int owner_set(struct cli_state *cli, enum chown_mode change_mode, 
478                         const char *filename, const char *new_username)
479 {
480         struct dom_sid sid;
481         struct security_descriptor *sd, *old;
482         size_t sd_size;
483
484         if (!StringToSid(cli, &sid, new_username))
485                 return EXIT_PARSE_ERROR;
486
487         old = get_secdesc(cli, filename);
488
489         if (!old) {
490                 return EXIT_FAILED;
491         }
492
493         sd = make_sec_desc(talloc_tos(),old->revision, SEC_DESC_SELF_RELATIVE,
494                                 (change_mode == REQUEST_CHOWN) ? &sid : NULL,
495                                 (change_mode == REQUEST_CHGRP) ? &sid : NULL,
496                            NULL, NULL, &sd_size);
497
498         if (!set_secdesc(cli, filename, sd)) {
499                 return EXIT_FAILED;
500         }
501
502         return EXIT_OK;
503 }
504
505
506 /* The MSDN is contradictory over the ordering of ACE entries in an
507    ACL.  However NT4 gives a "The information may have been modified
508    by a computer running Windows NT 5.0" if denied ACEs do not appear
509    before allowed ACEs. At
510    http://technet.microsoft.com/en-us/library/cc781716.aspx the
511    canonical order is specified as "Explicit Deny, Explicit Allow,
512    Inherited ACEs unchanged" */
513
514 static int ace_compare(struct security_ace *ace1, struct security_ace *ace2)
515 {
516         if (security_ace_equal(ace1, ace2))
517                 return 0;
518
519         if ((ace1->flags & SEC_ACE_FLAG_INHERITED_ACE) &&
520                         !(ace2->flags & SEC_ACE_FLAG_INHERITED_ACE))
521                 return 1;
522         if (!(ace1->flags & SEC_ACE_FLAG_INHERITED_ACE) &&
523                         (ace2->flags & SEC_ACE_FLAG_INHERITED_ACE))
524                 return -1;
525         if ((ace1->flags & SEC_ACE_FLAG_INHERITED_ACE) &&
526                         (ace2->flags & SEC_ACE_FLAG_INHERITED_ACE))
527                 return ace1 - ace2;
528
529         if (ace1->type != ace2->type)
530                 return ace2->type - ace1->type;
531
532         if (dom_sid_compare(&ace1->trustee, &ace2->trustee))
533                 return dom_sid_compare(&ace1->trustee, &ace2->trustee);
534
535         if (ace1->flags != ace2->flags)
536                 return ace1->flags - ace2->flags;
537
538         if (ace1->access_mask != ace2->access_mask)
539                 return ace1->access_mask - ace2->access_mask;
540
541         if (ace1->size != ace2->size)
542                 return ace1->size - ace2->size;
543
544         return memcmp(ace1, ace2, sizeof(struct security_ace));
545 }
546
547 static void sort_acl(struct security_acl *the_acl)
548 {
549         uint32 i;
550         if (!the_acl) return;
551
552         TYPESAFE_QSORT(the_acl->aces, the_acl->num_aces, ace_compare);
553
554         for (i=1;i<the_acl->num_aces;) {
555                 if (security_ace_equal(&the_acl->aces[i-1],
556                                        &the_acl->aces[i])) {
557                         int j;
558                         for (j=i; j<the_acl->num_aces-1; j++) {
559                                 the_acl->aces[j] = the_acl->aces[j+1];
560                         }
561                         the_acl->num_aces--;
562                 } else {
563                         i++;
564                 }
565         }
566 }
567
568 /***************************************************** 
569 set the ACLs on a file given an ascii description
570 *******************************************************/
571
572 static int cacl_set(struct cli_state *cli, const char *filename,
573                     char *the_acl, enum acl_mode mode, bool numeric)
574 {
575         struct security_descriptor *sd, *old;
576         uint32 i, j;
577         size_t sd_size;
578         int result = EXIT_OK;
579
580         if (sddl) {
581                 sd = sddl_decode(talloc_tos(), the_acl, get_domain_sid(cli));
582         } else {
583                 sd = sec_desc_parse(talloc_tos(), cli, the_acl);
584         }
585
586         if (!sd) return EXIT_PARSE_ERROR;
587         if (test_args) return EXIT_OK;
588
589         old = get_secdesc(cli, filename);
590
591         if (!old) {
592                 return EXIT_FAILED;
593         }
594
595         /* the logic here is rather more complex than I would like */
596         switch (mode) {
597         case SMB_ACL_DELETE:
598                 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
599                         bool found = False;
600
601                         for (j=0;old->dacl && j<old->dacl->num_aces;j++) {
602                                 if (security_ace_equal(&sd->dacl->aces[i],
603                                                        &old->dacl->aces[j])) {
604                                         uint32 k;
605                                         for (k=j; k<old->dacl->num_aces-1;k++) {
606                                                 old->dacl->aces[k] = old->dacl->aces[k+1];
607                                         }
608                                         old->dacl->num_aces--;
609                                         found = True;
610                                         break;
611                                 }
612                         }
613
614                         if (!found) {
615                                 printf("ACL for ACE:");
616                                 print_ace(cli, stdout, &sd->dacl->aces[i],
617                                           numeric);
618                                 printf(" not found\n");
619                         }
620                 }
621                 break;
622
623         case SMB_ACL_MODIFY:
624                 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
625                         bool found = False;
626
627                         for (j=0;old->dacl && j<old->dacl->num_aces;j++) {
628                                 if (dom_sid_equal(&sd->dacl->aces[i].trustee,
629                                               &old->dacl->aces[j].trustee)) {
630                                         old->dacl->aces[j] = sd->dacl->aces[i];
631                                         found = True;
632                                 }
633                         }
634
635                         if (!found) {
636                                 fstring str;
637
638                                 SidToString(cli, str,
639                                             &sd->dacl->aces[i].trustee,
640                                             numeric);
641                                 printf("ACL for SID %s not found\n", str);
642                         }
643                 }
644
645                 if (sd->owner_sid) {
646                         old->owner_sid = sd->owner_sid;
647                 }
648
649                 if (sd->group_sid) {
650                         old->group_sid = sd->group_sid;
651                 }
652
653                 break;
654
655         case SMB_ACL_ADD:
656                 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
657                         add_ace(&old->dacl, &sd->dacl->aces[i]);
658                 }
659                 break;
660
661         case SMB_ACL_SET:
662                 old = sd;
663                 break;
664         }
665
666         /* Denied ACE entries must come before allowed ones */
667         sort_acl(old->dacl);
668
669         /* Create new security descriptor and set it */
670
671         /* We used to just have "WRITE_DAC_ACCESS" without WRITE_OWNER.
672            But if we're sending an owner, even if it's the same as the one
673            that already exists then W2K3 insists we open with WRITE_OWNER access.
674            I need to check that setting a SD with no owner set works against WNT
675            and W2K. JRA.
676         */
677
678         sd = make_sec_desc(talloc_tos(),old->revision, old->type,
679                            old->owner_sid, old->group_sid,
680                            NULL, old->dacl, &sd_size);
681
682         if (!set_secdesc(cli, filename, sd)) {
683                 result = EXIT_FAILED;
684         }
685
686         return result;
687 }
688
689 /*****************************************************
690 set the inherit on a file
691 *******************************************************/
692 static int inherit(struct cli_state *cli, const char *filename,
693                    const char *type)
694 {
695         struct security_descriptor *old,*sd;
696         uint32 oldattr;
697         size_t sd_size;
698         int result = EXIT_OK;
699
700         old = get_secdesc(cli, filename);
701
702         if (!old) {
703                 return EXIT_FAILED;
704         }
705
706         oldattr = get_fileinfo(cli,filename);
707
708         if (strcmp(type,"allow")==0) {
709                 if ((old->type & SEC_DESC_DACL_PROTECTED) ==
710                     SEC_DESC_DACL_PROTECTED) {
711                         int i;
712                         char *parentname,*temp;
713                         struct security_descriptor *parent;
714                         temp = talloc_strdup(talloc_tos(), filename);
715
716                         old->type=old->type & (~SEC_DESC_DACL_PROTECTED);
717
718                         /* look at parent and copy in all its inheritable ACL's. */
719                         string_replace(temp, '\\', '/');
720                         if (!parent_dirname(talloc_tos(),temp,&parentname,NULL)) {
721                                 return EXIT_FAILED;
722                         }
723                         string_replace(parentname, '/', '\\');
724                         parent = get_secdesc(cli,parentname);
725                         if (parent == NULL) {
726                                 return EXIT_FAILED;
727                         }
728                         for (i=0;i<parent->dacl->num_aces;i++) {
729                                 struct security_ace *ace=&parent->dacl->aces[i];
730                                 /* Add inherited flag to all aces */
731                                 ace->flags=ace->flags|
732                                            SEC_ACE_FLAG_INHERITED_ACE;
733                                 if ((oldattr & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY) {
734                                         if ((ace->flags & SEC_ACE_FLAG_CONTAINER_INHERIT) ==
735                                             SEC_ACE_FLAG_CONTAINER_INHERIT) {
736                                                 add_ace(&old->dacl, ace);
737                                         }
738                                 } else {
739                                         if ((ace->flags & SEC_ACE_FLAG_OBJECT_INHERIT) ==
740                                             SEC_ACE_FLAG_OBJECT_INHERIT) {
741                                                 /* clear flags for files */
742                                                 ace->flags=0;
743                                                 add_ace(&old->dacl, ace);
744                                         }
745                                 }
746                         }
747                 } else {
748                         printf("Already set to inheritable permissions.\n");
749                         return EXIT_FAILED;
750                 }
751         } else if (strcmp(type,"remove")==0) {
752                 if ((old->type & SEC_DESC_DACL_PROTECTED) !=
753                     SEC_DESC_DACL_PROTECTED) {
754                         old->type=old->type | SEC_DESC_DACL_PROTECTED;
755
756                         /* remove all inherited ACL's. */
757                         if (old->dacl) {
758                                 int i;
759                                 struct security_acl *temp=old->dacl;
760                                 old->dacl=make_sec_acl(talloc_tos(), 3, 0, NULL);
761                                 for (i=temp->num_aces-1;i>=0;i--) {
762                                         struct security_ace *ace=&temp->aces[i];
763                                         /* Remove all ace with INHERITED flag set */
764                                         if ((ace->flags & SEC_ACE_FLAG_INHERITED_ACE) !=
765                                             SEC_ACE_FLAG_INHERITED_ACE) {
766                                                 add_ace(&old->dacl,ace);
767                                         }
768                                 }
769                         }
770                 } else {
771                         printf("Already set to no inheritable permissions.\n");
772                         return EXIT_FAILED;
773                 }
774         } else if (strcmp(type,"copy")==0) {
775                 if ((old->type & SEC_DESC_DACL_PROTECTED) !=
776                     SEC_DESC_DACL_PROTECTED) {
777                         old->type=old->type | SEC_DESC_DACL_PROTECTED;
778
779                         /* convert all inherited ACL's to non inherated ACL's. */
780                         if (old->dacl) {
781                                 int i;
782                                 for (i=0;i<old->dacl->num_aces;i++) {
783                                         struct security_ace *ace=&old->dacl->aces[i];
784                                         /* Remove INHERITED FLAG from all aces */
785                                         ace->flags=ace->flags&(~SEC_ACE_FLAG_INHERITED_ACE);
786                                 }
787                         }
788                 } else {
789                         printf("Already set to no inheritable permissions.\n");
790                         return EXIT_FAILED;
791                 }
792         }
793
794         /* Denied ACE entries must come before allowed ones */
795         sort_acl(old->dacl);
796
797         sd = make_sec_desc(talloc_tos(),old->revision, old->type,
798                            old->owner_sid, old->group_sid,
799                            NULL, old->dacl, &sd_size);
800
801         if (!set_secdesc(cli, filename, sd)) {
802                 result = EXIT_FAILED;
803         }
804
805         return result;
806 }
807
808 /*****************************************************
809  Return a connection to a server.
810 *******************************************************/
811 static struct cli_state *connect_one(struct user_auth_info *auth_info,
812                                      const char *server, const char *share)
813 {
814         struct cli_state *c = NULL;
815         NTSTATUS nt_status;
816         uint32_t flags = 0;
817
818         if (get_cmdline_auth_info_use_kerberos(auth_info)) {
819                 flags |= CLI_FULL_CONNECTION_USE_KERBEROS |
820                          CLI_FULL_CONNECTION_FALLBACK_AFTER_KERBEROS;
821         }
822
823         if (get_cmdline_auth_info_use_machine_account(auth_info) &&
824             !set_cmdline_auth_info_machine_account_creds(auth_info)) {
825                 return NULL;
826         }
827
828         set_cmdline_auth_info_getpass(auth_info);
829
830         nt_status = cli_full_connection(&c, lp_netbios_name(), server,
831                                 NULL, 0,
832                                 share, "?????",
833                                 get_cmdline_auth_info_username(auth_info),
834                                 lp_workgroup(),
835                                 get_cmdline_auth_info_password(auth_info),
836                                 flags,
837                                 get_cmdline_auth_info_signing_state(auth_info));
838         if (!NT_STATUS_IS_OK(nt_status)) {
839                 DEBUG(0,("cli_full_connection failed! (%s)\n", nt_errstr(nt_status)));
840                 return NULL;
841         }
842
843         if (get_cmdline_auth_info_smb_encrypt(auth_info)) {
844                 nt_status = cli_cm_force_encryption(c,
845                                         get_cmdline_auth_info_username(auth_info),
846                                         get_cmdline_auth_info_password(auth_info),
847                                         lp_workgroup(),
848                                         share);
849                 if (!NT_STATUS_IS_OK(nt_status)) {
850                         cli_shutdown(c);
851                         c = NULL;
852                 }
853         }
854
855         return c;
856 }
857
858 /****************************************************************************
859   main program
860 ****************************************************************************/
861 int main(int argc, char *argv[])
862 {
863         const char **argv_const = discard_const_p(const char *, argv);
864         char *share;
865         int opt;
866         enum acl_mode mode = SMB_ACL_SET;
867         static char *the_acl = NULL;
868         enum chown_mode change_mode = REQUEST_NONE;
869         int result;
870         char *path;
871         char *filename = NULL;
872         poptContext pc;
873         /* numeric is set when the user wants numeric SIDs and ACEs rather
874            than going via LSA calls to resolve them */
875         int numeric;
876
877         struct poptOption long_options[] = {
878                 POPT_AUTOHELP
879                 { "delete", 'D', POPT_ARG_STRING, NULL, 'D', "Delete an acl", "ACL" },
880                 { "modify", 'M', POPT_ARG_STRING, NULL, 'M', "Modify an acl", "ACL" },
881                 { "add", 'a', POPT_ARG_STRING, NULL, 'a', "Add an acl", "ACL" },
882                 { "set", 'S', POPT_ARG_STRING, NULL, 'S', "Set acls", "ACLS" },
883                 { "chown", 'C', POPT_ARG_STRING, NULL, 'C', "Change ownership of a file", "USERNAME" },
884                 { "chgrp", 'G', POPT_ARG_STRING, NULL, 'G', "Change group ownership of a file", "GROUPNAME" },
885                 { "inherit", 'I', POPT_ARG_STRING, NULL, 'I', "Inherit allow|remove|copy" },
886                 { "numeric", 0, POPT_ARG_NONE, &numeric, 1, "Don't resolve sids or masks to names" },
887                 { "sddl", 0, POPT_ARG_NONE, &sddl, 1, "Output and input acls in sddl format" },
888                 { "query-security-info", 0, POPT_ARG_INT, &query_sec_info, 1,
889                   "The security-info flags for queries"
890                 },
891                 { "set-security-info", 0, POPT_ARG_INT, &set_sec_info, 1,
892                   "The security-info flags for modifications"
893                 },
894                 { "test-args", 't', POPT_ARG_NONE, &test_args, 1, "Test arguments"},
895                 { "domain-sid", 0, POPT_ARG_STRING, &domain_sid, 0, "Domain SID for sddl", "SID"},
896                 { "max-protocol", 'm', POPT_ARG_STRING, NULL, 'm', "Set the max protocol level", "LEVEL" },
897                 POPT_COMMON_SAMBA
898                 POPT_COMMON_CONNECTION
899                 POPT_COMMON_CREDENTIALS
900                 POPT_TABLEEND
901         };
902
903         struct cli_state *cli;
904         TALLOC_CTX *frame = talloc_stackframe();
905         const char *owner_username = "";
906         char *server;
907         struct user_auth_info *auth_info;
908
909         smb_init_locale();
910
911         /* set default debug level to 1 regardless of what smb.conf sets */
912         setup_logging( "smbcacls", DEBUG_STDERR);
913         lp_set_cmdline("log level", "1");
914
915         setlinebuf(stdout);
916
917
918         auth_info = user_auth_info_init(frame);
919         if (auth_info == NULL) {
920                 exit(1);
921         }
922         popt_common_set_auth_info(auth_info);
923
924         pc = poptGetContext("smbcacls", argc, argv_const, long_options, 0);
925
926         poptSetOtherOptionHelp(pc, "//server1/share1 filename\nACLs look like: "
927                 "'ACL:user:[ALLOWED|DENIED]/flags/permissions'");
928
929         while ((opt = poptGetNextOpt(pc)) != -1) {
930                 switch (opt) {
931                 case 'S':
932                         the_acl = smb_xstrdup(poptGetOptArg(pc));
933                         mode = SMB_ACL_SET;
934                         break;
935
936                 case 'D':
937                         the_acl = smb_xstrdup(poptGetOptArg(pc));
938                         mode = SMB_ACL_DELETE;
939                         break;
940
941                 case 'M':
942                         the_acl = smb_xstrdup(poptGetOptArg(pc));
943                         mode = SMB_ACL_MODIFY;
944                         break;
945
946                 case 'a':
947                         the_acl = smb_xstrdup(poptGetOptArg(pc));
948                         mode = SMB_ACL_ADD;
949                         break;
950
951                 case 'C':
952                         owner_username = poptGetOptArg(pc);
953                         change_mode = REQUEST_CHOWN;
954                         break;
955
956                 case 'G':
957                         owner_username = poptGetOptArg(pc);
958                         change_mode = REQUEST_CHGRP;
959                         break;
960
961                 case 'I':
962                         owner_username = poptGetOptArg(pc);
963                         change_mode = REQUEST_INHERIT;
964                         break;
965                 case 'm':
966                         lp_set_cmdline("client max protocol", poptGetOptArg(pc));
967                         break;
968                 }
969         }
970
971         /* Make connection to server */
972         if(!poptPeekArg(pc)) {
973                 poptPrintUsage(pc, stderr, 0);
974                 return -1;
975         }
976
977         path = talloc_strdup(frame, poptGetArg(pc));
978         if (!path) {
979                 return -1;
980         }
981
982         if(!poptPeekArg(pc)) {
983                 poptPrintUsage(pc, stderr, 0);
984                 return -1;
985         }
986
987         lp_load_global(get_dyn_CONFIGFILE());
988         load_interfaces();
989
990         filename = talloc_strdup(frame, poptGetArg(pc));
991         if (!filename) {
992                 return -1;
993         }
994
995         poptFreeContext(pc);
996         popt_burn_cmdline_password(argc, argv);
997
998         string_replace(path,'/','\\');
999
1000         server = talloc_strdup(frame, path+2);
1001         if (!server) {
1002                 return -1;
1003         }
1004         share = strchr_m(server,'\\');
1005         if (!share) {
1006                 printf("Invalid argument: %s\n", share);
1007                 return -1;
1008         }
1009
1010         *share = 0;
1011         share++;
1012
1013         if (!test_args) {
1014                 cli = connect_one(auth_info, server, share);
1015                 if (!cli) {
1016                         exit(EXIT_FAILED);
1017                 }
1018         } else {
1019                 exit(0);
1020         }
1021
1022         string_replace(filename, '/', '\\');
1023         if (filename[0] != '\\') {
1024                 filename = talloc_asprintf(frame,
1025                                 "\\%s",
1026                                 filename);
1027                 if (!filename) {
1028                         return -1;
1029                 }
1030         }
1031
1032         /* Perform requested action */
1033
1034         if (change_mode == REQUEST_INHERIT) {
1035                 result = inherit(cli, filename, owner_username);
1036         } else if (change_mode != REQUEST_NONE) {
1037                 result = owner_set(cli, change_mode, filename, owner_username);
1038         } else if (the_acl) {
1039                 result = cacl_set(cli, filename, the_acl, mode, numeric);
1040         } else {
1041                 result = cacl_dump(cli, filename, numeric);
1042         }
1043
1044         TALLOC_FREE(frame);
1045
1046         return result;
1047 }