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

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <dirent.h>
#include <rsbac/types.h>
#include <rsbac/aci_data_structures.h>
#include <rsbac/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 LISTROOM 10

 union rsbac_attribute_value_t value;
 enum rsbac_switch_target_t module;
 enum rsbac_target_t target;
 enum rsbac_attribute_t attr;
 char * progname;
int verbose=0;
int recurse=0;
int inherit=0;
char * target_n;
char * attr_n;
rsbac_list_ta_number_t ta_number = 0;

void use(void)
    {
      printf(gettext("%s (RSBAC %s)\n***\n"), progname, VERSION);
      printf(gettext("Use: %s [-v] [-e] module target-type attribute [CAT category] [request] id(s)\n"), progname);
      printf(gettext(" -h = this help, -- = no more flags,\n"));
      printf(gettext(" -v = verbose, -e = show effective (maybe inherited) value, not real\n"));
      printf(gettext(" -r = recurse into subdirs, -n [target] = list all requests [for target]\n"));
      printf(gettext(" -a = list attributes and values\n"));
      printf(gettext(" -d = list NETDEV targets with non-default attribute values\n"));
      printf(gettext(" -N ta = transaction number (default = value of RSBAC_TA, if set, or 0)\n"));
      printf(gettext(" module = GEN, MAC, UDF or RC\n"));
      printf(gettext(" target-type = NETDEV, NETTEMP or NETOBJ\n"));
      printf(gettext(" category = category number for mac_categories\n"));
      printf(gettext(" request = request number for log_array_low|high\n"));
    }

int process(char * name, u_int request)
  {
    int res = 0;
    char tmp1[120];
    union rsbac_target_id_t tid;

    switch(target)
      {
        case T_NETDEV:
          strncpy((char *)tid.netdev, name, RSBAC_IFNAMSIZ);
          tid.netdev[RSBAC_IFNAMSIZ] = 0;
          break;
        case T_NETTEMP:
          tid.nettemp = strtoul(name, NULL, 10);
          if(   !tid.nettemp
             && strcmp(name, "0")
            )
            {
              fprintf(stderr, "Invalid network template %s!\n", name);
              return -RSBAC_EINVALIDTARGET;
            }
          break;
        case T_NETOBJ:
          break;
        default:
          fprintf(stderr, gettext("Internal error on %s %s!\n"),
                  target_n, name);
          return(1);
      }
    if(verbose)
      printf(gettext("Processing %s '%s', attribute %s\n"),
             target_n,
             name,
             attr_n);
    value.dummy = -1;
    if(target == T_NETOBJ)
      res = rsbac_get_attr_n(ta_number, module, target, name, attr, &value, inherit);
    else
      res = rsbac_get_attr(ta_number, module, target, &tid, attr, &value, inherit);
    show_error(res);
    if(res)
      return res;

    switch (attr)
      {
        case A_mac_categories:
        case A_local_mac_categories:
        case A_remote_mac_categories:
          if(request <= RSBAC_MAC_MAX_CAT)
            if(verbose)
              printf(gettext("%s: Returned value: %u\n"),
                     name, (u_int) (value.mac_categories & RSBAC_MAC_CAT_VECTOR(request)) >> request);
            else
              printf("%u\n",
                     (u_int) (value.mac_categories & RSBAC_MAC_CAT_VECTOR(request)) >> request);
          else
            if(verbose)
              printf(gettext("%s: Returned value: %s\n"),
                     name, u64tostrmac(tmp1,value.mac_categories));
            else
              printf("%s\n",
                     u64tostrmac(tmp1,value.mac_categories));
          break;
        case A_log_array_low:
        case A_log_array_high:
          if(request == R_NONE)
            {
              if(verbose)
                printf(gettext("%s: Returned value: %s\n"),
                       name, u64tostrlog(tmp1,value.log_array_low));
              else
                printf("%s\n",u64tostrlog(tmp1,value.log_array_low));
            }
          else
            {
              union rsbac_attribute_value_t value2;
              int log_level;
               res = rsbac_get_attr(ta_number, module, target, &tid, A_log_array_low, &value, FALSE);
              error_exit(res);
              res = rsbac_get_attr(ta_number, module, target, &tid, A_log_array_high, &value2, FALSE);
              error_exit(res);
              log_level =     ((value.log_array_low   >> request) & 1)
                          | ( ((value2.log_array_high >> request) & 1) << 1);
              printf("%u\n",log_level);
              return(0);
            }
          break;
        case A_security_level:
        case A_local_sec_level:
        case A_remote_sec_level:
          if(verbose)
            printf(gettext("%s: Returned value: %u\n"),
                   name, value.u_char_dummy);
          else
            printf("%u\n",
                   value.u_char_dummy);
          break;
        case A_rc_type:
        case A_local_rc_type:
        case A_remote_rc_type:
        case A_rc_type_nt:
          if(verbose)
            printf(gettext("%s: Returned value: %u\n"),
                   name, value.u_dummy);
          else
            printf("%u\n",
                   value.u_dummy);
          break;
        default:
          if(verbose)
            printf(gettext("%s: Returned value: %i\n"),
                   name, value.dummy);
          else
            printf("%i\n",
                   value.dummy);
      }
    return(0);
  }


int main(int argc, char ** argv)
{
  enum rsbac_attribute_t attr_list_dev[RSBAC_NETDEV_NR_ATTRIBUTES] = RSBAC_NETDEV_ATTR_LIST;
  enum rsbac_attribute_t attr_list_temp[RSBAC_NETTEMP_NR_ATTRIBUTES] = RSBAC_NETTEMP_ATTR_LIST;
  enum rsbac_attribute_t attr_list_obj[RSBAC_NETOBJ_NR_ATTRIBUTES] = RSBAC_NETOBJ_ATTR_LIST;
  int res = 0;
  char tmp1[RSBAC_MAXNAMELEN],tmp2[RSBAC_MAXNAMELEN],tmp3[RSBAC_MAXNAMELEN];
  int i,j;
  u_int request = R_NONE;
  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 'r':
                recurse=1;
                break;
              case 'e':
                inherit=1;
                break;
              case 'n':
                {
                  rsbac_request_vector_t rvector = -1;

                  if(argc > 2)
                    {
                      target = get_target_nr(argv[2]);
                      switch(target)
                        {
                          case T_NETDEV:
                            rvector = RSBAC_NETDEV_REQUEST_VECTOR;
                            break;
                          case T_NETTEMP:
                            rvector = RSBAC_NETTEMP_REQUEST_VECTOR;
                            break;
                          case T_NETOBJ:
                            rvector = RSBAC_NETOBJ_REQUEST_VECTOR;
                            break;
                          default:
                            if(!strcmp(argv[2], "NET"))
                              rvector =   RSBAC_NETTEMP_REQUEST_VECTOR
                                        | RSBAC_NETOBJ_REQUEST_VECTOR;
                        }
                    }
                  for(i=0; i<R_NONE; i++)
                    {
                      if(rvector & RSBAC_REQUEST_VECTOR(i))
                        printf("%s\n", get_request_name(tmp1, i));
                    }
                  exit(0);
                }
              case 'd':
                {
                  rsbac_netdev_id_t * netdev_array;
                  long count;

                  count = rsbac_net_list_all_netdev(ta_number, NULL, 0);
                  error_exit(count);
                  count += LISTROOM;
                  netdev_array = malloc(count * sizeof(*netdev_array));
                  if(!netdev_array)
                    error_exit(-ENOMEM);
                  count = rsbac_net_list_all_netdev(ta_number, netdev_array, count);
                  if(verbose)
                    printf("%li entries:\n", count);
                  for(i = 0; i< count ; i++)
                    printf("%s\n", netdev_array[i]);
                  free(netdev_array);
                  exit(0);
                }
              case 'a':
              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 lists:\n"));
                printf("NETDEV:\n");
                for (j=0;j<RSBAC_NETDEV_NR_ATTRIBUTES;j++)
                  {
                    get_switch_target_name(tmp1, get_attr_module(attr_list_dev[j]));
                    get_attribute_name(tmp2,attr_list_dev[j]);
                    get_attribute_param(tmp3,attr_list_dev[j]);
                    printf("[%-4s] %s\n\t%s\n",tmp1,tmp2,tmp3);
                  }
                printf("\nNETTEMP:\n");
                for (j=0;j<RSBAC_NETTEMP_NR_ATTRIBUTES;j++)
                  {
                    get_switch_target_name(tmp1, get_attr_module(attr_list_temp[j]));
                    get_attribute_name(tmp2,attr_list_temp[j]);
                    get_attribute_param(tmp3,attr_list_temp[j]);
                    printf("[%-4s] %s\n\t%s\n",tmp1,tmp2,tmp3);
                  }
                printf("\nNETOBJ:\n");
                for (j=0;j<RSBAC_NETOBJ_NR_ATTRIBUTES;j++)
                  {
                    get_switch_target_name(tmp1, get_attr_module(attr_list_obj[j]));
                    get_attribute_name(tmp2,attr_list_obj[j]);
                    get_attribute_param(tmp3,attr_list_obj[j]);
                    printf("[%-4s] %s\n\t%s\n",tmp1,tmp2,tmp3);
                  }
                exit(0);
              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 > 3)
    {
      if(verbose)
        printf(gettext("%s: %i targets\n\n"), progname, argc - 3);
      target = get_target_nr(argv[1]);
      switch(target)
        {
          case T_NETDEV:
          case T_NETTEMP:
          case T_NETOBJ:
            break;
          default:
            fprintf(stderr, gettext("%s: invalid target %s\n"), progname, argv[1]);
        }
      target_n = argv[1];
      attr = get_attribute_nr(argv[2]);
      attr_n = argv[2];
      switch(attr)
        {
          case A_log_array_low:
          case A_local_log_array_low:
          case A_remote_log_array_low:
          case A_log_array_high:
          case A_local_log_array_high:
          case A_remote_log_array_high:
            request = get_request_nr(argv[3]);
            if(request != R_NONE)
              {
                argv++;
                argc--;
              }
            break;
          case A_mac_categories:
          case A_local_mac_categories:
          case A_remote_mac_categories:
            if(   !strcmp(argv[3], "CAT")
               && (argc > 4)
              )
              {
                request = strtoul(argv[4],0,10);
                if(   (request > 0)
                   || !strcmp(argv[4],"0")
                  )
                  {
                    argv+=2;
                    argc-=2;
                  }
                else
                  {
                    fprintf(stderr, "Invalid category after CAT parameter!\n");
                    exit(1);
                  }
              }
            else
              request = RSBAC_MAC_MAX_CAT + 1;
            break;
          default:
            break;
        }
      for (i=3;i < (argc);i++)
        {
          process(argv[i], request);
        }
    }
  else
    {
      use();
      return 1;
    }
  return (res);
}
