1 #include <stdlib.h>
2
3 #include "private.h"
4 #include "debug.h"
5
6 #include <sepol/policydb/policydb.h>
7
8 /* Construct a policydb from the supplied (data, len) pair */
9
policydb_from_image(sepol_handle_t * handle,void * data,size_t len,policydb_t * policydb)10 int policydb_from_image(sepol_handle_t * handle,
11 void *data, size_t len, policydb_t * policydb)
12 {
13
14 policy_file_t pf;
15
16 policy_file_init(&pf);
17 pf.type = PF_USE_MEMORY;
18 pf.data = data;
19 pf.len = len;
20 pf.handle = handle;
21
22 if (policydb_read(policydb, &pf, 0)) {
23 ERR(handle, "policy image is invalid");
24 errno = EINVAL;
25 return STATUS_ERR;
26 }
27
28 return STATUS_SUCCESS;
29 }
30
31 /* Write a policydb to a memory region, and return the (data, len) pair. */
32
policydb_to_image(sepol_handle_t * handle,policydb_t * policydb,void ** newdata,size_t * newlen)33 int policydb_to_image(sepol_handle_t * handle,
34 policydb_t * policydb, void **newdata, size_t * newlen)
35 {
36
37 void *tmp_data = NULL;
38 size_t tmp_len;
39 policy_file_t pf;
40 struct policydb tmp_policydb;
41
42 /* Compute the length for the new policy image. */
43 policy_file_init(&pf);
44 pf.type = PF_LEN;
45 pf.handle = handle;
46 if (policydb_write(policydb, &pf)) {
47 ERR(handle, "could not compute policy length");
48 errno = EINVAL;
49 goto err;
50 }
51
52 /* Allocate the new policy image. */
53 pf.type = PF_USE_MEMORY;
54 pf.data = malloc(pf.len);
55 if (!pf.data) {
56 ERR(handle, "out of memory");
57 goto err;
58 }
59
60 /* Need to save len and data prior to modification by policydb_write. */
61 tmp_len = pf.len;
62 tmp_data = pf.data;
63
64 /* Write out the new policy image. */
65 if (policydb_write(policydb, &pf)) {
66 ERR(handle, "could not write policy");
67 errno = EINVAL;
68 goto err;
69 }
70
71 /* Verify the new policy image. */
72 pf.type = PF_USE_MEMORY;
73 pf.data = tmp_data;
74 pf.len = tmp_len;
75 if (policydb_init(&tmp_policydb)) {
76 ERR(handle, "Out of memory");
77 errno = ENOMEM;
78 goto err;
79 }
80 if (policydb_read(&tmp_policydb, &pf, 0)) {
81 ERR(handle, "new policy image is invalid");
82 errno = EINVAL;
83 goto err;
84 }
85 policydb_destroy(&tmp_policydb);
86
87 /* Update (newdata, newlen) */
88 *newdata = tmp_data;
89 *newlen = tmp_len;
90
91 /* Recover */
92 return STATUS_SUCCESS;
93
94 err:
95 ERR(handle, "could not create policy image");
96
97 /* Recover */
98 free(tmp_data);
99 return STATUS_ERR;
100 }
101