Return appropriate exit codes for various situations:
[samba.git] / source3 / utils / smbcacls.c
index aff5244fc5e50125732653465749e1ff5c0301ff..7600989655e931a76f2d286e6a99f88b46e76802 100644 (file)
@@ -4,6 +4,8 @@
    Version 3.0
    
    Copyright (C) Andrew Tridgell 2000
+   Copyright (C) Tim Potter      2000
+   Copyright (C) Jeremy Allison  2000
    
    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
@@ -23,7 +25,9 @@
 #include "includes.h"
 
 static fstring password;
-static fstring username;
+static pstring username;
+static pstring owner_username;
+static fstring server;
 static int got_pass;
 static int test_args;
 
@@ -31,7 +35,9 @@ static int test_args;
    than going via LSA calls to resolve them */
 static int numeric;
 
-enum acl_mode {ACL_SET, ACL_DELETE, ACL_MODIFY, ACL_ADD};
+enum acl_mode {ACL_SET, ACL_DELETE, ACL_MODIFY, ACL_ADD };
+enum chown_mode {REQUEST_NONE, REQUEST_CHOWN, REQUEST_CHGRP};
+enum exit_values {EXIT_OK, EXIT_FAILED, EXIT_PARSE_ERROR};
 
 struct perm_value {
        char *perm;
@@ -57,30 +63,94 @@ static struct perm_value standard_values[] = {
        { NULL, 0 },
 };
 
+struct cli_state lsa_cli;
+POLICY_HND pol;
+struct ntuser_creds creds;
+BOOL got_policy_hnd;
+
+/* Open cli connection and policy handle */
+
+static BOOL open_policy_hnd(void)
+{
+       creds.pwd.null_pwd = 1;
+
+       /* Initialise cli LSA connection */
+
+       if (!lsa_cli.initialised && 
+           !cli_lsa_initialise(&lsa_cli, server, &creds)) {
+               return False;
+       }
+
+       /* Open policy handle */
+
+       if (!got_policy_hnd) {
+               if (cli_lsa_open_policy(&lsa_cli, True, 
+                                       SEC_RIGHTS_MAXIMUM_ALLOWED, &pol)
+                   != NT_STATUS_NOPROBLEMO) {
+                       return False;
+               }
+
+               got_policy_hnd = True;
+       }
+       
+       return True;
+}
+
 /* convert a SID to a string, either numeric or username/group */
 static void SidToString(fstring str, DOM_SID *sid)
 {
-       if (numeric) {
-               sid_to_string(str, sid);
-       } else {
+       char **names = NULL;
+       uint32 *types = NULL;
+       int num_names;
+
+       sid_to_string(str, sid);
 
-               /* Need to add LSA lookups */
+       if (numeric) return;
 
-               sid_to_string(str, sid);
+       /* Ask LSA to convert the sid to a name */
+
+       if (!open_policy_hnd() ||
+           cli_lsa_lookup_sids(&lsa_cli, &pol, 1, sid, &names, &types, 
+                               &num_names) != NT_STATUS_NOPROBLEMO) {
+               return;
        }
+
+       /* Converted OK */
+       
+       fstrcpy(str, names[0]);
+       
+       safe_free(names[0]);
+       safe_free(names);
+       safe_free(types);
 }
 
 /* convert a string to a SID, either numeric or username/group */
-static BOOL StringToSid(DOM_SID *sid, fstring str)
+static BOOL StringToSid(DOM_SID *sid, char *str)
 {
-       if (strncmp(str,"S-", 2) == 0) {
+       uint32 *types = NULL;
+       DOM_SID *sids = NULL;
+       int num_sids;
+       BOOL result = True;
+       
+       if (strncmp(str, "S-", 2) == 0) {
                return string_to_sid(sid, str);
-       } else {
-
-               /* Need to add LSA lookups */
+       }
 
-               return string_to_sid(sid, str);
+       if (!open_policy_hnd() ||
+           cli_lsa_lookup_names(&lsa_cli, &pol, 1, &str, &sids, &types, 
+                                &num_sids) != NT_STATUS_NOPROBLEMO) {
+               result = False;
+               goto done;
        }
+
+       sid_copy(sid, &sids[0]);
+
+       safe_free(sids);
+       safe_free(types);
+
+ done:
+
+       return result;
 }
 
 
@@ -178,7 +248,7 @@ static BOOL parse_ace(SEC_ACE *ace, char *str)
 
        /* Try to parse text form */
 
-       if (!string_to_sid(&sid, str)) {
+       if (!StringToSid(&sid, str)) {
                return False;
        }
 
@@ -246,22 +316,22 @@ static BOOL parse_ace(SEC_ACE *ace, char *str)
 }
 
 /* add an ACE to a list of ACEs in a SEC_ACL */
-static BOOL add_ace(SEC_ACL **acl, SEC_ACE *ace)
+static BOOL add_ace(SEC_ACL **the_acl, SEC_ACE *ace)
 {
        SEC_ACL *new;
        SEC_ACE *aces;
-       if (! *acl) {
-               (*acl) = make_sec_acl(3, 1, ace);
+       if (! *the_acl) {
+               (*the_acl) = make_sec_acl(3, 1, ace);
                return True;
        }
 
-       aces = calloc(1+(*acl)->num_aces,sizeof(SEC_ACE));
-       memcpy(aces, (*acl)->ace, (*acl)->num_aces * sizeof(SEC_ACE));
-       memcpy(aces+(*acl)->num_aces, ace, sizeof(SEC_ACE));
-       new = make_sec_acl((*acl)->revision,1+(*acl)->num_aces, aces);
-       free_sec_acl(acl);
+       aces = calloc(1+(*the_acl)->num_aces,sizeof(SEC_ACE));
+       memcpy(aces, (*the_acl)->ace, (*the_acl)->num_aces * sizeof(SEC_ACE));
+       memcpy(aces+(*the_acl)->num_aces, ace, sizeof(SEC_ACE));
+       new = make_sec_acl((*the_acl)->revision,1+(*the_acl)->num_aces, aces);
+       free_sec_acl(the_acl);
        free(aces);
-       (*acl) = new;
+       (*the_acl) = new;
        return True;
 }
 
@@ -275,20 +345,14 @@ static SEC_DESC *sec_desc_parse(char *str)
        DOM_SID *grp_sid=NULL, *owner_sid=NULL;
        SEC_ACL *dacl=NULL;
        int revision=1;
-       int type=0x8004;
 
-       while (next_token(&p, tok, " \t,\r\n", sizeof(tok))) {
+       while (next_token(&p, tok, "\t,\r\n", sizeof(tok))) {
 
                if (strncmp(tok,"REVISION:", 9) == 0) {
                        revision = strtol(tok+9, NULL, 16);
                        continue;
                }
 
-               if (strncmp(tok,"TYPE:", 5) == 0) {
-                       type = strtol(tok+5, NULL, 16);
-                       continue;
-               }
-
                if (strncmp(tok,"OWNER:", 6) == 0) {
                        owner_sid = (DOM_SID *)calloc(1, sizeof(DOM_SID));
                        if (!owner_sid ||
@@ -311,9 +375,12 @@ static SEC_DESC *sec_desc_parse(char *str)
 
                if (strncmp(tok,"ACL:", 4) == 0) {
                        SEC_ACE ace;
-                       if (!parse_ace(&ace, tok+4) || 
-                           !add_ace(&dacl, &ace)) {
-                               printf("Failed to parse ACL\n");
+                       if (!parse_ace(&ace, tok+4)) {
+                               printf("Failed to parse ACL %s\n", tok);
+                               return NULL;
+                       }
+                       if(!add_ace(&dacl, &ace)) {
+                               printf("Failed to add ACL %s\n", tok);
                                return NULL;
                        }
                        continue;
@@ -341,7 +408,7 @@ static void sec_desc_print(FILE *f, SEC_DESC *sd)
        fstring sidstr;
        int i;
 
-       printf("REVISION:%d\nTYPE:0x%x\n", sd->revision, sd->type);
+       printf("REVISION:%d\n", sd->revision);
 
        /* Print owner and group sid */
 
@@ -370,28 +437,51 @@ static void sec_desc_print(FILE *f, SEC_DESC *sd)
 
 }
 
+/* Some systems seem to require unicode pathnames for the ntcreate&x call
+   despite Samba negotiating ascii filenames.  Try with unicode pathname if
+   the ascii version fails. */
+
+int do_cli_nt_create(struct cli_state *cli, char *fname, uint32 DesiredAccess)
+{
+       int result;
+
+       result = cli_nt_create(cli, fname, DesiredAccess);
+
+       if (result == -1) {
+               uint32 errnum, nt_rpc_error;
+               uint8 errclass;
+
+               cli_error(cli, &errclass, &errnum, &nt_rpc_error);
+
+               if (errclass == ERRDOS && errnum == ERRbadpath) {
+                       result = cli_nt_create_uni(cli, fname, DesiredAccess);
+               }
+       }
+
+       return result;
+}
 
 /***************************************************** 
 dump the acls for a file
 *******************************************************/
-static void cacl_dump(struct cli_state *cli, char *filename)
+static int cacl_dump(struct cli_state *cli, char *filename)
 {
        int fnum;
        SEC_DESC *sd;
 
-       if (test_args) return;
+       if (test_args) return EXIT_OK;
 
-       fnum = cli_nt_create(cli, filename, 0x20000);
+       fnum = do_cli_nt_create(cli, filename, 0x20000);
        if (fnum == -1) {
                printf("Failed to open %s: %s\n", filename, cli_errstr(cli));
-               return;
+               return EXIT_FAILED;
        }
 
        sd = cli_query_secdesc(cli, fnum);
 
        if (!sd) {
                printf("ERROR: secdesc query failed: %s\n", cli_errstr(cli));
-               return;
+               return EXIT_FAILED;
        }
 
        sec_desc_print(stdout, sd);
@@ -399,30 +489,125 @@ static void cacl_dump(struct cli_state *cli, char *filename)
        free_sec_desc(&sd);
 
        cli_close(cli, fnum);
+
+       return EXIT_OK;
+}
+
+/***************************************************** 
+Change the ownership or group ownership of a file. Just
+because the NT docs say this can't be done :-). JRA.
+*******************************************************/
+
+static int owner_set(struct cli_state *cli, enum chown_mode change_mode, 
+                    char *filename, char *new_username)
+{
+       int fnum;
+       DOM_SID sid;
+       SEC_DESC *sd, *old;
+       size_t sd_size;
+
+       fnum = do_cli_nt_create(cli, filename, 
+                               READ_CONTROL_ACCESS | WRITE_DAC_ACCESS
+                               | WRITE_OWNER_ACCESS);
+
+       if (fnum == -1) {
+               printf("Failed to open %s: %s\n", filename, cli_errstr(cli));
+               return EXIT_FAILED;
+       }
+
+       if (!StringToSid(&sid, new_username))
+               return EXIT_PARSE_ERROR;
+
+       old = cli_query_secdesc(cli, fnum);
+
+       sd = make_sec_desc(old->revision,
+                               (change_mode == REQUEST_CHOWN) ? &sid : old->owner_sid,
+                               (change_mode == REQUEST_CHGRP) ? &sid : old->grp_sid,
+                          NULL, old->dacl, &sd_size);
+
+       if (!cli_set_secdesc(cli, fnum, sd)) {
+               printf("ERROR: secdesc set failed: %s\n", cli_errstr(cli));
+       }
+
+       free_sec_desc(&sd);
+       free_sec_desc(&old);
+
+       cli_close(cli, fnum);
+
+       return EXIT_OK;
+}
+
+/* The MSDN is contradictory over the ordering of ACE entries in an ACL.
+   However NT4 gives a "The information may have been modified by a
+   computer running Windows NT 5.0" if denied ACEs do not appear before
+   allowed ACEs. */
+
+static void sort_acl(SEC_ACL *the_acl)
+{
+       SEC_ACE *tmp_ace;
+       int i, ace_ndx = 0;
+       BOOL do_denied = True;
+
+       tmp_ace = (SEC_ACE *)malloc(sizeof(SEC_ACE) * the_acl->num_aces);
+
+       if (!tmp_ace) return;
+
+ copy_aces:
+       
+       for (i = 0; i < the_acl->num_aces; i++) {
+
+               /* Copy denied ACEs */
+
+               if (do_denied &&
+                   the_acl->ace[i].type == SEC_ACE_TYPE_ACCESS_DENIED) {
+                       tmp_ace[ace_ndx] = the_acl->ace[i];
+                       ace_ndx++;
+               }
+
+               /* Copy other ACEs */
+
+               if (!do_denied &&
+                   the_acl->ace[i].type != SEC_ACE_TYPE_ACCESS_DENIED) {
+                       tmp_ace[ace_ndx] = the_acl->ace[i];
+                       ace_ndx++;
+               }
+       }
+
+       if (do_denied) {
+               do_denied = False;
+               goto copy_aces;
+       }
+
+       free(the_acl->ace);
+       the_acl->ace = tmp_ace;
 }
 
 /***************************************************** 
 set the ACLs on a file given an ascii description
 *******************************************************/
-static void cacl_set(struct cli_state *cli, char *filename, 
-                    char *acl, enum acl_mode mode)
+static int cacl_set(struct cli_state *cli, char *filename, 
+                   char *the_acl, enum acl_mode mode)
 {
        int fnum;
        SEC_DESC *sd, *old;
        int i, j;
-       unsigned sd_size;
+       size_t sd_size;
+       int result = EXIT_OK;
 
-       sd = sec_desc_parse(acl);
+       sd = sec_desc_parse(the_acl);
 
-       if (!sd) return;
-       if (test_args) return;
+       if (!sd) return EXIT_PARSE_ERROR;
+       if (test_args) return EXIT_OK;
+
+       /* The desired access below is the only one I could find that works
+          with NT4, W2KP and Samba */
+
+       fnum = do_cli_nt_create(cli, filename, 
+                               MAXIMUM_ALLOWED_ACCESS | 0x60000);
 
-       /* the desired access below is the only one I could find that works with
-          NT4, W2KP and Samba */
-       fnum = cli_nt_create(cli, filename, MAXIMUM_ALLOWED_ACCESS | 0x60000);
        if (fnum == -1) {
                printf("Failed to open %s: %s\n", filename, cli_errstr(cli));
-               return;
+               return EXIT_FAILED;
        }
 
        old = cli_query_secdesc(cli, fnum);
@@ -499,18 +684,28 @@ static void cacl_set(struct cli_state *cli, char *filename,
                free_sec_desc(&sd);
        }
 
+       /* Denied ACE entries must come before allowed ones */
+
+       sort_acl(old->dacl);
+
+       /* Create new security descriptor and set it */
+
        sd = make_sec_desc(old->revision, old->owner_sid, old->grp_sid, 
                           NULL, old->dacl, &sd_size);
 
        if (!cli_set_secdesc(cli, fnum, sd)) {
                printf("ERROR: secdesc set failed: %s\n", cli_errstr(cli));
-               return;
+               result = EXIT_FAILED;
        }
 
+       /* Clean up */
+
        free_sec_desc(&sd);
        free_sec_desc(&old);
 
        cli_close(cli, fnum);
+
+       return result;
 }
 
 
@@ -522,7 +717,6 @@ struct cli_state *connect_one(char *share)
        struct cli_state *c;
        struct nmb_name called, calling;
        char *server_n;
-       fstring server;
        struct in_addr ip;
        extern struct in_addr ipzero;
        extern pstring global_myname;
@@ -547,12 +741,15 @@ struct cli_state *connect_one(char *share)
        if (!(c=cli_initialise(NULL)) || (cli_set_port(c, 139) == 0) ||
            !cli_connect(c, server_n, &ip)) {
                DEBUG(0,("Connection to %s failed\n", server_n));
+               cli_shutdown(c);
+               safe_free(c);
                return NULL;
        }
 
        if (!cli_session_request(c, &calling, &called)) {
                DEBUG(0,("session request to %s failed\n", called.name));
                cli_shutdown(c);
+               safe_free(c);
                if (strcmp(called.name, "*SMBSERVER")) {
                        make_nmb_name(&called , "*SMBSERVER", 0x20);
                        goto again;
@@ -565,6 +762,7 @@ struct cli_state *connect_one(char *share)
        if (!cli_negprot(c)) {
                DEBUG(0,("protocol negotiation failed\n"));
                cli_shutdown(c);
+               safe_free(c);
                return NULL;
        }
 
@@ -580,6 +778,8 @@ struct cli_state *connect_one(char *share)
                               password, strlen(password),
                               lp_workgroup())) {
                DEBUG(0,("session setup failed: %s\n", cli_errstr(c)));
+               cli_shutdown(c);
+               safe_free(c);
                return NULL;
        }
 
@@ -589,6 +789,7 @@ struct cli_state *connect_one(char *share)
                            password, strlen(password)+1)) {
                DEBUG(0,("tree connect failed: %s\n", cli_errstr(c)));
                cli_shutdown(c);
+               safe_free(c);
                return NULL;
        }
 
@@ -601,12 +802,14 @@ struct cli_state *connect_one(char *share)
 static void usage(void)
 {
        printf(
-"Usage: smbcacls //server1/share1 filename -U username [options]\n\
+"Usage: smbcacls //server1/share1 filename [options]\n\
 \n\
 \t-D <acls>               delete an acl\n\
 \t-M <acls>               modify an acl\n\
 \t-A <acls>               add an acl\n\
 \t-S <acls>               set acls\n\
+\t-C username             change ownership of a file\n\
+\t-G username             change group ownership of a file\n\
 \t-n                      don't resolve sids or masks to names\n\
 \t-h                      print help\n\
 \n\
@@ -633,15 +836,17 @@ You can string acls together with spaces, commas or newlines\n\
        static pstring servicesf = CONFIGFILE;
        struct cli_state *cli;
        enum acl_mode mode;
-       char *acl = NULL;
+       char *the_acl = NULL;
+       enum chown_mode change_mode = REQUEST_NONE;
+       int result;
 
        setlinebuf(stdout);
 
        dbf = stderr;
 
-       if (argc < 4 || argv[1][0] == '-') {
+       if (argc < 3 || argv[1][0] == '-') {
                usage();
-               exit(1);
+               exit(EXIT_PARSE_ERROR);
        }
 
        setup_logging(argv[0],True);
@@ -662,11 +867,19 @@ You can string acls together with spaces, commas or newlines\n\
 
        if (getenv("USER")) {
                pstrcpy(username,getenv("USER"));
+
+               if ((p=strchr(username,'%'))) {
+                       *p = 0;
+                       pstrcpy(password,p+1);
+                       got_pass = True;
+                       memset(strchr(getenv("USER"), '%') + 1, 'X',
+                              strlen(password));
+               }
        }
 
        seed = time(NULL);
 
-       while ((opt = getopt(argc, argv, "U:nhS:D:A:M:t")) != EOF) {
+       while ((opt = getopt(argc, argv, "U:nhS:D:A:M:C:G:t")) != EOF) {
                switch (opt) {
                case 'U':
                        pstrcpy(username,optarg);
@@ -679,25 +892,35 @@ You can string acls together with spaces, commas or newlines\n\
                        break;
 
                case 'S':
-                       acl = optarg;
+                       the_acl = optarg;
                        mode = ACL_SET;
                        break;
 
                case 'D':
-                       acl = optarg;
+                       the_acl = optarg;
                        mode = ACL_DELETE;
                        break;
 
                case 'M':
-                       acl = optarg;
+                       the_acl = optarg;
                        mode = ACL_MODIFY;
                        break;
 
                case 'A':
-                       acl = optarg;
+                       the_acl = optarg;
                        mode = ACL_ADD;
                        break;
 
+               case 'C':
+                       pstrcpy(owner_username,optarg);
+                       change_mode = REQUEST_CHOWN;
+                       break;
+
+               case 'G':
+                       pstrcpy(owner_username,optarg);
+                       change_mode = REQUEST_CHGRP;
+                       break;
+
                case 'n':
                        numeric = 1;
                        break;
@@ -708,11 +931,11 @@ You can string acls together with spaces, commas or newlines\n\
 
                case 'h':
                        usage();
-                       exit(1);
+                       exit(EXIT_PARSE_ERROR);
 
                default:
                        printf("Unknown option %c (%d)\n", (char)opt, opt);
-                       exit(1);
+                       exit(EXIT_PARSE_ERROR);
                }
        }
 
@@ -721,19 +944,35 @@ You can string acls together with spaces, commas or newlines\n\
        
        if (argc > 0) {
                usage();
-               exit(1);
+               exit(EXIT_PARSE_ERROR);
        }
 
+       /* Make connection to server */
+
        if (!test_args) {
                cli = connect_one(share);
-               if (!cli) exit(1);
+               if (!cli) exit(EXIT_FAILED);
        }
 
-       if (acl) {
-               cacl_set(cli, filename, acl, mode);
+       {
+               char *s;
+
+               s = filename;
+               while(*s) {
+                       if (*s == '/') *s = '\\';
+                       s++;
+               }
+       }
+
+       /* Perform requested action */
+
+       if (change_mode != REQUEST_NONE) {
+               result = owner_set(cli, change_mode, filename, owner_username);
+       } else if (the_acl) {
+               result = cacl_set(cli, filename, the_acl, mode);
        } else {
-               cacl_dump(cli, filename);
+               result = cacl_dump(cli, filename);
        }
 
-       return(0);
+       return result;
 }