Skip to content

Creating SELinux Contexts with Python API

Endi S. Dewata edited this page Jul 17, 2023 · 3 revisions

Python SELinux is available from the following libraries:

  • libselinux-python

  • policycoreutils-python

import selinux
import seobject

if not selinux.is_selinux_enabled() or not seobject:
    return

transaction = seobject.semanageRecords('targeted')
transaction.start()

fcontexts = seobject.fcontextRecords(transaction)
fcontexts.add('/etc/pki/pki-tomcat(/.*)?', 'pki_tomcat_etc_rw_t', '', 's0', '')
fcontexts.add('/etc/pki/pki-tomcat/alias(/.*)?', 'pki_tomcat_cert_t', '', 's0', '')
fcontexts.add('/var/lib/pki/pki-tomcat(/.*)?', 'pki_tomcat_var_lib_t', '', 's0', '')
fcontexts.add('/var/log/pki/pki-tomcat(/.*)?', 'pki_tomcat_log_t', '', 's0', '')

ports = seobject.portRecords(transaction)
ports.add('8080', 'tcp', 's0', 'http_port_t')
ports.add('8443', 'tcp', 's0', 'http_port_t')
ports.add('8009', 'tcp', 's0', 'http_port_t')
ports.add('8005', 'tcp', 's0', 'http_port_t')

transaction.finish()
Clone this wiki locally