Make all the tools use the proper accessor functions.
[kai/samba.git] / source3 / utils / smbcacls.c
1 /* 
2    Unix SMB/CIFS implementation.
3    ACL get/set utility
4    
5    Copyright (C) Andrew Tridgell 2000
6    Copyright (C) Tim Potter      2000
7    Copyright (C) Jeremy Allison  2000
8    Copyright (C) Jelmer Vernooij 2003
9    
10    This program is free software; you can redistribute it and/or modify
11    it under the terms of the GNU General Public License as published by
12    the Free Software Foundation; either version 3 of the License, or
13    (at your option) any later version.
14    
15    This program is distributed in the hope that it will be useful,
16    but WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18    GNU General Public License for more details.
19    
20    You should have received a copy of the GNU General Public License
21    along with this program.  If not, see <http://www.gnu.org/licenses/>.
22 */
23
24 #include "includes.h"
25
26 static int test_args = False;
27
28 #define CREATE_ACCESS_READ READ_CONTROL_ACCESS
29
30 /* numeric is set when the user wants numeric SIDs and ACEs rather
31    than going via LSA calls to resolve them */
32 static int numeric = False;
33
34 enum acl_mode {SMB_ACL_SET, SMB_ACL_DELETE, SMB_ACL_MODIFY, SMB_ACL_ADD };
35 enum chown_mode {REQUEST_NONE, REQUEST_CHOWN, REQUEST_CHGRP};
36 enum exit_values {EXIT_OK, EXIT_FAILED, EXIT_PARSE_ERROR};
37
38 struct perm_value {
39         const char *perm;
40         uint32 mask;
41 };
42
43 /* These values discovered by inspection */
44
45 static const struct perm_value special_values[] = {
46         { "R", 0x00120089 },
47         { "W", 0x00120116 },
48         { "X", 0x001200a0 },
49         { "D", 0x00010000 },
50         { "P", 0x00040000 },
51         { "O", 0x00080000 },
52         { NULL, 0 },
53 };
54
55 static const struct perm_value standard_values[] = {
56         { "READ",   0x001200a9 },
57         { "CHANGE", 0x001301bf },
58         { "FULL",   0x001f01ff },
59         { NULL, 0 },
60 };
61
62 /* Open cli connection and policy handle */
63
64 static NTSTATUS cli_lsa_lookup_sid(struct cli_state *cli,
65                                    const DOM_SID *sid,
66                                    TALLOC_CTX *mem_ctx,
67                                    enum lsa_SidType *type,
68                                    char **domain, char **name)
69 {
70         uint16 orig_cnum = cli->cnum;
71         struct rpc_pipe_client *p;
72         struct policy_handle handle;
73         NTSTATUS status;
74         TALLOC_CTX *frame = talloc_stackframe();
75         enum lsa_SidType *types;
76         char **domains;
77         char **names;
78
79         if (!cli_send_tconX(cli, "IPC$", "?????", "", 0)) {
80                 return cli_nt_error(cli);
81         }
82
83         p = cli_rpc_pipe_open_noauth(cli, PI_LSARPC, &status);
84         if (p == NULL) {
85                 goto fail;
86         }
87
88         status = rpccli_lsa_open_policy(p, talloc_tos(), True,
89                                         GENERIC_EXECUTE_ACCESS, &handle);
90         if (!NT_STATUS_IS_OK(status)) {
91                 goto fail;
92         }
93
94         status = rpccli_lsa_lookup_sids(p, talloc_tos(), &handle, 1, sid,
95                                         &domains, &names, &types);
96         if (!NT_STATUS_IS_OK(status)) {
97                 goto fail;
98         }
99
100         *type = types[0];
101         *domain = talloc_move(mem_ctx, &domains[0]);
102         *name = talloc_move(mem_ctx, &names[0]);
103
104         status = NT_STATUS_OK;
105  fail:
106         if (p != NULL) {
107                 cli_rpc_pipe_close(p);
108         }
109         cli_tdis(cli);
110         cli->cnum = orig_cnum;
111         TALLOC_FREE(frame);
112         return status;
113 }
114
115 static NTSTATUS cli_lsa_lookup_name(struct cli_state *cli,
116                                     const char *name,
117                                     enum lsa_SidType *type,
118                                     DOM_SID *sid)
119 {
120         uint16 orig_cnum = cli->cnum;
121         struct rpc_pipe_client *p;
122         struct policy_handle handle;
123         NTSTATUS status;
124         TALLOC_CTX *frame = talloc_stackframe();
125         DOM_SID *sids;
126         enum lsa_SidType *types;
127
128         if (!cli_send_tconX(cli, "IPC$", "?????", "", 0)) {
129                 return cli_nt_error(cli);
130         }
131
132         p = cli_rpc_pipe_open_noauth(cli, PI_LSARPC, &status);
133         if (p == NULL) {
134                 goto fail;
135         }
136
137         status = rpccli_lsa_open_policy(p, talloc_tos(), True,
138                                         GENERIC_EXECUTE_ACCESS, &handle);
139         if (!NT_STATUS_IS_OK(status)) {
140                 goto fail;
141         }
142
143         status = rpccli_lsa_lookup_names(p, talloc_tos(), &handle, 1, &name,
144                                          NULL, 1, &sids, &types);
145         if (!NT_STATUS_IS_OK(status)) {
146                 goto fail;
147         }
148
149         *type = types[0];
150         *sid = sids[0];
151
152         status = NT_STATUS_OK;
153  fail:
154         if (p != NULL) {
155                 cli_rpc_pipe_close(p);
156         }
157         cli_tdis(cli);
158         cli->cnum = orig_cnum;
159         TALLOC_FREE(frame);
160         return status;
161 }
162
163 /* convert a SID to a string, either numeric or username/group */
164 static void SidToString(struct cli_state *cli, fstring str, const DOM_SID *sid)
165 {
166         char *domain = NULL;
167         char *name = NULL;
168         enum lsa_SidType type;
169         NTSTATUS status;
170
171         sid_to_string(str, sid);
172
173         if (numeric) {
174                 return;
175         }
176
177         status = cli_lsa_lookup_sid(cli, sid, talloc_tos(), &type,
178                                     &domain, &name);
179
180         if (!NT_STATUS_IS_OK(status)) {
181                 return;
182         }
183
184         slprintf(str, sizeof(fstring) - 1, "%s%s%s",
185                  domain, lp_winbind_separator(), name);
186         
187 }
188
189 /* convert a string to a SID, either numeric or username/group */
190 static bool StringToSid(struct cli_state *cli, DOM_SID *sid, const char *str)
191 {
192         enum lsa_SidType type;
193
194         if (strncmp(str, "S-", 2) == 0) {
195                 return string_to_sid(sid, str);
196         }
197
198         return NT_STATUS_IS_OK(cli_lsa_lookup_name(cli, str, &type, sid));
199 }
200
201
202 /* print an ACE on a FILE, using either numeric or ascii representation */
203 static void print_ace(struct cli_state *cli, FILE *f, SEC_ACE *ace)
204 {
205         const struct perm_value *v;
206         fstring sidstr;
207         int do_print = 0;
208         uint32 got_mask;
209
210         SidToString(cli, sidstr, &ace->trustee);
211
212         fprintf(f, "%s:", sidstr);
213
214         if (numeric) {
215                 fprintf(f, "%d/%d/0x%08x", 
216                         ace->type, ace->flags, ace->access_mask);
217                 return;
218         }
219
220         /* Ace type */
221
222         if (ace->type == SEC_ACE_TYPE_ACCESS_ALLOWED) {
223                 fprintf(f, "ALLOWED");
224         } else if (ace->type == SEC_ACE_TYPE_ACCESS_DENIED) {
225                 fprintf(f, "DENIED");
226         } else {
227                 fprintf(f, "%d", ace->type);
228         }
229
230         /* Not sure what flags can be set in a file ACL */
231
232         fprintf(f, "/%d/", ace->flags);
233
234         /* Standard permissions */
235
236         for (v = standard_values; v->perm; v++) {
237                 if (ace->access_mask == v->mask) {
238                         fprintf(f, "%s", v->perm);
239                         return;
240                 }
241         }
242
243         /* Special permissions.  Print out a hex value if we have
244            leftover bits in the mask. */
245
246         got_mask = ace->access_mask;
247
248  again:
249         for (v = special_values; v->perm; v++) {
250                 if ((ace->access_mask & v->mask) == v->mask) {
251                         if (do_print) {
252                                 fprintf(f, "%s", v->perm);
253                         }
254                         got_mask &= ~v->mask;
255                 }
256         }
257
258         if (!do_print) {
259                 if (got_mask != 0) {
260                         fprintf(f, "0x%08x", ace->access_mask);
261                 } else {
262                         do_print = 1;
263                         goto again;
264                 }
265         }
266 }
267
268
269 /* parse an ACE in the same format as print_ace() */
270 static bool parse_ace(struct cli_state *cli, SEC_ACE *ace,
271                       const char *orig_str)
272 {
273         char *p;
274         const char *cp;
275         fstring tok;
276         unsigned int atype = 0;
277         unsigned int aflags = 0;
278         unsigned int amask = 0;
279         DOM_SID sid;
280         SEC_ACCESS mask;
281         const struct perm_value *v;
282         char *str = SMB_STRDUP(orig_str);
283
284         if (!str) {
285                 return False;
286         }
287
288         ZERO_STRUCTP(ace);
289         p = strchr_m(str,':');
290         if (!p) {
291                 printf("ACE '%s': missing ':'.\n", orig_str);
292                 SAFE_FREE(str);
293                 return False;
294         }
295         *p = '\0';
296         p++;
297         /* Try to parse numeric form */
298
299         if (sscanf(p, "%i/%i/%i", &atype, &aflags, &amask) == 3 &&
300             StringToSid(cli, &sid, str)) {
301                 goto done;
302         }
303
304         /* Try to parse text form */
305
306         if (!StringToSid(cli, &sid, str)) {
307                 printf("ACE '%s': failed to convert '%s' to SID\n",
308                         orig_str, str);
309                 SAFE_FREE(str);
310                 return False;
311         }
312
313         cp = p;
314         if (!next_token(&cp, tok, "/", sizeof(fstring))) {
315                 printf("ACE '%s': failed to find '/' character.\n",
316                         orig_str);
317                 SAFE_FREE(str);
318                 return False;
319         }
320
321         if (strncmp(tok, "ALLOWED", strlen("ALLOWED")) == 0) {
322                 atype = SEC_ACE_TYPE_ACCESS_ALLOWED;
323         } else if (strncmp(tok, "DENIED", strlen("DENIED")) == 0) {
324                 atype = SEC_ACE_TYPE_ACCESS_DENIED;
325         } else {
326                 printf("ACE '%s': missing 'ALLOWED' or 'DENIED' entry at '%s'\n",
327                         orig_str, tok);
328                 SAFE_FREE(str);
329                 return False;
330         }
331
332         /* Only numeric form accepted for flags at present */
333
334         if (!(next_token(&cp, tok, "/", sizeof(fstring)) &&
335               sscanf(tok, "%i", &aflags))) {
336                 printf("ACE '%s': bad integer flags entry at '%s'\n",
337                         orig_str, tok);
338                 SAFE_FREE(str);
339                 return False;
340         }
341
342         if (!next_token(&cp, tok, "/", sizeof(fstring))) {
343                 printf("ACE '%s': missing / at '%s'\n",
344                         orig_str, tok);
345                 SAFE_FREE(str);
346                 return False;
347         }
348
349         if (strncmp(tok, "0x", 2) == 0) {
350                 if (sscanf(tok, "%i", &amask) != 1) {
351                         printf("ACE '%s': bad hex number at '%s'\n",
352                                 orig_str, tok);
353                         SAFE_FREE(str);
354                         return False;
355                 }
356                 goto done;
357         }
358
359         for (v = standard_values; v->perm; v++) {
360                 if (strcmp(tok, v->perm) == 0) {
361                         amask = v->mask;
362                         goto done;
363                 }
364         }
365
366         p = tok;
367
368         while(*p) {
369                 bool found = False;
370
371                 for (v = special_values; v->perm; v++) {
372                         if (v->perm[0] == *p) {
373                                 amask |= v->mask;
374                                 found = True;
375                         }
376                 }
377
378                 if (!found) {
379                         printf("ACE '%s': bad permission value at '%s'\n",
380                                 orig_str, p);
381                         SAFE_FREE(str);
382                         return False;
383                 }
384                 p++;
385         }
386
387         if (*p) {
388                 SAFE_FREE(str);
389                 return False;
390         }
391
392  done:
393         mask = amask;
394         init_sec_ace(ace, &sid, atype, mask, aflags);
395         SAFE_FREE(str);
396         return True;
397 }
398
399 /* add an ACE to a list of ACEs in a SEC_ACL */
400 static bool add_ace(SEC_ACL **the_acl, SEC_ACE *ace)
401 {
402         SEC_ACL *new_ace;
403         SEC_ACE *aces;
404         if (! *the_acl) {
405                 return (((*the_acl) = make_sec_acl(talloc_tos(), 3, 1, ace))
406                         != NULL);
407         }
408
409         if (!(aces = SMB_CALLOC_ARRAY(SEC_ACE, 1+(*the_acl)->num_aces))) {
410                 return False;
411         }
412         memcpy(aces, (*the_acl)->aces, (*the_acl)->num_aces * sizeof(SEC_ACE));
413         memcpy(aces+(*the_acl)->num_aces, ace, sizeof(SEC_ACE));
414         new_ace = make_sec_acl(talloc_tos(),(*the_acl)->revision,1+(*the_acl)->num_aces, aces);
415         SAFE_FREE(aces);
416         (*the_acl) = new_ace;
417         return True;
418 }
419
420 /* parse a ascii version of a security descriptor */
421 static SEC_DESC *sec_desc_parse(struct cli_state *cli, char *str)
422 {
423         const char *p = str;
424         fstring tok;
425         SEC_DESC *ret = NULL;
426         size_t sd_size;
427         DOM_SID *grp_sid=NULL, *owner_sid=NULL;
428         SEC_ACL *dacl=NULL;
429         int revision=1;
430
431         while (next_token(&p, tok, "\t,\r\n", sizeof(tok))) {
432
433                 if (strncmp(tok,"REVISION:", 9) == 0) {
434                         revision = strtol(tok+9, NULL, 16);
435                         continue;
436                 }
437
438                 if (strncmp(tok,"OWNER:", 6) == 0) {
439                         if (owner_sid) {
440                                 printf("Only specify owner once\n");
441                                 goto done;
442                         }
443                         owner_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
444                         if (!owner_sid ||
445                             !StringToSid(cli, owner_sid, tok+6)) {
446                                 printf("Failed to parse owner sid\n");
447                                 goto done;
448                         }
449                         continue;
450                 }
451
452                 if (strncmp(tok,"GROUP:", 6) == 0) {
453                         if (grp_sid) {
454                                 printf("Only specify group once\n");
455                                 goto done;
456                         }
457                         grp_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
458                         if (!grp_sid ||
459                             !StringToSid(cli, grp_sid, tok+6)) {
460                                 printf("Failed to parse group sid\n");
461                                 goto done;
462                         }
463                         continue;
464                 }
465
466                 if (strncmp(tok,"ACL:", 4) == 0) {
467                         SEC_ACE ace;
468                         if (!parse_ace(cli, &ace, tok+4)) {
469                                 goto done;
470                         }
471                         if(!add_ace(&dacl, &ace)) {
472                                 printf("Failed to add ACL %s\n", tok);
473                                 goto done;
474                         }
475                         continue;
476                 }
477
478                 printf("Failed to parse token '%s' in security descriptor,\n", tok);
479                 goto done;
480         }
481
482         ret = make_sec_desc(talloc_tos(),revision, SEC_DESC_SELF_RELATIVE, owner_sid, grp_sid,
483                             NULL, dacl, &sd_size);
484
485   done:
486         SAFE_FREE(grp_sid);
487         SAFE_FREE(owner_sid);
488
489         return ret;
490 }
491
492
493 /* print a ascii version of a security descriptor on a FILE handle */
494 static void sec_desc_print(struct cli_state *cli, FILE *f, SEC_DESC *sd)
495 {
496         fstring sidstr;
497         uint32 i;
498
499         fprintf(f, "REVISION:%d\n", sd->revision);
500
501         /* Print owner and group sid */
502
503         if (sd->owner_sid) {
504                 SidToString(cli, sidstr, sd->owner_sid);
505         } else {
506                 fstrcpy(sidstr, "");
507         }
508
509         fprintf(f, "OWNER:%s\n", sidstr);
510
511         if (sd->group_sid) {
512                 SidToString(cli, sidstr, sd->group_sid);
513         } else {
514                 fstrcpy(sidstr, "");
515         }
516
517         fprintf(f, "GROUP:%s\n", sidstr);
518
519         /* Print aces */
520         for (i = 0; sd->dacl && i < sd->dacl->num_aces; i++) {
521                 SEC_ACE *ace = &sd->dacl->aces[i];
522                 fprintf(f, "ACL:");
523                 print_ace(cli, f, ace);
524                 fprintf(f, "\n");
525         }
526
527 }
528
529 /***************************************************** 
530 dump the acls for a file
531 *******************************************************/
532 static int cacl_dump(struct cli_state *cli, char *filename)
533 {
534         int result = EXIT_FAILED;
535         int fnum = -1;
536         SEC_DESC *sd;
537
538         if (test_args) 
539                 return EXIT_OK;
540
541         fnum = cli_nt_create(cli, filename, CREATE_ACCESS_READ);
542
543         if (fnum == -1) {
544                 printf("Failed to open %s: %s\n", filename, cli_errstr(cli));
545                 goto done;
546         }
547
548         sd = cli_query_secdesc(cli, fnum, talloc_tos());
549
550         if (!sd) {
551                 printf("ERROR: secdesc query failed: %s\n", cli_errstr(cli));
552                 goto done;
553         }
554
555         sec_desc_print(cli, stdout, sd);
556
557         result = EXIT_OK;
558
559 done:
560         if (fnum != -1)
561                 cli_close(cli, fnum);
562
563         return result;
564 }
565
566 /***************************************************** 
567 Change the ownership or group ownership of a file. Just
568 because the NT docs say this can't be done :-). JRA.
569 *******************************************************/
570
571 static int owner_set(struct cli_state *cli, enum chown_mode change_mode, 
572                         const char *filename, const char *new_username)
573 {
574         int fnum;
575         DOM_SID sid;
576         SEC_DESC *sd, *old;
577         size_t sd_size;
578
579         fnum = cli_nt_create(cli, filename, CREATE_ACCESS_READ);
580
581         if (fnum == -1) {
582                 printf("Failed to open %s: %s\n", filename, cli_errstr(cli));
583                 return EXIT_FAILED;
584         }
585
586         if (!StringToSid(cli, &sid, new_username))
587                 return EXIT_PARSE_ERROR;
588
589         old = cli_query_secdesc(cli, fnum, talloc_tos());
590
591         cli_close(cli, fnum);
592
593         if (!old) {
594                 printf("owner_set: Failed to query old descriptor\n");
595                 return EXIT_FAILED;
596         }
597
598         sd = make_sec_desc(talloc_tos(),old->revision, old->type,
599                                 (change_mode == REQUEST_CHOWN) ? &sid : NULL,
600                                 (change_mode == REQUEST_CHGRP) ? &sid : NULL,
601                            NULL, NULL, &sd_size);
602
603         fnum = cli_nt_create(cli, filename, WRITE_OWNER_ACCESS);
604
605         if (fnum == -1) {
606                 printf("Failed to open %s: %s\n", filename, cli_errstr(cli));
607                 return EXIT_FAILED;
608         }
609
610         if (!cli_set_secdesc(cli, fnum, sd)) {
611                 printf("ERROR: secdesc set failed: %s\n", cli_errstr(cli));
612         }
613
614         cli_close(cli, fnum);
615
616         return EXIT_OK;
617 }
618
619
620 /* The MSDN is contradictory over the ordering of ACE entries in an ACL.
621    However NT4 gives a "The information may have been modified by a
622    computer running Windows NT 5.0" if denied ACEs do not appear before
623    allowed ACEs. */
624
625 static int ace_compare(SEC_ACE *ace1, SEC_ACE *ace2)
626 {
627         if (sec_ace_equal(ace1, ace2)) 
628                 return 0;
629
630         if (ace1->type != ace2->type) 
631                 return ace2->type - ace1->type;
632
633         if (sid_compare(&ace1->trustee, &ace2->trustee)) 
634                 return sid_compare(&ace1->trustee, &ace2->trustee);
635
636         if (ace1->flags != ace2->flags) 
637                 return ace1->flags - ace2->flags;
638
639         if (ace1->access_mask != ace2->access_mask) 
640                 return ace1->access_mask - ace2->access_mask;
641
642         if (ace1->size != ace2->size) 
643                 return ace1->size - ace2->size;
644
645         return memcmp(ace1, ace2, sizeof(SEC_ACE));
646 }
647
648 static void sort_acl(SEC_ACL *the_acl)
649 {
650         uint32 i;
651         if (!the_acl) return;
652
653         qsort(the_acl->aces, the_acl->num_aces, sizeof(the_acl->aces[0]), QSORT_CAST ace_compare);
654
655         for (i=1;i<the_acl->num_aces;) {
656                 if (sec_ace_equal(&the_acl->aces[i-1], &the_acl->aces[i])) {
657                         int j;
658                         for (j=i; j<the_acl->num_aces-1; j++) {
659                                 the_acl->aces[j] = the_acl->aces[j+1];
660                         }
661                         the_acl->num_aces--;
662                 } else {
663                         i++;
664                 }
665         }
666 }
667
668 /***************************************************** 
669 set the ACLs on a file given an ascii description
670 *******************************************************/
671 static int cacl_set(struct cli_state *cli, char *filename, 
672                     char *the_acl, enum acl_mode mode)
673 {
674         int fnum;
675         SEC_DESC *sd, *old;
676         uint32 i, j;
677         size_t sd_size;
678         int result = EXIT_OK;
679
680         sd = sec_desc_parse(cli, the_acl);
681
682         if (!sd) return EXIT_PARSE_ERROR;
683         if (test_args) return EXIT_OK;
684
685         /* The desired access below is the only one I could find that works
686            with NT4, W2KP and Samba */
687
688         fnum = cli_nt_create(cli, filename, CREATE_ACCESS_READ);
689
690         if (fnum == -1) {
691                 printf("cacl_set failed to open %s: %s\n", filename, cli_errstr(cli));
692                 return EXIT_FAILED;
693         }
694
695         old = cli_query_secdesc(cli, fnum, talloc_tos());
696
697         if (!old) {
698                 printf("calc_set: Failed to query old descriptor\n");
699                 return EXIT_FAILED;
700         }
701
702         cli_close(cli, fnum);
703
704         /* the logic here is rather more complex than I would like */
705         switch (mode) {
706         case SMB_ACL_DELETE:
707                 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
708                         bool found = False;
709
710                         for (j=0;old->dacl && j<old->dacl->num_aces;j++) {
711                                 if (sec_ace_equal(&sd->dacl->aces[i],
712                                                   &old->dacl->aces[j])) {
713                                         uint32 k;
714                                         for (k=j; k<old->dacl->num_aces-1;k++) {
715                                                 old->dacl->aces[k] = old->dacl->aces[k+1];
716                                         }
717                                         old->dacl->num_aces--;
718                                         found = True;
719                                         break;
720                                 }
721                         }
722
723                         if (!found) {
724                                 printf("ACL for ACE:"); 
725                                 print_ace(cli, stdout, &sd->dacl->aces[i]);
726                                 printf(" not found\n");
727                         }
728                 }
729                 break;
730
731         case SMB_ACL_MODIFY:
732                 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
733                         bool found = False;
734
735                         for (j=0;old->dacl && j<old->dacl->num_aces;j++) {
736                                 if (sid_equal(&sd->dacl->aces[i].trustee,
737                                               &old->dacl->aces[j].trustee)) {
738                                         old->dacl->aces[j] = sd->dacl->aces[i];
739                                         found = True;
740                                 }
741                         }
742
743                         if (!found) {
744                                 fstring str;
745
746                                 SidToString(cli, str,
747                                             &sd->dacl->aces[i].trustee);
748                                 printf("ACL for SID %s not found\n", str);
749                         }
750                 }
751
752                 if (sd->owner_sid) {
753                         old->owner_sid = sd->owner_sid;
754                 }
755
756                 if (sd->group_sid) { 
757                         old->group_sid = sd->group_sid;
758                 }
759
760                 break;
761
762         case SMB_ACL_ADD:
763                 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
764                         add_ace(&old->dacl, &sd->dacl->aces[i]);
765                 }
766                 break;
767
768         case SMB_ACL_SET:
769                 old = sd;
770                 break;
771         }
772
773         /* Denied ACE entries must come before allowed ones */
774         sort_acl(old->dacl);
775
776         /* Create new security descriptor and set it */
777
778         /* We used to just have "WRITE_DAC_ACCESS" without WRITE_OWNER.
779            But if we're sending an owner, even if it's the same as the one
780            that already exists then W2K3 insists we open with WRITE_OWNER access.
781            I need to check that setting a SD with no owner set works against WNT
782            and W2K. JRA.
783         */
784
785         sd = make_sec_desc(talloc_tos(),old->revision, old->type,
786                            old->owner_sid, old->group_sid,
787                            NULL, old->dacl, &sd_size);
788
789         fnum = cli_nt_create(cli, filename, WRITE_DAC_ACCESS|WRITE_OWNER_ACCESS);
790
791         if (fnum == -1) {
792                 printf("cacl_set failed to open %s: %s\n", filename, cli_errstr(cli));
793                 return EXIT_FAILED;
794         }
795
796         if (!cli_set_secdesc(cli, fnum, sd)) {
797                 printf("ERROR: secdesc set failed: %s\n", cli_errstr(cli));
798                 result = EXIT_FAILED;
799         }
800
801         /* Clean up */
802
803         cli_close(cli, fnum);
804
805         return result;
806 }
807
808
809 /*****************************************************
810  Return a connection to a server.
811 *******************************************************/
812 static struct cli_state *connect_one(const char *server, const char *share)
813 {
814         struct cli_state *c;
815         struct sockaddr_storage ss;
816         NTSTATUS nt_status;
817         zero_addr(&ss);
818
819         if (!get_cmdline_auth_info_got_pass()) {
820                 char *pass = getpass("Password: ");
821                 if (pass) {
822                         set_cmdline_auth_info_password(pass);
823                 }
824         }
825
826         if (NT_STATUS_IS_OK(nt_status = cli_full_connection(&c, global_myname(), server, 
827                                                             &ss, 0,
828                                                             share, "?????",
829                                                             get_cmdline_auth_info_username(),
830                                                             lp_workgroup(),
831                                                             get_cmdline_auth_info_password(),
832                                                             0,
833                                                             get_cmdline_auth_info_signing_state(),
834                                                             NULL))) {
835                 return c;
836         } else {
837                 DEBUG(0,("cli_full_connection failed! (%s)\n", nt_errstr(nt_status)));
838                 return NULL;
839         }
840 }
841
842 /****************************************************************************
843   main program
844 ****************************************************************************/
845  int main(int argc, const char *argv[])
846 {
847         char *share;
848         int opt;
849         enum acl_mode mode = SMB_ACL_SET;
850         static char *the_acl = NULL;
851         enum chown_mode change_mode = REQUEST_NONE;
852         int result;
853         char *path;
854         char *filename = NULL;
855         poptContext pc;
856         struct poptOption long_options[] = {
857                 POPT_AUTOHELP
858                 { "delete", 'D', POPT_ARG_STRING, NULL, 'D', "Delete an acl", "ACL" },
859                 { "modify", 'M', POPT_ARG_STRING, NULL, 'M', "Modify an acl", "ACL" },
860                 { "add", 'a', POPT_ARG_STRING, NULL, 'a', "Add an acl", "ACL" },
861                 { "set", 'S', POPT_ARG_STRING, NULL, 'S', "Set acls", "ACLS" },
862                 { "chown", 'C', POPT_ARG_STRING, NULL, 'C', "Change ownership of a file", "USERNAME" },
863                 { "chgrp", 'G', POPT_ARG_STRING, NULL, 'G', "Change group ownership of a file", "GROUPNAME" },
864                 { "numeric", 0, POPT_ARG_NONE, &numeric, True, "Don't resolve sids or masks to names" },
865                 { "test-args", 't', POPT_ARG_NONE, &test_args, True, "Test arguments"},
866                 POPT_COMMON_SAMBA
867                 POPT_COMMON_CREDENTIALS
868                 { NULL }
869         };
870
871         struct cli_state *cli;
872         TALLOC_CTX *frame = talloc_stackframe();
873         const char *owner_username = "";
874         char *server;
875
876         load_case_tables();
877
878
879         /* set default debug level to 1 regardless of what smb.conf sets */
880         setup_logging( "smbcacls", True );
881         DEBUGLEVEL_CLASS[DBGC_ALL] = 1;
882         dbf = x_stderr;
883         x_setbuf( x_stderr, NULL );
884
885         setlinebuf(stdout);
886
887         lp_load(dyn_CONFIGFILE,True,False,False,True);
888         load_interfaces();
889
890         pc = poptGetContext("smbcacls", argc, argv, long_options, 0);
891
892         poptSetOtherOptionHelp(pc, "//server1/share1 filename\nACLs look like: "
893                 "'ACL:user:[ALLOWED|DENIED]/flags/permissions'");
894
895         while ((opt = poptGetNextOpt(pc)) != -1) {
896                 switch (opt) {
897                 case 'S':
898                         the_acl = smb_xstrdup(poptGetOptArg(pc));
899                         mode = SMB_ACL_SET;
900                         break;
901
902                 case 'D':
903                         the_acl = smb_xstrdup(poptGetOptArg(pc));
904                         mode = SMB_ACL_DELETE;
905                         break;
906
907                 case 'M':
908                         the_acl = smb_xstrdup(poptGetOptArg(pc));
909                         mode = SMB_ACL_MODIFY;
910                         break;
911
912                 case 'a':
913                         the_acl = smb_xstrdup(poptGetOptArg(pc));
914                         mode = SMB_ACL_ADD;
915                         break;
916
917                 case 'C':
918                         owner_username = poptGetOptArg(pc);
919                         change_mode = REQUEST_CHOWN;
920                         break;
921
922                 case 'G':
923                         owner_username = poptGetOptArg(pc);
924                         change_mode = REQUEST_CHGRP;
925                         break;
926                 }
927         }
928
929         /* Make connection to server */
930         if(!poptPeekArg(pc)) {
931                 poptPrintUsage(pc, stderr, 0);
932                 return -1;
933         }
934
935         path = talloc_strdup(frame, poptGetArg(pc));
936         if (!path) {
937                 return -1;
938         }
939
940         if(!poptPeekArg(pc)) {
941                 poptPrintUsage(pc, stderr, 0);
942                 return -1;
943         }
944
945         filename = talloc_strdup(frame, poptGetArg(pc));
946         if (!filename) {
947                 return -1;
948         }
949
950         string_replace(path,'/','\\');
951
952         server = talloc_strdup(frame, path+2);
953         if (!server) {
954                 return -1;
955         }
956         share = strchr_m(server,'\\');
957         if (!share) {
958                 printf("Invalid argument: %s\n", share);
959                 return -1;
960         }
961
962         *share = 0;
963         share++;
964
965         if (!test_args) {
966                 cli = connect_one(server, share);
967                 if (!cli) {
968                         exit(EXIT_FAILED);
969                 }
970         } else {
971                 exit(0);
972         }
973
974         string_replace(filename, '/', '\\');
975         if (filename[0] != '\\') {
976                 filename = talloc_asprintf(frame,
977                                 "\\%s",
978                                 filename);
979                 if (!filename) {
980                         return -1;
981                 }
982         }
983
984         /* Perform requested action */
985
986         if (change_mode != REQUEST_NONE) {
987                 result = owner_set(cli, change_mode, filename, owner_username);
988         } else if (the_acl) {
989                 result = cacl_set(cli, filename, the_acl, mode);
990         } else {
991                 result = cacl_dump(cli, filename);
992         }
993
994         TALLOC_FREE(frame);
995
996         return result;
997 }