Merge remote-tracking branch 'aosp/upstream-master' into mymerge

Change-Id: I0cf6e149295a27152cea79c2e2658ebc0a4b7961
This commit is contained in:
dcashman 2016-08-23 13:03:12 -07:00
commit b24d5279b1
127 changed files with 2552 additions and 79202 deletions

View File

@ -1,3 +1,5 @@
* Extend checkpolicy pathname matching, from Stephen Smalley.
* Fix typos in test/dispol, from Petr Lautrbach.
* Set flex as default lexer, from Julien Pivotto.
* Fix checkmodule output message, from Petr Lautrbach.
* Build policy on systems not supporting DCCP protocol, from Richard Haines.

View File

@ -249,9 +249,9 @@ high |
HIGH { return(HIGH); }
low |
LOW { return(LOW); }
"/"({alnum}|[_\.\-/])* { return(PATH); }
\""/"[ !#-~]*\" { return(QPATH); }
\"({alnum}|[_\.\-\+\~\: ])+\" { return(FILENAME); }
"/"[^ \n\r\t\f]* { return(PATH); }
\""/"[^\"\n]*\" { return(QPATH); }
\"[^"/"\"\n]+\" { return(FILENAME); }
{letter}({alnum}|[_\-])*([\.]?({alnum}|[_\-]))* { return(IDENTIFIER); }
{digit}+|0x{hexval}+ { return(NUMBER); }
{alnum}*{letter}{alnum}* { return(FILESYSTEM); }

View File

@ -252,11 +252,11 @@ int display_cond_expressions(policydb_t * p, FILE * fp)
int display_handle_unknown(policydb_t * p, FILE * out_fp)
{
if (p->handle_unknown == ALLOW_UNKNOWN)
fprintf(out_fp, "Allow unknown classes and permisions\n");
fprintf(out_fp, "Allow unknown classes and permissions\n");
else if (p->handle_unknown == DENY_UNKNOWN)
fprintf(out_fp, "Deny unknown classes and permisions\n");
fprintf(out_fp, "Deny unknown classes and permissions\n");
else if (p->handle_unknown == REJECT_UNKNOWN)
fprintf(out_fp, "Reject unknown classes and permisions\n");
fprintf(out_fp, "Reject unknown classes and permissions\n");
return 0;
}
@ -349,7 +349,7 @@ int menu(void)
printf("\nSelect a command:\n");
printf("1) display unconditional AVTAB\n");
printf("2) display conditional AVTAB (entirely)\n");
printf("3) display conditional AVTAG (only ENABLED rules)\n");
printf("3) display conditional AVTAB (only ENABLED rules)\n");
printf("4) display conditional AVTAB (only DISABLED rules)\n");
printf("5) display conditional bools\n");
printf("6) display conditional expressions\n");

View File

@ -1,3 +1,14 @@
* Handle NULL pcre study data, from Stephen Smalley.
* Add setfiles support to selinux_restorecon(3), from Richard Haines.
* Evaluate inodes in selinux_restorecon(3), from Richard Haines.
* Fix in tree compilation of utils that depend on libsepol, from Laurent Bigonville.
* Change the location of _selinux.so, from Petr Lautrbach.
* Clarify is_selinux_mls_enabled() description, from David King.
* Explain how to free policy type from selinux_getpolicytype(), from David King.
* Compare absolute pathname in matchpathcon -V, from Petr Lautrbach.
* Add selinux_snapperd_contexts_path(), from Petr Lautrbach.
* Modify audit2why analyze function to use loaded policy, from Joshua Brindle.
* Sort object files for deterministic linking order, from Laurent Bigonville.
* Respect CC and PKG_CONFIG environment variable, from Julien Pivotto.
* Avoid mounting /proc outside of selinux_init_load_policy(), from Stephen Smalley.
* Fix multiple spelling errors, from Laurent Bigonville.

View File

@ -26,30 +26,75 @@ extern int selinux_restorecon(const char *pathname,
/*
* restorecon_flags options
*/
/* Force the checking of labels even if the stored SHA1
* digest matches the specfiles SHA1 digest. */
#define SELINUX_RESTORECON_IGNORE_DIGEST 1
/* Do not change file labels */
#define SELINUX_RESTORECON_NOCHANGE 2
/* If set set change file label to that in spec file.
* If not only change type component to that in spec file. */
#define SELINUX_RESTORECON_SET_SPECFILE_CTX 4
/* Recursively descend directories */
#define SELINUX_RESTORECON_RECURSE 8
/* Log changes to selinux log. Note that if VERBOSE and
* PROGRESS are set, then PROGRESS will take precedence. */
#define SELINUX_RESTORECON_VERBOSE 16
/* Show progress by printing * to stdout every 1000 files */
#define SELINUX_RESTORECON_PROGRESS 32
/* Convert passed-in pathname to canonical pathname */
#define SELINUX_RESTORECON_REALPATH 64
/* Prevent descending into directories that have a different
* device number than the pathname from which the descent began */
#define SELINUX_RESTORECON_XDEV 128
/*
* Force the checking of labels even if the stored SHA1
* digest matches the specfiles SHA1 digest.
*/
#define SELINUX_RESTORECON_IGNORE_DIGEST 0x0001
/*
* Do not change file labels.
*/
#define SELINUX_RESTORECON_NOCHANGE 0x0002
/*
* If set set change file label to that in spec file.
* If not only change type component to that in spec file.
*/
#define SELINUX_RESTORECON_SET_SPECFILE_CTX 0x0004
/*
* Recursively descend directories.
*/
#define SELINUX_RESTORECON_RECURSE 0x0008
/*
* Log changes to selinux log. Note that if VERBOSE and
* PROGRESS are set, then PROGRESS will take precedence.
*/
#define SELINUX_RESTORECON_VERBOSE 0x0010
/*
* Show progress by printing * to stdout every 1000 files, unless
* relabeling the entire OS, that will then show the approximate
* percentage complete.
*/
#define SELINUX_RESTORECON_PROGRESS 0x0020
/*
* Convert passed-in pathname to canonical pathname.
*/
#define SELINUX_RESTORECON_REALPATH 0x0040
/*
* Prevent descending into directories that have a different
* device number than the pathname from which the descent began.
*/
#define SELINUX_RESTORECON_XDEV 0x0080
/*
* Attempt to add an association between an inode and a specification.
* If there is already an association for the inode and it conflicts
* with the specification, then use the last matching specification.
*/
#define SELINUX_RESTORECON_ADD_ASSOC 0x0100
/*
* Abort on errors during the file tree walk.
*/
#define SELINUX_RESTORECON_ABORT_ON_ERROR 0x0200
/*
* Log any label changes to syslog.
*/
#define SELINUX_RESTORECON_SYSLOG_CHANGES 0x0400
/*
* Log what spec matched each file.
*/
#define SELINUX_RESTORECON_LOG_MATCHES 0x0800
/*
* Ignore files that do not exist.
*/
#define SELINUX_RESTORECON_IGNORE_NOENTRY 0x1000
/*
* Do not read /proc/mounts to obtain a list of non-seclabel
* mounts to be excluded from relabeling checks.
*/
#define SELINUX_RESTORECON_IGNORE_MOUNTS 0x2000
/**
* selinux_restorecon_set_sehandle - Set the global fc handle.
* @handle: specifies handle to set as the global fc handle.
* @hndl: specifies handle to set as the global fc handle.
*
* Called by a process that has already called selabel_open(3) with it's
* required parameters, or if selinux_restorecon_default_handle(3) has been
@ -61,18 +106,28 @@ extern void selinux_restorecon_set_sehandle(struct selabel_handle *hndl);
* selinux_restorecon_default_handle - Sets default selabel_open(3) parameters
* to use the currently loaded policy and
* file_contexts, also requests the digest.
*
* Return value is the created handle on success or NULL with @errno set on
* failure.
*/
extern struct selabel_handle *selinux_restorecon_default_handle(void);
/**
* selinux_restorecon_set_exclude_list - Add a list of files or
* directories that are to be excluded
* from relabeling.
* selinux_restorecon_set_exclude_list - Add a list of directories that are
* to be excluded from relabeling.
* @exclude_list: containing a NULL terminated list of one or more
* directories or files not to be relabeled.
* directories not to be relabeled.
*/
extern void selinux_restorecon_set_exclude_list(const char **exclude_list);
/**
* selinux_restorecon_set_alt_rootpath - Use alternate rootpath.
* @alt_rootpath: containing the alternate rootpath to be used.
*
* Return %0 on success, -%1 with @errno set on failure.
*/
extern int selinux_restorecon_set_alt_rootpath(const char *alt_rootpath);
#ifdef __cplusplus
}
#endif

View File

@ -544,6 +544,7 @@ extern const char *selinux_lxc_contexts_path(void);
extern const char *selinux_x_context_path(void);
extern const char *selinux_sepgsql_context_path(void);
extern const char *selinux_openssh_contexts_path(void);
extern const char *selinux_snapperd_contexts_path(void);
extern const char *selinux_systemd_contexts_path(void);
extern const char *selinux_contexts_path(void);
extern const char *selinux_securetty_types_path(void);

View File

@ -18,7 +18,9 @@ returns 1 if SELinux is running or 0 if it is not.
On error, \-1 is returned.
.BR is_selinux_mls_enabled ()
returns 1 if SELinux is running in MLS mode or 0 if it is not.
returns 1 if SELinux is capable of running in MLS mode or 0 if it is not. To
determine the policy in use on the system, use
.BR selinux_getpolicytype (3).
.
.SH "SEE ALSO"
.BR selinux "(8)"

View File

@ -13,7 +13,10 @@ Reads the contents of the
.I /etc/selinux/config
file to determine the SELinux policy used on the system, and sets
.I \%policytype
accordinly.
accordingly. Free
.I \%policytype
with
.BR free (3).
.
.SH "RETURN VALUE"
On success, zero is returned.

View File

@ -67,8 +67,6 @@ extended attribute.
If set, reset the files label to match the default specfile context.
If not set only reset the files "type" component of the context to match the
default specfile context.
.br
.sp
.B SELINUX_RESTORECON_RECURSE
change file and directory labels recursively (descend directories)
@ -84,13 +82,14 @@ Note that if
.B SELINUX_RESTORECON_VERBOSE
and
.B SELINUX_RESTORECON_PROGRESS
are set, then
flags are set, then
.B SELINUX_RESTORECON_PROGRESS
will take precedence.
.RE
.sp
.B SELINUX_RESTORECON_PROGRESS
show progress by printing * to stdout every 1000 files.
show progress by printing * to stdout every 1000 files unless relabeling the
entire OS, that will then show the approximate percentage complete.
.sp
.B SELINUX_RESTORECON_REALPATH
convert passed-in
@ -103,6 +102,34 @@ prevent descending into directories that have a different device number than
the
.I pathname
entry from which the descent began.
.sp
.B SELINUX_RESTORECON_ADD_ASSOC
attempt to add an association between an inode and a specification. If there
is already an association for the inode and it conflicts with the
specification, then use the last matching specification.
.sp
.B SELINUX_RESTORECON_ABORT_ON_ERROR
abort on errors during the file tree walk.
.sp
.B SELINUX_RESTORECON_SYSLOG_CHANGES
log any label changes to
.BR syslog (3).
.sp
.B SELINUX_RESTORECON_LOG_MATCHES
log what specfile context matched each file.
.sp
.B SELINUX_RESTORECON_IGNORE_NOENTRY
ignore files that do not exist.
.sp
.B SELINUX_RESTORECON_IGNORE_MOUNTS
do not read
.B /proc/mounts
to obtain a list of non-seclabel mounts to be excluded from relabeling checks.
.br
Setting
.B SELINUX_RESTORECON_IGNORE_MOUNTS
is useful where there is a non-seclabel fs mounted with a seclabel fs mounted
on a directory below this.
.RE
.sp
The behavior regarding the checking and updating of the SHA1 digest described
@ -117,13 +144,22 @@ to set the handle to be used by
.sp
If the
.I pathname
is a directory path, then it is possible to set files/directories to be
excluded from the path by calling
is a directory path, then it is possible to set directories to be excluded
from the path by calling
.BR selinux_restorecon_set_exclude_list (3)
with a
.B NULL
terminated list before calling
.BR selinux_restorecon (3).
.sp
By default
.BR selinux_restorecon (3)
reads
.B /proc/mounts
to obtain a list of non-seclabel mounts to be excluded from relabeling checks
unless the
.B SELINUX_RESTORECON_IGNORE_MOUNTS
flag has been set.
.RE
.
.SH "RETURN VALUE"
@ -132,6 +168,7 @@ On success, zero is returned. On error, \-1 is returned and
is set appropriately.
.
.SH "NOTES"
.IP "1." 4
To improve performance when relabeling file systems recursively (e.g. the
.IR restorecon_flags
.B SELINUX_RESTORECON_RECURSE
@ -143,21 +180,23 @@ to an extended attribute named
.IR security.restorecon_last
to the directory specified in the
.IR pathname .
.sp
.IP "2." 4
To check the extended attribute entry use
.BR getfattr (1) ,
for example:
.sp
.RS
.RS
getfattr -e hex -n security.restorecon_last /
.RE
.sp
.RE
.IP "3." 4
The SHA1 digest is calculated by
.BR selabel_open (3)
concatenating the specfiles it reads during initialisation with the
resulting digest and list of specfiles being retrieved by
.BR selabel_digest (3).
.sp
.IP "4." 4
The specfiles consist of the mandatory
.I file_contexts
file plus any subs, subs_dist, local and homedir entries (text or binary versions)
@ -176,24 +215,20 @@ relabeled depending on the settings of the
flag (provided
.B SELINUX_RESTORECON_NOCHANGE
is not set).
.sp
.IP "5." 4
.B /sys
and in-memory filesystems do not support the
.IR security.restorecon_last
extended attribute and are automatically excluded from any relabeling checks.
.sp
.BR selinux_restorecon ()
does not check whether mounted filesystems support the
.B seclabel
option (i.e. support extended attributes as described in
.BR xattr (7)).
To exclude these filesystems from any relabeling checks
.BR selinux_restorecon_set_exclude_list (3)
should be called prior to
.BR selinux_restorecon ()
with a NULL terminated
.IR exclude_list
of these filesystems.
.IP "6." 4
By default
.B stderr
is used to log output messages and errors. This may be changed by calling
.BR selinux_set_callback (3)
with the
.B SELINUX_CB_LOG
.I type
option.
.
.SH "SEE ALSO"
.BR selinux_restorecon_set_sehandle (3),
@ -201,3 +236,7 @@ of these filesystems.
.BR selinux_restorecon_default_handle (3),
.br
.BR selinux_restorecon_set_exclude_list (3),
.br
.BR selinux_restorecon_set_alt_rootpath (3),
.br
.BR selinux_set_callback (3)

View File

@ -0,0 +1,35 @@
.TH "selinux_restorecon_set_alt_rootpath" "3" "29 May 2016" "Security Enhanced Linux" "SELinux API documentation"
.SH "NAME"
selinux_restorecon_set_alt_rootpath \- set an alternate rootpath.
.
.SH "SYNOPSIS"
.B #include <selinux/restorecon.h>
.sp
.BI "int selinux_restorecon_set_alt_rootpath(const char *" alt_rootpath ");"
.in +\w'void selinux_restorecon_set_alt_rootpath('u
.
.SH "DESCRIPTION"
.BR selinux_restorecon_set_alt_rootpath ()
passes to
.BR selinux_restorecon (3)
a pointer containing an alternate rootpath
.IR alt_rootpath .
.sp
.BR selinux_restorecon_set_alt_rootpath ()
must be called prior to
.BR selinux_restorecon (3).
.
.SH "RETURN VALUE"
On success, zero is returned. On error, \-1 is returned and
.I errno
is set appropriately.
.
.SH "SEE ALSO"
.BR selinux_restorecon (3),
.br
.BR selinux_restorecon_set_sehandle (3),
.br
.BR selinux_restorecon_default_handle (3),
.br
.BR selinux_restorecon_set_exclude_list (3)

View File

@ -1,7 +1,7 @@
.TH "selinux_restorecon_set_exclude_list" "3" "20 Oct 2015" "Security Enhanced Linux" "SELinux API documentation"
.SH "NAME"
selinux_restorecon_set_exclude_list \- set list of files/directories to be
selinux_restorecon_set_exclude_list \- set list of directories to be
excluded from relabeling.
.
.SH "SYNOPSIS"
@ -16,8 +16,7 @@ passes to
.BR selinux_restorecon (3)
a pointer containing a
.B NULL
terminated list of one or more directories or files that are not to be
relabeled in
terminated list of one or more directories that are not to be relabeled in
.IR exclude_list .
.sp
.BR selinux_restorecon_set_exclude_list ()
@ -29,4 +28,6 @@ must be called prior to
.br
.BR selinux_restorecon_set_sehandle (3),
.br
.BR selinux_restorecon_default_handle (3)
.BR selinux_restorecon_default_handle (3),
.br
.BR selinux_restorecon_set_alt_rootpath (3)

View File

@ -36,4 +36,6 @@ digest and a list of specfiles used to compute the digest.
.br
.BR selinux_restorecon_set_exclude_list (3),
.br
.BR selinux_restorecon_default_handle (3)
.BR selinux_restorecon_default_handle (3),
.br
.BR selinux_restorecon_set_alt_rootpath (3)

View File

@ -49,7 +49,7 @@ ifeq ($(DISABLE_BOOL),y)
endif
GENERATED=$(SWIGCOUT) $(SWIGRUBYCOUT) selinuxswig_python_exception.i
SRCS= $(filter-out $(UNUSED_SRCS) $(GENERATED) audit2why.c, $(wildcard *.c))
SRCS= $(filter-out $(UNUSED_SRCS) $(GENERATED) audit2why.c, $(sort $(wildcard *.c)))
MAX_STACK_SIZE=32768
@ -156,7 +156,7 @@ install: all
install-pywrap: pywrap
test -d $(PYLIBDIR)/site-packages/selinux || install -m 755 -d $(PYLIBDIR)/site-packages/selinux
install -m 755 $(SWIGSO) $(PYLIBDIR)/site-packages/selinux/_selinux.so
install -m 755 $(SWIGSO) $(PYLIBDIR)/site-packages/_selinux.so
install -m 755 $(AUDIT2WHYSO) $(PYLIBDIR)/site-packages/selinux/audit2why.so
install -m 644 $(SWIGPYOUT) $(PYLIBDIR)/site-packages/selinux/__init__.py

View File

@ -343,8 +343,8 @@ static PyObject *analyze(PyObject *self __attribute__((unused)) , PyObject *args
if (rc < 0)
RETURN(BADTCON)
tclass = string_to_security_class(tclassstr);
if (!tclass)
rc = sepol_string_to_security_class(tclassstr, &tclass);
if (rc < 0)
RETURN(BADTCLASS)
/* Convert the permission list to an AV. */
@ -365,8 +365,8 @@ static PyObject *analyze(PyObject *self __attribute__((unused)) , PyObject *args
permstr = PyString_AsString( strObj );
#endif
perm = string_to_av_perm(tclass, permstr);
if (!perm)
rc = sepol_string_to_av_perm(tclass, permstr, &perm);
if (rc < 0)
RETURN(BADPERM)
av |= perm;

View File

@ -24,6 +24,7 @@ S_(BINPOLICY, "/policy/policy")
S_(VIRTUAL_IMAGE, "/contexts/virtual_image_context")
S_(LXC_CONTEXTS, "/contexts/lxc_contexts")
S_(OPENSSH_CONTEXTS, "/contexts/openssh_contexts")
S_(SNAPPERD_CONTEXTS, "/contexts/snapperd_contexts")
S_(SYSTEMD_CONTEXTS, "/contexts/systemd_contexts")
S_(FILE_CONTEXT_SUBS, "/contexts/files/file_contexts.subs")
S_(FILE_CONTEXT_SUBS_DIST, "/contexts/files/file_contexts.subs_dist")

View File

@ -388,18 +388,21 @@ static int load_mmap(struct selabel_handle *rec, const char *path,
rc = -1;
goto err;
}
spec->lsd.study_data = (void *)mmap_area->next_addr;
spec->lsd.flags |= PCRE_EXTRA_STUDY_DATA;
rc = next_entry(NULL, mmap_area, entry_len);
if (rc < 0)
goto err;
/* Check that study data lengths match. */
rc = pcre_fullinfo(spec->regex, &spec->lsd,
PCRE_INFO_STUDYSIZE, &len);
if (rc < 0 || len != entry_len) {
rc = -1;
goto err;
if (entry_len) {
spec->lsd.study_data = (void *)mmap_area->next_addr;
spec->lsd.flags |= PCRE_EXTRA_STUDY_DATA;
rc = next_entry(NULL, mmap_area, entry_len);
if (rc < 0)
goto err;
/* Check that study data lengths match. */
rc = pcre_fullinfo(spec->regex, &spec->lsd,
PCRE_INFO_STUDYSIZE, &len);
if (rc < 0 || len != entry_len) {
rc = -1;
goto err;
}
}
data->nspec++;

View File

@ -80,9 +80,12 @@ struct saved_data {
static inline pcre_extra *get_pcre_extra(struct spec *spec)
{
if (spec->from_mmap)
return &spec->lsd;
else
if (spec->from_mmap) {
if (spec->lsd.study_data)
return &spec->lsd;
else
return NULL;
} else
return spec->sd;
}

View File

@ -470,6 +470,17 @@ int selinux_file_context_verify(const char *path, mode_t mode)
char * con = NULL;
char * fcontext = NULL;
int rc = 0;
char stackpath[PATH_MAX + 1];
char *p = NULL;
if (S_ISLNK(mode)) {
if (!realpath_not_final(path, stackpath))
path = stackpath;
} else {
p = realpath(path, stackpath);
if (p)
path = p;
}
rc = lgetfilecon_raw(path, &con);
if (rc == -1) {

View File

@ -50,7 +50,8 @@
#define BOOLEAN_SUBS 27
#define OPENSSH_CONTEXTS 28
#define SYSTEMD_CONTEXTS 29
#define NEL 30
#define SNAPPERD_CONTEXTS 30
#define NEL 31
/* Part of one-time lazy init */
static pthread_once_t once = PTHREAD_ONCE_INIT;
@ -499,6 +500,13 @@ const char *selinux_openssh_contexts_path(void)
hidden_def(selinux_openssh_contexts_path)
const char *selinux_snapperd_contexts_path(void)
{
return get_path(SNAPPERD_CONTEXTS);
}
hidden_def(selinux_snapperd_contexts_path)
const char *selinux_systemd_contexts_path(void)
{
return get_path(SYSTEMD_CONTEXTS);

View File

@ -84,6 +84,7 @@ hidden_proto(selinux_mkload_policy)
hidden_proto(selinux_x_context_path)
hidden_proto(selinux_sepgsql_context_path)
hidden_proto(selinux_openssh_contexts_path)
hidden_proto(selinux_snapperd_contexts_path)
hidden_proto(selinux_systemd_contexts_path)
hidden_proto(selinux_path)
hidden_proto(selinux_check_passwd_access)

View File

@ -1,7 +1,7 @@
/*
* The majority of this code is from Android's
* external/libselinux/src/android.c and upstream
* selinux/policycoreutils/setfiles/restorecon.c
* selinux/policycoreutils/setfiles/restore.c
*
* See selinux_restorecon(3) for details.
*/
@ -16,12 +16,18 @@
#include <fcntl.h>
#include <fts.h>
#include <limits.h>
#include <stdint.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/xattr.h>
#include <sys/vfs.h>
#include <sys/statvfs.h>
#include <sys/utsname.h>
#include <linux/magic.h>
#include <libgen.h>
#include <syslog.h>
#include <assert.h>
#include <selinux/selinux.h>
#include <selinux/context.h>
#include <selinux/label.h>
@ -35,12 +41,52 @@
#define SYS_PATH "/sys"
#define SYS_PREFIX SYS_PATH "/"
#define STAR_COUNT 1000
static struct selabel_handle *fc_sehandle = NULL;
static unsigned char *fc_digest = NULL;
static size_t fc_digest_len = 0;
static const char **fc_exclude_list = NULL;
static size_t fc_count = 0;
#define STAR_COUNT 1000
static char *rootpath = NULL;
static int rootpathlen;
/* Information on excluded fs and directories. */
struct edir {
char *directory;
size_t size;
/* True if excluded by selinux_restorecon_set_exclude_list(3). */
bool caller_excluded;
};
#define CALLER_EXCLUDED true
static bool ignore_mounts;
static int exclude_non_seclabel_mounts(void);
static int exclude_count = 0;
static struct edir *exclude_lst = NULL;
static uint64_t fc_count = 0; /* Number of files processed so far */
static uint64_t efile_count; /* Estimated total number of files */
/*
* If SELINUX_RESTORECON_PROGRESS is set and mass_relabel = true, then
* output approx % complete, else output * for every STAR_COUNT files
* processed to stdout.
*/
static bool mass_relabel;
/* restorecon_flags for passing to restorecon_sb() */
struct rest_flags {
bool nochange;
bool verbose;
bool progress;
bool set_specctx;
bool add_assoc;
bool ignore_digest;
bool recurse;
bool userealpath;
bool set_xdev;
bool abort_on_error;
bool syslog_changes;
bool log_matches;
bool ignore_noent;
};
static void restorecon_init(void)
{
@ -50,24 +96,365 @@ static void restorecon_init(void)
sehandle = selinux_restorecon_default_handle();
selinux_restorecon_set_sehandle(sehandle);
}
efile_count = 0;
if (!ignore_mounts)
efile_count = exclude_non_seclabel_mounts();
}
static pthread_once_t fc_once = PTHREAD_ONCE_INIT;
/*
* Manage excluded directories:
* remove_exclude() - This removes any conflicting entries as there could be
* a case where a non-seclabel fs is mounted on /foo and
* then a seclabel fs is mounted on top of it.
* However if an entry has been added via
* selinux_restorecon_set_exclude_list(3) do not remove.
*
* add_exclude() - Add a directory/fs to be excluded from labeling. If it
* has already been added, then ignore.
*
* check_excluded() - Check if directory/fs is to be excluded when relabeling.
*
* file_system_count() - Calculates the the number of files to be processed.
* The count is only used if SELINUX_RESTORECON_PROGRESS
* is set and a mass relabel is requested.
*
* exclude_non_seclabel_mounts() - Reads /proc/mounts to determine what
* non-seclabel mounts to exclude from
* relabeling. restorecon_init() will not
* call this function if the
* SELINUX_RESTORECON_IGNORE_MOUNTS
* flag is set.
* Setting SELINUX_RESTORECON_IGNORE_MOUNTS
* is useful where there is a non-seclabel fs
* mounted on /foo and then a seclabel fs is
* mounted on a directory below this.
*/
static void remove_exclude(const char *directory)
{
int i;
for (i = 0; i < exclude_count; i++) {
if (strcmp(directory, exclude_lst[i].directory) == 0 &&
!exclude_lst[i].caller_excluded) {
free(exclude_lst[i].directory);
if (i != exclude_count - 1)
exclude_lst[i] = exclude_lst[exclude_count - 1];
exclude_count--;
return;
}
}
}
static int add_exclude(const char *directory, bool who)
{
struct edir *tmp_list, *current;
size_t len = 0;
int i;
/* Check if already present. */
for (i = 0; i < exclude_count; i++) {
if (strcmp(directory, exclude_lst[i].directory) == 0)
return 0;
}
if (directory == NULL || directory[0] != '/') {
selinux_log(SELINUX_ERROR,
"Full path required for exclude: %s.\n",
directory);
errno = EINVAL;
return -1;
}
tmp_list = realloc(exclude_lst,
sizeof(struct edir) * (exclude_count + 1));
if (!tmp_list)
goto oom;
exclude_lst = tmp_list;
len = strlen(directory);
while (len > 1 && directory[len - 1] == '/')
len--;
current = (exclude_lst + exclude_count);
current->directory = strndup(directory, len);
if (!current->directory)
goto oom;
current->size = len;
current->caller_excluded = who;
exclude_count++;
return 0;
oom:
selinux_log(SELINUX_ERROR, "%s: Out of memory\n", __func__);
return -1;
}
static int check_excluded(const char *file)
{
int i;
for (i = 0; fc_exclude_list[i]; i++) {
if (strcmp(file, fc_exclude_list[i]) == 0)
for (i = 0; i < exclude_count; i++) {
if (strncmp(file, exclude_lst[i].directory,
exclude_lst[i].size) == 0) {
if (file[exclude_lst[i].size] == 0 ||
file[exclude_lst[i].size] == '/')
return 1;
}
}
return 0;
}
/* Called if SELINUX_RESTORECON_SET_SPECFILE_CTX is not set to check if
* the type components differ, updating newtypecon if so. */
static int file_system_count(char *name)
{
struct statvfs statvfs_buf;
int nfile = 0;
memset(&statvfs_buf, 0, sizeof(statvfs_buf));
if (!statvfs(name, &statvfs_buf))
nfile = statvfs_buf.f_files - statvfs_buf.f_ffree;
return nfile;
}
/*
* This is called once when selinux_restorecon() is first called.
* Searches /proc/mounts for all file systems that do not support extended
* attributes and adds them to the exclude directory table. File systems
* that support security labels have the seclabel option, return
* approximate total file count.
*/
static int exclude_non_seclabel_mounts(void)
{
struct utsname uts;
FILE *fp;
size_t len;
ssize_t num;
int index = 0, found = 0, nfile = 0;
char *mount_info[4];
char *buf = NULL, *item;
/* Check to see if the kernel supports seclabel */
if (uname(&uts) == 0 && strverscmp(uts.release, "2.6.30") < 0)
return 0;
fp = fopen("/proc/mounts", "r");
if (!fp)
return 0;
while ((num = getline(&buf, &len, fp)) != -1) {
found = 0;
index = 0;
item = strtok(buf, " ");
while (item != NULL) {
mount_info[index] = item;
if (index == 3)
break;
index++;
item = strtok(NULL, " ");
}
if (index < 3) {
selinux_log(SELINUX_ERROR,
"/proc/mounts record \"%s\" has incorrect format.\n",
buf);
continue;
}
/* Remove pre-existing entry */
remove_exclude(mount_info[1]);
item = strtok(mount_info[3], ",");
while (item != NULL) {
if (strcmp(item, "seclabel") == 0) {
found = 1;
nfile += file_system_count(mount_info[1]);
break;
}
item = strtok(NULL, ",");
}
/* Exclude mount points without the seclabel option */
if (!found) {
if (add_exclude(mount_info[1], !CALLER_EXCLUDED) &&
errno == ENOMEM)
assert(0);
}
}
free(buf);
fclose(fp);
/* return estimated #Files + 5% for directories and hard links */
return nfile * 1.05;
}
/*
* Support filespec services filespec_add(), filespec_eval() and
* filespec_destroy().
*
* selinux_restorecon(3) uses filespec services when the
* SELINUX_RESTORECON_ADD_ASSOC flag is set for adding associations between
* an inode and a specification.
*/
/*
* The hash table of associations, hashed by inode number. Chaining is used
* for collisions, with elements ordered by inode number in each bucket.
* Each hash bucket has a dummy header.
*/
#define HASH_BITS 16
#define HASH_BUCKETS (1 << HASH_BITS)
#define HASH_MASK (HASH_BUCKETS-1)
/*
* An association between an inode and a context.
*/
typedef struct file_spec {
ino_t ino; /* inode number */
char *con; /* matched context */
char *file; /* full pathname */
struct file_spec *next; /* next association in hash bucket chain */
} file_spec_t;
static file_spec_t *fl_head;
/*
* Try to add an association between an inode and a context. If there is a
* different context that matched the inode, then use the first context
* that matched.
*/
static int filespec_add(ino_t ino, const char *con, const char *file)
{
file_spec_t *prevfl, *fl;
int h, ret;
struct stat64 sb;
if (!fl_head) {
fl_head = malloc(sizeof(file_spec_t) * HASH_BUCKETS);
if (!fl_head)
goto oom;
memset(fl_head, 0, sizeof(file_spec_t) * HASH_BUCKETS);
}
h = (ino + (ino >> HASH_BITS)) & HASH_MASK;
for (prevfl = &fl_head[h], fl = fl_head[h].next; fl;
prevfl = fl, fl = fl->next) {
if (ino == fl->ino) {
ret = lstat64(fl->file, &sb);
if (ret < 0 || sb.st_ino != ino) {
freecon(fl->con);
free(fl->file);
fl->file = strdup(file);
if (!fl->file)
goto oom;
fl->con = strdup(con);
if (!fl->con)
goto oom;
return 1;
}
if (strcmp(fl->con, con) == 0)
return 1;
selinux_log(SELINUX_ERROR,
"conflicting specifications for %s and %s, using %s.\n",
file, fl->file, fl->con);
free(fl->file);
fl->file = strdup(file);
if (!fl->file)
goto oom;
return 1;
}
if (ino > fl->ino)
break;
}
fl = malloc(sizeof(file_spec_t));
if (!fl)
goto oom;
fl->ino = ino;
fl->con = strdup(con);
if (!fl->con)
goto oom_freefl;
fl->file = strdup(file);
if (!fl->file)
goto oom_freefl;
fl->next = prevfl->next;
prevfl->next = fl;
return 0;
oom_freefl:
free(fl);
oom:
selinux_log(SELINUX_ERROR, "%s: Out of memory\n", __func__);
return -1;
}
/*
* Evaluate the association hash table distribution.
*/
static void filespec_eval(void)
{
file_spec_t *fl;
int h, used, nel, len, longest;
if (!fl_head)
return;
used = 0;
longest = 0;
nel = 0;
for (h = 0; h < HASH_BUCKETS; h++) {
len = 0;
for (fl = fl_head[h].next; fl; fl = fl->next)
len++;
if (len)
used++;
if (len > longest)
longest = len;
nel += len;
}
selinux_log(SELINUX_INFO,
"filespec hash table stats: %d elements, %d/%d buckets used, longest chain length %d\n",
nel, used, HASH_BUCKETS, longest);
}
/*
* Destroy the association hash table.
*/
static void filespec_destroy(void)
{
file_spec_t *fl, *tmp;
int h;
if (!fl_head)
return;
for (h = 0; h < HASH_BUCKETS; h++) {
fl = fl_head[h].next;
while (fl) {
tmp = fl;
fl = fl->next;
freecon(tmp->con);
free(tmp->file);
free(tmp);
}
fl_head[h].next = NULL;
}
free(fl_head);
fl_head = NULL;
}
/*
* Called if SELINUX_RESTORECON_SET_SPECFILE_CTX is not set to check if
* the type components differ, updating newtypecon if so.
*/
static int compare_types(char *curcon, char *newcon, char **newtypecon)
{
int types_differ = 0;
@ -109,17 +496,77 @@ out:
}
static int restorecon_sb(const char *pathname, const struct stat *sb,
bool nochange, bool verbose,
bool progress, bool specctx)
struct rest_flags *flags)
{
char *newcon = NULL;
char *curcon = NULL;
char *newtypecon = NULL;
int rc = 0;
int rc;
bool updated = false;
const char *lookup_path = pathname;
float pc;
if (rootpath) {
if (strncmp(rootpath, lookup_path, rootpathlen) != 0) {
selinux_log(SELINUX_ERROR,
"%s is not located in alt_rootpath %s\n",
lookup_path, rootpath);
return -1;
}
lookup_path += rootpathlen;
}
if (rootpath != NULL && lookup_path[0] == '\0')
/* this is actually the root dir of the alt root. */
rc = selabel_lookup_raw(fc_sehandle, &newcon, "/",
sb->st_mode);
else
rc = selabel_lookup_raw(fc_sehandle, &newcon, lookup_path,
sb->st_mode);
if (rc < 0) {
if (errno == ENOENT && flags->verbose)
selinux_log(SELINUX_INFO,
"Warning no default label for %s\n",
lookup_path);
if (selabel_lookup_raw(fc_sehandle, &newcon, pathname, sb->st_mode) < 0)
return 0; /* no match, but not an error */
}
if (flags->progress) {
fc_count++;
if (fc_count % STAR_COUNT == 0) {
if (mass_relabel && efile_count > 0) {
pc = (fc_count < efile_count) ? (100.0 *
fc_count / efile_count) : 100;
fprintf(stdout, "\r%-.1f%%", (double)pc);
} else {
fprintf(stdout, "*");
}
fflush(stdout);
}
}
if (flags->add_assoc) {
rc = filespec_add(sb->st_ino, newcon, pathname);
if (rc < 0) {
selinux_log(SELINUX_ERROR,
"filespec_add error: %s\n", pathname);
freecon(newcon);
return -1;
}
if (rc > 0) {
/* Already an association and it took precedence. */
freecon(newcon);
return 0;
}
}
if (flags->log_matches)
selinux_log(SELINUX_INFO, "%s matched by %s\n",
pathname, newcon);
if (lgetfilecon_raw(pathname, &curcon) < 0) {
if (errno != ENODATA)
@ -128,18 +575,10 @@ static int restorecon_sb(const char *pathname, const struct stat *sb,
curcon = NULL;
}
if (progress) {
fc_count++;
if (fc_count % STAR_COUNT == 0) {
fprintf(stdout, "*");
fflush(stdout);
}
}
if (strcmp(curcon, newcon) != 0) {
if (!specctx && curcon &&
if (!flags->set_specctx && curcon &&
(is_context_customizable(curcon) > 0)) {
if (verbose) {
if (flags->verbose) {
selinux_log(SELINUX_INFO,
"%s not reset as customized by admin to %s\n",
pathname, curcon);
@ -147,7 +586,7 @@ static int restorecon_sb(const char *pathname, const struct stat *sb,
}
}
if (!specctx && curcon) {
if (!flags->set_specctx && curcon) {
/* If types different then update newcon. */
rc = compare_types(curcon, newcon, &newtypecon);
if (rc)
@ -161,17 +600,27 @@ static int restorecon_sb(const char *pathname, const struct stat *sb,
}
}
if (!nochange) {
if (!flags->nochange) {
if (lsetfilecon(pathname, newcon) < 0)
goto err;
updated = true;
}
if (verbose)
if (flags->verbose)
selinux_log(SELINUX_INFO,
"%s %s from %s to %s\n",
updated ? "Relabeled" : "Would relabel",
pathname, curcon, newcon);
if (flags->syslog_changes && !flags->nochange) {
if (curcon)
syslog(LOG_INFO,
"relabeling %s from %s to %s\n",
pathname, curcon, newcon);
else
syslog(LOG_INFO, "labeling %s to %s\n",
pathname, newcon);
}
}
out:
@ -196,22 +645,37 @@ err:
int selinux_restorecon(const char *pathname_orig,
unsigned int restorecon_flags)
{
bool ignore = (restorecon_flags &
struct rest_flags flags;
flags.ignore_digest = (restorecon_flags &
SELINUX_RESTORECON_IGNORE_DIGEST) ? true : false;
bool nochange = (restorecon_flags &
flags.nochange = (restorecon_flags &
SELINUX_RESTORECON_NOCHANGE) ? true : false;
bool verbose = (restorecon_flags &
flags.verbose = (restorecon_flags &
SELINUX_RESTORECON_VERBOSE) ? true : false;
bool progress = (restorecon_flags &
flags.progress = (restorecon_flags &
SELINUX_RESTORECON_PROGRESS) ? true : false;
bool recurse = (restorecon_flags &
flags.recurse = (restorecon_flags &
SELINUX_RESTORECON_RECURSE) ? true : false;
bool specctx = (restorecon_flags &
flags.set_specctx = (restorecon_flags &
SELINUX_RESTORECON_SET_SPECFILE_CTX) ? true : false;
bool userealpath = (restorecon_flags &
flags.userealpath = (restorecon_flags &
SELINUX_RESTORECON_REALPATH) ? true : false;
bool xdev = (restorecon_flags &
flags.set_xdev = (restorecon_flags &
SELINUX_RESTORECON_XDEV) ? true : false;
flags.add_assoc = (restorecon_flags &
SELINUX_RESTORECON_ADD_ASSOC) ? true : false;
flags.abort_on_error = (restorecon_flags &
SELINUX_RESTORECON_ABORT_ON_ERROR) ? true : false;
flags.syslog_changes = (restorecon_flags &
SELINUX_RESTORECON_SYSLOG_CHANGES) ? true : false;
flags.log_matches = (restorecon_flags &
SELINUX_RESTORECON_LOG_MATCHES) ? true : false;
flags.ignore_noent = (restorecon_flags &
SELINUX_RESTORECON_IGNORE_NOENTRY) ? true : false;
ignore_mounts = (restorecon_flags &
SELINUX_RESTORECON_IGNORE_MOUNTS) ? true : false;
bool issys;
bool setrestoreconlast = true; /* TRUE = set xattr RESTORECON_LAST
* FALSE = don't use xattr */
@ -220,14 +684,14 @@ int selinux_restorecon(const char *pathname_orig,
FTS *fts;
FTSENT *ftsent;
char *pathname = NULL, *pathdnamer = NULL, *pathdname, *pathbname;
char *paths[2] = { NULL , NULL };
int fts_flags;
int error, sverrno;
char *paths[2] = { NULL, NULL };
int fts_flags, error, sverrno;
char *xattr_value = NULL;
ssize_t size;
dev_t dev_num = 0;
if (verbose && progress)
verbose = false;
if (flags.verbose && flags.progress)
flags.verbose = false;
__selinux_once(fc_once, restorecon_init);
@ -244,7 +708,7 @@ int selinux_restorecon(const char *pathname_orig,
* Convert passed-in pathname to canonical pathname by resolving
* realpath of containing dir, then appending last component name.
*/
if (userealpath) {
if (flags.userealpath) {
pathbname = basename((char *)pathname_orig);
if (!strcmp(pathbname, "/") || !strcmp(pathbname, ".") ||
!strcmp(pathbname, "..")) {
@ -276,17 +740,30 @@ int selinux_restorecon(const char *pathname_orig,
sizeof(SYS_PREFIX) - 1)) ? true : false;
if (lstat(pathname, &sb) < 0) {
error = -1;
goto cleanup;
if (flags.ignore_noent && errno == ENOENT) {
free(pathdnamer);
free(pathname);
return 0;
} else {
selinux_log(SELINUX_ERROR,
"lstat(%s) failed: %s\n",
pathname, strerror(errno));
error = -1;
goto cleanup;
}
}
/* Ignore restoreconlast if not a directory */
if ((sb.st_mode & S_IFDIR) != S_IFDIR)
setrestoreconlast = false;
if (!recurse) {
error = restorecon_sb(pathname, &sb, nochange, verbose,
progress, specctx);
if (!flags.recurse) {
if (check_excluded(pathname)) {
error = 0;
goto cleanup;
}
error = restorecon_sb(pathname, &sb, &flags);
goto cleanup;
}
@ -304,7 +781,7 @@ int selinux_restorecon(const char *pathname_orig,
size = getxattr(pathname, RESTORECON_LAST, xattr_value,
fc_digest_len);
if (!ignore && size == fc_digest_len &&
if (!flags.ignore_digest && size == fc_digest_len &&
memcmp(fc_digest, xattr_value, fc_digest_len)
== 0) {
selinux_log(SELINUX_INFO,
@ -315,19 +792,47 @@ int selinux_restorecon(const char *pathname_orig,
}
}
if (xdev)
mass_relabel = false;
if (!strcmp(pathname, "/")) {
mass_relabel = true;
if (flags.set_xdev && flags.progress)
/*
* Need to recalculate to get accurate % complete
* as only root device id will be processed.
*/
efile_count = file_system_count(pathname);
}
if (flags.set_xdev)
fts_flags = FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV;
else
fts_flags = FTS_PHYSICAL | FTS_NOCHDIR;
fts = fts_open(paths, fts_flags, NULL);
if (!fts) {
error = -1;
goto cleanup;
}
if (!fts)
goto fts_err;
ftsent = fts_read(fts);
if (!ftsent)
goto fts_err;
/*
* Keep the inode of the first device. This is because the FTS_XDEV
* flag tells fts not to descend into directories with different
* device numbers, but fts will still give back the actual directory.
* By saving the device number of the directory that was passed to
* selinux_restorecon() and then skipping all actions on any
* directories with a different device number when the FTS_XDEV flag
* is set (from http://marc.info/?l=selinux&m=124688830500777&w=2).
*/
dev_num = ftsent->fts_statp->st_dev;
error = 0;
while ((ftsent = fts_read(fts)) != NULL) {
do {
/* If the FTS_XDEV flag is set and the device is different */
if (flags.set_xdev && ftsent->fts_statp->st_dev != dev_num)
continue;
switch (ftsent->fts_info) {
case FTS_DC:
selinux_log(SELINUX_ERROR,
@ -365,46 +870,60 @@ int selinux_restorecon(const char *pathname_orig,
fts_set(fts, ftsent, FTS_SKIP);
continue;
}
if (check_excluded(ftsent->fts_path)) {
fts_set(fts, ftsent, FTS_SKIP);
continue;
}
/* fall through */
default:
if (fc_exclude_list) {
if (check_excluded(ftsent->fts_path)) {
fts_set(fts, ftsent, FTS_SKIP);
continue;
}
}
error |= restorecon_sb(ftsent->fts_path,
ftsent->fts_statp, nochange,
verbose, progress, specctx);
ftsent->fts_statp, &flags);
if (error && flags.abort_on_error)
goto out;
break;
}
}
} while ((ftsent = fts_read(fts)) != NULL);
/* Labeling successful. Mark the top level directory as completed. */
if (setrestoreconlast && !nochange && !error) {
if (setrestoreconlast && !flags.nochange && !error && fc_digest) {
error = setxattr(pathname, RESTORECON_LAST, fc_digest,
fc_digest_len, 0);
if (!error && verbose)
if (!error && flags.verbose)
selinux_log(SELINUX_INFO,
"Updated digest for: %s\n", pathname);
}
out:
if (flags.progress) {
if (mass_relabel)
fprintf(stdout, "\r100.0%%\n");
else
fprintf(stdout, "\n");
}
sverrno = errno;
(void) fts_close(fts);
errno = sverrno;
cleanup:
if (flags.add_assoc) {
if (flags.verbose)
filespec_eval();
filespec_destroy();
}
free(pathdnamer);
free(pathname);
free(xattr_value);
return error;
oom:
sverrno = errno;
selinux_log(SELINUX_ERROR, "%s: Out of memory\n", __func__);
errno = sverrno;
error = -1;
goto cleanup;
realpatherr:
sverrno = errno;
selinux_log(SELINUX_ERROR,
@ -413,51 +932,37 @@ realpatherr:
errno = sverrno;
error = -1;
goto cleanup;
fts_err:
selinux_log(SELINUX_ERROR,
"fts error while labeling %s: %s\n",
paths[0], strerror(errno));
error = -1;
goto cleanup;
}
/* selinux_restorecon_set_sehandle(3) is called to set the global fc handle */
void selinux_restorecon_set_sehandle(struct selabel_handle *hndl)
{
char **specfiles, *sha1_buf = NULL;
size_t num_specfiles, i;
char **specfiles;
size_t num_specfiles;
fc_sehandle = (struct selabel_handle *) hndl;
/* Read digest if requested in selabel_open(3).
* If not the set global params. */
if (selabel_digest(hndl, &fc_digest, &fc_digest_len,
/*
* Read digest if requested in selabel_open(3) and set global params.
*/
if (selabel_digest(fc_sehandle, &fc_digest, &fc_digest_len,
&specfiles, &num_specfiles) < 0) {
fc_digest = NULL;
fc_digest_len = 0;
selinux_log(SELINUX_INFO, "Digest not requested.\n");
return;
}
sha1_buf = malloc(fc_digest_len * 2 + 1);
if (!sha1_buf) {
selinux_log(SELINUX_ERROR,
"Error allocating digest buffer: %s\n",
strerror(errno));
return;
}
for (i = 0; i < fc_digest_len; i++)
sprintf((&sha1_buf[i * 2]), "%02x", fc_digest[i]);
selinux_log(SELINUX_INFO,
"specfiles SHA1 digest: %s\n", sha1_buf);
selinux_log(SELINUX_INFO,
"calculated using the following specfile(s):\n");
if (specfiles) {
for (i = 0; i < num_specfiles; i++)
selinux_log(SELINUX_INFO,
"%s\n", specfiles[i]);
}
free(sha1_buf);
}
/* selinux_restorecon_default_handle(3) is called to set the global restorecon
* handle by a process if the default params are required. */
/*
* selinux_restorecon_default_handle(3) is called to set the global restorecon
* handle by a process if the default params are required.
*/
struct selabel_handle *selinux_restorecon_default_handle(void)
{
struct selabel_handle *sehandle;
@ -478,9 +983,48 @@ struct selabel_handle *selinux_restorecon_default_handle(void)
return sehandle;
}
/* selinux_restorecon_set_exclude_list(3) is called to set a NULL terminated
* list of files/directories to exclude. */
/*
* selinux_restorecon_set_exclude_list(3) is called to add additional entries
* to be excluded from labeling checks.
*/
void selinux_restorecon_set_exclude_list(const char **exclude_list)
{
fc_exclude_list = exclude_list;
int i;
struct stat sb;
for (i = 0; exclude_list[i]; i++) {
if (lstat(exclude_list[i], &sb) < 0 && errno != EACCES) {
selinux_log(SELINUX_ERROR,
"lstat error on exclude path \"%s\", %s - ignoring.\n",
exclude_list[i], strerror(errno));
break;
}
if (add_exclude(exclude_list[i], CALLER_EXCLUDED) &&
errno == ENOMEM)
assert(0);
}
}
/* selinux_restorecon_set_alt_rootpath(3) sets an alternate rootpath. */
int selinux_restorecon_set_alt_rootpath(const char *alt_rootpath)
{
int len;
/* This should be NULL on first use */
if (rootpath)
free(rootpath);
rootpath = strdup(alt_rootpath);
if (!rootpath) {
selinux_log(SELINUX_ERROR, "%s: Out of memory\n", __func__);
return -1;
}
/* trim trailing /, if present */
len = strlen(rootpath);
while (len && (rootpath[len - 1] == '/'))
rootpath[--len] = '\0';
rootpathlen = len;
return 0;
}

View File

@ -3,6 +3,7 @@ PREFIX ?= $(DESTDIR)/usr
LIBDIR ?= $(PREFIX)/lib
USRBINDIR ?= $(PREFIX)/sbin
SBINDIR ?= $(DESTDIR)/sbin
INCLUDEDIR ?= $(PREFIX)/include
MAX_STACK_SIZE=8192
CFLAGS ?= -O -Wall -W -Wundef -Wformat-y2k -Wformat-security -Winit-self -Wmissing-include-dirs \
@ -23,7 +24,7 @@ CFLAGS ?= -O -Wall -W -Wundef -Wformat-y2k -Wformat-security -Winit-self -Wmissi
-fasynchronous-unwind-tables -fdiagnostics-show-option -funit-at-a-time \
-fipa-pure-const -Wno-suggest-attribute=pure -Wno-suggest-attribute=const \
-Werror -Wno-aggregate-return -Wno-redundant-decls
override CFLAGS += -I../include -D_GNU_SOURCE $(EMFLAGS)
override CFLAGS += -I../include -I$(INCLUDEDIR) -D_GNU_SOURCE $(EMFLAGS)
LDLIBS += -L../src -lselinux -L$(LIBDIR)
TARGETS=$(patsubst %.c,%,$(wildcard *.c))

View File

@ -228,10 +228,13 @@ static int write_binary_file(struct saved_data *data, int fd)
if (len != to_write)
goto err;
/* determine the size of the pcre study info */
rc = pcre_fullinfo(re, sd, PCRE_INFO_STUDYSIZE, &size);
if (rc < 0)
goto err;
if (sd) {
/* determine the size of the pcre study info */
rc = pcre_fullinfo(re, sd, PCRE_INFO_STUDYSIZE, &size);
if (rc < 0)
goto err;
} else
size = 0;
/* write the number of bytes in the pcre study data */
to_write = size;
@ -239,10 +242,12 @@ static int write_binary_file(struct saved_data *data, int fd)
if (len != 1)
goto err;
/* write the actual pcre study data as a char array */
len = fwrite(sd->study_data, 1, to_write, bin_file);
if (len != to_write)
goto err;
if (sd) {
/* write the actual pcre study data as a char array */
len = fwrite(sd->study_data, 1, to_write, bin_file);
if (len != to_write)
goto err;
}
}
rc = 0;

View File

@ -37,9 +37,9 @@ static int validate_context(char **contextp)
static void usage(const char *progname)
{
fprintf(stderr,
"\nusage: %s [-FCnRrdei] [-v|-P] [-p policy] [-f specfile] "
"pathname ...\n"
"Where:\n\t"
"\nusage: %s [-FCnRrdmiIaAsl] [-e dir] [-v|-P]\n"
"[-x alt_rootpath] [-p policy] [-f specfile] pathname ...\n"
"\nWhere:\n\t"
"-F Set the label to that in specfile.\n\t"
" If not set then reset the \"type\" component of the "
"label to that\n\t in the specfile.\n\t"
@ -49,14 +49,25 @@ static void usage(const char *progname)
"-R Recursively change file and directory labels.\n\t"
"-v Show changes in file labels (-v and -P are mutually "
" exclusive).\n\t"
"-P Show progress by printing \"*\" to stdout every 1000 files.\n\t"
"-P Show progress by printing \"*\" to stdout every 1000 files"
",\n\t unless relabeling entire OS, then show percentage complete.\n\t"
"-r Use realpath(3) to convert pathnames to canonical form.\n\t"
"-d Prevent descending into directories that have a "
"different\n\t device number than the pathname from which "
"the descent began.\n\t"
"-e Exclude this file/directory (add multiple -e entries).\n\t"
"-i Do not set SELABEL_OPT_VALIDATE option in selabel_open(3)"
" then call\n\t selinux_restorecon_set_sehandle(3).\n\t"
"-m Do not automatically read /proc/mounts to determine what\n\t"
" non-seclabel mounts to exclude from relabeling.\n\t"
"-e Exclude this directory (add multiple -e entries).\n\t"
"-i Do not set SELABEL_OPT_DIGEST option when calling "
" selabel_open(3).\n\t"
"-I Ignore files that do not exist.\n\t"
"-a Add an association between an inode and a context.\n\t"
" If there is a different context that matched the inode,\n\t"
" then use the first context that matched.\n\t"
"-A Abort on errors during the file tree walk.\n\t"
"-s Log any label changes to syslog(3).\n\t"
"-l Log what specfile context matched each file.\n\t"
"-x Set alternate rootpath.\n\t"
"-p Optional binary policy file (also sets validate context "
"option).\n\t"
"-f Optional file contexts file.\n\t"
@ -98,6 +109,7 @@ int main(int argc, char **argv)
int opt, i;
unsigned int restorecon_flags = 0;
char *path = NULL, *digest = NULL, *validate = NULL;
char *alt_rootpath = NULL;
FILE *policystream;
bool ignore_digest = false, require_selinux = true;
bool verbose = false, progress = false;
@ -115,7 +127,7 @@ int main(int argc, char **argv)
exclude_list = NULL;
exclude_count = 0;
while ((opt = getopt(argc, argv, "iFCnRvPrde:f:p:")) > 0) {
while ((opt = getopt(argc, argv, "iIFCnRvPrdaAslme:f:p:x:")) > 0) {
switch (opt) {
case 'F':
restorecon_flags |=
@ -155,6 +167,9 @@ int main(int argc, char **argv)
case 'd':
restorecon_flags |= SELINUX_RESTORECON_XDEV;
break;
case 'm':
restorecon_flags |= SELINUX_RESTORECON_IGNORE_MOUNTS;
break;
case 'e':
add_exclude(optarg);
break;
@ -187,6 +202,24 @@ int main(int argc, char **argv)
case 'i':
ignore_digest = true;
break;
case 'I':
restorecon_flags |= SELINUX_RESTORECON_IGNORE_NOENTRY;
break;
case 'a':
restorecon_flags |= SELINUX_RESTORECON_ADD_ASSOC;
break;
case 'A':
restorecon_flags |= SELINUX_RESTORECON_ABORT_ON_ERROR;
break;
case 's':
restorecon_flags |= SELINUX_RESTORECON_SYSLOG_CHANGES;
break;
case 'l':
restorecon_flags |= SELINUX_RESTORECON_LOG_MATCHES;
break;
case 'x':
alt_rootpath = optarg;
break;
default:
usage(argv[0]);
}
@ -241,6 +274,9 @@ int main(int argc, char **argv)
selinux_restorecon_set_exclude_list
((const char **)exclude_list);
if (alt_rootpath)
selinux_restorecon_set_alt_rootpath(alt_rootpath);
/* Call restorecon for each path in list */
for (i = optind; i < argc; i++) {
if (selinux_restorecon(argv[i], restorecon_flags) < 0) {

View File

@ -1,3 +1,6 @@
* Validate and compile file contexts before installing, from Stephen Smalley.
* Swap tcp and udp protocol numbers, from Miroslav Vadkerti.
* Sort object files for deterministic linking order, from Laurent Bigonville.
* Support overriding Makefile RANLIB, from Julien Pivotto.
* Respect CC and PKG_CONFIG environment variable, from Julien Pivotto.
* Fix multiple spelling errors, from Laurent Bigonville.

View File

@ -52,7 +52,7 @@ SWIGRUBYSO=$(RUBYPREFIX)_semanage.so
LIBSO=$(TARGET).$(LIBVERSION)
GENERATED=$(SWIGCOUT) $(SWIGRUBYCOUT) semanageswig_python_exception.i
SRCS= $(filter-out $(GENERATED),$(wildcard *.c))
SRCS= $(filter-out $(GENERATED),$(sort $(wildcard *.c)))
OBJS= $(patsubst %.c,%.o,$(SRCS)) conf-scan.o conf-parse.o
LOBJS= $(patsubst %.c,%.lo,$(SRCS)) conf-scan.lo conf-parse.lo

View File

@ -292,6 +292,13 @@ static int semanage_init_final_suffix(semanage_handle_t *sh)
goto cleanup;
}
if (asprintf(&semanage_final_suffix[SEMANAGE_FC_BIN], "%s.bin",
semanage_final_suffix[SEMANAGE_FC]) < 0) {
ERR(sh, "Unable to allocate space for file context path.");
status = -1;
goto cleanup;
}
semanage_final_suffix[SEMANAGE_FC_HOMEDIRS] =
strdup(selinux_file_context_homedir_path() + offset);
if (semanage_final_suffix[SEMANAGE_FC_HOMEDIRS] == NULL) {
@ -300,6 +307,13 @@ static int semanage_init_final_suffix(semanage_handle_t *sh)
goto cleanup;
}
if (asprintf(&semanage_final_suffix[SEMANAGE_FC_HOMEDIRS_BIN], "%s.bin",
semanage_final_suffix[SEMANAGE_FC_HOMEDIRS]) < 0) {
ERR(sh, "Unable to allocate space for file context home directory path.");
status = -1;
goto cleanup;
}
semanage_final_suffix[SEMANAGE_FC_LOCAL] =
strdup(selinux_file_context_local_path() + offset);
if (semanage_final_suffix[SEMANAGE_FC_LOCAL] == NULL) {
@ -308,6 +322,13 @@ static int semanage_init_final_suffix(semanage_handle_t *sh)
goto cleanup;
}
if (asprintf(&semanage_final_suffix[SEMANAGE_FC_LOCAL_BIN], "%s.bin",
semanage_final_suffix[SEMANAGE_FC_LOCAL]) < 0) {
ERR(sh, "Unable to allocate space for local file context path.");
status = -1;
goto cleanup;
}
semanage_final_suffix[SEMANAGE_NC] =
strdup(selinux_netfilter_context_path() + offset);
if (semanage_final_suffix[SEMANAGE_NC] == NULL) {
@ -1491,6 +1512,45 @@ static int sefcontext_compile(semanage_handle_t * sh, const char *path) {
return 0;
}
static int semanage_validate_and_compile_fcontexts(semanage_handle_t * sh)
{
int status = -1;
if (sh->do_check_contexts) {
int ret;
ret = semanage_exec_prog(
sh,
sh->conf->setfiles,
semanage_final_path(SEMANAGE_FINAL_TMP,
SEMANAGE_KERNEL),
semanage_final_path(SEMANAGE_FINAL_TMP,
SEMANAGE_FC));
if (ret != 0) {
ERR(sh, "setfiles returned error code %d.", ret);
goto cleanup;
}
}
if (sefcontext_compile(sh,
semanage_final_path(SEMANAGE_FINAL_TMP, SEMANAGE_FC)) != 0) {
goto cleanup;
}
if (sefcontext_compile(sh,
semanage_final_path(SEMANAGE_FINAL_TMP, SEMANAGE_FC_LOCAL)) != 0) {
goto cleanup;
}
if (sefcontext_compile(sh,
semanage_final_path(SEMANAGE_FINAL_TMP, SEMANAGE_FC_HOMEDIRS)) != 0) {
goto cleanup;
}
status = 0;
cleanup:
return status;
}
/* Load the contexts of the final tmp into the final selinux directory.
* Return 0 on success, -3 on error.
*/
@ -1566,35 +1626,6 @@ static int semanage_install_final_tmp(semanage_handle_t * sh)
}
skip_reload:
if (sh->do_check_contexts) {
ret = semanage_exec_prog(
sh,
sh->conf->setfiles,
semanage_final_path(SEMANAGE_FINAL_SELINUX,
SEMANAGE_KERNEL),
semanage_final_path(SEMANAGE_FINAL_SELINUX,
SEMANAGE_FC));
if (ret != 0) {
ERR(sh, "setfiles returned error code %d.", ret);
goto cleanup;
}
}
if (sefcontext_compile(sh,
semanage_final_path(SEMANAGE_FINAL_SELINUX, SEMANAGE_FC)) != 0) {
goto cleanup;
}
if (sefcontext_compile(sh,
semanage_final_path(SEMANAGE_FINAL_SELINUX, SEMANAGE_FC_LOCAL)) != 0) {
goto cleanup;
}
if (sefcontext_compile(sh,
semanage_final_path(SEMANAGE_FINAL_SELINUX, SEMANAGE_FC_HOMEDIRS)) != 0) {
goto cleanup;
}
status = 0;
cleanup:
return status;
@ -1737,6 +1768,9 @@ int semanage_install_sandbox(semanage_handle_t * sh)
goto cleanup;
}
if (semanage_validate_and_compile_fcontexts(sh) < 0)
goto cleanup;
if ((commit_num = semanage_commit_sandbox(sh)) < 0) {
retval = commit_num;
goto cleanup;

View File

@ -71,8 +71,11 @@ enum semanage_final_defs {
enum semanage_final_path_defs {
SEMANAGE_FINAL_TOPLEVEL,
SEMANAGE_FC,
SEMANAGE_FC_BIN,
SEMANAGE_FC_HOMEDIRS,
SEMANAGE_FC_HOMEDIRS_BIN,
SEMANAGE_FC_LOCAL,
SEMANAGE_FC_LOCAL_BIN,
SEMANAGE_KERNEL,
SEMANAGE_NC,
SEMANAGE_SEUSERS,

View File

@ -1,3 +1,16 @@
* Change which attributes CIL keeps in the binary policy, from James Carter.
* Port str_read() from kernel and remove multiple occurances of similar code, from William Roberts.
* Use calloc instead of malloc for all the *_to_val_structs, from William Roberts.
* Fix bugs found by AFL, from William Roberts.
* Fix memory leak in expand.c, from William Roberts.
* Fix invalid read when policy file is corrupt, from William Roberts.
* Fix possible use of uninitialized variables, from William Roberts.
* Warn instead of fail if permission is not resolved, from James Carter.
* Ignore object_r when adding userrole mappings to policydb, from Steve Lawrence.
* Add missing return to sepol_node_query(), from Petr Lautrbach.
* Add missing <stdarg.h> include, from Thomas Petazzoni.
* Correctly detect unknown classes in sepol_string_to_security_class, from Joshua Brindle.
* Sort object files for deterministic linking order, from Laurent Bigonville.
* Fix neverallowxperm checking on attributes, from Jeff Vander Stoep.
* Remove libsepol.map when cleaning, from Nicolas Iooss.
* Add high-level language line marking support to CIL, from James Carter.

View File

@ -754,6 +754,12 @@ int cil_userrole_to_policydb(policydb_t *pdb, const struct cil_db *db, struct ci
goto exit;
}
if (sepol_role->s.value == 1) {
// role is object_r, ignore it since it is implicitly associated
// with all users
continue;
}
if (ebitmap_set_bit(&sepol_user->roles.roles, sepol_role->s.value - 1, 1)) {
cil_log(CIL_INFO, "Failed to set role bit for user\n");
rc = SEPOL_ERR;

View File

@ -30,6 +30,7 @@
#define CIL_LOG_H_
#include <stdlib.h>
#include <stdarg.h>
#include <cil/cil.h>
#define MAX_LOG_SIZE 512

View File

@ -47,6 +47,9 @@
#include "cil_verify.h"
#include "cil_symtab.h"
#define GEN_REQUIRE_ATTR "cil_gen_require" /* Also in libsepol/src/module_to_cil.c */
#define TYPEATTR_INFIX "_typeattr_" /* Also in libsepol/src/module_to_cil.c */
static int __cil_expr_to_bitmap(struct cil_list *expr, ebitmap_t *out, int max, struct cil_db *db);
static int __cil_expr_list_to_bitmap(struct cil_list *expr_list, ebitmap_t *out, int max, struct cil_db *db);
@ -1186,6 +1189,27 @@ exit:
return SEPOL_ERR;
}
static int cil_typeattribute_used(struct cil_typeattribute *cil_attr)
{
if (cil_attr->used) {
return CIL_TRUE;
}
if (strcmp(DATUM(cil_attr)->name, GEN_REQUIRE_ATTR) == 0) {
return CIL_FALSE;
}
if (strstr(DATUM(cil_attr)->name,TYPEATTR_INFIX) != NULL) {
return CIL_FALSE;
}
if (ebitmap_cardinality(cil_attr->types) == 0) {
return CIL_FALSE;
}
return CIL_TRUE;
}
static int __cil_post_db_attr_helper(struct cil_tree_node *node, uint32_t *finished, void *extra_args)
{
int rc = SEPOL_ERR;
@ -1208,6 +1232,9 @@ static int __cil_post_db_attr_helper(struct cil_tree_node *node, uint32_t *finis
if (attr->types == NULL) {
rc = __evaluate_type_expression(attr, db);
if (rc != SEPOL_OK) goto exit;
if (cil_typeattribute_used(attr)) {
attr->used = CIL_TRUE;
}
}
break;
}

View File

@ -131,10 +131,10 @@ static int __cil_resolve_perms(symtab_t *class_symtab, symtab_t *common_symtab,
}
}
if (rc != SEPOL_OK) {
cil_log(CIL_ERR, "Failed to resolve permission %s\n", (char*)curr->data);
goto exit;
cil_log(CIL_WARN, "Failed to resolve permission %s\n", (char*)curr->data);
} else {
cil_list_append(*perm_datums, CIL_DATUM, perm_datum);
}
cil_list_append(*perm_datums, CIL_DATUM, perm_datum);
} else {
cil_list_append(*perm_datums, curr->flavor, curr->data);
}
@ -3660,7 +3660,7 @@ int __cil_resolve_ast_node_helper(struct cil_tree_node *node, uint32_t *finished
rc = SEPOL_OK;
}
cil_tree_log(node, lvl, "Failed to resolve '%s' in %s statement", args->last_resolved_name, cil_node_to_string(node));
cil_tree_log(node, lvl, "Failed to resolve %s statement", cil_node_to_string(node));
goto exit;
}

View File

@ -18,15 +18,15 @@ TARGET=libsepol.so
LIBPC=libsepol.pc
LIBMAP=libsepol.map
LIBSO=$(TARGET).$(LIBVERSION)
OBJS= $(patsubst %.c,%.o,$(wildcard *.c))
LOBJS= $(patsubst %.c,%.lo,$(wildcard *.c))
OBJS= $(patsubst %.c,%.o,$(sort $(wildcard *.c)))
LOBJS= $(patsubst %.c,%.lo,$(sort $(wildcard *.c)))
CFLAGS ?= -Werror -Wall -W -Wundef -Wshadow -Wmissing-format-attribute -O2
override CFLAGS += -I. -I../include -D_GNU_SOURCE
ifneq ($(DISABLE_CIL),y)
OBJS += $(sort $(patsubst %.c,%.o,$(wildcard $(CILDIR)/src/*.c) $(CIL_GENERATED)))
LOBJS += $(sort $(patsubst %.c,%.lo,$(wildcard $(CILDIR)/src/*.c) $(CIL_GENERATED)))
OBJS += $(sort $(patsubst %.c,%.o,$(sort $(wildcard $(CILDIR)/src/*.c)) $(CIL_GENERATED)))
LOBJS += $(sort $(patsubst %.c,%.lo,$(sort $(wildcard $(CILDIR)/src/*.c)) $(CIL_GENERATED)))
override CFLAGS += -I$(CILDIR)/include
endif

View File

@ -589,14 +589,8 @@ int cond_read_bool(policydb_t * p,
goto err;
len = le32_to_cpu(buf[2]);
key = malloc(len + 1);
if (!key)
if (str_read(&key, fp, len))
goto err;
rc = next_entry(key, fp, len);
if (rc < 0)
goto err;
key[len] = 0;
if (p->policy_type != POLICY_KERN &&
p->policyvers >= MOD_POLICYDB_VERSION_TUNABLE_SEP) {

View File

@ -10,6 +10,7 @@
#include "context.h"
#include "handle.h"
#include "mls.h"
#include "private.h"
/* ----- Compatibility ---- */
int policydb_context_isvalid(const policydb_t * p, const context_struct_t * c)
@ -55,7 +56,7 @@ int context_is_valid(const policydb_t * p, const context_struct_t * c)
* Role must be authorized for the type.
*/
role = p->role_val_to_struct[c->role - 1];
if (!ebitmap_get_bit(&role->cache, c->type - 1))
if (!role || !ebitmap_get_bit(&role->cache, c->type - 1))
/* role may not be associated with type */
return 0;
@ -297,10 +298,18 @@ int context_from_string(sepol_handle_t * handle,
char *con_cpy = NULL;
sepol_context_t *ctx_record = NULL;
if (zero_or_saturated(con_str_len)) {
ERR(handle, "Invalid context length");
goto err;
}
/* sepol_context_from_string expects a NULL-terminated string */
con_cpy = malloc(con_str_len + 1);
if (!con_cpy)
goto omem;
if (!con_cpy) {
ERR(handle, "out of memory");
goto err;
}
memcpy(con_cpy, con_str, con_str_len);
con_cpy[con_str_len] = '\0';
@ -315,9 +324,6 @@ int context_from_string(sepol_handle_t * handle,
sepol_context_free(ctx_record);
return STATUS_SUCCESS;
omem:
ERR(handle, "out of memory");
err:
ERR(handle, "could not create context structure");
free(con_cpy);

View File

@ -5,6 +5,7 @@
#include "context_internal.h"
#include "debug.h"
#include "private.h"
struct sepol_context {
@ -279,44 +280,69 @@ int sepol_context_from_string(sepol_handle_t * handle,
hidden_def(sepol_context_from_string)
static inline int safe_sum(size_t *sum, const size_t augends[], const size_t cnt) {
size_t a, i;
*sum = 0;
for(i=0; i < cnt; i++) {
/* sum should not be smaller than the addend */
a = augends[i];
*sum += a;
if (*sum < a) {
return i;
}
}
return 0;
}
int sepol_context_to_string(sepol_handle_t * handle,
const sepol_context_t * con, char **str_ptr)
{
int rc;
const int user_sz = strlen(con->user);
const int role_sz = strlen(con->role);
const int type_sz = strlen(con->type);
const int mls_sz = (con->mls) ? strlen(con->mls) : 0;
const int total_sz = user_sz + role_sz + type_sz +
mls_sz + ((con->mls) ? 3 : 2);
char *str = NULL;
size_t total_sz, err;
const size_t sizes[] = {
strlen(con->user), /* user length */
strlen(con->role), /* role length */
strlen(con->type), /* type length */
(con->mls) ? strlen(con->mls) : 0, /* mls length */
((con->mls) ? 3 : 2) + 1 /* mls has extra ":" also null byte */
};
char *str = (char *)malloc(total_sz + 1);
if (!str)
goto omem;
err = safe_sum(&total_sz, sizes, ARRAY_SIZE(sizes));
if (err) {
ERR(handle, "invalid size, overflow at position: %zu", err);
goto err;
}
str = (char *)malloc(total_sz);
if (!str) {
ERR(handle, "out of memory");
goto err;
}
if (con->mls) {
rc = snprintf(str, total_sz + 1, "%s:%s:%s:%s",
rc = snprintf(str, total_sz, "%s:%s:%s:%s",
con->user, con->role, con->type, con->mls);
if (rc < 0 || (rc >= total_sz + 1)) {
ERR(handle, "print error");
goto err;
}
} else {
rc = snprintf(str, total_sz + 1, "%s:%s:%s",
rc = snprintf(str, total_sz, "%s:%s:%s",
con->user, con->role, con->type);
if (rc < 0 || (rc >= total_sz + 1)) {
ERR(handle, "print error");
goto err;
}
}
/*
* rc is >= 0 on the size_t cast and is safe to promote
* to an unsigned value.
*/
if (rc < 0 || (size_t)rc >= total_sz) {
ERR(handle, "print error");
goto err;
}
*str_ptr = str;
return STATUS_SUCCESS;
omem:
ERR(handle, "out of memory");
err:
ERR(handle, "could not convert context to string");
free(str);

View File

@ -394,6 +394,10 @@ int ebitmap_read(ebitmap_t * e, void *fp)
e->highbit, MAPSIZE);
goto bad;
}
if (e->highbit && !count)
goto bad;
l = NULL;
for (i = 0; i < count; i++) {
rc = next_entry(buf, fp, sizeof(uint32_t));

View File

@ -2497,6 +2497,7 @@ int type_set_expand(type_set_t * set, ebitmap_t * t, policydb_t * p,
unsigned int i;
ebitmap_t types, neg_types;
ebitmap_node_t *tnode;
int rc =-1;
ebitmap_init(&types);
ebitmap_init(t);
@ -2505,17 +2506,29 @@ int type_set_expand(type_set_t * set, ebitmap_t * t, policydb_t * p,
/* First go through the types and OR all the attributes to types */
ebitmap_for_each_bit(&set->types, tnode, i) {
if (ebitmap_node_get_bit(tnode, i)) {
/*
* invalid policies might have more types set in the ebitmap than
* what's available in the type_val_to_struct mapping
*/
if (i > p->p_types.nprim - 1)
goto err_types;
if (!p->type_val_to_struct[i]) {
goto err_types;
}
if (p->type_val_to_struct[i]->flavor ==
TYPE_ATTRIB) {
if (ebitmap_union
(&types,
&p->type_val_to_struct[i]->
types)) {
return -1;
goto err_types;
}
} else {
if (ebitmap_set_bit(&types, i, 1)) {
return -1;
goto err_types;
}
}
}
@ -2523,7 +2536,7 @@ int type_set_expand(type_set_t * set, ebitmap_t * t, policydb_t * p,
} else {
/* No expansion of attributes, just copy the set as is. */
if (ebitmap_cpy(&types, &set->types))
return -1;
goto err_types;
}
/* Now do the same thing for negset */
@ -2535,11 +2548,11 @@ int type_set_expand(type_set_t * set, ebitmap_t * t, policydb_t * p,
if (ebitmap_union
(&neg_types,
&p->type_val_to_struct[i]->types)) {
return -1;
goto err_neg;
}
} else {
if (ebitmap_set_bit(&neg_types, i, 1)) {
return -1;
goto err_neg;
}
}
}
@ -2554,7 +2567,7 @@ int type_set_expand(type_set_t * set, ebitmap_t * t, policydb_t * p,
p->type_val_to_struct[i]->flavor == TYPE_ATTRIB)
continue;
if (ebitmap_set_bit(t, i, 1))
return -1;
goto err_neg;
}
goto out;
}
@ -2563,7 +2576,7 @@ int type_set_expand(type_set_t * set, ebitmap_t * t, policydb_t * p,
if (ebitmap_node_get_bit(tnode, i)
&& (!ebitmap_get_bit(&neg_types, i)))
if (ebitmap_set_bit(t, i, 1))
return -1;
goto err_neg;
}
if (set->flags & TYPE_COMP) {
@ -2575,20 +2588,23 @@ int type_set_expand(type_set_t * set, ebitmap_t * t, policydb_t * p,
}
if (ebitmap_get_bit(t, i)) {
if (ebitmap_set_bit(t, i, 0))
return -1;
goto err_neg;
} else {
if (ebitmap_set_bit(t, i, 1))
return -1;
goto err_neg;
}
}
}
out:
out:
rc = 0;
ebitmap_destroy(&types);
err_neg:
ebitmap_destroy(&neg_types);
err_types:
ebitmap_destroy(&types);
return 0;
return rc;
}
static int copy_neverallow(policydb_t * dest_pol, uint32_t * typemap,

View File

@ -262,6 +262,7 @@ int mls_context_isvalid(const policydb_t * p, const context_struct_t * c)
user_datum_t *usrdatum;
unsigned int i, l;
ebitmap_node_t *cnode;
hashtab_key_t key;
if (!p->mls)
return 1;
@ -279,11 +280,12 @@ int mls_context_isvalid(const policydb_t * p, const context_struct_t * c)
if (!c->range.level[l].sens
|| c->range.level[l].sens > p->p_levels.nprim)
return 0;
levdatum = (level_datum_t *) hashtab_search(p->p_levels.table,
p->
p_sens_val_to_name
[c->range.level[l].
sens - 1]);
key = p->p_sens_val_to_name[c->range.level[l].sens - 1];
if (!key)
return 0;
levdatum = (level_datum_t *) hashtab_search(p->p_levels.table, key);
if (!levdatum)
return 0;
@ -310,7 +312,7 @@ int mls_context_isvalid(const policydb_t * p, const context_struct_t * c)
if (!c->user || c->user > p->p_users.nprim)
return 0;
usrdatum = p->user_val_to_struct[c->user - 1];
if (!mls_range_contains(usrdatum->exp_range, c->range))
if (!usrdatum || !mls_range_contains(usrdatum->exp_range, c->range))
return 0; /* user may not be associated with range */
return 1;

View File

@ -30,6 +30,7 @@
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <inttypes.h>
#define SEPOL_PACKAGE_SECTION_FC 0xf97cff90
#define SEPOL_PACKAGE_SECTION_SEUSER 0x97cff91
@ -792,20 +793,13 @@ int sepol_module_package_info(struct sepol_policy_file *spf, int *type,
i);
goto cleanup;
}
len = le32_to_cpu(buf[0]);
*name = malloc(len + 1);
if (!*name) {
ERR(file->handle, "out of memory");
if (str_read(name, file, len)) {
ERR(file->handle, "%s", strerror(errno));
goto cleanup;
}
rc = next_entry(*name, file, len);
if (rc < 0) {
ERR(file->handle,
"cannot get module name string (at section %u)",
i);
goto cleanup;
}
(*name)[len] = '\0';
rc = next_entry(buf, file, sizeof(uint32_t));
if (rc < 0) {
ERR(file->handle,
@ -814,19 +808,10 @@ int sepol_module_package_info(struct sepol_policy_file *spf, int *type,
goto cleanup;
}
len = le32_to_cpu(buf[0]);
*version = malloc(len + 1);
if (!*version) {
ERR(file->handle, "out of memory");
if (str_read(version, file, len)) {
ERR(file->handle, "%s", strerror(errno));
goto cleanup;
}
rc = next_entry(*version, file, len);
if (rc < 0) {
ERR(file->handle,
"cannot get module version string (at section %u)",
i);
goto cleanup;
}
(*version)[len] = '\0';
seen |= SEEN_MOD;
break;
default:

View File

@ -47,6 +47,8 @@
#include <sepol/policydb/services.h>
#include <sepol/policydb/util.h>
#include "private.h"
#ifdef __GNUC__
# define UNUSED(x) UNUSED_ ## x __attribute__((__unused__))
#else
@ -58,7 +60,9 @@ FILE *out_file;
#define STACK_SIZE 16
#define DEFAULT_LEVEL "systemlow"
#define DEFAULT_OBJECT "object_r"
#define GEN_REQUIRE_ATTR "cil_gen_require"
#define GEN_REQUIRE_ATTR "cil_gen_require" /* Also in libsepol/cil/src/cil_post.c */
#define TYPEATTR_INFIX "_typeattr_" /* Also in libsepol/cil/src/cil_post.c */
#define ROLEATTR_INFIX "_roleattr_"
__attribute__ ((format(printf, 1, 2)))
static void log_err(const char *fmt, ...)
@ -124,7 +128,7 @@ static int get_line(char **start, char *end, char **line)
for (len = 0; p < end && *p != '\n' && *p != '\0'; p++, len++);
if (len == 0) {
if (zero_or_saturated(len)) {
rc = 0;
goto exit;
}
@ -626,9 +630,9 @@ static int set_to_cil_attr(struct policydb *pdb, int is_type, char ***names, uin
num_attrs++;
if (is_type) {
attr_infix = "_typeattr_";
attr_infix = TYPEATTR_INFIX;
} else {
attr_infix = "_roleattr_";
attr_infix = ROLEATTR_INFIX;
}
len = strlen(pdb->name) + strlen(attr_infix) + num_digits(num_attrs) + 1;
@ -1303,7 +1307,7 @@ static int cond_list_to_cil(int indent, struct policydb *pdb, struct cond_node *
{
int rc = -1;
struct cond_node *cond;
struct list *attr_list;
struct list *attr_list = NULL;
rc = list_init(&attr_list);
if (rc != 0) {
@ -3482,7 +3486,7 @@ static int block_to_cil(struct policydb *pdb, struct avrule_block *block, struct
{
int rc = -1;
struct avrule_decl *decl;
struct list *attr_list;
struct list *attr_list = NULL;
decl = block->branch_list;
@ -3631,7 +3635,7 @@ static int blocks_to_cil(struct policydb *pdb)
int rc = -1;
struct avrule_block *block;
int indent = 0;
struct stack *stack;
struct stack *stack = NULL;
rc = stack_init(&stack);
if (rc != 0) {
@ -3699,7 +3703,7 @@ static int linked_blocks_to_cil(struct policydb *pdb)
// Since it is linked, all optional blocks have been resolved
int rc = -1;
struct avrule_block *block;
struct stack *stack;
struct stack *stack = NULL;
rc = stack_init(&stack);
if (rc != 0) {

View File

@ -273,6 +273,7 @@ int sepol_node_query(sepol_handle_t * handle,
c, SEPOL_PROTO_IP6,
response) < 0)
goto err;
return STATUS_SUCCESS;
}
}
break;

View File

@ -1068,13 +1068,13 @@ int policydb_index_others(sepol_handle_t * handle,
free(p->role_val_to_struct);
p->role_val_to_struct = (role_datum_t **)
malloc(p->p_roles.nprim * sizeof(role_datum_t *));
calloc(p->p_roles.nprim, sizeof(role_datum_t *));
if (!p->role_val_to_struct)
return -1;
free(p->user_val_to_struct);
p->user_val_to_struct = (user_datum_t **)
malloc(p->p_users.nprim * sizeof(user_datum_t *));
calloc(p->p_users.nprim, sizeof(user_datum_t *));
if (!p->user_val_to_struct)
return -1;
@ -1911,15 +1911,10 @@ static int perm_read(policydb_t * p
goto bad;
len = le32_to_cpu(buf[0]);
perdatum->s.value = le32_to_cpu(buf[1]);
if(str_read(&key, fp, len))
goto bad;
key = malloc(len + 1);
if (!key)
goto bad;
rc = next_entry(key, fp, len);
if (rc < 0)
goto bad;
key[len] = 0;
perdatum->s.value = le32_to_cpu(buf[1]);
if (hashtab_insert(h, key, perdatum))
goto bad;
@ -1949,6 +1944,9 @@ static int common_read(policydb_t * p, hashtab_t h, struct policy_file *fp)
goto bad;
len = le32_to_cpu(buf[0]);
if (zero_or_saturated(len))
goto bad;
comdatum->s.value = le32_to_cpu(buf[1]);
if (symtab_init(&comdatum->permissions, PERM_SYMTAB_SIZE))
@ -2092,7 +2090,11 @@ static int class_read(policydb_t * p, hashtab_t h, struct policy_file *fp)
goto bad;
len = le32_to_cpu(buf[0]);
if (zero_or_saturated(len))
goto bad;
len2 = le32_to_cpu(buf[1]);
if (is_saturated(len2))
goto bad;
cladatum->s.value = le32_to_cpu(buf[2]);
if (symtab_init(&cladatum->permissions, PERM_SYMTAB_SIZE))
@ -2199,6 +2201,9 @@ static int role_read(policydb_t * p, hashtab_t h, struct policy_file *fp)
goto bad;
len = le32_to_cpu(buf[0]);
if (zero_or_saturated(len))
goto bad;
role->s.value = le32_to_cpu(buf[1]);
if (policydb_has_boundary_feature(p))
role->bounds = le32_to_cpu(buf[2]);
@ -2287,6 +2292,9 @@ static int type_read(policydb_t * p, hashtab_t h, struct policy_file *fp)
goto bad;
len = le32_to_cpu(buf[pos]);
if (zero_or_saturated(len))
goto bad;
typdatum->s.value = le32_to_cpu(buf[++pos]);
if (policydb_has_boundary_feature(p)) {
uint32_t properties;
@ -2447,6 +2455,8 @@ int filename_trans_read(filename_trans_t **t, struct policy_file *fp)
if (rc < 0)
return -1;
len = le32_to_cpu(buf[0]);
if (zero_or_saturated(len))
return -1;
name = calloc(len + 1, sizeof(*name));
if (!name)
@ -2556,6 +2566,9 @@ static int ocontext_read_xen(struct policydb_compat_info *info,
if (rc < 0)
return -1;
len = le32_to_cpu(buf[0]);
if (zero_or_saturated(len))
return -1;
c->u.name = malloc(len + 1);
if (!c->u.name)
return -1;
@ -2618,6 +2631,8 @@ static int ocontext_read_selinux(struct policydb_compat_info *info,
if (rc < 0)
return -1;
len = le32_to_cpu(buf[0]);
if (zero_or_saturated(len))
return -1;
c->u.name = malloc(len + 1);
if (!c->u.name)
return -1;
@ -2659,6 +2674,8 @@ static int ocontext_read_selinux(struct policydb_compat_info *info,
return -1;
c->v.behavior = le32_to_cpu(buf[0]);
len = le32_to_cpu(buf[1]);
if (zero_or_saturated(len))
return -1;
c->u.name = malloc(len + 1);
if (!c->u.name)
return -1;
@ -2719,7 +2736,7 @@ static int genfs_read(policydb_t * p, struct policy_file *fp)
uint32_t buf[1];
size_t nel, nel2, len, len2;
genfs_t *genfs_p, *newgenfs, *genfs;
unsigned int i, j;
size_t i, j;
ocontext_t *l, *c, *newc = NULL;
int rc;
@ -2733,6 +2750,8 @@ static int genfs_read(policydb_t * p, struct policy_file *fp)
if (rc < 0)
goto bad;
len = le32_to_cpu(buf[0]);
if (zero_or_saturated(len))
goto bad;
newgenfs = calloc(1, sizeof(genfs_t));
if (!newgenfs)
goto bad;
@ -2778,6 +2797,8 @@ static int genfs_read(policydb_t * p, struct policy_file *fp)
if (rc < 0)
goto bad;
len = le32_to_cpu(buf[0]);
if (zero_or_saturated(len))
goto bad;
newc->u.name = malloc(len + 1);
if (!newc->u.name) {
goto bad;
@ -2812,6 +2833,8 @@ static int genfs_read(policydb_t * p, struct policy_file *fp)
l->next = newc;
else
newgenfs->head = newc;
/* clear newc after a new owner has the pointer */
newc = NULL;
}
}
@ -2875,6 +2898,9 @@ static int user_read(policydb_t * p, hashtab_t h, struct policy_file *fp)
goto bad;
len = le32_to_cpu(buf[0]);
if (zero_or_saturated(len))
goto bad;
usrdatum->s.value = le32_to_cpu(buf[1]);
if (policydb_has_boundary_feature(p))
usrdatum->bounds = le32_to_cpu(buf[2]);
@ -2958,6 +2984,9 @@ static int sens_read(policydb_t * p
goto bad;
len = le32_to_cpu(buf[0]);
if (zero_or_saturated(len))
goto bad;
levdatum->isalias = le32_to_cpu(buf[1]);
key = malloc(len + 1);
@ -3001,6 +3030,9 @@ static int cat_read(policydb_t * p
goto bad;
len = le32_to_cpu(buf[0]);
if(zero_or_saturated(len))
goto bad;
catdatum->s.value = le32_to_cpu(buf[1]);
catdatum->isalias = le32_to_cpu(buf[2]);
@ -3337,6 +3369,8 @@ static int filename_trans_rule_read(filename_trans_rule_t ** r, struct policy_fi
return -1;
len = le32_to_cpu(buf[0]);
if (zero_or_saturated(len))
return -1;
ftr->name = malloc(len + 1);
if (!ftr->name)
@ -3578,6 +3612,8 @@ static int scope_read(policydb_t * p, int symnum, struct policy_file *fp)
if (rc < 0)
goto cleanup;
key_len = le32_to_cpu(buf[0]);
if (zero_or_saturated(key_len))
goto cleanup;
key = malloc(key_len + 1);
if (!key)
goto cleanup;
@ -3662,8 +3698,8 @@ int policydb_read(policydb_t * p, struct policy_file *fp, unsigned verbose)
}
len = buf[1];
if (len > POLICYDB_STRING_MAX_LENGTH) {
ERR(fp->handle, "policydb string length too long ");
if (len == 0 || len > POLICYDB_STRING_MAX_LENGTH) {
ERR(fp->handle, "policydb string length %s ", len ? "too long" : "zero");
return POLICYDB_ERROR;
}
@ -3796,6 +3832,8 @@ int policydb_read(policydb_t * p, struct policy_file *fp, unsigned verbose)
goto bad;
}
len = le32_to_cpu(buf[0]);
if (zero_or_saturated(len))
goto bad;
if ((p->name = malloc(len + 1)) == NULL) {
goto bad;
}
@ -3807,6 +3845,8 @@ int policydb_read(policydb_t * p, struct policy_file *fp, unsigned verbose)
goto bad;
}
len = le32_to_cpu(buf[0]);
if (zero_or_saturated(len))
goto bad;
if ((p->version = malloc(len + 1)) == NULL) {
goto bad;
}
@ -3924,6 +3964,10 @@ int policydb_read(policydb_t * p, struct policy_file *fp, unsigned verbose)
if (!ebitmap_node_get_bit(tnode, j)
|| i == j)
continue;
if (j >= p->p_types.nprim)
goto bad;
if (ebitmap_set_bit
(&p->attr_type_map[j], i, 1))
goto bad;
@ -3954,12 +3998,12 @@ int policydb_reindex_users(policydb_t * p)
free(p->sym_val_to_name[i]);
p->user_val_to_struct = (user_datum_t **)
malloc(p->p_users.nprim * sizeof(user_datum_t *));
calloc(p->p_users.nprim, sizeof(user_datum_t *));
if (!p->user_val_to_struct)
return -1;
p->sym_val_to_name[i] = (char **)
malloc(p->symtab[i].nprim * sizeof(char *));
calloc(p->symtab[i].nprim, sizeof(char *));
if (!p->sym_val_to_name[i])
return -1;

View File

@ -45,6 +45,9 @@
#define ARRAY_SIZE(x) (sizeof(x)/sizeof((x)[0]))
#define is_saturated(x) (x == (typeof(x))-1)
#define zero_or_saturated(x) ((x == 0) || is_saturated(x))
/* Policy compatibility information. */
struct policydb_compat_info {
unsigned int type;
@ -62,3 +65,4 @@ extern struct policydb_compat_info *policydb_lookup_compat(unsigned int version,
extern int next_entry(void *buf, struct policy_file *fp, size_t bytes) hidden;
extern size_t put_entry(const void *ptr, size_t size, size_t n,
struct policy_file *fp) hidden;
extern int str_read(char **strp, struct policy_file *fp, size_t len) hidden;

View File

@ -1152,20 +1152,16 @@ int hidden sepol_compute_av(sepol_security_id_t ssid,
int hidden sepol_string_to_security_class(const char *class_name,
sepol_security_class_t *tclass)
{
char *class = NULL;
sepol_security_class_t id;
class_datum_t *tclass_datum;
for (id = 1;; id++) {
class = policydb->p_class_val_to_name[id - 1];
if (class == NULL) {
ERR(NULL, "could not convert %s to class id", class_name);
return STATUS_ERR;
}
if ((strcmp(class, class_name)) == 0) {
*tclass = id;
return STATUS_SUCCESS;
}
tclass_datum = hashtab_search(policydb->p_classes.table,
(hashtab_key_t) class_name);
if (!tclass_datum) {
ERR(NULL, "unrecognized class %s", class_name);
return STATUS_ERR;
}
*tclass = tclass_datum->s.value;
return STATUS_SUCCESS;
}
/*
@ -1643,13 +1639,16 @@ int hidden next_entry(void *buf, struct policy_file *fp, size_t bytes)
return -1;
break;
case PF_USE_MEMORY:
if (bytes > fp->len)
if (bytes > fp->len) {
errno = EOVERFLOW;
return -1;
}
memcpy(buf, fp->data, bytes);
fp->data += bytes;
fp->len -= bytes;
break;
default:
errno = EINVAL;
return -1;
}
return 0;
@ -1682,6 +1681,40 @@ size_t hidden put_entry(const void *ptr, size_t size, size_t n,
return 0;
}
/*
* Reads a string and null terminates it from the policy file.
* This is a port of str_read from the SE Linux kernel code.
*
* It returns:
* 0 - Success
* -1 - Failure with errno set
*/
int hidden str_read(char **strp, struct policy_file *fp, size_t len)
{
int rc;
char *str;
if (zero_or_saturated(len)) {
errno = EINVAL;
return -1;
}
str = malloc(len + 1);
if (!str)
return -1;
/* it's expected the caller should free the str */
*strp = str;
/* next_entry sets errno */
rc = next_entry(str, fp, len);
if (rc)
return rc;
str[len] = '\0';
return 0;
}
/*
* Read a new set of configuration data from
* a policy database binary representation file.

View File

@ -19,12 +19,17 @@ static int user_to_record(sepol_handle_t * handle,
const char *name = policydb->p_user_val_to_name[user_idx];
user_datum_t *usrdatum = policydb->user_val_to_struct[user_idx];
ebitmap_t *roles = &(usrdatum->roles.roles);
ebitmap_t *roles;
ebitmap_node_t *rnode;
unsigned bit;
sepol_user_t *tmp_record = NULL;
if (!usrdatum)
goto err;
roles = &(usrdatum->roles.roles);
if (sepol_user_create(handle, &tmp_record) < 0)
goto err;
@ -234,6 +239,7 @@ int sepol_user_modify(sepol_handle_t * handle,
if (!tmp_ptr)
goto omem;
policydb->user_val_to_struct = tmp_ptr;
policydb->user_val_to_struct[policydb->p_users.nprim] = NULL;
tmp_ptr = realloc(policydb->sym_val_to_name[SYM_USERS],
(policydb->p_users.nprim +
@ -241,6 +247,7 @@ int sepol_user_modify(sepol_handle_t * handle,
if (!tmp_ptr)
goto omem;
policydb->sym_val_to_name[SYM_USERS] = tmp_ptr;
policydb->p_user_val_to_name[policydb->p_users.nprim] = NULL;
/* Need to copy the user name */
name = strdup(cname);

View File

@ -1,3 +1,28 @@
* audit2allow: tests should use local copy not system, from Jason Zaman.
* audit2allow: fix audit2why import from seobject, from Jason Zaman.
* audit2allow: remove audit2why so that it gets symlinked, from Jason Zaman.
* semanage: fix man page and help message for import option, from AJ.
* semanage: fix error message for fcontext -m, from Miroslav Vadkerti.
* semanage: Fix semanage fcontext -D, from Stephen Smalley.
* semanage: Correct fcontext auditing, from Miroslav Vadkerti.
* semanage: Default serange to "s0" for port modify, from Miroslav Vadkerti.
* semanage: Use socket.getprotobyname for protocol, from Miroslav Vadkerti.
* restorecond: Modify to use selinux_restorecon, from Richard Haines.
* setfiles: Modify to use selinux_restorecon, from Richard Haines.
* semanage: fix modify action in node and interface, from Miroslav Vadkerti.
* fixfiles: Pass -n to restorecon for fixfiles check, from Petr Lautrbach.
* sepolicy: Check get_rpm_nvr_list() return value, from Vit Mojzis.
* Don't use subprocess.getstatusoutput() in Python 2 code, from Petr Lautrbach.
* semanage: Add auditing of changes in records, from Miroslav Vadkerti.
* Improve compatibility with Python 3, from Jason Zaman.
* Remove unused 'q' from semodule getopt string, from Petr Lautrbach.
* Remove unused autoconf files from po/, from Petr Lautrbach.
* Remove duplicate, empty translation files, from Piotr Drąg.
* open_init_pty: Do not error on EINTR, from Jason Zaman.
* Fix [-s STORE] typos in semanage, from Petr Lautrbach.
* Update sandbox types in sandbox manual, from Michael De La Rue.
* Fix typos in semanage manpages, from Philipp Gesang.
* Fix the documentation of -l,--list for semodule, from Petr Lautrbach.
* Minor fix in a French translation, from Laurent Bigonville.
* Fix the extract example in semodule.8, from Petr Lautrbach.
* Update sandbox.8 man page, from Petr Lautrbach.

View File

@ -240,7 +240,7 @@ class AuditToPolicy:
def __output_audit2why(self):
import selinux
import seobject
import sepolicy
for i in self.__parser.avc_msgs:
rc = i.type
data = i.data
@ -260,11 +260,11 @@ class AuditToPolicy:
if len(data) > 1:
print("\tOne of the following booleans was set incorrectly.")
for b in data:
print("\tDescription:\n\t%s\n" % seobject.boolean_desc(b[0]))
print("\tDescription:\n\t%s\n" % sepolicy.boolean_desc(b[0]))
print("\tAllow access by executing:\n\t# setsebool -P %s %d" % (b[0], b[1]))
else:
print("\tThe boolean %s was set incorrectly. " % (data[0][0]))
print("\tDescription:\n\t%s\n" % seobject.boolean_desc(data[0][0]))
print("\tDescription:\n\t%s\n" % sepolicy.boolean_desc(data[0][0]))
print("\tAllow access by executing:\n\t# setsebool -P %s %d" % (data[0][0], data[0][1]))
continue

View File

@ -1,364 +0,0 @@
#! /usr/bin/python -Es
# Authors: Karl MacMillan <kmacmillan@mentalrootkit.com>
# Authors: Dan Walsh <dwalsh@redhat.com>
#
# Copyright (C) 2006-2013 Red Hat
# see file 'COPYING' for use and warranty information
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; version 2 only
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
import sys
import os
import sepolgen.audit as audit
import sepolgen.policygen as policygen
import sepolgen.interfaces as interfaces
import sepolgen.output as output
import sepolgen.objectmodel as objectmodel
import sepolgen.defaults as defaults
import sepolgen.module as module
from sepolgen.sepolgeni18n import _
import selinux.audit2why as audit2why
import locale
try:
locale.setlocale(locale.LC_ALL, '')
except:
pass
class AuditToPolicy:
VERSION = "%prog .1"
SYSLOG = "/var/log/messages"
def __init__(self):
self.__options = None
self.__parser = None
self.__avs = None
def __parse_options(self):
from optparse import OptionParser
parser = OptionParser(version=self.VERSION)
parser.add_option("-b", "--boot", action="store_true", dest="boot", default=False,
help="audit messages since last boot conflicts with -i")
parser.add_option("-a", "--all", action="store_true", dest="audit", default=False,
help="read input from audit log - conflicts with -i")
parser.add_option("-p", "--policy", dest="policy", default=None, help="Policy file to use for analysis")
parser.add_option("-d", "--dmesg", action="store_true", dest="dmesg", default=False,
help="read input from dmesg - conflicts with --all and --input")
parser.add_option("-i", "--input", dest="input",
help="read input from <input> - conflicts with -a")
parser.add_option("-l", "--lastreload", action="store_true", dest="lastreload", default=False,
help="read input only after the last reload")
parser.add_option("-r", "--requires", action="store_true", dest="requires", default=False,
help="generate require statements for rules")
parser.add_option("-m", "--module", dest="module",
help="set the module name - implies --requires")
parser.add_option("-M", "--module-package", dest="module_package",
help="generate a module package - conflicts with -o and -m")
parser.add_option("-o", "--output", dest="output",
help="append output to <filename>, conflicts with -M")
parser.add_option("-D", "--dontaudit", action="store_true",
dest="dontaudit", default=False,
help="generate policy with dontaudit rules")
parser.add_option("-R", "--reference", action="store_true", dest="refpolicy",
default=True, help="generate refpolicy style output")
parser.add_option("-N", "--noreference", action="store_false", dest="refpolicy",
default=False, help="do not generate refpolicy style output")
parser.add_option("-v", "--verbose", action="store_true", dest="verbose",
default=False, help="explain generated output")
parser.add_option("-e", "--explain", action="store_true", dest="explain_long",
default=False, help="fully explain generated output")
parser.add_option("-t", "--type", help="only process messages with a type that matches this regex",
dest="type")
parser.add_option("--perm-map", dest="perm_map", help="file name of perm map")
parser.add_option("--interface-info", dest="interface_info", help="file name of interface information")
parser.add_option("--debug", dest="debug", action="store_true", default=False,
help="leave generated modules for -M")
parser.add_option("-w", "--why", dest="audit2why", action="store_true", default=(os.path.basename(sys.argv[0]) == "audit2why"),
help="Translates SELinux audit messages into a description of why the access was denied")
options, args = parser.parse_args()
# Make -d, -a, and -i conflict
if options.audit is True or options.boot:
if options.input is not None:
sys.stderr.write("error: --all/--boot conflicts with --input\n")
if options.dmesg is True:
sys.stderr.write("error: --all/--boot conflicts with --dmesg\n")
if options.input is not None and options.dmesg is True:
sys.stderr.write("error: --input conflicts with --dmesg\n")
# Turn on requires generation if a module name is given. Also verify
# the module name.
if options.module:
name = options.module
else:
name = options.module_package
if name:
options.requires = True
if not module.is_valid_name(name):
sys.stderr.write('error: module names must begin with a letter, optionally followed by letters, numbers, "-", "_", "."\n')
sys.exit(2)
# Make -M and -o conflict
if options.module_package:
if options.output:
sys.stderr.write("error: --module-package conflicts with --output\n")
sys.exit(2)
if options.module:
sys.stderr.write("error: --module-package conflicts with --module\n")
sys.exit(2)
self.__options = options
def __read_input(self):
parser = audit.AuditParser(last_load_only=self.__options.lastreload)
filename = None
messages = None
f = None
# Figure out what input we want
if self.__options.input is not None:
filename = self.__options.input
elif self.__options.dmesg:
messages = audit.get_dmesg_msgs()
elif self.__options.audit:
try:
messages = audit.get_audit_msgs()
except OSError as e:
sys.stderr.write('could not run ausearch - "%s"\n' % str(e))
sys.exit(1)
elif self.__options.boot:
try:
messages = audit.get_audit_boot_msgs()
except OSError as e:
sys.stderr.write('could not run ausearch - "%s"\n' % str(e))
sys.exit(1)
else:
# This is the default if no input is specified
f = sys.stdin
# Get the input
if filename is not None:
try:
f = open(filename)
except IOError as e:
sys.stderr.write('could not open file %s - "%s"\n' % (filename, str(e)))
sys.exit(1)
if f is not None:
parser.parse_file(f)
f.close()
if messages is not None:
parser.parse_string(messages)
self.__parser = parser
def __process_input(self):
if self.__options.type:
avcfilter = audit.AVCTypeFilter(self.__options.type)
self.__avs = self.__parser.to_access(avcfilter)
csfilter = audit.ComputeSidTypeFilter(self.__options.type)
self.__role_types = self.__parser.to_role(csfilter)
else:
self.__avs = self.__parser.to_access()
self.__role_types = self.__parser.to_role()
def __load_interface_info(self):
# Load interface info file
if self.__options.interface_info:
fn = self.__options.interface_info
else:
fn = defaults.interface_info()
try:
fd = open(fn)
except:
sys.stderr.write("could not open interface info [%s]\n" % fn)
sys.exit(1)
ifs = interfaces.InterfaceSet()
ifs.from_file(fd)
fd.close()
# Also load perm maps
if self.__options.perm_map:
fn = self.__options.perm_map
else:
fn = defaults.perm_map()
try:
fd = open(fn)
except:
sys.stderr.write("could not open perm map [%s]\n" % fn)
sys.exit(1)
perm_maps = objectmodel.PermMappings()
perm_maps.from_file(fd)
return (ifs, perm_maps)
def __output_modulepackage(self, writer, generator):
generator.set_module_name(self.__options.module_package)
filename = self.__options.module_package + ".te"
packagename = self.__options.module_package + ".pp"
try:
fd = open(filename, "w")
except IOError as e:
sys.stderr.write("could not write output file: %s\n" % str(e))
sys.exit(1)
writer.write(generator.get_module(), fd)
fd.close()
mc = module.ModuleCompiler()
try:
mc.create_module_package(filename, self.__options.refpolicy)
except RuntimeError as e:
print(e)
sys.exit(1)
sys.stdout.write(_("******************** IMPORTANT ***********************\n"))
sys.stdout.write((_("To make this policy package active, execute:" +
"\n\nsemodule -i %s\n\n") % packagename))
def __output_audit2why(self):
import selinux
import seobject
for i in self.__parser.avc_msgs:
rc = i.type
data = i.data
if rc >= 0:
print("%s\n\tWas caused by:" % i.message)
if rc == audit2why.ALLOW:
print("\t\tUnknown - would be allowed by active policy")
print("\t\tPossible mismatch between this policy and the one under which the audit message was generated.\n")
print("\t\tPossible mismatch between current in-memory boolean settings vs. permanent ones.\n")
continue
if rc == audit2why.DONTAUDIT:
print("\t\tUnknown - should be dontaudit'd by active policy")
print("\t\tPossible mismatch between this policy and the one under which the audit message was generated.\n")
print("\t\tPossible mismatch between current in-memory boolean settings vs. permanent ones.\n")
continue
if rc == audit2why.BOOLEAN:
if len(data) > 1:
print("\tOne of the following booleans was set incorrectly.")
for b in data:
print("\tDescription:\n\t%s\n" % seobject.boolean_desc(b[0]))
print("\tAllow access by executing:\n\t# setsebool -P %s %d" % (b[0], b[1]))
else:
print("\tThe boolean %s was set incorrectly. " % (data[0][0]))
print("\tDescription:\n\t%s\n" % seobject.boolean_desc(data[0][0]))
print("\tAllow access by executing:\n\t# setsebool -P %s %d" % (data[0][0], data[0][1]))
continue
if rc == audit2why.TERULE:
print("\t\tMissing type enforcement (TE) allow rule.\n")
print("\t\tYou can use audit2allow to generate a loadable module to allow this access.\n")
continue
if rc == audit2why.CONSTRAINT:
print() # !!!! This avc is a constraint violation. You would need to modify the attributes of either the source or target types to allow this access.\n"
print("#Constraint rule: \n\t" + data[0])
for reason in data[1:]:
print("#\tPossible cause is the source %s and target %s are different.\n\b" % reason)
if rc == audit2why.RBAC:
print("\t\tMissing role allow rule.\n")
print("\t\tAdd an allow rule for the role pair.\n")
continue
audit2why.finish()
return
def __output(self):
if self.__options.audit2why:
try:
return self.__output_audit2why()
except RuntimeError as e:
print(e)
sys.exit(1)
g = policygen.PolicyGenerator()
g.set_gen_dontaudit(self.__options.dontaudit)
if self.__options.module:
g.set_module_name(self.__options.module)
# Interface generation
if self.__options.refpolicy:
ifs, perm_maps = self.__load_interface_info()
g.set_gen_refpol(ifs, perm_maps)
# Explanation
if self.__options.verbose:
g.set_gen_explain(policygen.SHORT_EXPLANATION)
if self.__options.explain_long:
g.set_gen_explain(policygen.LONG_EXPLANATION)
# Requires
if self.__options.requires:
g.set_gen_requires(True)
# Generate the policy
g.add_access(self.__avs)
g.add_role_types(self.__role_types)
# Output
writer = output.ModuleWriter()
# Module package
if self.__options.module_package:
self.__output_modulepackage(writer, g)
else:
# File or stdout
if self.__options.module:
g.set_module_name(self.__options.module)
if self.__options.output:
fd = open(self.__options.output, "a")
else:
fd = sys.stdout
writer.write(g.get_module(), fd)
def main(self):
try:
self.__parse_options()
if self.__options.policy:
audit2why.init(self.__options.policy)
else:
audit2why.init()
self.__read_input()
self.__process_input()
self.__output()
except KeyboardInterrupt:
sys.exit(0)
except ValueError as e:
print(e)
sys.exit(1)
except IOError as e:
print(e)
sys.exit(1)
if __name__ == "__main__":
app = AuditToPolicy()
app.main()

View File

@ -0,0 +1 @@
audit2allow

View File

@ -33,7 +33,7 @@ class Audit2allowTests(unittest.TestCase):
def test_audit2allow(self):
"Verify audit2allow works"
p = Popen(['audit2allow', "-i", "test.log"], stdout=PIPE)
p = Popen(['python', './audit2allow', "-i", "test.log"], stdout=PIPE)
out, err = p.communicate()
if err:
print(out, err)
@ -41,7 +41,7 @@ class Audit2allowTests(unittest.TestCase):
def test_audit2why(self):
"Verify audit2why works"
p = Popen(['audit2why', "-i", "test.log"], stdout=PIPE)
p = Popen(['python', './audit2why', "-i", "test.log"], stdout=PIPE)
out, err = p.communicate()
if err:
print(out, err)

View File

@ -31,7 +31,11 @@ import semanagePage
INSTALLPATH = '/usr/share/system-config-selinux'
sys.path.append(INSTALLPATH)
import commands
try:
from subprocess import getstatusoutput
except ImportError:
from commands import getstatusoutput
ENFORCING = 0
PERMISSIVE = 1
DISABLED = 2
@ -40,18 +44,22 @@ DISABLED = 2
## I18N
##
PROGNAME = "policycoreutils"
import gettext
gettext.bindtextdomain(PROGNAME, "/usr/share/locale")
gettext.textdomain(PROGNAME)
try:
import gettext
kwargs = {}
if sys.version_info < (3,):
kwargs['unicode'] = True
gettext.install(PROGNAME,
localedir="/usr/share/locale",
unicode=False,
codeset='utf-8')
except IOError:
import __builtin__
__builtin__.__dict__['_'] = unicode
codeset='utf-8',
**kwargs)
except:
try:
import builtins
builtins.__dict__['_'] = str
except ImportError:
import __builtin__
__builtin__.__dict__['_'] = unicode
from glob import fnmatch
@ -178,13 +186,13 @@ class booleansPage:
return
try:
self.wait()
(rc, out) = commands.getstatusoutput("semanage boolean -d %s" % boolean)
(rc, out) = getstatusoutput("semanage boolean -d %s" % boolean)
self.ready()
if rc != 0:
return self.error(out)
self.load(self.filter)
except ValueError, e:
except ValueError as e:
self.error(e.args[0])
def filter_changed(self, *arg):
@ -229,7 +237,7 @@ class booleansPage:
self.store.set_value(iter, ACTIVE, not val)
self.wait()
setsebool = "/usr/sbin/setsebool -P %s %d" % (key, not val)
rc, out = commands.getstatusoutput(setsebool)
rc, out = getstatusoutput(setsebool)
if rc != 0:
self.error(out)
self.load(self.filter)
@ -238,7 +246,7 @@ class booleansPage:
def on_revert_clicked(self, button):
self.wait()
setsebool = "semanage boolean --deleteall"
commands.getstatusoutput(setsebool)
getstatusoutput(setsebool)
self.load(self.filter)
self.ready()

View File

@ -20,29 +20,38 @@ import string
import gtk
import gtk.glade
import os
import commands
try:
from subprocess import getstatusoutput
except ImportError:
from commands import getstatusoutput
import gobject
import sys
import seobject
import selinux
import sepolicy
from semanagePage import *
from sepolicy import get_all_entrypoint_domains
##
## I18N
##
PROGNAME = "policycoreutils"
import gettext
gettext.bindtextdomain(PROGNAME, "/usr/share/locale")
gettext.textdomain(PROGNAME)
try:
import gettext
kwargs = {}
if sys.version_info < (3,):
kwargs['unicode'] = True
gettext.install(PROGNAME,
localedir="/usr/share/locale",
unicode=False,
codeset='utf-8')
except IOError:
import __builtin__
__builtin__.__dict__['_'] = unicode
codeset='utf-8',
**kwargs)
except:
try:
import builtins
builtins.__dict__['_'] = str
except ImportError:
import __builtin__
__builtin__.__dict__['_'] = unicode
class domainsPage(semanagePage):
@ -70,7 +79,7 @@ class domainsPage(semanagePage):
self.permissive_button = xml.get_widget("permissiveButton")
self.enforcing_button = xml.get_widget("enforcingButton")
self.domains = get_all_entrypoint_domains()
self.domains = sepolicy.get_all_entrypoint_domains()
self.load()
def get_modules(self):
@ -119,7 +128,7 @@ class domainsPage(semanagePage):
domain = store.get_value(iter, 0)
try:
self.wait()
status, output = commands.getstatusoutput("semanage permissive -d %s_t" % domain)
status, output = getstatusoutput("semanage permissive -d %s_t" % domain)
self.ready()
if status != 0:
self.error(output)
@ -127,7 +136,7 @@ class domainsPage(semanagePage):
domain = store.set_value(iter, 1, "")
self.itemSelected(selection)
except ValueError, e:
except ValueError as e:
self.error(e.args[0])
def propertiesDialog(self):
@ -144,7 +153,7 @@ class domainsPage(semanagePage):
domain = store.get_value(iter, 0)
try:
self.wait()
status, output = commands.getstatusoutput("semanage permissive -a %s_t" % domain)
status, output = getstatusoutput("semanage permissive -a %s_t" % domain)
self.ready()
if status != 0:
self.error(output)
@ -152,5 +161,5 @@ class domainsPage(semanagePage):
domain = store.set_value(iter, 1, _("Permissive"))
self.itemSelected(selection)
except ValueError, e:
except ValueError as e:
self.error(e.args[0])

View File

@ -21,7 +21,11 @@ import gtk.glade
import os
import gobject
import seobject
import commands
try:
from subprocess import getstatusoutput
except ImportError:
from commands import getstatusoutput
from semanagePage import *
SPEC_COL = 0
@ -47,18 +51,22 @@ class context:
## I18N
##
PROGNAME = "policycoreutils"
import gettext
gettext.bindtextdomain(PROGNAME, "/usr/share/locale")
gettext.textdomain(PROGNAME)
try:
import gettext
kwargs = {}
if sys.version_info < (3,):
kwargs['unicode'] = True
gettext.install(PROGNAME,
localedir="/usr/share/locale",
unicode=False,
codeset='utf-8')
except IOError:
import __builtin__
__builtin__.__dict__['_'] = unicode
codeset='utf-8',
**kwargs)
except:
try:
import builtins
builtins.__dict__['_'] = str
except ImportError:
import __builtin__
__builtin__.__dict__['_'] = unicode
class fcontextPage(semanagePage):
@ -127,9 +135,7 @@ class fcontextPage(semanagePage):
self.fcontext = seobject.fcontextRecords()
self.store.clear()
fcon_dict = self.fcontext.get_all(self.local)
keys = fcon_dict.keys()
keys.sort()
for k in keys:
for k in sorted(fcon_dict.keys()):
if not self.match(fcon_dict, k, filter):
continue
iter = self.store.append()
@ -177,14 +183,14 @@ class fcontextPage(semanagePage):
fspec = store.get_value(iter, SPEC_COL)
ftype = store.get_value(iter, FTYPE_COL)
self.wait()
(rc, out) = commands.getstatusoutput("semanage fcontext -d -f '%s' '%s'" % (ftype, fspec))
(rc, out) = getstatusoutput("semanage fcontext -d -f '%s' '%s'" % (ftype, fspec))
self.ready()
if rc != 0:
return self.error(out)
store.remove(iter)
self.view.get_selection().select_path((0,))
except ValueError, e:
except ValueError as e:
self.error(e.args[0])
def add(self):
@ -195,7 +201,7 @@ class fcontextPage(semanagePage):
list_model = self.fcontextFileTypeCombo.get_model()
active = self.fcontextFileTypeCombo.get_active()
self.wait()
(rc, out) = commands.getstatusoutput("semanage fcontext -a -t %s -r %s -f '%s' '%s'" % (type, mls, ftype[active], fspec))
(rc, out) = getstatusoutput("semanage fcontext -a -t %s -r %s -f '%s' '%s'" % (type, mls, ftype[active], fspec))
self.ready()
if rc != 0:
self.error(out)
@ -214,7 +220,7 @@ class fcontextPage(semanagePage):
iter = self.fcontextFileTypeCombo.get_active_iter()
ftype = list_model.get_value(iter, 0)
self.wait()
(rc, out) = commands.getstatusoutput("semanage fcontext -m -t %s -r %s -f '%s' '%s'" % (type, mls, ftype, fspec))
(rc, out) = getstatusoutput("semanage fcontext -m -t %s -r %s -f '%s' '%s'" % (type, mls, ftype, fspec))
self.ready()
if rc != 0:
self.error(out)

View File

@ -30,7 +30,10 @@ import htmllib
import formatter as Formatter
import string
from types import *
import StringIO
try:
from io import StringIO
except ImportError:
from StringIO import StringIO
#------------------------------------------------------------------------------
@ -127,7 +130,7 @@ def unescape_html(s):
def html_to_text(html, maxcol=80):
try:
buffer = StringIO.StringIO()
buffer = StringIO()
formatter = Formatter.AbstractFormatter(TextWriter(buffer, maxcol))
parser = HTMLParserAnchor(formatter)
parser.feed(html)
@ -135,7 +138,7 @@ def html_to_text(html, maxcol=80):
text = buffer.getvalue()
buffer.close()
return text
except Exception, e:
except Exception as e:
log_program.error('cannot convert html to text: %s' % e)
return None

View File

@ -22,7 +22,11 @@ import gtk.glade
import os
import gobject
import sys
import commands
try:
from subprocess import getstatusoutput
except ImportError:
from commands import getstatusoutput
import seobject
from semanagePage import *
@ -30,17 +34,22 @@ from semanagePage import *
## I18N
##
PROGNAME = "policycoreutils"
import gettext
gettext.bindtextdomain(PROGNAME, "/usr/share/locale")
gettext.textdomain(PROGNAME)
try:
import gettext
kwargs = {}
if sys.version_info < (3,):
kwargs['unicode'] = True
gettext.install(PROGNAME,
localedir="/usr/share/locale",
unicode=False,
codeset='utf-8')
except IOError:
import __builtin__
__builtin__.__dict__['_'] = unicode
codeset='utf-8',
**kwargs)
except:
try:
import builtins
builtins.__dict__['_'] = str
except ImportError:
import __builtin__
__builtin__.__dict__['_'] = unicode
class loginsPage(semanagePage):
@ -70,10 +79,8 @@ class loginsPage(semanagePage):
self.filter = filter
self.login = seobject.loginRecords()
dict = self.login.get_all(0)
keys = dict.keys()
keys.sort()
self.store.clear()
for k in keys:
for k in sorted(dict.keys()):
range = seobject.translate(dict[k][1])
if not (self.match(k, filter) or self.match(dict[k][0], filter) or self.match(range, filter)):
continue
@ -94,9 +101,7 @@ class loginsPage(semanagePage):
self.loginsSelinuxUserCombo.add_attribute(cell, 'text', 0)
selusers = seobject.seluserRecords().get_all(0)
keys = selusers.keys()
keys.sort()
for k in keys:
for k in sorted(selusers.keys()):
if k != "system_u":
self.loginsSelinuxUserCombo.append_text(k)
@ -134,14 +139,14 @@ class loginsPage(semanagePage):
raise ValueError(_("Login '%s' is required") % login)
self.wait()
(rc, out) = commands.getstatusoutput("semanage login -d %s" % login)
(rc, out) = getstatusoutput("semanage login -d %s" % login)
self.ready()
if rc != 0:
self.error(out)
return False
store.remove(iter)
self.view.get_selection().select_path((0,))
except ValueError, e:
except ValueError as e:
self.error(e.args[0])
def add(self):
@ -153,7 +158,7 @@ class loginsPage(semanagePage):
iter = self.loginsSelinuxUserCombo.get_active_iter()
seuser = list_model.get_value(iter, 0)
self.wait()
(rc, out) = commands.getstatusoutput("semanage login -a -s %s -r %s %s" % (seuser, serange, target))
(rc, out) = getstatusoutput("semanage login -a -s %s -r %s %s" % (seuser, serange, target))
self.ready()
if rc != 0:
self.error(out)
@ -173,7 +178,7 @@ class loginsPage(semanagePage):
iter = self.loginsSelinuxUserCombo.get_active_iter()
seuser = list_model.get_value(iter, 0)
self.wait()
(rc, out) = commands.getstatusoutput("semanage login -m -s %s -r %s %s" % (seuser, serange, target))
(rc, out) = getstatusoutput("semanage login -m -s %s -r %s %s" % (seuser, serange, target))
self.ready()
if rc != 0:
self.error(out)

View File

@ -28,17 +28,22 @@ import seobject
## I18N
##
PROGNAME = "policycoreutils"
import gettext
gettext.bindtextdomain(PROGNAME, "/usr/share/locale")
gettext.textdomain(PROGNAME)
try:
import gettext
kwargs = {}
if sys.version_info < (3,):
kwargs['unicode'] = True
gettext.install(PROGNAME,
localedir="/usr/share/locale",
unicode=False,
codeset='utf-8')
except IOError:
import __builtin__
__builtin__.__dict__['_'] = unicode
codeset='utf-8',
**kwargs)
except:
try:
import builtins
builtins.__dict__['_'] = str
except ImportError:
import __builtin__
__builtin__.__dict__['_'] = unicode
class loginsPage:
@ -51,7 +56,5 @@ class loginsPage:
self.view.set_model(self.store)
self.login = loginRecords()
dict = self.login.get_all(0)
keys = dict.keys()
keys.sort()
for k in keys:
print "%-25s %-25s %-25s" % (k, dict[k][0], translate(dict[k][1]))
for k in sorted(dict.keys()):
print("%-25s %-25s %-25s" % (k, dict[k][0], translate(dict[k][1])))

View File

@ -20,7 +20,11 @@ import string
import gtk
import gtk.glade
import os
import commands
try:
from subprocess import getstatusoutput
except ImportError:
from commands import getstatusoutput
import gobject
import sys
import seobject
@ -32,17 +36,22 @@ from subprocess import Popen, PIPE
## I18N
##
PROGNAME = "policycoreutils"
import gettext
gettext.bindtextdomain(PROGNAME, "/usr/share/locale")
gettext.textdomain(PROGNAME)
try:
import gettext
kwargs = {}
if sys.version_info < (3,):
kwargs['unicode'] = True
gettext.install(PROGNAME,
localedir="/usr/share/locale",
unicode=False,
codeset='utf-8')
except IOError:
import __builtin__
__builtin__.__dict__['_'] = unicode
codeset='utf-8',
**kwargs)
except:
try:
import builtins
builtins.__dict__['_'] = str
except ImportError:
import __builtin__
__builtin__.__dict__['_'] = unicode
class modulesPage(semanagePage):
@ -108,7 +117,7 @@ class modulesPage(semanagePage):
def new_module(self, args):
try:
Popen(["/usr/share/system-config-selinux/polgengui.py"])
except ValueError, e:
except ValueError as e:
self.error(e.args[0])
def delete(self):
@ -116,7 +125,7 @@ class modulesPage(semanagePage):
module = store.get_value(iter, 0)
try:
self.wait()
status, output = commands.getstatusoutput("semodule -r %s" % module)
status, output = getstatusoutput("semodule -r %s" % module)
self.ready()
if status != 0:
self.error(output)
@ -124,7 +133,7 @@ class modulesPage(semanagePage):
store.remove(iter)
self.view.get_selection().select_path((0,))
except ValueError, e:
except ValueError as e:
self.error(e.args[0])
def enable_audit(self, button):
@ -132,28 +141,28 @@ class modulesPage(semanagePage):
try:
self.wait()
if self.audit_enabled:
status, output = commands.getstatusoutput("semodule -DB")
status, output = getstatusoutput("semodule -DB")
button.set_label(_("Disable Audit"))
else:
status, output = commands.getstatusoutput("semodule -B")
status, output = getstatusoutput("semodule -B")
button.set_label(_("Enable Audit"))
self.ready()
if status != 0:
self.error(output)
except ValueError, e:
except ValueError as e:
self.error(e.args[0])
def disable_audit(self, button):
try:
self.wait()
status, output = commands.getstatusoutput("semodule -B")
status, output = getstatusoutput("semodule -B")
self.ready()
if status != 0:
self.error(output)
except ValueError, e:
except ValueError as e:
self.error(e.args[0])
def propertiesDialog(self):
@ -181,12 +190,12 @@ class modulesPage(semanagePage):
def add(self, file):
try:
self.wait()
status, output = commands.getstatusoutput("semodule -i %s" % file)
status, output = getstatusoutput("semodule -i %s" % file)
self.ready()
if status != 0:
self.error(output)
else:
self.load()
except ValueError, e:
except ValueError as e:
self.error(e.args[0])

View File

@ -29,13 +29,17 @@ import gobject
import gnome
import sys
try:
from sepolicy import generate
except ValueError, e:
import sepolicy
except ValueError as e:
sys.stderr.write("%s: %s\n" % (e.__class__.__name__, str(e)))
sys.exit(1)
import sepolicy.interface
import commands
try:
from subprocess import getstatusoutput
except ImportError:
from commands import getstatusoutput
import re
@ -43,7 +47,7 @@ import re
def get_all_modules():
try:
all_modules = []
rc, output = commands.getstatusoutput("semodule -l 2>/dev/null")
rc, output = getstatusoutput("semodule -l 2>/dev/null")
if rc == 0:
l = output.split("\n")
for i in l:
@ -58,18 +62,22 @@ def get_all_modules():
## I18N
##
PROGNAME = "policycoreutils"
import gettext
gettext.bindtextdomain(PROGNAME, "/usr/share/locale")
gettext.textdomain(PROGNAME)
try:
import gettext
kwargs = {}
if sys.version_info < (3,):
kwargs['unicode'] = True
gettext.install(PROGNAME,
localedir="/usr/share/locale",
unicode=False,
codeset='utf-8')
except IOError:
import __builtin__
__builtin__.__dict__['_'] = unicode
codeset='utf-8',
**kwargs)
except:
try:
import builtins
builtins.__dict__['_'] = str
except ImportError:
import __builtin__
__builtin__.__dict__['_'] = unicode
gnome.program_init("SELinux Policy Generation Tool", "5")
@ -194,11 +202,11 @@ class childWindow:
self.tooltip_dict[label] = label.get_tooltip_text()
try:
self.all_types = generate.get_all_types()
self.all_types = sepolicy.generate.get_all_types()
self.all_modules = get_all_modules()
self.all_roles = generate.get_all_roles()
self.all_users = generate.get_all_users()
except RuntimeError, e:
self.all_roles = sepolicy.generate.get_all_roles()
self.all_users = sepolicy.generate.get_all_users()
except RuntimeError as e:
self.all_types = []
self.all_modules = []
self.all_roles = []
@ -225,16 +233,16 @@ class childWindow:
self.boolean_description_entry = xml.get_widget("boolean_description_entry")
self.pages = {}
for i in generate.USERS:
for i in sepolicy.generate.USERS:
self.pages[i] = [self.SELECT_TYPE_PAGE, self.APP_PAGE, self.TRANSITION_PAGE, self.ROLE_PAGE, self.IN_NET_PAGE, self.OUT_NET_PAGE, self.BOOLEAN_PAGE, self.SELECT_DIR_PAGE]
self.pages[generate.RUSER] = [self.SELECT_TYPE_PAGE, self.APP_PAGE, self.ADMIN_PAGE, self.USER_TRANSITION_PAGE, self.BOOLEAN_PAGE, self.SELECT_DIR_PAGE]
self.pages[generate.LUSER] = [self.SELECT_TYPE_PAGE, self.APP_PAGE, self.TRANSITION_PAGE, self.IN_NET_PAGE, self.OUT_NET_PAGE, self.BOOLEAN_PAGE, self.SELECT_DIR_PAGE]
self.pages[generate.SANDBOX] = [self.SELECT_TYPE_PAGE, self.APP_PAGE, self.IN_NET_PAGE, self.OUT_NET_PAGE, self.BOOLEAN_PAGE, self.SELECT_DIR_PAGE]
self.pages[generate.EUSER] = [self.SELECT_TYPE_PAGE, self.EXISTING_USER_PAGE, self.TRANSITION_PAGE, self.ROLE_PAGE, self.IN_NET_PAGE, self.OUT_NET_PAGE, self.BOOLEAN_PAGE, self.SELECT_DIR_PAGE]
self.pages[sepolicy.generate.RUSER] = [self.SELECT_TYPE_PAGE, self.APP_PAGE, self.ADMIN_PAGE, self.USER_TRANSITION_PAGE, self.BOOLEAN_PAGE, self.SELECT_DIR_PAGE]
self.pages[sepolicy.generate.LUSER] = [self.SELECT_TYPE_PAGE, self.APP_PAGE, self.TRANSITION_PAGE, self.IN_NET_PAGE, self.OUT_NET_PAGE, self.BOOLEAN_PAGE, self.SELECT_DIR_PAGE]
self.pages[sepolicy.generate.SANDBOX] = [self.SELECT_TYPE_PAGE, self.APP_PAGE, self.IN_NET_PAGE, self.OUT_NET_PAGE, self.BOOLEAN_PAGE, self.SELECT_DIR_PAGE]
self.pages[sepolicy.generate.EUSER] = [self.SELECT_TYPE_PAGE, self.EXISTING_USER_PAGE, self.TRANSITION_PAGE, self.ROLE_PAGE, self.IN_NET_PAGE, self.OUT_NET_PAGE, self.BOOLEAN_PAGE, self.SELECT_DIR_PAGE]
for i in generate.APPLICATIONS:
for i in sepolicy.generate.APPLICATIONS:
self.pages[i] = [self.SELECT_TYPE_PAGE, self.APP_PAGE, self.IN_NET_PAGE, self.OUT_NET_PAGE, self.COMMON_APPS_PAGE, self.FILES_PAGE, self.BOOLEAN_PAGE, self.SELECT_DIR_PAGE]
self.pages[generate.USER] = [self.SELECT_TYPE_PAGE, self.APP_PAGE, self.USER_TRANSITION_PAGE, self.IN_NET_PAGE, self.OUT_NET_PAGE, self.COMMON_APPS_PAGE, self.FILES_PAGE, self.BOOLEAN_PAGE, self.SELECT_DIR_PAGE]
self.pages[sepolicy.generate.USER] = [self.SELECT_TYPE_PAGE, self.APP_PAGE, self.USER_TRANSITION_PAGE, self.IN_NET_PAGE, self.OUT_NET_PAGE, self.COMMON_APPS_PAGE, self.FILES_PAGE, self.BOOLEAN_PAGE, self.SELECT_DIR_PAGE]
self.current_page = 0
self.back_button.set_sensitive(0)
@ -336,11 +344,11 @@ class childWindow:
for a in sepolicy.interface.get_admin():
iter = self.admin_store.append()
self.admin_store.set_value(iter, 0, a)
except ValueError, e:
except ValueError as e:
self.error(e.message)
def confine_application(self):
return self.get_type() in generate.APPLICATIONS
return self.get_type() in sepolicy.generate.APPLICATIONS
def forward(self, arg):
type = self.get_type()
@ -437,41 +445,41 @@ class childWindow:
def get_type(self):
if self.sandbox_radiobutton.get_active():
return generate.SANDBOX
return sepolicy.generate.SANDBOX
if self.cgi_radiobutton.get_active():
return generate.CGI
return sepolicy.generate.CGI
if self.user_radiobutton.get_active():
return generate.USER
return sepolicy.generate.USER
if self.init_radiobutton.get_active():
return generate.DAEMON
return sepolicy.generate.DAEMON
if self.dbus_radiobutton.get_active():
return generate.DBUS
return sepolicy.generate.DBUS
if self.inetd_radiobutton.get_active():
return generate.INETD
return sepolicy.generate.INETD
if self.login_user_radiobutton.get_active():
return generate.LUSER
return sepolicy.generate.LUSER
if self.admin_user_radiobutton.get_active():
return generate.AUSER
return sepolicy.generate.AUSER
if self.xwindows_user_radiobutton.get_active():
return generate.XUSER
return sepolicy.generate.XUSER
if self.terminal_user_radiobutton.get_active():
return generate.TUSER
return sepolicy.generate.TUSER
if self.root_user_radiobutton.get_active():
return generate.RUSER
return sepolicy.generate.RUSER
if self.existing_user_radiobutton.get_active():
return generate.EUSER
return sepolicy.generate.EUSER
def generate_policy(self, *args):
outputdir = self.output_entry.get_text()
try:
my_policy = generate.policy(self.get_name(), self.get_type())
my_policy = sepolicy.generate.policy(self.get_name(), self.get_type())
iter = self.boolean_store.get_iter_first()
while(iter):
my_policy.add_boolean(self.boolean_store.get_value(iter, 0), self.boolean_store.get_value(iter, 1))
iter = self.boolean_store.iter_next(iter)
if self.get_type() in generate.APPLICATIONS:
if self.get_type() in sepolicy.generate.APPLICATIONS:
my_policy.set_program(self.exec_entry.get_text())
my_policy.gen_symbols()
@ -484,14 +492,14 @@ class childWindow:
my_policy.set_use_audit(self.audit_checkbutton.get_active() == 1)
my_policy.set_use_terminal(self.terminal_checkbutton.get_active() == 1)
my_policy.set_use_mail(self.mail_checkbutton.get_active() == 1)
if self.get_type() is generate.DAEMON:
if self.get_type() is sepolicy.generate.DAEMON:
my_policy.set_init_script(self.init_script_entry.get_text())
if self.get_type() == generate.USER:
if self.get_type() == sepolicy.generate.USER:
selected = []
self.user_transition_treeview.get_selection().selected_foreach(foreach, selected)
my_policy.set_transition_users(selected)
else:
if self.get_type() == generate.RUSER:
if self.get_type() == sepolicy.generate.RUSER:
selected = []
self.admin_treeview.get_selection().selected_foreach(foreach, selected)
my_policy.set_admin_domains(selected)
@ -522,7 +530,7 @@ class childWindow:
self.info(my_policy.generate(outputdir))
return False
except ValueError, e:
except ValueError as e:
self.error(e.message)
def delete(self, args):
@ -690,7 +698,7 @@ class childWindow:
try:
generate.verify_ports(self.in_tcp_entry.get_text())
generate.verify_ports(self.in_udp_entry.get_text())
except ValueError, e:
except ValueError as e:
self.error(e.message)
return True
@ -698,7 +706,7 @@ class childWindow:
try:
generate.verify_ports(self.out_tcp_entry.get_text())
generate.verify_ports(self.out_udp_entry.get_text())
except ValueError, e:
except ValueError as e:
self.error(e.message)
return True

View File

@ -23,28 +23,33 @@ import os
import gobject
import sys
import seobject
import commands
try:
from subprocess import getstatusoutput
except ImportError:
from commands import getstatusoutput
from semanagePage import *
##
## I18N
##
PROGNAME = "policycoreutils"
import gettext
gettext.bindtextdomain(PROGNAME, "/usr/share/locale")
gettext.textdomain(PROGNAME)
TYPE_COL = 0
PROTOCOL_COL = 1
MLS_COL = 2
PORT_COL = 3
try:
import gettext
kwargs = {}
if sys.version_info < (3,):
kwargs['unicode'] = True
gettext.install(PROGNAME,
localedir="/usr/share/locale",
unicode=False,
codeset='utf-8')
except IOError:
import __builtin__
__builtin__.__dict__['_'] = unicode
codeset='utf-8',
**kwargs)
except:
try:
import builtins
builtins.__dict__['_'] = str
except ImportError:
import __builtin__
__builtin__.__dict__['_'] = unicode
class portsPage(semanagePage):
@ -122,10 +127,8 @@ class portsPage(semanagePage):
self.filter = filter
self.port = seobject.portRecords()
dict = self.port.get_all(self.local)
keys = dict.keys()
keys.sort()
self.store.clear()
for k in keys:
for k in sorted(dict.keys()):
if not (self.match(str(k[0]), filter) or self.match(dict[k][0], filter) or self.match(k[2], filter) or self.match(dict[k][1], filter) or self.match(dict[k][1], filter)):
continue
iter = self.store.append()
@ -143,10 +146,8 @@ class portsPage(semanagePage):
self.filter = filter
self.port = seobject.portRecords()
dict = self.port.get_all_by_type(self.local)
keys = dict.keys()
keys.sort()
self.store.clear()
for k in keys:
for k in sorted(dict.keys()):
ports_string = ", ".join(dict[k])
if not (self.match(ports_string, filter) or self.match(k[0], filter) or self.match(k[1], filter)):
continue
@ -189,13 +190,13 @@ class portsPage(semanagePage):
protocol = store.get_value(iter, 1)
try:
self.wait()
(rc, out) = commands.getstatusoutput("semanage port -d -p %s %s" % (protocol, port))
(rc, out) = getstatusoutput("semanage port -d -p %s %s" % (protocol, port))
self.ready()
if rc != 0:
return self.error(out)
store.remove(iter)
self.view.get_selection().select_path((0,))
except ValueError, e:
except ValueError as e:
self.error(e.args[0])
def add(self):
@ -212,7 +213,7 @@ class portsPage(semanagePage):
iter = self.ports_protocol_combo.get_active_iter()
protocol = list_model.get_value(iter, 0)
self.wait()
(rc, out) = commands.getstatusoutput("semanage port -a -p %s -r %s -t %s %s" % (protocol, mls, target, port_number))
(rc, out) = getstatusoutput("semanage port -a -p %s -r %s -t %s %s" % (protocol, mls, target, port_number))
self.ready()
if rc != 0:
self.error(out)
@ -232,7 +233,7 @@ class portsPage(semanagePage):
iter = self.ports_protocol_combo.get_active_iter()
protocol = list_model.get_value(iter, 0)
self.wait()
(rc, out) = commands.getstatusoutput("semanage port -m -p %s -r %s -t %s %s" % (protocol, mls, target, port_number))
(rc, out) = getstatusoutput("semanage port -m -p %s -r %s -t %s %s" % (protocol, mls, target, port_number))
self.ready()
if rc != 0:
self.error(out)

View File

@ -28,17 +28,22 @@ import seobject
## I18N
##
PROGNAME = "policycoreutils"
import gettext
gettext.bindtextdomain(PROGNAME, "/usr/share/locale")
gettext.textdomain(PROGNAME)
try:
import gettext
kwargs = {}
if sys.version_info < (3,):
kwargs['unicode'] = True
gettext.install(PROGNAME,
localedir="/usr/share/locale",
unicode=False,
codeset='utf-8')
except IOError:
import __builtin__
__builtin__.__dict__['_'] = unicode
codeset='utf-8',
**kwargs)
except:
try:
import builtins
builtins.__dict__['_'] = str
except ImportError:
import __builtin__
__builtin__.__dict__['_'] = unicode
def idle_func():
@ -142,7 +147,7 @@ class semanagePage:
if self.add() == False:
continue
break
except ValueError, e:
except ValueError as e:
self.error(e.args[0])
self.dialog.hide()
@ -155,7 +160,7 @@ class semanagePage:
if self.modify() == False:
continue
break
except ValueError, e:
except ValueError as e:
self.error(e.args[0])
self.dialog.hide()

View File

@ -23,11 +23,16 @@ import os
import gobject
import sys
import tempfile
import selinux
INSTALLPATH = '/usr/share/system-config-selinux'
sys.path.append(INSTALLPATH)
import commands
try:
from subprocess import getstatusoutput
except ImportError:
from commands import getstatusoutput
ENFORCING = 1
PERMISSIVE = 0
DISABLED = -1
@ -40,15 +45,22 @@ RELABELFILE = "/.autorelabel"
## I18N
##
PROGNAME = "policycoreutils"
import gettext
gettext.bindtextdomain(PROGNAME, "/usr/share/locale")
gettext.textdomain(PROGNAME)
import selinux
try:
gettext.install(PROGNAME, localedir="/usr/share/locale", unicode=1)
except IOError:
import __builtin__
__builtin__.__dict__['_'] = unicode
import gettext
kwargs = {}
if sys.version_info < (3,):
kwargs['unicode'] = True
gettext.install(PROGNAME,
localedir="/usr/share/locale",
codeset='utf-8',
**kwargs)
except:
try:
import builtins
builtins.__dict__['_'] = str
except ImportError:
import __builtin__
__builtin__.__dict__['_'] = unicode
class statusPage:

View File

@ -25,9 +25,9 @@ import string
import sys
try:
import gtk
except RuntimeError, e:
print "system-config-selinux:", e
print "This is a graphical application and requires DISPLAY to be set."
except RuntimeError as e:
print("system-config-selinux:", e)
print("This is a graphical application and requires DISPLAY to be set.")
sys.exit(1)
import gtk.glade
@ -47,18 +47,22 @@ import selinux
## I18N
##
PROGNAME = "policycoreutils"
import gettext
gettext.bindtextdomain(PROGNAME, "/usr/share/locale")
gettext.textdomain(PROGNAME)
try:
import gettext
kwargs = {}
if sys.version_info < (3,):
kwargs['unicode'] = True
gettext.install(PROGNAME,
localedir="/usr/share/locale",
unicode=False,
codeset='utf-8')
except IOError:
import __builtin__
__builtin__.__dict__['_'] = unicode
codeset='utf-8',
**kwargs)
except:
try:
import builtins
builtins.__dict__['_'] = str
except ImportError:
import __builtin__
__builtin__.__dict__['_'] = unicode
gnome.program_init("SELinux Management Tool", "5")
@ -96,7 +100,7 @@ class childWindow:
self.add_page(portsPage.portsPage(xml))
self.add_page(modulesPage.modulesPage(xml)) # modules
self.add_page(domainsPage.domainsPage(xml)) # domains
except ValueError, e:
except ValueError as e:
self.error(e.message)
xml.signal_connect("on_quit_activate", self.destroy)

View File

@ -22,7 +22,11 @@ import gtk.glade
import os
import gobject
import sys
import commands
try:
from subprocess import getstatusoutput
except ImportError:
from commands import getstatusoutput
import seobject
from semanagePage import *
@ -30,14 +34,22 @@ from semanagePage import *
## I18N
##
PROGNAME = "policycoreutils"
import gettext
gettext.bindtextdomain(PROGNAME, "/usr/share/locale")
gettext.textdomain(PROGNAME)
try:
gettext.install(PROGNAME, localedir="/usr/share/locale", unicode=1)
except IOError:
import __builtin__
__builtin__.__dict__['_'] = unicode
import gettext
kwargs = {}
if sys.version_info < (3,):
kwargs['unicode'] = True
gettext.install(PROGNAME,
localedir="/usr/share/locale",
codeset='utf-8',
**kwargs)
except:
try:
import builtins
builtins.__dict__['_'] = str
except ImportError:
import __builtin__
__builtin__.__dict__['_'] = unicode
class usersPage(semanagePage):
@ -71,10 +83,8 @@ class usersPage(semanagePage):
self.filter = filter
self.user = seobject.seluserRecords()
dict = self.user.get_all()
keys = dict.keys()
keys.sort()
self.store.clear()
for k in keys:
for k in sorted(dict.keys()):
range = seobject.translate(dict[k][2])
if not (self.match(k, filter) or self.match(dict[k][0], filter) or self.match(range, filter) or self.match(dict[k][3], filter)):
continue
@ -108,7 +118,7 @@ class usersPage(semanagePage):
roles = self.selinuxRolesEntry.get_text()
self.wait()
(rc, out) = commands.getstatusoutput("semanage user -a -R '%s' -r %s %s" % (roles, range, user))
(rc, out) = getstatusoutput("semanage user -a -R '%s' -r %s %s" % (roles, range, user))
self.ready()
if rc != 0:
self.error(out)
@ -124,7 +134,7 @@ class usersPage(semanagePage):
roles = self.selinuxRolesEntry.get_text()
self.wait()
(rc, out) = commands.getstatusoutput("semanage user -m -R '%s' -r %s %s" % (roles, range, user))
(rc, out) = getstatusoutput("semanage user -m -R '%s' -r %s %s" % (roles, range, user))
self.ready()
if rc != 0:
@ -140,12 +150,12 @@ class usersPage(semanagePage):
raise ValueError(_("SELinux user '%s' is required") % user)
self.wait()
(rc, out) = commands.getstatusoutput("semanage user -d %s" % user)
(rc, out) = getstatusoutput("semanage user -d %s" % user)
self.ready()
if rc != 0:
self.error(out)
return False
store.remove(iter)
self.view.get_selection().select_path((0,))
except ValueError, e:
except ValueError as e:
self.error(e.args[0])

View File

@ -1,218 +0,0 @@
# Makefile for program source directory in GNU NLS utilities package.
# Copyright (C) 1995, 1996, 1997 by Ulrich Drepper <drepper@gnu.ai.mit.edu>
#
# This file file be copied and used freely without restrictions. It can
# be used in projects which are not available under the GNU Public License
# but which still want to provide support for the GNU gettext functionality.
# Please note that the actual code is *not* freely available.
PACKAGE = policycoreutils
VERSION = 1.1
SHELL = /bin/sh
srcdir = .
top_srcdir = ..
prefix = /usr
exec_prefix = ${prefix}
datadir = $(prefix)/share
localedir = $(datadir)/locale
gnulocaledir = $(prefix)/share/locale
gettextsrcdir = $(prefix)/share/gettext/po
subdir = po
INSTALL = /usr/bin/install -c
INSTALL_DATA = ${INSTALL} -m 644
MKINSTALLDIRS = mkdir -p
CC = gcc
GENCAT =
GMSGFMT = PATH=../src:$$PATH /usr/bin/msgfmt
MSGFMT = /usr/bin/msgfmt
XGETTEXT = PATH=../src:$$PATH /usr/bin/xgettext
MSGMERGE = PATH=../src:$$PATH msgmerge
DEFS = -DHAVE_CONFIG_H
CFLAGS = -g -O2
CPPFLAGS =
INCLUDES = -I.. -I$(top_srcdir)/intl
COMPILE = $(CC) -c $(DEFS) $(INCLUDES) $(CPPFLAGS) $(CFLAGS) $(XCFLAGS)
POFILES = da.po de.po es.po et.po fr.po gl.po id.po it.po ko.po nl.po pl.po pt_BR.po ru.po sv.po
GMOFILES = da.gmo de.gmo es.gmo et.gmo fr.gmo gl.gmo id.gmo it.gmo ko.gmo nl.gmo pl.gmo pt_BR.gmo ru.gmo sv.gmo
DISTFILES = Makefile.in.in POTFILES.in $(PACKAGE).pot \
$(POFILES) $(GMOFILES) $(SOURCES)
POTFILES = \
CATALOGS = #da.gmo de.gmo es.gmo et.gmo fr.gmo gl.gmo id.gmo it.gmo ko.gmo nl.gmo pl.gmo pt_BR.gmo ru.gmo sv.gmo
CATOBJEXT = .gmo
INSTOBJEXT = .mo
.SUFFIXES:
.SUFFIXES: .c .o .po .pox .gmo .mo .msg .cat
.c.o:
$(COMPILE) $<
.po.pox:
$(MAKE) $(PACKAGE).pot
$(MSGMERGE) $< $(srcdir)/$(PACKAGE).pot -o $*.pox
.po.mo:
$(MSGFMT) -o $@ $<
.po.gmo:
file=$(srcdir)/`echo $* | sed 's,.*/,,'`.gmo \
&& rm -f $$file && $(GMSGFMT) -o $$file $<
.po.cat:
sed -f ../intl/po2msg.sed < $< > $*.msg \
&& rm -f $@ && $(GENCAT) $@ $*.msg
all: all-yes
all-yes: $(CATALOGS)
all-no:
$(srcdir)/$(PACKAGE).pot: $(POTFILES)
$(XGETTEXT) --default-domain=$(PACKAGE) --directory=$(top_srcdir) \
--add-comments --keyword=_ --keyword=N_ \
--files-from=$(srcdir)/POTFILES.in \
&& test ! -f $(PACKAGE).po \
|| ( rm -f $(srcdir)/$(PACKAGE).pot \
&& mv $(PACKAGE).po $(srcdir)/$(PACKAGE).pot )
install: install-exec install-data
install-exec:
install-data: install-data-yes
install-data-no: all
install-data-yes: all
$(MKINSTALLDIRS) $(DESTDIR)$(datadir);
for cat in $(CATALOGS); do \
cat=`basename $$cat`; \
case "$$cat" in \
*.gmo) destdir=$(DESTDIR)$(gnulocaledir);; \
*) destdir=$(DESTDIR)$(localedir);; \
esac; \
lang=`echo $$cat | sed 's/\$(CATOBJEXT)$$//'`; \
dir=$$destdir/$$lang/LC_MESSAGES; \
echo $dir \
$(MKINSTALLDIRS) $$dir; \
if test -r $$cat; then \
$(INSTALL_DATA) $$cat $$dir/$(PACKAGE)$(INSTOBJEXT); \
echo "installing $$cat as $$dir/$(PACKAGE)$(INSTOBJEXT)"; \
else \
$(INSTALL_DATA) $(srcdir)/$$cat $$dir/$(PACKAGE)$(INSTOBJEXT); \
echo "installing $(srcdir)/$$cat as" \
"$$dir/$(PACKAGE)$(INSTOBJEXT)"; \
fi; \
if test -r $$cat.m; then \
$(INSTALL_DATA) $$cat.m $$dir/$(PACKAGE)$(INSTOBJEXT).m; \
echo "installing $$cat.m as $$dir/$(PACKAGE)$(INSTOBJEXT).m"; \
else \
if test -r $(srcdir)/$$cat.m ; then \
$(INSTALL_DATA) $(srcdir)/$$cat.m \
$$dir/$(PACKAGE)$(INSTOBJEXT).m; \
echo "installing $(srcdir)/$$cat as" \
"$$dir/$(PACKAGE)$(INSTOBJEXT).m"; \
else \
true; \
fi; \
fi; \
done
if test "$(PACKAGE)" = "gettext"; then \
$(MKINSTALLDIRS) $(DESTDIR)$(gettextsrcdir); \
$(INSTALL_DATA) $(srcdir)/Makefile.in.in \
$(DESTDIR)$(gettextsrcdir)/Makefile.in.in; \
else \
: ; \
fi
# Define this as empty until I found a useful application.
installcheck:
uninstall:
catalogs='$(CATALOGS)'; \
for cat in $$catalogs; do \
cat=`basename $$cat`; \
lang=`echo $$cat | sed 's/\$(CATOBJEXT)$$//'`; \
rm -f $(DESTDIR)$(localedir)/$$lang/LC_MESSAGES/$(PACKAGE)$(INSTOBJEXT); \
rm -f $(DESTDIR)$(localedir)/$$lang/LC_MESSAGES/$(PACKAGE)$(INSTOBJEXT).m; \
rm -f $(DESTDIR)$(gnulocaledir)/$$lang/LC_MESSAGES/$(PACKAGE)$(INSTOBJEXT); \
rm -f $(DESTDIR)$(gnulocaledir)/$$lang/LC_MESSAGES/$(PACKAGE)$(INSTOBJEXT).m; \
done
check: all
dvi info tags TAGS ID:
mostlyclean:
rm -f core core.* *.pox $(PACKAGE).po *.old.po
rm -fr *.o
clean: mostlyclean
rm -f *.gmo
distclean: clean
rm -f Makefile Makefile.in POTFILES *.mo *.msg *.cat *.cat.m
maintainer-clean: distclean
@echo "This command is intended for maintainers to use;"
@echo "it deletes files that may require special tools to rebuild."
rm -f $(GMOFILES)
distdir = ../$(PACKAGE)-$(VERSION)/$(subdir)
dist distdir: update-po $(DISTFILES)
dists="$(DISTFILES)"; \
for file in $$dists; do \
ln $(srcdir)/$$file $(distdir) 2> /dev/null \
|| cp -p $(srcdir)/$$file $(distdir); \
done
update-po: Makefile
$(MAKE) $(PACKAGE).pot
PATH=`pwd`/../src:$$PATH; \
cd $(srcdir); \
catalogs='$(CATALOGS)'; \
for cat in $$catalogs; do \
cat=`basename $$cat`; \
lang=`echo $$cat | sed 's/\$(CATOBJEXT)$$//'`; \
mv $$lang.po $$lang.old.po; \
echo "$$lang:"; \
if $(MSGMERGE) $$lang.old.po $(PACKAGE).pot -o $$lang.po; then \
rm -f $$lang.old.po; \
else \
echo "msgmerge for $$cat failed!"; \
rm -f $$lang.po; \
mv $$lang.old.po $$lang.po; \
fi; \
done
POTFILES: POTFILES.in
( if test 'x$(srcdir)' != 'x.'; then \
posrcprefix='$(top_srcdir)/'; \
else \
posrcprefix="../"; \
fi; \
rm -f $@-t $@ \
&& (sed -e '/^#/d' -e '/^[ ]*$$/d' \
-e "s@.*@ $$posrcprefix& \\\\@" < $(srcdir)/$@.in \
| sed -e '$$s/\\$$//') > $@-t \
&& chmod a-w $@-t \
&& mv $@-t $@ )
Makefile: Makefile.in.in ../config.status POTFILES
cd .. \
&& CONFIG_FILES=$(subdir)/$@.in CONFIG_HEADERS= \
$(SHELL) ./config.status
# Tell versions [3.59,3.63) of GNU make not to export all variables.
# Otherwise a system limit (for SysV at least) may be exceeded.
.NOEXPORT:

View File

@ -1,230 +0,0 @@
# Makefile for program source directory in GNU NLS utilities package.
# Copyright (C) 1995, 1996, 1997 by Ulrich Drepper <drepper@gnu.ai.mit.edu>
#
# This file file be copied and used freely without restrictions. It can
# be used in projects which are not available under the GNU Public License
# but which still want to provide support for the GNU gettext functionality.
# Please note that the actual code is *not* freely available.
PACKAGE = @PACKAGE@
VERSION = @VERSION@
SHELL = /bin/sh
@SET_MAKE@
srcdir = @srcdir@
top_srcdir = @top_srcdir@
VPATH = @srcdir@
prefix = @prefix@
exec_prefix = @exec_prefix@
datadir = $(prefix)/@DATADIRNAME@
localedir = $(datadir)/locale
gnulocaledir = $(prefix)/share/locale
gettextsrcdir = $(prefix)/share/gettext/po
subdir = po
INSTALL = @INSTALL@
INSTALL_DATA = @INSTALL_DATA@
MKINSTALLDIRS = @MKINSTALLDIRS@
CC = @CC@
GENCAT = @GENCAT@
GMSGFMT = PATH=../src:$$PATH @GMSGFMT@
MSGFMT = @MSGFMT@
XGETTEXT = PATH=../src:$$PATH @XGETTEXT@
MSGMERGE = PATH=../src:$$PATH msgmerge
DEFS = @DEFS@
CFLAGS = @CFLAGS@
CPPFLAGS = @CPPFLAGS@
INCLUDES = -I.. -I$(top_srcdir)/intl
COMPILE = $(CC) -c $(DEFS) $(INCLUDES) $(CPPFLAGS) $(CFLAGS) $(XCFLAGS)
POFILES = @POFILES@
GMOFILES = @GMOFILES@
DISTFILES = Makefile.in.in POTFILES.in $(PACKAGE).pot \
$(POFILES) $(GMOFILES) $(SOURCES)
POTFILES = \
CATALOGS = @CATALOGS@
CATOBJEXT = @CATOBJEXT@
INSTOBJEXT = @INSTOBJEXT@
.SUFFIXES:
.SUFFIXES: .c .o .po .pox .gmo .mo .msg .cat
.c.o:
$(COMPILE) $<
.po.pox:
$(MAKE) $(PACKAGE).pot
$(MSGMERGE) $< $(srcdir)/$(PACKAGE).pot -o $*.pox
.po.mo:
$(MSGFMT) -o $@ $<
.po.gmo:
file=$(srcdir)/`echo $* | sed 's,.*/,,'`.gmo \
&& rm -f $$file && $(GMSGFMT) -o $$file $<
.po.cat:
sed -f ../intl/po2msg.sed < $< > $*.msg \
&& rm -f $@ && $(GENCAT) $@ $*.msg
all: all-@USE_NLS@
all-yes: $(CATALOGS)
all-no:
$(srcdir)/$(PACKAGE).pot: $(POTFILES)
$(XGETTEXT) --default-domain=$(PACKAGE) --directory=$(top_srcdir) \
--add-comments --keyword=_ --keyword=N_ \
--files-from=$(srcdir)/POTFILES.in \
&& test ! -f $(PACKAGE).po \
|| ( rm -f $(srcdir)/$(PACKAGE).pot \
&& mv $(PACKAGE).po $(srcdir)/$(PACKAGE).pot )
install: install-exec install-data
install-exec:
install-data: install-data-@USE_NLS@
install-data-no: all
install-data-yes: all
if test -x "$(MKINSTALLDIRS)"; then \
$(MKINSTALLDIRS) $(DESTDIR)$(datadir); \
else \
$(SHELL) $(top_srcdir)/mkinstalldirs $(DESTDIR)$(datadir); \
fi
@catalogs='$(CATALOGS)'; \
for cat in $$catalogs; do \
cat=`basename $$cat`; \
case "$$cat" in \
*.gmo) destdir=$(DESTDIR)$(gnulocaledir);; \
*) destdir=$(DESTDIR)$(localedir);; \
esac; \
lang=`echo $$cat | sed 's/\$(CATOBJEXT)$$//'`; \
dir=$$destdir/$$lang/LC_MESSAGES; \
if test -r "$(MKINSTALLDIRS)"; then \
$(MKINSTALLDIRS) $$dir; \
else \
$(SHELL) $(top_srcdir)/mkinstalldirs $$dir; \
fi; \
if test -r $$cat; then \
$(INSTALL_DATA) $$cat $$dir/$(PACKAGE)$(INSTOBJEXT); \
echo "installing $$cat as $$dir/$(PACKAGE)$(INSTOBJEXT)"; \
else \
$(INSTALL_DATA) $(srcdir)/$$cat $$dir/$(PACKAGE)$(INSTOBJEXT); \
echo "installing $(srcdir)/$$cat as" \
"$$dir/$(PACKAGE)$(INSTOBJEXT)"; \
fi; \
if test -r $$cat.m; then \
$(INSTALL_DATA) $$cat.m $$dir/$(PACKAGE)$(INSTOBJEXT).m; \
echo "installing $$cat.m as $$dir/$(PACKAGE)$(INSTOBJEXT).m"; \
else \
if test -r $(srcdir)/$$cat.m ; then \
$(INSTALL_DATA) $(srcdir)/$$cat.m \
$$dir/$(PACKAGE)$(INSTOBJEXT).m; \
echo "installing $(srcdir)/$$cat as" \
"$$dir/$(PACKAGE)$(INSTOBJEXT).m"; \
else \
true; \
fi; \
fi; \
done
if test "$(PACKAGE)" = "gettext"; then \
if test -x "$(MKINSTALLDIRS)"; then \
$(MKINSTALLDIRS) $(DESTDIR)$(gettextsrcdir); \
else \
$(SHELL) $(top_srcdir)/mkinstalldirs $(DESTDIR)$(gettextsrcdir); \
fi; \
$(INSTALL_DATA) $(srcdir)/Makefile.in.in \
$(DESTDIR)$(gettextsrcdir)/Makefile.in.in; \
else \
: ; \
fi
# Define this as empty until I found a useful application.
installcheck:
uninstall:
catalogs='$(CATALOGS)'; \
for cat in $$catalogs; do \
cat=`basename $$cat`; \
lang=`echo $$cat | sed 's/\$(CATOBJEXT)$$//'`; \
rm -f $(DESTDIR)$(localedir)/$$lang/LC_MESSAGES/$(PACKAGE)$(INSTOBJEXT); \
rm -f $(DESTDIR)$(localedir)/$$lang/LC_MESSAGES/$(PACKAGE)$(INSTOBJEXT).m; \
rm -f $(DESTDIR)$(gnulocaledir)/$$lang/LC_MESSAGES/$(PACKAGE)$(INSTOBJEXT); \
rm -f $(DESTDIR)$(gnulocaledir)/$$lang/LC_MESSAGES/$(PACKAGE)$(INSTOBJEXT).m; \
done
check: all
dvi info tags TAGS ID:
mostlyclean:
rm -f core core.* *.pox $(PACKAGE).po *.old.po
rm -fr *.o
clean: mostlyclean
rm -f *.gmo
distclean: clean
rm -f Makefile Makefile.in POTFILES *.mo *.msg *.cat *.cat.m
maintainer-clean: distclean
@echo "This command is intended for maintainers to use;"
@echo "it deletes files that may require special tools to rebuild."
rm -f $(GMOFILES)
distdir = ../$(PACKAGE)-$(VERSION)/$(subdir)
dist distdir: update-po $(DISTFILES)
dists="$(DISTFILES)"; \
for file in $$dists; do \
ln $(srcdir)/$$file $(distdir) 2> /dev/null \
|| cp -p $(srcdir)/$$file $(distdir); \
done
update-po: Makefile
$(MAKE) $(PACKAGE).pot
PATH=`pwd`/../src:$$PATH; \
cd $(srcdir); \
catalogs='$(CATALOGS)'; \
for cat in $$catalogs; do \
cat=`basename $$cat`; \
lang=`echo $$cat | sed 's/\$(CATOBJEXT)$$//'`; \
mv $$lang.po $$lang.old.po; \
echo "$$lang:"; \
if $(MSGMERGE) $$lang.old.po $(PACKAGE).pot -o $$lang.po; then \
rm -f $$lang.old.po; \
else \
echo "msgmerge for $$cat failed!"; \
rm -f $$lang.po; \
mv $$lang.old.po $$lang.po; \
fi; \
done
POTFILES: POTFILES.in
( if test 'x$(srcdir)' != 'x.'; then \
posrcprefix='$(top_srcdir)/'; \
else \
posrcprefix="../"; \
fi; \
rm -f $@-t $@ \
&& (sed -e '/^#/d' -e '/^[ ]*$$/d' \
-e "s@.*@ $$posrcprefix& \\\\@" < $(srcdir)/$@.in \
| sed -e '$$s/\\$$//') > $@-t \
&& chmod a-w $@-t \
&& mv $@-t $@ )
Makefile: Makefile.in.in ../config.status POTFILES
cd .. \
&& CONFIG_FILES=$(subdir)/$@.in CONFIG_HEADERS= \
$(SHELL) ./config.status
# Tell versions [3.59,3.63) of GNU make not to export all variables.
# Otherwise a system limit (for SysV at least) may be exceeded.
.NOEXPORT:

View File

@ -1,72 +0,0 @@
../run_init/open_init_pty.c
../run_init/run_init.c
../semodule_link/semodule_link.c
../audit2allow/audit2allow
../semanage/seobject.py
../setsebool/setsebool.c
../newrole/newrole.c
../load_policy/load_policy.c
../sestatus/sestatus.c
../semodule/semodule.c
../setfiles/setfiles.c
../semodule_package/semodule_package.c
../semodule_deps/semodule_deps.c
../semodule_expand/semodule_expand.c
../scripts/chcat
../scripts/fixfiles
../restorecond/stringslist.c
../restorecond/restorecond.h
../restorecond/utmpwatcher.h
../restorecond/stringslist.h
../restorecond/restorecond.c
../restorecond/utmpwatcher.c
../gui/booleansPage.py
../gui/fcontextPage.py
../gui/loginsPage.py
../gui/mappingsPage.py
../gui/modulesPage.py
../gui/polgen.glade
../gui/polgengui.py
../gui/polgen.py
../gui/portsPage.py
../gui/selinux.tbl
../gui/semanagePage.py
../gui/statusPage.py
../gui/system-config-selinux.glade
../gui/system-config-selinux.py
../gui/usersPage.py
../gui/templates/executable.py
../gui/templates/__init__.py
../gui/templates/network.py
../gui/templates/rw.py
../gui/templates/script.py
../gui/templates/semodule.py
../gui/templates/tmp.py
../gui/templates/user.py
../gui/templates/var_lib.py
../gui/templates/var_log.py
../gui/templates/var_run.py
../gui/templates/var_spool.py
../sepolicy/info.c
../sepolicy/search.c
../sepolicy/sepolicy.py
../sepolicy/sepolicy/communicate.py
../sepolicy/sepolicy/__init__.py
../sepolicy/sepolicy/network.py
../sepolicy/sepolicy/generate.py
../sepolicy/sepolicy/sepolicy.glade
../sepolicy/sepolicy/gui.py
../sepolicy/sepolicy/manpage.py
../sepolicy/sepolicy/transition.py
../sepolicy/sepolicy/templates/executable.py
../sepolicy/sepolicy/templates/__init__.py
../sepolicy/sepolicy/templates/network.py
../sepolicy/sepolicy/templates/rw.py
../sepolicy/sepolicy/templates/script.py
../sepolicy/sepolicy/templates/semodule.py
../sepolicy/sepolicy/templates/tmp.py
../sepolicy/sepolicy/templates/user.py
../sepolicy/sepolicy/templates/var_lib.py
../sepolicy/sepolicy/templates/var_log.py
../sepolicy/sepolicy/templates/var_run.py
../sepolicy/sepolicy/templates/var_spool.py

View File

@ -1,60 +0,0 @@
run_init/open_init_pty.c
run_init/run_init.c
semodule_link/semodule_link.c
audit2allow/audit2allow
semanage/seobject.py
setsebool/setsebool.c
newrole/newrole.c
load_policy/load_policy.c
sestatus/sestatus.c
semodule/semodule.c
setfiles/setfiles.c
semodule_package/semodule_package.c
semodule_deps/semodule_deps.c
semodule_expand/semodule_expand.c
scripts/chcat
scripts/fixfiles
restorecond/stringslist.c
restorecond/restorecond.h
restorecond/utmpwatcher.h
restorecond/stringslist.h
restorecond/restorecond.c
restorecond/utmpwatcher.c
gui/booleansPage.py
gui/fcontextPage.py
gui/loginsPage.py
gui/mappingsPage.py
gui/modulesPage.py
gui/polgen.glade
gui/polgengui.py
gui/portsPage.py
gui/selinux.tbl
gui/semanagePage.py
gui/statusPage.py
gui/system-config-selinux.glade
gui/system-config-selinux.py
gui/usersPage.py
secon/secon.c
sepolicy/info.c
sepolicy/search.c
sepolicy/sepolicy.py
sepolicy/sepolicy/communicate.py
sepolicy/sepolicy/__init__.py
sepolicy/sepolicy/network.py
sepolicy/sepolicy/generate.py
sepolicy/sepolicy/sepolicy.glade
sepolicy/sepolicy/gui.py
sepolicy/sepolicy/manpage.py
sepolicy/sepolicy/transition.py
sepolicy/sepolicy/templates/executable.py
sepolicy/sepolicy/templates/__init__.py
sepolicy/sepolicy/templates/network.py
sepolicy/sepolicy/templates/rw.py
sepolicy/sepolicy/templates/script.py
sepolicy/sepolicy/templates/semodule.py
sepolicy/sepolicy/templates/tmp.py
sepolicy/sepolicy/templates/user.py
sepolicy/sepolicy/templates/var_lib.py
sepolicy/sepolicy/templates/var_log.py
sepolicy/sepolicy/templates/var_run.py
sepolicy/sepolicy/templates/var_spool.py

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -42,6 +42,11 @@
*
*/
/*
* Note that the restorecond(8) service build links with functions provided
* by ../setfiles/restore.c
*/
#define _GNU_SOURCE
#include <sys/inotify.h>
#include <errno.h>
@ -68,7 +73,7 @@ static int master_fd = -1;
static const char *server_watch_file = "/etc/selinux/restorecond.conf";
static const char *user_watch_file = "/etc/selinux/restorecond_user.conf";
static const char *watch_file;
static struct restore_opts r_opts;
struct restore_opts r_opts;
#include <selinux/selinux.h>
@ -81,7 +86,7 @@ static void done(void) {
watch_list_free(master_fd);
close(master_fd);
utmpwatcher_free();
matchpathcon_fini();
selabel_close(r_opts.hnd);
}
static const char *pidfile = "/var/run/restorecond.pid";
@ -140,30 +145,17 @@ int main(int argc, char **argv)
int opt;
struct sigaction sa;
memset(&r_opts, 0, sizeof(r_opts));
r_opts.progress = 0;
r_opts.count = 0;
r_opts.debug = 0;
r_opts.change = 1;
r_opts.verbose = 0;
r_opts.logging = 0;
r_opts.rootpath = NULL;
r_opts.rootpathlen = 0;
r_opts.outfile = NULL;
r_opts.force = 0;
r_opts.hard_links = 0;
r_opts.abort_on_error = 0;
r_opts.add_assoc = 0;
r_opts.expand_realpath = 0;
r_opts.fts_flags = FTS_PHYSICAL;
r_opts.selabel_opt_validate = NULL;
r_opts.selabel_opt_path = NULL;
r_opts.ignore_enoent = 1;
restore_init(&r_opts);
/* If we are not running SELinux then just exit */
if (is_selinux_enabled() != 1) return 0;
if (is_selinux_enabled() != 1)
return 0;
/* Set all options to zero/NULL except for ignore_noent & digest. */
memset(&r_opts, 0, sizeof(r_opts));
r_opts.ignore_noent = SELINUX_RESTORECON_IGNORE_NOENTRY;
r_opts.ignore_digest = SELINUX_RESTORECON_IGNORE_DIGEST;
/* As r_opts.selabel_opt_digest = NULL, no digest will be requested. */
restore_init(&r_opts);
/* Register sighandlers */
sa.sa_flags = 0;
@ -171,9 +163,6 @@ int main(int argc, char **argv)
sigemptyset(&sa.sa_mask);
sigaction(SIGTERM, &sa, NULL);
set_matchpathcon_flags(MATCHPATHCON_NOTRANS);
exclude_non_seclabel_mounts();
atexit( done );
while ((opt = getopt(argc, argv, "hdf:uv")) > 0) {
switch (opt) {
@ -191,7 +180,7 @@ int main(int argc, char **argv)
exit(0);
break;
case 'v':
r_opts.verbose++;
r_opts.verbose = SELINUX_RESTORECON_VERBOSE;
break;
case '?':
usage(argv[0]);
@ -230,7 +219,7 @@ int main(int argc, char **argv)
watch_list_free(master_fd);
close(master_fd);
matchpathcon_fini();
if (pidfile)
unlink(pidfile);

View File

@ -42,4 +42,6 @@ extern int watch_list_find(int wd, const char *file);
extern void watch_list_free(int fd);
extern int watch_list_isempty(void);
extern struct restore_opts r_opts;
#endif

View File

@ -25,7 +25,6 @@
/* reasonable guess as to size of 1024 events */
#define BUF_LEN (1024 * (EVENT_SIZE + 16))
struct watchList {
struct watchList *next;
int wd;
@ -49,20 +48,23 @@ void watch_list_add(int fd, const char *path)
char *file = basename(x);
char *dir = dirname(x);
ptr = firstDir;
if (exclude(path)) goto end;
int len;
globbuf.gl_offs = 1;
if (glob(path,
GLOB_TILDE | GLOB_PERIOD,
NULL,
&globbuf) >= 0) {
for (i=0; i < globbuf.gl_pathc; i++) {
int len = strlen(globbuf.gl_pathv[i]) -2;
if (len > 0 && strcmp(&globbuf.gl_pathv[i][len--], "/.") == 0) continue;
if (len > 0 && strcmp(&globbuf.gl_pathv[i][len], "/..") == 0) continue;
if (process_one_realpath(globbuf.gl_pathv[i], 0) > 0)
process_one_realpath(globbuf.gl_pathv[i], 1);
for (i = 0; i < globbuf.gl_pathc; i++) {
len = strlen(globbuf.gl_pathv[i]) - 2;
if (len > 0 &&
strcmp(&globbuf.gl_pathv[i][len--], "/.") == 0)
continue;
if (len > 0 &&
strcmp(&globbuf.gl_pathv[i][len], "/..") == 0)
continue;
selinux_restorecon(globbuf.gl_pathv[i],
r_opts.restorecon_flags);
}
globfree(&globbuf);
}
@ -114,7 +116,9 @@ end:
int watch_list_find(int wd, const char *file)
{
struct watchList *ptr = NULL;
ptr = firstDir;
if (debug_mode)
printf("%d: File=%s\n", wd, file);
while (ptr != NULL) {
@ -126,7 +130,8 @@ int watch_list_find(int wd, const char *file)
0)
exitApp("Error allocating memory.");
process_one_realpath(path, 0);
selinux_restorecon(path,
r_opts.restorecon_flags);
free(path);
return 0;
}

View File

@ -327,8 +327,9 @@ int main(int argc, char *argv[])
break;
}
errno = 0;
int select_rc = select(pty_master + 1, &readfds, &writefds, NULL, NULL);
if (select_rc < 0) {
if (select_rc < 0 && errno != EINTR) {
perror("select()");
exit(EX_IOERR);
}

View File

@ -35,18 +35,19 @@ from tempfile import mkdtemp
import pwd
import sepolicy
PROGNAME = "policycoreutils"
SEUNSHARE = "/usr/sbin/seunshare"
SANDBOXSH = "/usr/share/sandbox/sandboxX.sh"
import gettext
gettext.bindtextdomain(PROGNAME, "/usr/share/locale")
gettext.textdomain(PROGNAME)
PROGNAME = "policycoreutils"
try:
import gettext
kwargs = {}
if sys.version_info < (3,):
kwargs['unicode'] = True
gettext.install(PROGNAME,
localedir="/usr/share/locale",
codeset='utf-8')
except IOError:
codeset='utf-8',
**kwargs)
except:
try:
import builtins
builtins.__dict__['_'] = str

View File

@ -55,11 +55,13 @@ sandbox_t \- No X, No Network Access, No Open, read/write on passed in file desc
.br
sandbox_min_t \- No Network Access
.br
sandbox_x_t \- Printer Ports
sandbox_x_t \- Ports for X applications to run locally
.br
sandbox_web_t \- Ports required for web browsing
.br
sandbox_net_t \- All network ports
sandbox_net_t \- Network ports (for server software)
.br
sandbox_net_client_t \- All network ports
.TP
\fB\-T\fR \fB\-\-tmpdir\fR

View File

@ -1,10 +1,12 @@
#! /usr/bin/python -Es
import gtk
import subprocess
try:
from subprocess import getstatusoutput
except ImportError:
from commands import getstatusoutput
import sys
rc = [-1, '']
try:
rc = subprocess.getstatusoutput(sys.argv[1])
rc = getstatusoutput(sys.argv[1])
except:
pass
if rc[0] == 0:

View File

@ -22,7 +22,10 @@
# 02111-1307 USA
#
#
import subprocess
try:
from subprocess import getstatusoutput
except ImportError:
from commands import getstatusoutput
import sys
import os
import pwd
@ -30,11 +33,18 @@ import string
import getopt
import selinux
import seobject
import gettext
PROGNAME = "policycoreutils"
try:
gettext.install('policycoreutils')
except IOError:
import gettext
kwargs = {}
if sys.version_info < (3,):
kwargs['unicode'] = True
gettext.install(PROGNAME,
localedir="/usr/share/locale",
codeset='utf-8',
**kwargs)
except:
try:
import builtins
builtins.__dict__['_'] = str
@ -92,7 +102,7 @@ def chcat_user_add(newcat, users):
cmd = "semanage login -a -r %s -s %s %s" % (new_serange, user[0], u)
else:
cmd = "semanage login -m -r %s -s %s %s" % (new_serange, user[0], u)
rc = subprocess.getstatusoutput(cmd)
rc = getstatusoutput(cmd)
if rc[0] != 0:
print(rc[1])
errors += 1
@ -131,7 +141,7 @@ def chcat_add(orig, newcat, objects, login_ind):
else:
cat_string = cat
cmd = 'chcon -l %s:%s %s' % (sensitivity, cat_string, f)
rc = subprocess.getstatusoutput(cmd)
rc = getstatusoutput(cmd)
if rc[0] != 0:
print(rc[1])
errors += 1
@ -172,7 +182,7 @@ def chcat_user_remove(newcat, users):
cmd = "semanage login -a -r %s -s %s %s" % (new_serange, user[0], u)
else:
cmd = "semanage login -m -r %s -s %s %s" % (new_serange, user[0], u)
rc = subprocess.getstatusoutput(cmd)
rc = getstatusoutput(cmd)
if rc[0] != 0:
print(rc[1])
errors += 1
@ -217,7 +227,7 @@ def chcat_remove(orig, newcat, objects, login_ind):
cmd = 'chcon -l %s %s' % (sensitivity, f)
else:
cmd = 'chcon -l %s:%s %s' % (sensitivity, cat, f)
rc = subprocess.getstatusoutput(cmd)
rc = getstatusoutput(cmd)
if rc[0] != 0:
print(rc[1])
errors += 1
@ -245,7 +255,7 @@ def chcat_user_replace(newcat, users):
cmd = "semanage login -a -r %s -s %s %s" % (new_serange, user[0], u)
else:
cmd = "semanage login -m -r %s -s %s %s" % (new_serange, user[0], u)
rc = subprocess.getstatusoutput(cmd)
rc = getstatusoutput(cmd)
if rc[0] != 0:
print(rc[1])
errors += 1
@ -268,7 +278,7 @@ def chcat_replace(newcat, objects, login_ind):
for f in objects:
cmd = "%s %s" % (cmd, f)
rc = subprocess.getstatusoutput(cmd)
rc = getstatusoutput(cmd)
if rc[0] != 0:
print(rc[1])
errors += 1

View File

@ -150,8 +150,9 @@ fi
#
newer() {
DATE=$1
shift
for m in `echo $FILESYSTEMSRW`; do
find $m -mount -newermt $DATE -print0 2>/dev/null | ${RESTORECON} ${FORCEFLAG} ${VERBOSE} -i -0 -f -
find $m -mount -newermt $DATE -print0 2>/dev/null | ${RESTORECON} ${FORCEFLAG} ${VERBOSE} $* -i -0 -f -
done;
}
@ -190,7 +191,7 @@ if [ -f ${PREFC} -a -x /usr/bin/diff ]; then
esac; \
fi; \
done | \
${RESTORECON} ${VERBOSE} -i -f - -R `exclude_dirs`; \
${RESTORECON} ${VERBOSE} -i -f - -R $* `exclude_dirs`; \
rm -f ${TEMPFILE} ${PREFCTEMPFILE}
fi
}
@ -222,7 +223,7 @@ if [ ! -z "$PREFC" ]; then
exit $?
fi
if [ ! -z "$BOOTTIME" ]; then
newer $BOOTTIME
newer $BOOTTIME $*
exit $?
fi
[ -x /usr/sbin/genhomedircon ] && /usr/sbin/genhomedircon

View File

@ -23,12 +23,13 @@
#
#
import traceback
import argparse
import seobject
import sys
import gettext
PROGNAME = "policycoreutils"
try:
import gettext
kwargs = {}
if sys.version_info < (3,):
kwargs['unicode'] = True
@ -36,7 +37,7 @@ try:
localedir="/usr/share/locale",
codeset='utf-8',
**kwargs)
except IOError:
except:
try:
import builtins
builtins.__dict__['_'] = str
@ -45,25 +46,25 @@ except IOError:
__builtin__.__dict__['_'] = unicode
# define custom usages for selected main actions
usage_login = "semanage login [-h] [-n] [-N] [-s STORE] ["
usage_login = "semanage login [-h] [-n] [-N] [-S STORE] ["
usage_login_dict = {' --add': ('-s SEUSER', '-r RANGE', 'LOGIN',), ' --modify': ('-s SEUSER', '-r RANGE', 'LOGIN',), ' --delete': ('LOGIN',), ' --list': ('-C',), ' --extract': ('',), ' --deleteall': ('',)}
usage_fcontext = "semanage fcontext [-h] [-n] [-N] [-s STORE] ["
usage_fcontext = "semanage fcontext [-h] [-n] [-N] [-S STORE] ["
usage_fcontext_dict = {' --add': ('(', '-t TYPE', '-f FTYPE', '-r RANGE', '-s SEUSER', '|', '-e EQUAL', ')', 'FILE_SPEC', ')',), ' --delete': ('(', '-t TYPE', '-f FTYPE', '|', '-e EQUAL', ')', 'FILE_SPEC', ')',), ' --modify': ('(', '-t TYPE', '-f FTYPE', '-r RANGE', '-s SEUSER', '|', '-e EQUAL', ')', 'FILE_SPEC )',), ' --list': ('-C',), ' --extract': ('',), ' --deleteall': ('',)}
usage_user = "semanage user [-h] [-n] [-N] [-s STORE] ["
usage_user = "semanage user [-h] [-n] [-N] [-S STORE] ["
usage_user_dict = {' --add': ('(', '-L LEVEL', '-R ROLES', '-r RANGE', '-s SEUSER', 'selinux_name'')'), ' --delete': ('selinux_name',), ' --modify': ('(', '-L LEVEL', '-R ROLES', '-r RANGE', '-s SEUSER', 'selinux_name', ')'), ' --list': ('-C',), ' --extract': ('',), ' --deleteall': ('',)}
usage_port = "semanage port [-h] [-n] [-N] [-s STORE] ["
usage_port = "semanage port [-h] [-n] [-N] [-S STORE] ["
usage_port_dict = {' --add': ('-t TYPE', '-p PROTOCOL', '-r RANGE', '(', 'port_name', '|', 'port_range', ')'), ' --modify': ('-t TYPE', '-p PROTOCOL', '-r RANGE', '(', 'port_name', '|', 'port_range', ')'), ' --delete': ('-p PROTOCOL', '(', 'port_name', '|', 'port_range', ')'), ' --list': ('-C',), ' --extract': ('',), ' --deleteall': ('',)}
usage_node = "semanage node [-h] [-n] [-N] [-s STORE] ["
usage_node = "semanage node [-h] [-n] [-N] [-S STORE] ["
usage_node_dict = {' --add': ('-M NETMASK', '-p PROTOCOL', '-t TYPE', '-r RANGE', 'node'), ' --modify': ('-M NETMASK', '-p PROTOCOL', '-t TYPE', '-r RANGE', 'node'), ' --delete': ('-M NETMASK', '-p PROTOCOL', 'node'), ' --list': ('-C',), ' --extract': ('',), ' --deleteall': ('',)}
usage_interface = "semanage interface [-h] [-n] [-N] [-s STORE] ["
usage_interface = "semanage interface [-h] [-n] [-N] [-S STORE] ["
usage_interface_dict = {' --add': ('-t TYPE', '-r RANGE', 'interface'), ' --modify': ('-t TYPE', '-r RANGE', 'interface'), ' --delete': ('interface',), ' --list': ('-C',), ' --extract': ('',), ' --deleteall': ('',)}
usage_boolean = "semanage boolean [-h] [-n] [-N] [-s STORE] ["
usage_boolean = "semanage boolean [-h] [-n] [-N] [-S STORE] ["
usage_boolean_dict = {' --modify': ('(', '--on', '|', '--off', ')', 'boolean'), ' --list': ('-C',), ' --extract': ('',), ' --deleteall': ('',)}
import sepolicy
@ -111,7 +112,7 @@ class SetExportFile(argparse.Action):
try:
sys.stdout = open(values, 'w')
except:
sys.stderr.write("%s: %s\n" % (e.__class__.__name__, str(e)))
sys.stderr.write(traceback.format_exc())
sys.exit(1)
setattr(namespace, self.dest, values)
@ -524,7 +525,7 @@ def handleInterface(args):
if args.action is "add":
OBJECT.add(args.interface, args.range, args.type)
if args.action is "modify":
OBJECT.add(args.interface, args.range, args.type)
OBJECT.modify(args.interface, args.range, args.type)
if args.action is "delete":
OBJECT.delete(args.interface)
if args.action is "list":
@ -607,7 +608,7 @@ def handleNode(args):
if args.action is "add":
OBJECT.add(args.node, args.netmask, args.proto, args.range, args.type)
if args.action is "modify":
OBJECT.add(args.node, args.netmask, args.proto, args.range, args.type)
OBJECT.modify(args.node, args.netmask, args.proto, args.range, args.type)
if args.action is "delete":
OBJECT.delete(args.node, args.netmask, args.proto)
if args.action is "list":
@ -702,7 +703,7 @@ def handlePermissive(args):
if args.action is "list":
OBJECT.list(args.noheading)
elif args.type != None:
elif args.type is not None:
if args.action is "add":
OBJECT.add(args.type)
if args.action is "delete":
@ -839,7 +840,7 @@ def handleImport(args):
def setupImportParser(subparsers):
importParser = subparsers.add_parser('import', help=_('Output local customizations'))
importParser = subparsers.add_parser('import', help=_('Import local customizations'))
parser_add_noreload(importParser, "import")
parser_add_store(importParser, "import")
importParser.add_argument('-f', '--input_file', dest='input_file', action=SetImportFile, help=_('Input file'))
@ -855,6 +856,7 @@ def createCommandParser():
#To add a new subcommand define the parser for it in a function above and call it here.
subparsers = commandParser.add_subparsers(dest='subcommand')
subparsers.required = True
setupImportParser(subparsers)
setupExportParser(subparsers)
setupLoginParser(subparsers)

View File

@ -2,7 +2,7 @@
.SH "NAME"
semanage\-boolean \- SELinux Policy Management boolean tool
.SH "SYNOPSIS"
.B semanage boolean [\-h] [\-n] [\-N] [\-s STORE] [ \-\-extract | \-\-deleteall | \-\-list [\-C] | \-\-modify ( \-\-on | \-\-off ) boolean ]
.B semanage boolean [\-h] [\-n] [\-N] [\-S STORE] [ \-\-extract | \-\-deleteall | \-\-list [\-C] | \-\-modify ( \-\-on | \-\-off ) boolean ]
.SH "DESCRIPTION"
semanage is used to configure certain elements of

View File

@ -8,7 +8,7 @@
semanage is used to configure certain elements of
SELinux policy without requiring modification to or recompilation
from policy sources. semanage dontaudit toggles whether or not dontaudit rules will be in the policy. Policy writers use dontaudit rules to cause
confined applications to use alternative paths. Dontaudit rules are denied but not reported in the logs. Some times dontaudit rules can cause bugs in applications but policy writers will not relize it since the AVC is not audited. Turning off dontaudit rules with this command to see if the kernel is blocking an access.
confined applications to use alternative paths. Dontaudit rules are denied but not reported in the logs. Some times dontaudit rules can cause bugs in applications but policy writers will not realize it since the AVC is not audited. Turning off dontaudit rules with this command to see if the kernel is blocking an access.
.SH "OPTIONS"
.TP

View File

@ -7,7 +7,7 @@
.SH "DESCRIPTION"
semanage is used to configure certain elements of
SELinux policy without requiring modification to or recompilation
from policy sources. semanage import and export can be used to extract the SELinux modifications from one machine and apply them to another. You can put a hole group of semanage commands within a file and apply them to a machine in a single transaction.
from policy sources. semanage import and export can be used to extract the SELinux modifications from one machine and apply them to another. You can put a whole group of semanage commands within a file and apply them to a machine in a single transaction.
.SH "OPTIONS"
.TP

View File

@ -3,7 +3,7 @@
semanage\-fcontext \- SELinux Policy Management file context tool
.SH "SYNOPSIS"
.B semanage fcontext [\-h] [\-n] [\-N] [\-s STORE] [ \-\-add ( \-t TYPE \-f FTYPE \-r RANGE \-s SEUSER | \-e EQUAL ) FILE_SPEC ) | \-\-delete ( \-t TYPE \-f FTYPE | \-e EQUAL ) FILE_SPEC ) | \-\-deleteall | \-\-extract | \-\-list [\-C] | \-\-modify ( \-t TYPE \-f FTYPE \-r RANGE \-s SEUSER | \-e EQUAL ) FILE_SPEC ) ]
.B semanage fcontext [\-h] [\-n] [\-N] [\-S STORE] [ \-\-add ( \-t TYPE \-f FTYPE \-r RANGE \-s SEUSER | \-e EQUAL ) FILE_SPEC ) | \-\-delete ( \-t TYPE \-f FTYPE | \-e EQUAL ) FILE_SPEC ) | \-\-deleteall | \-\-extract | \-\-list [\-C] | \-\-modify ( \-t TYPE \-f FTYPE \-r RANGE \-s SEUSER | \-e EQUAL ) FILE_SPEC ) ]
.SH "DESCRIPTION"
semanage is used to configure certain elements of

View File

@ -7,7 +7,7 @@
.SH "DESCRIPTION"
semanage is used to configure certain elements of
SELinux policy without requiring modification to or recompilation
from policy sources. semanage import and export can be used to extract the SELinux modifications from one machine and apply them to another. You can put a hole group of semanage commands within a file and apply them to a machine in a single transaction.
from policy sources. semanage import and export can be used to extract the SELinux modifications from one machine and apply them to another. You can put a whole group of semanage commands within a file and apply them to a machine in a single transaction.
.SH "OPTIONS"
.TP

View File

@ -2,7 +2,7 @@
.SH "NAME"
.B semanage\-interface \- SELinux Policy Management network interface tool
.SH "SYNOPSIS"
.B semanage interface [\-h] [\-n] [\-N] [\-s STORE] [ \-\-add \-t TYPE \-r RANGE interface | \-\-delete interface | \-\-deleteall | \-\-extract | \-\-list [\-C] | \-\-modify \-t TYPE \-r RANGE interface ]
.B semanage interface [\-h] [\-n] [\-N] [\-S STORE] [ \-\-add \-t TYPE \-r RANGE interface | \-\-delete interface | \-\-deleteall | \-\-extract | \-\-list [\-C] | \-\-modify \-t TYPE \-r RANGE interface ]
.SH "DESCRIPTION"
semanage is used to configure certain elements of
@ -52,7 +52,7 @@ MLS/MCS Security Range (MLS/MCS Systems only) SELinux Range for SELinux login ma
.SH EXAMPLE
.nf
list all interface defitions
list all interface definitions
# semanage interface \-l
.SH "SEE ALSO"

Some files were not shown because too many files have changed in this diff Show More