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

#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <rsbac/types.h>
#include <rsbac/aci_data_structures.h>
#include <rsbac/getname.h>
#include <rsbac/res_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

#define CAP_TO_INDEX(x)     ((x) >> 5)        /* 1 << 5 == bits in __u32 */

char * progname;

void use(void)
  {
    printf(gettext("%s (RSBAC %s)\n***\n"), progname, VERSION);
    printf(gettext("Use: %s module user attribute [position] value\n\n"), progname);  
    printf(gettext("Use: %s [switches] module user log_user_based [request-list]\n\n"), progname);  
    printf(gettext(" -h = this help, -- = no more flags,\n"));
    printf(gettext(" -p = print requests names, -a = add, not set, -m = remove, not set\n"));
    printf(gettext(" -z = do not also try numeric username as uid\n"));
    printf(gettext(" -A = list attributes and values\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(" module = CAP, GEN, MAC, FC, SIM, UDF, DAZ, FF, RC or AUTH\n"));
  }

int main(int argc, char ** argv)
{
  int attr_list[RSBAC_USER_NR_ATTRIBUTES] = RSBAC_USER_ATTR_LIST;
  int res = 0;
  char tmp1[RSBAC_MAXNAMELEN],tmp2[RSBAC_MAXNAMELEN],tmp3[RSBAC_MAXNAMELEN];
  int j;
  enum rsbac_switch_target_t module = SW_NONE;
  union rsbac_attribute_value_t value;
  union rsbac_target_id_t tid;
  enum rsbac_attribute_t attr;
  u_int position, catval;
  rsbac_res_limit_t res_limit;
  __u64 k;
  int verbose = 0;
  int printall = 0;
  int add = 0;
  int remove = 0;
  int nonumeric = 0;
  rsbac_list_ta_number_t ta_number = 0;
  u_int stopflags = FALSE;

  locale_init();

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

    if(env)
      ta_number = strtoul(env,0,0);
  }
  while((argc > 1) && (argv[1][0] == '-') && !stopflags)
    {
      char * pos = argv[1];
      pos++;
      while(*pos)
        {
          switch(*pos)
            {
              case '-':
                stopflags = TRUE;
                break;
              case 'h':
                use();
                return 0;
              case 'v':
                verbose++;
                break;
              case 'p':
                printall=1;
                break;
              case 'a':
                add=1;
                break;
              case 'm':
                remove=1;
                break;
              case 'z':
                nonumeric=1;
                break;
              case 'n':
                {
                  char tmp[80];
                  int i;

                  for(i=0; i<R_NONE; i++)
                    printf("%s\n", get_request_name(tmp, i));
                  exit(0);
                }
              case 'A':
                if(   (argc > 2)
                   && ((attr = get_attribute_nr(argv[2])) != A_none)
                  )
                  {
                    get_switch_target_name(tmp1, get_attr_module(attr));
                    get_attribute_name(tmp2, attr);
                    get_attribute_param(tmp3, attr);
                    printf("[%-4s] %s\n\t%s\n",tmp1,tmp2,tmp3);
                    exit(0);
                  }
                printf(gettext("- attribute (string) and returned value = see following list:\n"));
                printf(gettext("[MAC ] mac_[min_|initial_]categories (with additional parameter position)\n\t0=no, 1=yes\n"));
                printf(gettext("[GEN ] log_user_based (with space separated list of requests)\n\t0=no, 1=yes\n"));
                for (j=0;j<RSBAC_USER_NR_ATTRIBUTES;j++)
                  {
                    get_switch_target_name(tmp1, get_attr_module(attr_list[j]));
                    get_attribute_name(tmp2,attr_list[j]);
                    get_attribute_param(tmp3,attr_list[j]);
                    printf("[%-4s] %s\n\t%s\n",tmp1,tmp2,tmp3);
                  }
                exit(0);
              case 'V':
                if(argc < 3)
                  {
                    fprintf(stderr, gettext("%s: no version number for switch V\n"), progname);
                    exit(1);
                  }
                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 > 1)
    {
      module = get_switch_target_nr(argv[1]);
      if(module != SW_NONE)
        {
          argv++;
          argc--;
        }
    }
  if(   (argc>2)
     && !strcmp(argv[2],"log_user_based")
    )
    {
      rsbac_boolean_t rused = FALSE;
      rsbac_boolean_t wused = FALSE;
      enum rsbac_adf_request_t request;
      rsbac_request_vector_t request_vector = 0;

      value.log_user_based = 0;
      if(rsbac_get_uid(ta_number, &tid.user, argv[1], nonumeric))
        {
          fprintf(stderr, gettext("%s: Invalid User %s!\n"),
                  progname, argv[1]);
          exit(1);
        }

      argv+=2;
      argc-=2;

      if(add || remove)
        {
          res = rsbac_get_attr(ta_number, module, T_USER, &tid, A_log_user_based, &value, FALSE);
          error_exit(res);
        }
      while(argc > 1)
        {
          if(strlen(argv[1]) == R_NONE)
            {
              int j;
              rsbac_request_vector_t tmp_rv;

              for(j=0; j<R_NONE; j++)
                if(   (argv[1][j] != '0')
                   && (argv[1][j] != '1')
                  )
                  {
                    fprintf(stderr, gettext("%s: Invalid mask vector %s\n"), progname, argv[1]);
                    exit(1);
                  }
              strtou64acl(argv[1], &tmp_rv);
              request_vector |= tmp_rv;
              argv++;
              argc--;
              continue;
            }
          request = get_request_nr(argv[1]);
          if(request == R_NONE)
            {
              request = strtoul(argv[1],0,10);
              if(   (request >= R_NONE)
                 || (   (request == 0)
                     && strcmp(argv[1],"0")
                    )
                )
                {
                  if(!strcmp(argv[1],"RW"))
                    {
                      request_vector |= RSBAC_READ_WRITE_REQUEST_VECTOR;
                    }
                  else
                  if(!strcmp(argv[1],"SY"))
                    {
                      request_vector |= RSBAC_SYSTEM_REQUEST_VECTOR;
                    }
                  else
                  if(!strcmp(argv[1],"SE"))
                    {
                      request_vector |= RSBAC_SECURITY_REQUEST_VECTOR;
                    }
                  else
                  if(!strcmp(argv[1],"R"))
                    {
                      request_vector |= RSBAC_READ_REQUEST_VECTOR;
                      rused = TRUE;
                    }
                  else
                  if(!strcmp(argv[1],"W"))
                    {
                      request_vector |= RSBAC_WRITE_REQUEST_VECTOR;
                      wused = TRUE;
                    }
                  else
                  if(!strcmp(argv[1],"A"))
                    {
                      request_vector |= RSBAC_ALL_REQUEST_VECTOR;
                    }
                  else
                  if(!strcmp(argv[1],"UA"))
                    {
                      request_vector = 0;
                    }
                  else
                  if(!strcmp(argv[1],"NWS"))
                    {
                      request_vector |= RSBAC_NWS_REQUEST_VECTOR;
                    }
                  else
                  if(!strcmp(argv[1],"NWR"))
                    {
                      request_vector |= RSBAC_NWR_REQUEST_VECTOR;
                      rused = TRUE;
                    }
                  else
                  if(!strcmp(argv[1],"NWW"))
                    {
                      request_vector |= RSBAC_NWW_REQUEST_VECTOR;
                      wused = TRUE;
                    }
                  else
                  if(!strcmp(argv[1],"NWC"))
                    {
                      request_vector |= RSBAC_NWC_REQUEST_VECTOR;
                    }
                  else
                  if(!strcmp(argv[1],"NWE"))
                    {
                      request_vector |= RSBAC_NWE_REQUEST_VECTOR;
                    }
                  else
                  if(!strcmp(argv[1],"NWA"))
                    {
                      request_vector |= RSBAC_NWA_REQUEST_VECTOR;
                    }
                  else
                  if(!strcmp(argv[1],"NWF"))
                    {
                      request_vector |= RSBAC_NWF_REQUEST_VECTOR;
                    }
                  else
                  if(!strcmp(argv[1],"NWM"))
                    {
                      request_vector |= RSBAC_NWM_REQUEST_VECTOR;
                    }
                  else
                    { /* end of requests */
                      break;
                    }
                }
            }
          else
            {
              request_vector |= ((rsbac_request_vector_t) 1 << request);
            }
          argv++;
          argc--;
        }
      if(rused && wused)
        {
          request_vector |= RSBAC_READ_WRITE_OPEN_REQUEST_VECTOR;
        }
      if(remove)
          value.log_user_based &= ~request_vector;
      else
          value.log_user_based |= request_vector;

      if(printall)
        {
          int i;

          for (i=0; i<R_NONE; i++)
            if(value.log_user_based & ((rsbac_request_vector_t) 1 << i))
              printf(" %s\n", get_request_name(tmp1,i));
        }

      res = rsbac_set_attr(ta_number, module, T_USER, &tid, A_log_user_based, &value);
      error_exit(res);
      exit(0);
    }
  if(   (argc>2)
     && (   !strcmp(argv[2],"min_caps")
         || !strcmp(argv[2],"max_caps")
        )
    )
    {
      int cap;
      int bitlen;
      rsbac_boolean_t mincalled;
      rsbac_cap_vector_t cap_vector;

      cap_vector.cap[0] = (__u32) 0;
      cap_vector.cap[1] = (__u32) 0;

      if (!strcmp(argv[2],"min_caps"))
        mincalled = TRUE;
      else
        mincalled = FALSE;

      if(rsbac_get_uid(ta_number, &tid.user, argv[1], nonumeric))
        {
          fprintf(stderr, gettext("%s: Invalid User %s!\n"),
                  progname, argv[1]);
          exit(1);
        }
      attr = get_attribute_nr(argv[2]);
      value.min_caps.cap[0] = (__u32) 0;
      value.min_caps.cap[1] = (__u32) 0;
      argv+=2;
      argc-=2;
      if(add || remove)
        {
          res = rsbac_get_attr(ta_number, module, T_USER, &tid, attr, &value, FALSE);
          error_exit(res);
        }
      while(argc > 1)
        {
          /* Bit string: Allow for backwards compatibility */
          bitlen = strlen(argv[1]);
          if((bitlen == CAP_NONE) || (bitlen == CAP_NONE_OLD))
            {
              int j;
              rsbac_cap_vector_t tmp_cv;

              for(j=0; j<bitlen; j++)
                if(   (argv[1][j] != '0')
                   && (argv[1][j] != '1')
                  )
                  {
                    fprintf(stderr, gettext("%s: Invalid cap vector %s\n"), progname, argv[1]);
                    exit(1);
                  }
              if (bitlen == CAP_NONE_OLD) {
                strtou32cap(argv[1], &tmp_cv.cap[0]);
                if (mincalled == TRUE)
                  tmp_cv.cap[1] = (__u32) 0;
                else
                  {
                    int i;

                    for (i=CAP_NONE_OLD; i<32; i++)
                      tmp_cv.cap[0] |= (1 << i);
                    tmp_cv.cap[1] = (__u32) -1;
                  }
              } else {
                if (strcaptokcap(argv[1], &tmp_cv) < 0)
                  {
                    fprintf(stderr, gettext("%s: Invalid cap vector %s\n"), progname, argv[1]);
                    exit(1);
                  }
                else if (verbose)
                  printf("caps %s -> %s\n", argv[1], kcaptostrcap(tmp1, tmp_cv));
              }
              cap_vector.cap[0] |= tmp_cv.cap[0];
              cap_vector.cap[1] |= tmp_cv.cap[1];
              argv++;
              argc--;
              continue;
            }
          cap = get_cap_nr(argv[1]);
          if(cap == CAP_NONE)
            {
              cap = strtoul(argv[1],0,10);
              if(   (cap >= CAP_NONE)
                 || (   (cap == 0)
                     && strcmp(argv[1],"0")
                    )
                )
                {
                  if(!strcmp(argv[1],"A"))
                    {
			    cap_vector.cap[0] = (__u32) -1;
			    cap_vector.cap[1] = (__u32) -1;
                    }
                  else
                  if(!strcmp(argv[1],"UA"))
                    {
			    cap_vector.cap[0] = (__u32) 0;
			    cap_vector.cap[1] = (__u32) 0;
                    }
                  else
                  if(!strcmp(argv[1],"FS_MASK"))
                    { /* one day we're going to have problem here. look attr_set_file_dir.c */
                      cap_vector.cap[0] |= CAP_FS_MASK;
                    }
                  else
                    { /* end of requests */
                      fprintf(stderr, "%s: Wrong CAP %s\n", progname, argv[1]);
                      exit(1);
                    }
                }
              else
                {
                  fprintf(stderr, "%s: Wrong CAP %s\n", progname, argv[1]);
                  exit(1);
                }
            }
          else
            {
		    cap_vector.cap[CAP_TO_INDEX(cap)] |= ((__u32) 1 << (cap % 32));
            }
          argv++;
          argc--;
        }
      if(remove) {
        value.min_caps.cap[0] &= ~cap_vector.cap[0];
        value.min_caps.cap[1] &= ~cap_vector.cap[1];
      } else {
        value.min_caps.cap[0] |= cap_vector.cap[0];
        value.min_caps.cap[1] |= cap_vector.cap[1];
      }

      if(printall)
        {
          int i;

          for (i=0; i<CAP_NONE; i++)
		  if((value.min_caps.cap[0] & ((__u32) 1 << i)) || (value.min_caps.cap[1] & ((__u32) 1 << i)))
              printf(" %s\n", get_cap_name(tmp1,i));
        }
      res = rsbac_set_attr(ta_number, module, T_USER, &tid, attr, &value);
      error_exit(res);
      exit(0);
    }

/* normal attributes */
  switch(argc)
    {
      case 1:
      case 2:
      case 3:
        use();
        return 1;

      case 4:
        attr = get_attribute_nr(argv[2]);
        if(attr == A_none)
          {
            fprintf(stderr, gettext("%s: Invalid Attribute %s!\n"), progname, argv[2]);
            exit(1);
          }
        if(rsbac_get_uid(ta_number, &tid.user, argv[1], nonumeric))
          {
            fprintf(stderr, gettext("%s: Invalid User %s!\n"),
                    progname, argv[1]);
            exit(1);
          }

        switch(attr)
          {
            case A_none:
              fprintf(stderr, gettext("%s: Invalid attribute %s\n"), progname, argv[3]);
              exit(1);
            case A_res_min:
            case A_res_max:
              fprintf(stderr, gettext("%s: Invalid number of arguments for attribute %s\n"), progname, argv[3]);
              exit(1);
            case A_mac_categories:
            case A_mac_initial_categories:
            case A_mac_min_categories:
              if(strlen(argv[3]) != RSBAC_MAC_NR_CATS)
                {
                  fprintf(stderr, gettext("%s: Invalid attribute value, length must be %i\n"), progname,
                          RSBAC_MAC_NR_CATS);
                  exit(1);
                }
              strtou64mac(argv[3], &value.mac_categories);
              break;
            case A_mac_user_flags:
              if(add || remove)
                {
                  res = rsbac_get_attr(ta_number, module, T_USER, &tid, A_mac_user_flags, &value, FALSE);
                  error_exit(res);
                  if(add)
                    value.mac_user_flags |= strtoul(argv[3],0,10);
                  else
                    value.mac_user_flags &= ~strtoul(argv[3],0,10);
                }
              else
                value.mac_user_flags = strtoul(argv[3],0,10);
              break;

            case A_pseudo:
              value.pseudo = strtoul(argv[3],0,10);
              break;

            case A_log_user_based:
              value.log_user_based = strtoul(argv[3],0,10);
              break;

            case A_security_level:
            case A_initial_security_level:
            case A_min_security_level:
              value.security_level = strtoul(argv[3],0,10);
              break;

            case A_system_role:
            case A_mac_role:
            case A_daz_role:
            case A_udf_role:
            case A_ff_role:
            case A_auth_role:
            case A_cap_role:
            case A_jail_role:
            case A_res_role:
            case A_pax_role:
              value.system_role = strtoul(argv[3],0,10);
              break;

            case A_rc_def_role:
              value.rc_def_role = strtoul(argv[3],0,10);
              break;

            case A_min_caps:
              value.mac_user_flags = strtoul(argv[3],0,10);
              break;

            case A_max_caps:
              value.mac_user_flags = strtoul(argv[3],0,10);
              break;

            default:
              value.dummy = strtoul(argv[3],0,10);
          }
        /* backwards compatibility for system_role without module param */
        if(   (module == SW_NONE)
           && (attr == A_system_role)
          )
          {
            int tmpres;

            if(RSBAC_UID_SET(tid.user))
              fprintf(stderr, gettext("User %u/%u: system_role without module, setting for MAC, FC, SIM, DAZ, FF, AUTH\n"),
                      RSBAC_UID_SET(tid.user), RSBAC_UID_NUM(tid.user));
            else
              fprintf(stderr, gettext("User %u: system_role without module, setting for MAC, FC, SIM, DAZ, FF, AUTH\n"),
                      RSBAC_UID_NUM(tid.user));
            tmpres = rsbac_set_attr(ta_number, SW_MAC, T_USER, &tid, attr, &value);
            if(   tmpres
               && (errno != RSBAC_EINVALIDMODULE)
              )
              res = tmpres;
            tmpres = rsbac_set_attr(ta_number, SW_DAZ, T_USER, &tid, attr, &value);
            if(   tmpres
               && (errno != RSBAC_EINVALIDMODULE)
              )
              res = tmpres;
            tmpres = rsbac_set_attr(ta_number, SW_FF, T_USER, &tid, attr, &value);
            if(   tmpres
               && (errno != RSBAC_EINVALIDMODULE)
              )
              res = tmpres;
            tmpres = rsbac_set_attr(ta_number, SW_AUTH, T_USER, &tid, attr, &value);
            if(   tmpres
               && (errno != RSBAC_EINVALIDMODULE)
              )
              res = tmpres;
          }
        else
          {
            res = rsbac_set_attr(ta_number, module, T_USER, &tid, attr, &value);
          }
        error_exit(res);
        exit(0);

      case 5:
        if(rsbac_get_uid(ta_number, &tid.user, argv[1], nonumeric))
          {
            fprintf(stderr, gettext("%s: Invalid User %s!\n"),
                    progname, argv[1]);
            exit(1);
          }
        if(   !strcmp(argv[2],"mac_categories")
           || !strcmp(argv[2],"mac_initial_categories")
           || !strcmp(argv[2],"mac_min_categories")
          )
          {
            if(!strcmp(argv[2],"mac_min_categories"))
              attr = A_mac_min_categories;
            else
            if(!strcmp(argv[2],"mac_initial_categories"))
              attr = A_mac_initial_categories;
            else
              attr = A_mac_categories;
            position = strtoul(argv[3],0,10);
            if(position > RSBAC_MAC_MAX_CAT)
              {
                fprintf(stderr, gettext("Invalid position counter %s\n"), argv[4]);
                exit(1);
              }
            catval = strtoul(argv[4],0,10);
            if(catval > 1)
              {
                fprintf(stderr, gettext("Invalid value %s\n"), argv[4]);
                exit(1);
              }
            res = rsbac_get_attr(ta_number, module, T_USER, &tid, attr, &value, FALSE);
            error_exit(res);
            k = ((__u64) 1) << position;
            if(catval)
              value.mac_categories |= k;
            else
              value.mac_categories &= ~k;
            res = rsbac_set_attr(ta_number, module, T_USER, &tid, attr, &value);
            error_exit(res);
            exit(0);
          }
        else
        if(   !strcmp(argv[2],"res_min")
           || !strcmp(argv[2],"res_max")
          )
          {
            position = get_res_nr(argv[3]);
            if(position == RSBAC_RES_NONE)
              {
                position = strtoul(argv[3],0,10);
                if(   (!position && strcmp(argv[3], "0"))
                   || (position > RSBAC_RES_MAX)
                  )
                  {
                    fprintf(stderr, gettext("Invalid position counter %s\n"), argv[4]);
                    exit(1);
                  }
              }
            res_limit = strtoul(argv[4],0,10);
            if(!strcmp(argv[2],"res_min"))
              attr = A_res_min;
            else
              attr = A_res_max;
            res = rsbac_get_attr(ta_number, module, T_USER, &tid, attr, &value, TRUE);
            error_exit(res);
            value.res_array[position] = res_limit;
            res = rsbac_set_attr(ta_number, module, T_USER, &tid, attr, &value);
            error_exit(res);
            exit(0);
          }

      default:
        break;
    }
  exit(1);
}
