blob: c448e3d343c354b93d1fb758fb13f669aaec7b28 [file] [log] [blame]
Stephen Smalleyf0740362012-01-04 12:30:47 -05001/*
2 * Generalized labeling frontend for userspace object managers.
3 *
4 * Author : Eamon Walsh <ewalsh@epoch.ncsc.mil>
5 */
6
7#include <sys/types.h>
8#include <ctype.h>
9#include <errno.h>
10#include <stdio.h>
11#include <stdlib.h>
12#include <string.h>
13#include <selinux/selinux.h>
14#include "callbacks.h"
15#include "label_internal.h"
16
17#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))
18
19typedef int (*selabel_initfunc)(struct selabel_handle *rec,
20 struct selinux_opt *opts, unsigned nopts);
21
22static selabel_initfunc initfuncs[] = {
23 &selabel_file_init,
24};
25
26/*
27 * Validation functions
28 */
29
30static inline int selabel_is_validate_set(struct selinux_opt *opts, unsigned n)
31{
32 while (n--)
33 if (opts[n].type == SELABEL_OPT_VALIDATE)
34 return !!opts[n].value;
35
36 return 0;
37}
38
39int selabel_validate(struct selabel_handle *rec,
40 struct selabel_lookup_rec *contexts)
41{
42 int rc = 0;
43
44 if (!rec->validating || contexts->validated)
45 goto out;
46
47 rc = selinux_validate(&contexts->ctx_raw);
48 if (rc < 0)
49 goto out;
50
51 contexts->validated = 1;
52out:
53 return rc;
54}
55
56/*
57 * Public API
58 */
59
60struct selabel_handle *selabel_open(unsigned int backend,
61 struct selinux_opt *opts, unsigned nopts)
62{
63 struct selabel_handle *rec = NULL;
64
65 if (backend >= ARRAY_SIZE(initfuncs)) {
66 errno = EINVAL;
67 goto out;
68 }
69
70 rec = (struct selabel_handle *)malloc(sizeof(*rec));
71 if (!rec)
72 goto out;
73
74 memset(rec, 0, sizeof(*rec));
75 rec->backend = backend;
76 rec->validating = selabel_is_validate_set(opts, nopts);
77
78 if ((*initfuncs[backend])(rec, opts, nopts)) {
79 free(rec);
80 rec = NULL;
81 }
82
83out:
84 return rec;
85}
86
87static struct selabel_lookup_rec *
88selabel_lookup_common(struct selabel_handle *rec, int translating,
89 const char *key, int type)
90{
91 struct selabel_lookup_rec *lr;
92 lr = rec->func_lookup(rec, key, type);
93 if (!lr)
94 return NULL;
95
96 return lr;
97}
98
99int selabel_lookup(struct selabel_handle *rec, security_context_t *con,
100 const char *key, int type)
101{
102 struct selabel_lookup_rec *lr;
103
104 lr = selabel_lookup_common(rec, 1, key, type);
105 if (!lr)
106 return -1;
107
108 *con = strdup(lr->ctx_raw);
109 return *con ? 0 : -1;
110}
111
112void selabel_close(struct selabel_handle *rec)
113{
114 rec->func_close(rec);
115 free(rec);
116}
117
118void selabel_stats(struct selabel_handle *rec)
119{
120 rec->func_stats(rec);
121}