Example #1
0
/*
  This function takes a path and a mode, it calls computecon to get the
  label of the path object if the current process created it, then it calls
  matchpathcon to get the default type for the object.  It substitutes the
  default type into label.  It tells the SELinux Kernel to label all new file
  system objects created by the current process with this label.

  Returns -1 on failure.  errno will be set appropriately.
*/
int
defaultcon (char const *path, mode_t mode)
{
  int rc = -1;
  char *scon = NULL;
  char *tcon = NULL;
  context_t scontext = 0, tcontext = 0;
  const char *contype;
  char *constr;
  char *newpath = NULL;

  if (! IS_ABSOLUTE_FILE_NAME (path))
    {
      /* Generate absolute path as required by subsequent matchpathcon(),
         with libselinux < 2.1.5 2011-0826.  */
      newpath = canonicalize_filename_mode (path, CAN_MISSING);
      if (! newpath)
        error (EXIT_FAILURE, errno, _("error canonicalizing %s"),
               quote (path));
      path = newpath;
    }

  if (matchpathcon (path, mode, &scon) < 0)
    {
      /* "No such file or directory" is a confusing error,
         when processing files, when in fact it was the
         associated default context that was not found.
         Therefore map the error to something more appropriate
         to the context in which we're using matchpathcon().  */
      if (errno == ENOENT)
        errno = ENODATA;
      goto quit;
    }
  if (computecon (path, mode, &tcon) < 0)
    goto quit;
  if (!(scontext = context_new (scon)))
    goto quit;
  if (!(tcontext = context_new (tcon)))
    goto quit;

  if (!(contype = context_type_get (scontext)))
    goto quit;
  if (context_type_set (tcontext, contype))
    goto quit;
  if (!(constr = context_str (tcontext)))
    goto quit;

  rc = setfscreatecon (constr);

quit:
  context_free (scontext);
  context_free (tcontext);
  freecon (scon);
  freecon (tcon);
  free (newpath);
  return rc;
}
Example #2
0
static int set_context_from_socket( const struct service_config *scp, int fd )
{
   security_context_t curr_context = NULL;
   security_context_t peer_context = NULL;
   security_context_t exec_context = NULL;
   context_t bcon = NULL;
   context_t pcon = NULL;
   security_context_t new_context = NULL;
   security_context_t new_exec_context = NULL;
   int retval = -1;
   const char *exepath = NULL;

   if (getcon(&curr_context) < 0)
     goto fail;
   
   if (getpeercon(fd, &peer_context) < 0)
     goto fail;

   exepath = SC_SERVER_ARGV( scp )[0];
   if (getfilecon(exepath, &exec_context) < 0)
     goto fail;

   if (!(bcon = context_new(curr_context)))
     goto fail;

   if (!(pcon = context_new(peer_context)))
     goto fail;

   if (!context_range_get(pcon))
     goto fail;
   
   if (context_range_set(bcon, context_range_get(pcon)))
     goto fail;

   if (!(new_context = context_str(bcon)))
     goto fail;
   
   if (security_compute_create(new_context, exec_context, SECCLASS_PROCESS,
                               &new_exec_context) < 0)
     goto fail;

   retval = set_context(new_exec_context);

   freecon(new_exec_context);

 fail:
   context_free(pcon);
   context_free(bcon);
   freecon(exec_context);   
   freecon(peer_context);
   freecon(curr_context);

   return retval;
}
static int
testSELinuxGenLabel(const void *opaque)
{
    const struct testSELinuxGenLabelData *data = opaque;
    int ret = -1;
    virDomainDefPtr def;
    context_t con = NULL;
    context_t imgcon = NULL;

    if (setcon_raw((security_context_t)data->pidcon) < 0) {
        perror("Cannot set process security context");
        return -1;
    }

    if (!(def = testBuildDomainDef(data->dynamic,
                                   data->label,
                                   data->baselabel)))
        goto cleanup;

    if (virSecurityManagerGenLabel(data->mgr, def) < 0) {
        virErrorPtr err = virGetLastError();
        fprintf(stderr, "Cannot generate label: %s\n", err->message);
        goto cleanup;
    }

    VIR_DEBUG("label=%s imagelabel=%s",
              def->seclabels[0]->label, def->seclabels[0]->imagelabel);

    if (!(con = context_new(def->seclabels[0]->label)))
        goto cleanup;
    if (!(imgcon = context_new(def->seclabels[0]->imagelabel)))
        goto cleanup;

    if (!testSELinuxCheckCon(con,
                             data->user, data->role, data->type,
                             data->sensMin, data->sensMax,
                             data->catMin, data->catMax))
        goto cleanup;

    if (!testSELinuxCheckCon(imgcon,
                             data->user, data->imagerole, data->imagetype,
                             data->sensMin, data->sensMax,
                             data->catMin, data->catMax))
        goto cleanup;

    ret = 0;

cleanup:
    context_free(con);
    context_free(imgcon);
    virDomainDefFree(def);
    return ret;
}
Example #4
0
void repl() {
    char str[FG_MAX_INPUT];
    struct context *context = context_new(NULL, true, true);

    for (;;) {
        fflush(stdin);
        str[0] = 0;
        printf("f> ");
        if (!fgets(str, FG_MAX_INPUT, stdin)) {
            if (feof(stdin))
                return;
            if (ferror(stdin)) {
                printf("unknown error reading stdin\n");
                return;
            }
        }

        struct byte_array *input = byte_array_from_string(str);
        struct byte_array *program = build_string(input, NULL);
        if (!setjmp(trying)) {
            run(context, program, NULL, true);
        }
        byte_array_del(input);
        byte_array_del(program);
    }
}
Example #5
0
/* Look up colors.
 */
int raw_color(const security_context_t raw, char **color_str) {
#define CHARS_PER_COLOR 16
	context_t con;
	uint32_t i, j, mask = 0;
	const secolor_t *items[N_COLOR];
	char *result, *components[N_COLOR];
	char buf[CHARS_PER_COLOR + 1];
	size_t result_size = (N_COLOR * CHARS_PER_COLOR) + 1;
	int rc = -1;

	if (!color_str || *color_str) {
		return -1;
	}

	/* parse context and allocate memory */
	con = context_new(raw);
	if (!con)
		return -1;
	if (parse_components(con, components) < 0)
		goto out;

	result = malloc(result_size);
	if (!result)
		goto out;
	result[0] = '\0';

	/* find colors for which we have a match */
	for (i = 0; i < N_COLOR; i++) {
		items[i] = find_color(i, components[i], raw);
		if (items[i])
			mask |= (1 << i);
	}
	if (mask == 0) {
		items[0] = &default_color;
		mask = 1;
	}

	/* propagate colors according to the precedence rules */
	for (i = 0; i < N_COLOR; i++)
		if (!(mask & (1 << i)))
			for (j = 0; j < N_COLOR - 1; j++)
				if (mask & (1 << precedence[i][j])) {
					items[i] = items[precedence[i][j]];
					break;
				}

	/* print results into a big long string */
	for (i = 0; i < N_COLOR; i++) {
		snprintf(buf, sizeof(buf), "#%06x #%06x ",
			 items[i]->fg, items[i]->bg);
		strncat(result, buf, result_size-1);
	}

	*color_str = result;
	rc = 0;
out:
	context_free(con);

	return rc;
}
Example #6
0
static context_t runcon_compute_new_context(char *user, char *role, char *type, char *range,
			char *command, int compute_trans)
{
	context_t con;
	security_context_t cur_context;

	if (getcon(&cur_context))
		bb_error_msg_and_die("can't get current context");

	if (compute_trans) {
		security_context_t file_context, new_context;

		if (getfilecon(command, &file_context) < 0)
			bb_error_msg_and_die("can't retrieve attributes of '%s'",
					command);
		if (security_compute_create(cur_context, file_context,
					SECCLASS_PROCESS, &new_context))
			bb_error_msg_and_die("unable to compute a new context");
		cur_context = new_context;
	}

	con = context_new(cur_context);
	if (!con)
		bb_error_msg_and_die("'%s' is not a valid context", cur_context);
	if (user && context_user_set(con, user))
		bb_error_msg_and_die("can't set new user '%s'", user);
	if (type && context_type_set(con, type))
		bb_error_msg_and_die("can't set new type '%s'", type);
	if (range && context_range_set(con, range))
		bb_error_msg_and_die("can't set new range '%s'", range);
	if (role && context_role_set(con, role))
		bb_error_msg_and_die("can't set new role '%s'", role);

	return con;
}
Example #7
0
void *incoming_connection(void *arg)
{
	char readline[MAXLINE];
    struct thread_argument *ta = (struct thread_argument *)arg;
    struct context *context = context_new(true, true);
    context->find = ta->find;

    for (;;)
    {
        bzero(readline, sizeof(readline));
        int n;
        if (((n = CyaSSL_read(ta->ssl, readline, MAXLINE)) <= 0))
        {
            fprintf(stderr, "client closed connection\n");
            goto free_ssl;
        }

        fprintf(stderr, "%d bytes received: %s\n", n, readline);
        struct byte_array *raw_message = byte_array_new_size(n);
        raw_message->data = (uint8_t*)readline;
        int32_t raw_message_length = serial_decode_int(raw_message);
        assert_message(raw_message_length < MAXLINE, "todo: handle long messages");
        struct variable *message = variable_deserialize(context, raw_message);

        struct variable *listener = (struct variable *)map_get(server_listeners, (void*)(VOID_INT)ta->fd);
        vm_call(context, listener, message);
    }

free_ssl:
	CyaSSL_free(ta->ssl); // Free CYASSL object
    free(ta);
    context_del(context);
	return NULL;
}
Example #8
0
int main(void) {
    Context ctx = context_new("<stdin>", file_to_char_stream(stdin));
    ctx.color_enabled = true;
    int ret_value = EXIT_SUCCESS;

    if (yyparse(&ctx) == 0) {
        printf("Parsed as:\n");
        translation_unit_pprint(&ctx, stdout, &ctx.ast);
        putchar('\n');

        for (size_t i = 0; i < ctx.ast.num_top_levels; i++) {
            if (!type_check_top_level(&ctx, &ctx.ast.top_levels[i])) {
                fprintf(stderr, "Failed to type check \"%s\".\n",
                    ctx.ast.top_levels[i].name);
                ret_value = EXIT_FAILURE;
            }
        }
    } else {
        ret_value = EXIT_FAILURE;
    }

    context_free(&ctx);

    putchar('\n');
    print_allocation_info(stdout);

    return ret_value;
}
Example #9
0
File: main.c Project: Daiver/ad-fy
void testExecute(const char *source, bool verbose){
    LOG("testExecuteSecond", "begin");
    Context *globalContext = context_new();
    context_enterScope(globalContext); 
    LOG("testExecuteSecond", "filling op table");
    fillOpTable(globalContext);
    LOG("testExecuteSecond", "loading extensions");
    int ext_num = loadExtensions(EXT_LOCATION, globalContext);
    printf("Loaded %d extensions\n", ext_num);
    LOG("testExecuteSecond", "op table filled");
    import(globalContext, "stl.x");
    TokenStream ts;
    LOG("testExecuteSecond", "starting fill token stream");
    fillTokenStream(&ts, source); 
    LOG("testExecuteSecond", "token stream filled");
    while(!isEndOfStream(&ts)){
        LOG("testExecuteSecond", "calling parse");
        Node head = parse(&ts, 0);
        LOG("testExecuteSecond", "returning form parse");
        LOG("TestExecuteSecond", "calling execute");
        if(verbose)
            printTree(head, 0);
        LOG("testExecuteSecond", "calling execute");
        ObjectNode *node = execute(globalContext, &head);
        if(verbose){
            printf("res>");
            printObjectNode(node);
            printf("\n");
        }
    }
//    closeExtensions(lib_handle, ext_num);
    context_leaveScope(globalContext);
}
Example #10
0
File: main.c Project: Daiver/ad-fy
void REPL(bool verbose){
    Context *globalContext = context_new();
    context_enterScope(globalContext); 
    fillOpTable(globalContext);
    int ext_num = loadExtensions(EXT_LOCATION, globalContext);
    printf("Loaded %d extensions\n", ext_num);
    import(globalContext, "stl.x");
    int n_bytes = 100;
    char *source = malloc(n_bytes + 1);
    for(int i = 0;i < n_bytes + 1;i++) source[i] = 0;
    while (1){
        getline(&source, &n_bytes, stdin);
        //printf("%s\n", source);
        TokenStream ts;
        fillTokenStream(&ts, source); 
        while(!isEndOfStream(&ts)){
            Node head = parse(&ts, 0);
            if(verbose)
                printTree(head, 0);
            ObjectNode *node = execute(globalContext, &head);
            printf("res>");
            printObjectNode(node);
            printf("\n");
        }
    }
//    closeExtensions(lib_handle, ext_num);
    context_leaveScope(globalContext);
}
Example #11
0
int main(int argc, char **argv)
{
    if (argc < 2) {
        printf("Need .beam file\n");
        return EXIT_FAILURE;
    }
    MappedFile *mapped_file = mapped_file_open_beam(argv[1]);
    if (IS_NULL_PTR(mapped_file)) {
        return EXIT_FAILURE;
    }

    GlobalContext *glb = globalcontext_new();

    const void *startup_beam;
    uint32_t startup_beam_size;
    const char *startup_module_name = argv[1];

    if (avmpack_is_valid(mapped_file->mapped, mapped_file->size)) {
        glb->avmpack_data = mapped_file->mapped;
        glb->avmpack_platform_data = mapped_file;

        if (!avmpack_find_section_by_flag(mapped_file->mapped, 1, &startup_beam, &startup_beam_size, &startup_module_name)) {
            fprintf(stderr, "%s cannot be started.\n", argv[1]);
            mapped_file_close(mapped_file);
            return EXIT_FAILURE;
        }
    } else if (iff_is_valid_beam(mapped_file->mapped)) {
        glb->avmpack_data = NULL;
        glb->avmpack_platform_data = NULL;
        startup_beam = mapped_file->mapped;
        startup_beam_size = mapped_file->size;

    } else {
        fprintf(stderr, "%s is not a BEAM file.\n", argv[1]);
        mapped_file_close(mapped_file);
        return EXIT_FAILURE;
    }

    Module *mod = module_new_from_iff_binary(glb, startup_beam, startup_beam_size);
    if (IS_NULL_PTR(mod)) {
        fprintf(stderr, "Cannot load startup module: %s\n", startup_module_name);
        return EXIT_FAILURE;
    }
    globalcontext_insert_module_with_filename(glb, mod, startup_module_name);
    mod->module_platform_data = NULL;
    Context *ctx = context_new(glb);
    ctx->leader = 1;

    context_execute_loop(ctx, mod, "start", 0);

    printf("Return value: %lx\n", ctx->x[0]);

    context_destroy(ctx);
    globalcontext_destroy(glb);
    module_destroy(mod);
    mapped_file_close(mapped_file);

    return EXIT_SUCCESS;
}
Example #12
0
// run a script, using the same context
struct context *interpret_string_with(struct context *context, struct byte_array *script) {
    if (NULL == context) {
        context = context_new(NULL, true, true);
    }

    interpret_string(context, script);
    return context;
}
Example #13
0
static term nif_erlang_open_port_2(Context *ctx, int argc, term argv[])
{
    if (UNLIKELY(argc != 2)) {
        fprintf(stderr, "wrong arity\n");
        abort();
    }

    term port_name = argv[0];
    term opts = argv[1];

    if (!(term_is_tuple(port_name) && term_get_tuple_arity(port_name) == 2) && !term_is_nonempty_list(opts)) {
        fprintf(stderr, "bad args\n");
        abort();
    }

    term t = term_get_tuple_element(port_name, 1);
    char *driver_name = interop_term_to_string(t);
    if (IS_NULL_PTR(driver_name)) {
        int error_index = globalcontext_insert_atom(ctx->global, error_atom);
        if (error_index < 0) {
            abort();
        }
        return term_from_atom_index(error_index);
    }

    Context *new_ctx = NULL;

    if (!strcmp("echo", driver_name)) {
        new_ctx = context_new(ctx->global);
        new_ctx->native_handler = process_echo_mailbox;

    } else if (!strcmp("console", driver_name)) {
        new_ctx = context_new(ctx->global);
        new_ctx->native_handler = process_console_mailbox;
    }

    if (!new_ctx) {
        new_ctx = platform_open_port(ctx->global, driver_name, opts);
    }

    free(driver_name);

    scheduler_make_waiting(ctx->global, new_ctx);

    return term_from_local_process_id(new_ctx->process_id);
}
Example #14
0
static int check_dominance(const char *pattern, const char *raw) {
	security_context_t ctx;
	context_t con;
	struct av_decision avd;
	int rc = -1;
	context_t my_tmp;
	const char *raw_range;
	security_class_t context_class = string_to_security_class("context");
	access_vector_t context_contains_perm = string_to_av_perm(context_class, "contains");

	con = context_new(raw);
	if (!con)
		return -1;
	raw_range = context_range_get(con);

	my_tmp = context_new(my_context);
	if (!my_tmp) {
		context_free(con);
		return -1;
	}

	ctx = NULL;
	if (context_range_set(my_tmp, pattern))
		goto out;
	ctx = strdup(context_str(my_tmp));
	if (!ctx)
		goto out;

	if (context_range_set(my_tmp, raw_range))
		goto out;
	raw = context_str(my_tmp);
	if (!raw)
		goto out;

	rc = security_compute_av_raw(ctx, (security_context_t)raw, context_class, context_contains_perm, &avd);
	if (rc)
		goto out;

	rc = (context_contains_perm & avd.allowed) != context_contains_perm;
out:
	free(ctx);
	context_free(my_tmp);
	context_free(con);
	return rc;
}
Example #15
0
static int mls_range_allowed(pam_handle_t *pamh, security_context_t src, security_context_t dst, int debug)
{
  struct av_decision avd;
  int retval;
  unsigned int bit = CONTEXT__CONTAINS;
  context_t src_context = context_new (src);
  context_t dst_context = context_new (dst);
  context_range_set(dst_context, context_range_get(src_context));
  if (debug)
    pam_syslog(pamh, LOG_NOTICE, "Checking if %s mls range valid for  %s", dst, context_str(dst_context));

  retval = security_compute_av(context_str(dst_context), dst, SECCLASS_CONTEXT, bit, &avd);
  context_free(src_context);
  context_free(dst_context);
  if (retval || ((bit & avd.allowed) != bit))
    return 0;
  
  return 1;
}
Example #16
0
// run a file, using the same context
struct context *interpret_file_with(struct context *context, struct byte_array *path) {
    if (NULL == context) {
        context = context_new(NULL, true, true);
    }

    struct byte_array *script = read_file(path, 0, 0);
    assert_message(NULL != script, "file not found: %s\n", byte_array_to_string(path));
    interpret_string(context, script);
    return context;
}
Example #17
0
int main(int argc, char *argv[])
{
	security_context_t security_context;
	context_t context;
	pthread_t thread;
	int rc;

	if (argc != 2) {
		fprintf(stderr, "usage: %s <new domain>\n", argv[0]);
		return 1;
	}

	rc = getcon(&security_context);
	if (rc < 0) {
		fprintf(stderr, "%s: unable to get my context\n", argv[0]);
		return 1;
	}

	context = context_new(security_context);
	if (!context) {
		fprintf(stderr, "%s: unable to create context structure\n", argv[0]);
		return 1;
	}

	if (context_type_set(context, argv[1])) {
		fprintf(stderr, "%s: unable to set new type\n", argv[0]);
		return 1;
        }

	freecon(security_context);
	security_context = context_str(context);
	if (!security_context) {
		fprintf(stderr, "%s: unable to obtain new context string\n", argv[0]);
		return 1;
	}

	rc = pthread_create(&thread, NULL, worker, security_context);
	if (rc) {
		fprintf(stderr, "%s: unable to kick a new thread\n", argv[0]);
		return 1;
	}

	rc = pthread_join(thread, NULL);
	if (rc) {
		fprintf(stderr, "%s: unable to join its thread\n", argv[0]);
		return 1;
	}

	fprintf(stderr, "%s: setcon('%s') : %s\n",
		argv[0], argv[1], strerror(thread_status));

	return thread_status;
}
Example #18
0
/*  Set the context of all files associated with this VM to the new context
 *  complete with the unique generated category.
 */
static int
file_con_fixup (data_t *data)
{
        security_context_t sec_con = { 0, };
        context_t con = { 0, };
        char mcs_str[9] = { 0, };
        int ret = 0, p_ret = 0, i = 0;;
        
        p_ret = snprintf (mcs_str, sizeof (mcs_str), "s0:c%d", data->category);
        if (p_ret < 0 || p_ret > 9) {
                syslog (LOG_CRIT, "insufficient buffer size");
                return -1;
        }
        for (i = 0; data->files [i] != NULL; ++i) {
                if (getfilecon (data->files [i], &sec_con) == -1) {
                        syslog (LOG_CRIT,
                                "error getting context from file: %s, error %s",
                                data->files [i], strerror (errno));
                        continue;
                }
                con = context_new (sec_con);
                if (con == NULL) {
                        syslog (LOG_CRIT, 
                                "Error creating new context from string: %s",
                                sec_con);
                        ret = -1;
                        goto err_freecon;
                }
                if (context_range_set (con, mcs_str) == -1) {
                        syslog (LOG_CRIT, 
                                "Error setting context range to %s, "
                                "error: %s", mcs_str, strerror (errno));
                        ret = -1;
                        goto err_confree;
                }
                syslog (LOG_INFO, "Setting context for file %s to %s",
                        data->files [i], context_str (con));
                ret = setfilecon (data->files [i], context_str (con));
                if (ret != 0)
                        syslog (LOG_CRIT, "setfilecon error:%s",
                                strerror (errno));
                context_free (con);
                freecon (sec_con);
        }
        return ret;

 err_confree:
        context_free (con);
 err_freecon:
        freecon (sec_con);
        return ret;
}
Example #19
0
File: sys.c Project: sdwarak/AtomVM
Context *platform_open_port(GlobalContext *glb, const char *driver_name, term opts)
{
    UNUSED(opts);

    Context *new_ctx = context_new(glb);

    if (!strcmp(driver_name, "udp")) {
        udpdriver_init(new_ctx);
    } else {
        context_destroy(new_ctx);
        return NULL;
    }

    return new_ctx;
}
Example #20
0
static char *
SELinuxGenNewContext(const char *oldcontext, const char *mcs)
{
    char *newcontext = NULL;
    char *scontext = strdup(oldcontext);
    context_t con;
    if (!scontext) goto err;
    con = context_new(scontext);
    if (!con) goto err;
    context_range_set(con, mcs);
    newcontext = strdup(context_str(con));
    context_free(con);
err:
    freecon(scontext);
    return newcontext;
}
Example #21
0
static term nif_erlang_spawn_3(Context *ctx, int argc, term argv[])
{
    if (UNLIKELY(argc != 3)) {
        fprintf(stderr, "spawn: wrong args count\n");
        abort();
    }

    if (UNLIKELY(!term_is_atom(argv[0]) || !term_is_atom(argv[1]) || !term_is_list(argv[2]))) {
        fprintf(stderr, "spawn: invalid arguments\n");
        abort();
    }

    Context *new_ctx = context_new(ctx->global);

    int mod_atom_index = term_to_atom_index(argv[0]);
    AtomString module_string = (AtomString) valueshashtable_get_value(ctx->global->atoms_ids_table, mod_atom_index, (unsigned long) NULL);
    int func_atom_index = term_to_atom_index(argv[1]);
    AtomString function_string = (AtomString) valueshashtable_get_value(ctx->global->atoms_ids_table, func_atom_index, (unsigned long) NULL);

    Module *found_module = globalcontext_get_module(ctx->global, module_string);
    if (UNLIKELY(!found_module)) {
        int undefined_index = globalcontext_insert_atom(ctx->global, undefined_atom);
        if (undefined_index < 0) {
            abort();
        }
        return term_from_atom_index(undefined_index);
    }

    int label = module_search_exported_function(found_module, function_string, term_list_length(argv[2]));
    //TODO: fail here if no function has been found
    new_ctx->saved_module = found_module;
    new_ctx->saved_ip = found_module->labels[label];
    new_ctx->cp = module_address(found_module->module_index, found_module->end_instruction_ii);

    //TODO: check available registers count
    int reg_index = 0;
    term t = argv[2];
    while (!term_is_nil(t)) {
        term *t_ptr = term_get_list_ptr(t);
        new_ctx->x[reg_index] = memory_copy_term_tree(&new_ctx->heap_ptr, &new_ctx->e, t_ptr[1], 0);
        t = *t_ptr;
        reg_index++;
    }

    return term_from_local_process_id(new_ctx->process_id);
}
Example #22
0
File: runcon.c Project: nhanh0/hah
int runcon_main(int argc UNUSED_PARAM, char **argv)
{
    char *role = NULL;
    char *range = NULL;
    char *user = NULL;
    char *type = NULL;
    char *context = NULL;
    unsigned opts;
    context_t con;

    selinux_or_die();

#if ENABLE_FEATURE_RUNCON_LONG_OPTIONS
    applet_long_options = runcon_longopts;
#endif
    opt_complementary = "-1";
    opts = getopt32(argv, "r:t:u:l:ch", &role, &type, &user, &range);
    argv += optind;

    if (!(opts & OPTS_CONTEXT_COMPONENT)) {
        context = *argv++;
        if (!argv[0])
            bb_error_msg_and_die("no command given");
    }

    if (context) {
        con = context_new(context);
        if (!con)
            bb_error_msg_and_die("'%s' is not a valid context", context);
    } else {
        con = runcon_compute_new_context(user, role, type, range,
                                         argv[0], opts & OPTS_COMPUTE);
    }

    if (security_check_context(context_str(con)))
        bb_error_msg_and_die("'%s' is not a valid context",
                             context_str(con));

    if (setexeccon(context_str(con)))
        bb_error_msg_and_die("cannot set up security context '%s'",
                             context_str(con));

    execvp(argv[0], argv);

    bb_perror_msg_and_die("cannot execute '%s'", argv[0]);
}
Example #23
0
int runcon_main(int argc UNUSED_PARAM, char **argv)
{
	char *role = NULL;
	char *range = NULL;
	char *user = NULL;
	char *type = NULL;
	char *context = NULL;
	unsigned opts;
	context_t con;

	selinux_or_die();

	opts = getopt32long(argv, "^"
			"r:t:u:l:ch"
			"\0" "-1",
			runcon_longopts,
			&role, &type, &user, &range
	);
	argv += optind;

	if (!(opts & OPTS_CONTEXT_COMPONENT)) {
		context = *argv++;
		if (!argv[0])
			bb_error_msg_and_die("no command given");
	}

	if (context) {
		con = context_new(context);
		if (!con)
			bb_error_msg_and_die("'%s' is not a valid context", context);
	} else {
		con = runcon_compute_new_context(user, role, type, range,
				argv[0], opts & OPTS_COMPUTE);
	}

	if (security_check_context(context_str(con)))
		bb_error_msg_and_die("'%s' is not a valid context",
				context_str(con));

	if (setexeccon(context_str(con)))
		bb_error_msg_and_die("can't set up security context '%s'",
				context_str(con));

	BB_EXECVP_or_die(argv);
}
Example #24
0
static int check_selinux_access (const char *changed_user,
                                 uid_t changed_uid,
                                 access_vector_t requested_access)
{
	int status = -1;
	security_context_t user_context;
	context_t c;
	const char *user;

	/* if in permissive mode then allow the operation */
	if (security_getenforce() == 0) {
		return 0;
	}

	/* get the context of the process which executed passwd */
	if (getprevcon(&user_context) != 0) {
		return -1;
	}

	/* get the "user" portion of the context (the part before the first
	   colon) */
	c = context_new(user_context);
	user = context_user_get(c);

	/* if changing a password for an account with UID==0 or for an account
	   where the identity matches then return success */
	if (changed_uid != 0 && strcmp(changed_user, user) == 0) {
		status = 0;
	} else {
		struct av_decision avd;
		int retval;
		retval = security_compute_av(user_context,
		                             user_context,
		                             SECCLASS_PASSWD,
		                             requested_access,
		                             &avd);
		if ((retval == 0) &&
		    ((requested_access & avd.allowed) == requested_access)) {
			status = 0;
		}
	}
	context_free(c);
	freecon(user_context);
	return status;
}
Example #25
0
int main(int argc, char **argv)
{
	int rc;
	security_context_t context_s;
	context_t context;

	if (argc != 2) {
		fprintf(stderr, "usage:  %s newdomain\n", argv[0]);
		exit(-1);
	}

	rc = getcon(&context_s);
	if (rc < 0) {
		fprintf(stderr, "%s:  unable to get my context\n", argv[0]);
		exit(-1);

	}

	context = context_new(context_s);
	if (!context) {
		fprintf(stderr, "%s:  unable to create context structure\n", argv[0]);
		exit(-1);
	}

	if (context_type_set(context, argv[1])) {
		fprintf(stderr, "%s:  unable to set new type\n", argv[0]);
		exit(-1);
	}

	freecon(context_s);
	context_s = context_str(context);
	if (!context_s) {
		fprintf(stderr, "%s:  unable to obtain new context string\n", argv[0]);
		exit(-1);
	}

	rc = setcon(context_s);
	if (rc < 0) {
		perror("setcon failed");
		exit(-1);
	}

	printf("All systems go\n");
	exit(0);
}
Example #26
0
int
ub_resolve(struct ub_ctx* ctx, char* name, int rrtype,
           int rrclass, struct ub_result** result)
{
    struct ctx_query* q;
    int r;
    *result = NULL;

    lock_basic_lock(&ctx->cfglock);
    if(!ctx->finalized) {
        r = context_finalize(ctx);
        if(r) {
            lock_basic_unlock(&ctx->cfglock);
            return r;
        }
    }
    /* create new ctx_query and attempt to add to the list */
    lock_basic_unlock(&ctx->cfglock);
    q = context_new(ctx, name, rrtype, rrclass, NULL, NULL);
    if(!q)
        return UB_NOMEM;
    /* become a resolver thread for a bit */

    r = libworker_fg(ctx, q);
    if(r) {
        lock_basic_lock(&ctx->cfglock);
        (void)rbtree_delete(&ctx->queries, q->node.key);
        context_query_delete(q);
        lock_basic_unlock(&ctx->cfglock);
        return r;
    }
    q->res->answer_packet = q->msg;
    q->res->answer_len = (int)q->msg_len;
    q->msg = NULL;
    *result = q->res;
    q->res = NULL;

    lock_basic_lock(&ctx->cfglock);
    (void)rbtree_delete(&ctx->queries, q->node.key);
    context_query_delete(q);
    lock_basic_unlock(&ctx->cfglock);
    return UB_NOERROR;
}
Example #27
0
void display_program(struct byte_array *program)
{
    struct context *context = context_new(false);

    INDENT
    DEBUGPRINT("%sprogram bytes:\n", indentation(context));

    INDENT
    for (int i=0; i<program->length; i++)
        DEBUGPRINT("%s%2d:%3d\n", indentation(context), i, program->data[i]);
    UNDENT

    DEBUGPRINT("%sprogram instructions:\n", indentation(context));
    byte_array_reset(program);
    display_code(context, program);

    UNDENT
    UNDENT
}
Example #28
0
int test_modules_execution()
{
    struct Test *test = tests;

    if (chdir("erlang_tests")) {
        return EXIT_FAILURE;
    }

    do {
        printf("-- EXECUTING TEST: %s\n", test->test_file);
        MappedFile *beam_file = mapped_file_open_beam(test->test_file);
        assert(beam_file != NULL);

        GlobalContext *glb = globalcontext_new();
        glb->avmpack_data = NULL;
        glb->avmpack_platform_data = NULL;
        Module *mod = module_new_from_iff_binary(glb, beam_file->mapped, beam_file->size);
        if (IS_NULL_PTR(mod)) {
            fprintf(stderr, "Cannot load startup module: %s\n", test->test_file);
            test++;
            continue;
        }
        globalcontext_insert_module_with_filename(glb, mod, test->test_file);
        Context *ctx = context_new(glb);
        ctx->leader = 1;

        context_execute_loop(ctx, mod, "start", 0);

        int32_t value = term_to_int32(ctx->x[0]);
        if (value != test->expected_value) {
            fprintf(stderr, "\x1b[1;31mFailed test module %s, got value: %i\x1b[0m\n", test->test_file, value);
        }

        context_destroy(ctx);
        globalcontext_destroy(glb);
        module_destroy(mod);
        mapped_file_close(beam_file);

        test++;
    } while (test->test_file);

    return EXIT_SUCCESS;
}
Example #29
0
int get_default_context_with_rolelevel(const char *user,
				       const char *role,
				       const char *level,
				       security_context_t fromcon,
				       security_context_t * newcon)
{

	int rc = 0;
	int freefrom = 0;
	context_t con;
	char *newfromcon;
	if (!level)
		return get_default_context_with_role(user, role, fromcon,
						     newcon);

	if (!fromcon) {
		rc = getcon(&fromcon);
		if (rc < 0)
			return rc;
		freefrom = 1;
	}

	rc = -1;
	con = context_new(fromcon);
	if (!con)
		goto out;

	if (context_range_set(con, level))
		goto out;

	newfromcon = context_str(con);
	if (!newfromcon)
		goto out;

	rc = get_default_context_with_role(user, role, newfromcon, newcon);

      out:
	context_free(con);
	if (freefrom)
		freecon(fromcon);
	return rc;

}
Example #30
0
static context_t compute_context_from_mask(security_context_t context, unsigned long opts)
{
	context_t new_context = context_new(context);
	if (!new_context)
		return NULL;

	if ((opts & OPT_CHCON_USER) && context_user_set(new_context, user))
		goto error;
	if ((opts & OPT_CHCON_RANGE) && context_range_set(new_context, range))
		goto error;
	if ((opts & OPT_CHCON_ROLE) && context_role_set(new_context, role))
		goto error;
	if ((opts & OPT_CHCON_TYPE) && context_type_set(new_context, type))
		goto error;

	return new_context;
error:
	context_free (new_context);
	return NULL;
}