/*************************************************** */
/* Rule Set Based Access Control                     */
/*                                                   */
/* Author and (c) 1999-2008: Amon Ott <ao@rsbac.org> */
/*                                                   */
/* Last modified: 25/Feb/2008                        */
/*************************************************** */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <dirent.h>
#include <pwd.h>
#include <time.h>
#include <rsbac/types.h>
#include <rsbac/aci_data_structures.h>
#include <rsbac/getname.h>
#include <rsbac/acl_getname.h>
#include <rsbac/syscalls.h>
#include <rsbac/error.h>
#include <rsbac/helpers.h>
#include "nls.h"
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

int verbose=0;
int recurse=0;
int printall=0;
int bitstring=0;
int exitval=0;
int numdev=0;
rsbac_version_t version=RSBAC_VERSION_NR;
rsbac_time_t ttl=RSBAC_ACL_TTL_KEEP;
rsbac_list_ta_number_t ta_number = 0;
union rsbac_attribute_value_t value;
enum rsbac_target_t target;
char * target_n;
enum rsbac_attribute_t attr;
char * progname;
rsbac_acl_rights_vector_t rights_vector;
enum rsbac_acl_subject_type_t  subj_type = ACLS_NONE;
rsbac_acl_subject_id_t    subj_id;
enum rsbac_acl_syscall_type_t call = ACLC_add_to_acl_entry;

void use(void)
    {
      printf(gettext("%s (RSBAC %s)\n***\n"), progname, VERSION);
      printf(gettext("Use: %s [switches] subj_type subj_id [rights] target-type file/dirname(s)\n"), progname);  
      printf(gettext("  -v = verbose, -r = recurse into subdirs,\n"));
      printf(gettext("  -p = print right names, -s = set rights, not add\n"));
      printf(gettext("  -k = revoke rights, not add, -m remove entry (set back to inherit)\n"));
      printf(gettext("  -b = expect rights as bitstring, -n = list valid SCD names\n"));
      printf(gettext("  -d = numeric device specification ({b|c}major[:minor])\n"));
      printf(gettext("  -u, -g, -l = shortcuts for USER, GROUP and ROLE\n"));
      printf(gettext("  -t = set relative time-to-live for this trustee in seconds (add and set only)\n"));
      printf(gettext("  -T = set absolute time-to-live for this trustee in seconds (add and set only)\n"));
      printf(gettext("  -D = set relative time-to-live for this trustee in days (add and set only)\n"));
      printf(gettext("  -V version = supply RSBAC integer version number for upgrading\n"));
      printf(gettext("  -N ta = transaction number (default = value of RSBAC_TA, if set, or 0)\n"));
      printf(gettext("  subj_type = USER, GROUP or ROLE,\n"));
      printf(gettext("  subj_id = user name or id number,\n"));
      printf(gettext("  rights = list of space-separated right names (requests and ACL specials),\n"));
      printf(gettext("        also request groups R (read requests), RW (read-write), W (write)\n"));
      printf(gettext("        SY (system), SE (security), A (all)\n"));
      printf(gettext("        S (ACL special rights)\n"));
      printf(gettext("        and NWx with x = S R W C E A F M (similar to well-known network system)\n"));
      printf(gettext("  target-type = FILE, DIR, FIFO, SYMLINK, DEV, IPC, SCD, USER, PROCESS, NETDEV,\n"));
      printf(gettext("                NETTEMP_NT, NETTEMP, NETOBJ or FD\n"));
      printf(gettext("  (FD: let %s decide between FILE, DIR, FIFO and SYMLINK, no DEV),\n"), progname);
      printf(gettext("  (IPC, USER, PROCESS: only :DEFAULT:\n"));
      printf(gettext("  (NETTEMP: no :DEFAULT:\n"));
      printf(gettext("- Use name :DEFAULT: for default ACL\n"));
    }

int process(char * name)
  {
    int res = 0;
    char tmp1[120];
    struct stat buf;
    struct rsbac_acl_syscall_arg_t   arg;
    struct rsbac_acl_syscall_n_arg_t arg_n;

    if(!strcmp(name,":DEFAULT:"))
      {
        switch(target)
          {
            case T_FILE:
            case T_DIR:
            case T_FIFO:
            case T_SYMLINK:
            case T_FD:
              arg_n.name = NULL;
              break;
            case T_DEV:
              if(numdev)
                arg.tid.dev = RSBAC_ZERO_DEV_DESC;
              else
                arg_n.name = NULL;
              break;

            case T_IPC:
              arg.tid.ipc.type = I_none;
              break;
            case T_SCD:
              arg.tid.scd = AST_none;
              break;
            case T_USER:
              arg.tid.user = RSBAC_NO_USER;
              break;
            case T_PROCESS:
              arg.tid.process = 0;
              break;
            case T_GROUP:
              arg.tid.group = RSBAC_NO_GROUP;
              break;
            case T_NETDEV:
              arg.tid.netdev[0] = 0;
              break;
            case T_NETTEMP_NT:
              arg.tid.nettemp = 0;
              break;
            case T_NETOBJ:
              arg.tid.netobj.sock_p = NULL;
              arg.tid.netobj.local_addr = NULL;
              arg.tid.netobj.local_len = 0;
              arg.tid.netobj.remote_addr = NULL;
              arg.tid.netobj.remote_len = 0;
              break;

            default:
              fprintf(stderr, gettext("Invalid target %u for %s, skipped!\n"),
                      target, name);
              return(1);
          }
        if(verbose)
          printf(gettext("Processing default %s '%s'\n"),
                 target_n,
                 name);
      }
    else
      {
        arg_n.name = name;
        switch(target)
          {
            case T_FILE:
            case T_DIR:
            case T_FIFO:
            case T_SYMLINK:
            case T_FD:
              break;
            case T_DEV:
              if(   numdev
                 && strtodevdesc(name, &arg.tid.dev)
                )
                {
                  fprintf(stderr, gettext("%s is no valid device specification, skipped\n"),
                           name);
                  return(1);
                }
              break;
            case T_SCD:
              arg.tid.scd = get_acl_scd_type_nr(name);
              if((arg.tid.scd == ST_none) || (arg.tid.scd == AST_none))
                {
                  fprintf(stderr, gettext("%s is no valid SCD name, skipped\n"),
                           name);
                  return(1);
                }
              break;
            case T_USER:
              if(rsbac_get_uid(ta_number, &arg.tid.user, name))
                {
                  fprintf(stderr, gettext("%s: Invalid User %s!\n"),
                          progname, name);
                  exit(1);
                }
              break;
            case T_GROUP:
              if(rsbac_get_gid(ta_number, &arg.tid.group, name))
                {
                  fprintf(stderr, gettext("%s: Invalid Group %s!\n"),
                          progname, name);
                  exit(1);
                }
              break;
            case T_NETDEV:
              strncpy((char *)arg.tid.netdev, name, RSBAC_IFNAMSIZ);
              arg.tid.netdev[RSBAC_IFNAMSIZ] = 0;
              break;
            case T_NETTEMP:
            case T_NETTEMP_NT:
              arg.tid.nettemp = strtoul(name, 0, 10);
              break;
            case T_NETOBJ:
              arg.tid.netobj.sock_p = (void *) strtoul(name, 0, 0);
              arg.tid.netobj.remote_addr = NULL;
              arg.tid.netobj.remote_len = 0;
              break;

            default:
              fprintf(stderr, gettext("Invalid target type %u for %s, skipped!\n"),
                      target, name);
              return(1);
          }
        if(verbose)
          printf(gettext("Processing %s '%s'\n"),
                 target_n,
                 name);
      } /* end of no default */
     
    switch(target)
      {
        case T_FILE:
        case T_DIR:
        case T_FIFO:
        case T_SYMLINK:
        case T_FD:
          arg_n.target = target;
          arg_n.subj_type = subj_type;
          arg_n.subj_id = subj_id;
          arg_n.rights = rights_vector;
          arg_n.ttl = ttl;
          res = rsbac_acl_n(ta_number, call, &arg_n);
          break;

        case T_DEV:
          if(!numdev)
            {
              arg_n.target = target;
              arg_n.subj_type = subj_type;
              arg_n.subj_id = subj_id;
              arg_n.rights = rights_vector;
              arg_n.ttl = ttl;
              res = rsbac_acl_n(ta_number, call, &arg_n);
              break;
            }
          /* fall through */

        default:
          arg.target = target;
          arg.subj_type = subj_type;
          arg.subj_id = subj_id;
          arg.rights = rights_vector;
          arg.ttl = ttl;
          res = rsbac_acl(ta_number, call, &arg);
      }
    if(res)
      {
        get_error_name(tmp1,res);
        fprintf(stderr, gettext("%s: error: %s\n"), name, tmp1);
        exitval=1;
      }

    if(   !lstat(name,&buf)
       && S_ISDIR(buf.st_mode)
       && recurse)
      {
        DIR * dir_stream_p;
        struct dirent * dirent_p;
        char name2[PATH_MAX];

        if(S_ISLNK(buf.st_mode))
          return(0);
        if(!(dir_stream_p = opendir(name)))
          {
            fprintf(stderr, gettext("opendir for dir %s returned error: %s\n"),
                   name,
                   strerror(errno));
            return(-2);
          }
        while((dirent_p = readdir(dir_stream_p)))
          {
            if(   (strcmp(".",dirent_p->d_name))
               && (strcmp("..",dirent_p->d_name)) )
              {
                strcpy(name2,name);
                strcat(name2,"/");
                strcat(name2,dirent_p->d_name);
                process(name2);
              }
          }
        closedir(dir_stream_p);
      }
    return(0);
  }

int main(int argc, char ** argv)
{
  int i;
  enum  rsbac_acl_special_rights_t right;
  rsbac_boolean_t rused = FALSE;
  rsbac_boolean_t wused = FALSE;
  char none_name[] = "FD";

  locale_init();

  progname = argv[0];
  {
    char * env = getenv("RSBAC_TA");

    if(env)
      ta_number = strtoul(env,0,0);
  }
  while((argc > 1) && (argv[1][0] == '-'))
    {
      char * pos = argv[1];
      pos++;
      while(*pos)
        {
          switch(*pos)
            {
              case 'h':
                use();
                return 0;
              case 'v':
                verbose++;
                break;
              case 'r':
                recurse=1;
                break;
              case 's':
                call = ACLC_set_acl_entry;
                break;
              case 'k':
                call = ACLC_remove_from_acl_entry;
                break;
              case 'm':
                call = ACLC_remove_acl_entry;
                break;
              case 'p':
                printall=1;
                break;
              case 'b':
                bitstring=1;
                break;
              case 'd':
                numdev=1;
                break;
              case 'n':
                {
                  char tmp[80];
                  for(i=0; i<ST_none; i++)
                    printf("%s\n", get_scd_type_name(tmp, i));
                  for(i=AST_min; i<AST_none; i++)
                    printf("%s\n", get_acl_scd_type_name(tmp, i));
                  exit(0);
                }
              case 'u':
                subj_type=ACLS_USER;
                break;
              case 'g':
                subj_type=ACLS_GROUP;
                break;
              case 'l':
                subj_type=ACLS_ROLE;
                break;
              case 't':
                if(argc > 2)
                  {
                    ttl = strtoul(argv[2], 0, 10);
                    argc--;
                    argv++;
                  }
                else
                  fprintf(stderr, gettext("%s: missing ttl value for parameter %c\n"), progname, *pos);
                break;
              case 'D':
                if(argc > 2)
                  {
                    ttl = 86400 * strtoul(argv[2], 0, 10);
                    argc--;
                    argv++;
                  }
                else
                  fprintf(stderr, gettext("%s: missing ttl value for parameter %c\n"), progname, *pos);
                break;
              case 'T':
                if(argc > 2)
                  {
                    rsbac_time_t now = time(NULL);
                    ttl = strtoul(argv[2], 0, 10);
                    if(ttl > now)
                      {
                        ttl -= now;
                        argc--;
                        argv++;
                      }
                    else
                      {
                        fprintf(stderr,
                                gettext("%s: ttl value for parameter %c is in the past, exiting\n"), progname, *pos);
                        exit(1);
                      }
                  }
                else
                  fprintf(stderr, gettext("%s: missing ttl value for parameter %c\n"), progname, *pos);
                break;
              case 'V':
                if(argc < 3)
                  {
                    fprintf(stderr, gettext("%s: no version number for switch V\n"), progname);
                    exit(1);
                  }
                version = strtol(argv[2],0,10);
                argv++;
                argc--;
                break;
              case 'N':
                if(argc > 2)
                  {
                    ta_number = strtoul(argv[2], 0, 10);
                    argc--;
                    argv++;
                  }
                else
                  {
                    fprintf(stderr, gettext("%s: missing transaction number value for parameter %c\n"), progname, *pos);
                    exit(1);
                  }
                break;
              default:
                fprintf(stderr, gettext("%s: unknown parameter %c\n"), progname, *pos);
                exit(1);
            }
          pos++;
        }
      argv++;
      argc--;
    }
  if (argc > 3)
    {
      if(subj_type == ACLS_NONE)
        {
          subj_type = get_acl_subject_type_nr(argv[1]);
          if(subj_type == ACLS_NONE)
            {
              fprintf(stderr, gettext("%s: unknown subject_type %s\n"), progname, argv[1]);
              exit(1);
            }
          argv++;
          argc--;
        }
      if(subj_type == ACLS_USER)
        {
          rsbac_uid_t uid;

          if(rsbac_get_uid(ta_number, &uid, argv[1]))
            {
              fprintf(stderr, gettext("%s: Invalid User %s!\n"),
                      progname, argv[1]);
              exit(1);
            }
          subj_id = uid;
        }
      else
        {
          subj_id = strtol(argv[1],0,10);
        }
      argv++;
      argc--;

      if(bitstring && (argc > 2))
        {
          if(strlen(argv[1]) != ACLR_NONE)
            {
              fprintf(stderr, gettext("Invalid bitstring length %u, must be %u!\n"),
                      strlen(argv[1]),
                      ACLR_NONE);
              exit(1);
            }
          strtou64acl(argv[1], &rights_vector);
          argv++;
          argc--;
        }
      else
        {
          while(argc > 2)
            {
              right = get_acl_special_right_nr(argv[1]);
              if((right == R_NONE) || (right == ACLR_NONE))
                {
                  if(!strcmp(argv[1],"UA"))
                    {
                      rights_vector &= RSBAC_ACL_SPECIAL_RIGHTS_VECTOR;
                    }
                  else
                  if(!strcmp(argv[1],"RW"))
                    {
                      rights_vector |= RSBAC_READ_WRITE_REQUEST_VECTOR;
                    }
                  else
                  if(!strcmp(argv[1],"R"))
                    {
                      rights_vector |= RSBAC_READ_REQUEST_VECTOR;
                      rused = TRUE;
                    }
                  else
                  if(!strcmp(argv[1],"W"))
                    {
                      rights_vector |= RSBAC_WRITE_REQUEST_VECTOR;
                      wused = TRUE;
                    }
                  else
                  if(!strcmp(argv[1],"SY"))
                    {
                      rights_vector |= RSBAC_SYSTEM_REQUEST_VECTOR;
                    }
                  else
                  if(!strcmp(argv[1],"SE"))
                    {
                      rights_vector |= RSBAC_SECURITY_REQUEST_VECTOR;
                    }
                  else
                  if(!strcmp(argv[1],"S"))
                    {
                      rights_vector |= RSBAC_ACL_SPECIAL_RIGHTS_VECTOR;
                    }
                  else
                  if(!strcmp(argv[1],"A"))
                    {
                      rights_vector |= RSBAC_ALL_REQUEST_VECTOR;
                    }
                  else
                  if(!strcmp(argv[1],"NWS"))
                    {
                      rights_vector |= RSBAC_NWS_REQUEST_VECTOR;
                    }
                  else
                  if(!strcmp(argv[1],"NWR"))
                    {
                      rights_vector |= RSBAC_NWR_REQUEST_VECTOR;
                      rused = TRUE;
                    }
                  else
                  if(!strcmp(argv[1],"NWW"))
                    {
                      rights_vector |= RSBAC_NWW_REQUEST_VECTOR;
                      wused = TRUE;
                    }
                  else
                  if(!strcmp(argv[1],"NWC"))
                    {
                      rights_vector |= RSBAC_NWC_REQUEST_VECTOR;
                    }
                  else
                  if(!strcmp(argv[1],"NWE"))
                    {
                      rights_vector |= RSBAC_NWE_REQUEST_VECTOR;
                    }
                  else
                  if(!strcmp(argv[1],"NWA"))
                    {
                      rights_vector |= RSBAC_NWA_REQUEST_VECTOR;
                    }
                  else
                  if(!strcmp(argv[1],"NWF"))
                    {
                      rights_vector |= RSBAC_NWF_REQUEST_VECTOR;
                    }
                  else
                  if(!strcmp(argv[1],"NWM"))
                    {
                      rights_vector |= RSBAC_NWM_REQUEST_VECTOR;
                    }
                  else
                    { /* end of rights */
                      break;
                    }
                }
              else
                {
                  rights_vector |= ((rsbac_acl_rights_vector_t) 1 << right);
                }
              argv++;
              argc--;
            }
          if(rused && wused)
            {
              rights_vector |= RSBAC_READ_WRITE_REQUEST_VECTOR;
            }
        } /* end of !bitstring */

      target = get_target_nr(argv[1]);
      target_n = argv[1];
      /* trim rights_vector for target */
      switch(target)
        {
          case T_DIR:
          case T_FILE:
          case T_FIFO:
          case T_SYMLINK:
          case T_FD:
            argv++;
            argc--;
            rights_vector &= (RSBAC_FD_REQUEST_VECTOR | RSBAC_ACL_SPECIAL_RIGHTS_VECTOR);
            break;
          case T_DEV:
            argv++;
            argc--;
            rights_vector &= (RSBAC_DEV_REQUEST_VECTOR | RSBAC_ACL_SPECIAL_RIGHTS_VECTOR);
            break;
          case T_IPC:
            argv++;
            argc--;
            rights_vector &= (RSBAC_IPC_REQUEST_VECTOR | RSBAC_ACL_SPECIAL_RIGHTS_VECTOR);
            break;
          case T_SCD:
            argv++;
            argc--;
            rights_vector &= (RSBAC_SCD_REQUEST_VECTOR | RSBAC_NONE_REQUEST_VECTOR | RSBAC_ACL_SPECIAL_RIGHTS_VECTOR);
            break;
          case T_USER:
            argv++;
            argc--;
            rights_vector &= (RSBAC_ACL_USER_RIGHTS_VECTOR | RSBAC_ACL_SPECIAL_RIGHTS_VECTOR);
            break;
          case T_PROCESS:
            argv++;
            argc--;
            rights_vector &= (RSBAC_PROCESS_REQUEST_VECTOR | RSBAC_ACL_SPECIAL_RIGHTS_VECTOR);
            break;
          case T_GROUP:
            argv++;
            argc--;
            rights_vector &= (RSBAC_ACL_GROUP_RIGHTS_VECTOR | RSBAC_ACL_SPECIAL_RIGHTS_VECTOR);
            break;
          case T_NETDEV:
            argv++;
            argc--;
            rights_vector &= (RSBAC_NETDEV_REQUEST_VECTOR | RSBAC_ACL_SPECIAL_RIGHTS_VECTOR);
            break;
          case T_NETTEMP_NT:
            argv++;
            argc--;
            rights_vector &= (RSBAC_NETTEMP_REQUEST_VECTOR | RSBAC_ACL_SPECIAL_RIGHTS_VECTOR);
            break;
          case T_NETTEMP:
          case T_NETOBJ:
            argv++;
            argc--;
            rights_vector &= (RSBAC_NETOBJ_REQUEST_VECTOR | RSBAC_ACL_SPECIAL_RIGHTS_VECTOR);
            break;
          case T_NONE:
            fprintf(stderr, "%s: No target type given, assuming FD\n", progname);
            target = T_FD;
            target_n = none_name;
            rights_vector &= (RSBAC_FD_REQUEST_VECTOR | RSBAC_ACL_SPECIAL_RIGHTS_VECTOR);
            break;
          default:
            fprintf(stderr, gettext("%s: Invalid target type %s\n"), progname, argv[1]);
        }
      if(verbose)
        {
          char tmp1[RSBAC_MAXNAMELEN];
          char tmp2[RSBAC_MAXNAMELEN];

          switch(call)
            {
              case ACLC_set_acl_entry:
                if (RSBAC_UID_SET(subj_id))
                  printf(gettext("Set rights: %s\nfor %s %u/%u\n"),
                       u64tostracl(tmp1, rights_vector),
                       get_acl_subject_type_name(tmp2, subj_type),
                       RSBAC_UID_SET(subj_id),
                       RSBAC_UID_NUM(subj_id));
                else
                  printf(gettext("Set rights: %s\nfor %s %u\n"),
                       u64tostracl(tmp1, rights_vector),
                       get_acl_subject_type_name(tmp2, subj_type),
                       RSBAC_UID_NUM(subj_id));
                break;
              case ACLC_add_to_acl_entry:
                if (RSBAC_UID_SET(subj_id))
                  printf(gettext("Add rights: %s\nfor %s %u/%u\n"),
                       u64tostracl(tmp1, rights_vector),
                       get_acl_subject_type_name(tmp2, subj_type),
                       RSBAC_UID_SET(subj_id),
                       RSBAC_UID_NUM(subj_id));
                else
                  printf(gettext("Add rights: %s\nfor %s %u\n"),
                       u64tostracl(tmp1, rights_vector),
                       get_acl_subject_type_name(tmp2, subj_type),
                       RSBAC_UID_NUM(subj_id));
                break;
              case ACLC_remove_from_acl_entry:
                if (RSBAC_UID_SET(subj_id))
                  printf(gettext("Revoke rights: %s\nfor %s %u/%u\n"),
                       u64tostracl(tmp1, rights_vector),
                       get_acl_subject_type_name(tmp2, subj_type),
                       RSBAC_UID_SET(subj_id),
                       RSBAC_UID_NUM(subj_id));
                else
                  printf(gettext("Revoke rights: %s\nfor %s %u\n"),
                       u64tostracl(tmp1, rights_vector),
                       get_acl_subject_type_name(tmp2, subj_type),
                       RSBAC_UID_NUM(subj_id));
                break;
              case ACLC_remove_acl_entry:
                if (RSBAC_UID_SET(subj_id))
                  printf(gettext("Remove entry for %s %u/%u.\n"),
                       get_acl_subject_type_name(tmp2, subj_type),
                       RSBAC_UID_SET(subj_id),
                       RSBAC_UID_NUM(subj_id));
                else
                  printf(gettext("Remove entry for %s %u.\n"),
                       get_acl_subject_type_name(tmp2, subj_type),
                       RSBAC_UID_NUM(subj_id));
                break;
              default:
                fprintf(stderr, gettext("%s: Internal error in call switch!\n"), progname);
                exit(1);
            }
          if(printall)
          {
            int i;

            for (i=0; i<R_NONE; i++)
              if(rights_vector & ((rsbac_acl_rights_vector_t) 1 << i))
                printf("  %s\n", get_request_name(tmp1,i));
            for (i=RSBAC_ACL_SPECIAL_RIGHT_BASE; i<ACLR_NONE; i++)
              if(rights_vector & ((rsbac_acl_rights_vector_t) 1 << i))
                printf("  %s\n", get_acl_special_right_name(tmp1,i));
          }
        }
      if(verbose>1)
        printf(gettext("\n%s: %i targets\n\n"), progname, argc - 1);
      for (i=1;i < (argc);i++)
        {
          process(argv[i]);
        }
    }
  else
    {
      use();
      return 1;
    }
  return(exitval);
}
