selinux 6.33 KB
Newer Older
Derek Carter committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
#!/usr/bin/python
# -*- coding: utf-8 -*-

# (c) 2012, Derek Carter<goozbach@friocorte.com>
#
# This file is part of Ansible
#
# Ansible 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, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible 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 Ansible.  If not, see <http://www.gnu.org/licenses/>.

21 22 23 24 25 26 27 28 29 30
DOCUMENTATION = '''
---
module: selinux
short_description: Change policy and state of SELinux
description:
  - Configures the SELinux mode and policy. A reboot may be required after usage. Ansible will not issue this reboot but will let you know when it is required.
version_added: "0.7"
options:
  policy:
    description:
Jan-Piet Mens committed
31
      - "name of the SELinux policy to use (example: C(targeted)) will be required if state is not C(disabled)"
32
    required: false
33 34 35 36 37 38 39 40 41 42 43 44 45 46
    default: null
  state:
    description:
      - The SELinux mode
    required: true
    default: null
    choices: [ "enforcing", "permissive", "disabled" ]
  conf:
    description:
      - path to the SELinux configuration file, if non-standard
    required: false
    default: "/etc/selinux/config"
notes:
   - Not tested on any debian based system
47 48
requirements: [ libselinux-python ]
author: Derek Carter <goozbach@friocorte.com>
49
'''
Derek Carter committed
50

51 52 53 54 55 56
EXAMPLES = '''
- selinux: policy=targeted state=enforcing
- selinux: policy=targeted state=permissive
- selinux: state=disabled
'''

Derek Carter committed
57 58
import os
import re
Michael DeHaan committed
59
import sys
Derek Carter committed
60 61 62 63

try:
    import selinux
except ImportError:
64
    print "failed=True msg='libselinux-python required for this module'"
65
    sys.exit(1)
Derek Carter committed
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107

# getter subroutines
def get_config_state(configfile):
    myfile = open(configfile, "r")
    lines = myfile.readlines()
    myfile.close()
    for line in lines:
        stateline = re.match('^SELINUX=.*$', line)
        if (stateline):
            return(line.split('=')[1].strip())

def get_config_policy(configfile):
    myfile = open(configfile, "r")
    lines = myfile.readlines()
    myfile.close()
    for line in lines:
        stateline = re.match('^SELINUXTYPE=.*$', line)
        if (stateline):
            return(line.split('=')[1].strip())

# setter subroutines
def set_config_state(state, configfile):
    #SELINUX=permissive
    # edit config file with state value
    stateline='SELINUX=%s' % state
    myfile = open(configfile, "r")
    lines = myfile.readlines()
    myfile.close()
    myfile = open(configfile, "w")
    for line in lines:
        myfile.write(re.sub(r'^SELINUX=.*', stateline, line))
    myfile.close()

def set_state(state):
    if (state == 'enforcing'):
        selinux.security_setenforce(1)
    elif (state == 'permissive'):
        selinux.security_setenforce(0)
    elif (state == 'disabled'):
        pass
    else:
        msg = 'trying to set invalid runtime state %s' % state
108
        module.fail_json(msg=msg)
Derek Carter committed
109 110 111

def set_config_policy(policy, configfile):
    # edit config file with state value
112
    #SELINUXTYPE=targeted
Derek Carter committed
113 114 115 116 117 118 119 120 121 122 123 124 125
    policyline='SELINUXTYPE=%s' % policy
    myfile = open(configfile, "r")
    lines = myfile.readlines()
    myfile.close()
    myfile = open(configfile, "w")
    for line in lines:
        myfile.write(re.sub(r'^SELINUXTYPE=.*', policyline, line))
    myfile.close()

def main():

    module = AnsibleModule(
        argument_spec = dict(
126
            policy=dict(required=False),
Michael DeHaan committed
127
            state=dict(choices=['enforcing', 'permissive', 'disabled'], required=True),
Derek Carter committed
128
            configfile=dict(aliases=['conf','file'], default='/etc/selinux/config')
129 130
        ),
        supports_check_mode=True
Derek Carter committed
131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
    )

    # global vars
    changed=False
    msgs                  = []
    configfile            = module.params['configfile']
    policy                = module.params['policy']
    state                 = module.params['state']
    runtime_enabled       = selinux.is_selinux_enabled()
    runtime_policy        = selinux.selinux_getpolicytype()[1]
    runtime_state         = 'disabled'
    if (runtime_enabled):
        # enabled means 'enforcing' or 'permissive'
        if (selinux.security_getenforce()):
            runtime_state = 'enforcing'
        else:
            runtime_state = 'permissive'
    config_policy         = get_config_policy(configfile)
    config_state          = get_config_state(configfile)

151 152
    # check to see if policy is set if state is not 'disabled'
    if (state != 'disabled'):
153
        if not policy:
154 155
            module.fail_json(msg='policy is required if state is not \'disabled\'')
    else:
156
        if not policy:
157 158
            policy = config_policy

Derek Carter committed
159 160
    # check changed values and run changes
    if (policy != runtime_policy):
161 162
        if module.check_mode:
            module.exit_json(changed=True)
Derek Carter committed
163 164
        # cannot change runtime policy
        msgs.append('reboot to change the loaded policy')
165
        changed=True
Derek Carter committed
166 167

    if (policy != config_policy):
168 169
        if module.check_mode:
            module.exit_json(changed=True)
Derek Carter committed
170 171
        msgs.append('config policy changed from \'%s\' to \'%s\'' % (config_policy, policy))
        set_config_policy(policy, configfile)
172
        changed=True
Derek Carter committed
173 174

    if (state != runtime_state):
175 176
        if module.check_mode:
            module.exit_json(changed=True)
Derek Carter committed
177
        if (state == 'disabled'):
178
            msgs.append('state change will take effect next reboot')
Derek Carter committed
179
        else:
180 181 182 183 184
            if (runtime_enabled):
                set_state(state)
                msgs.append('runtime state changed from \'%s\' to \'%s\'' % (runtime_state, state))
            else:
                msgs.append('state change will take effect next reboot')
185
        changed=True
Derek Carter committed
186 187

    if (state != config_state):
188 189
        if module.check_mode:
            module.exit_json(changed=True)
Derek Carter committed
190 191
        msgs.append('config state changed from \'%s\' to \'%s\'' % (config_state, state))
        set_config_state(state, configfile)
192 193
        changed=True

Derek Carter committed
194 195 196 197 198 199 200 201 202
    module.exit_json(changed=changed, msg=', '.join(msgs),
        configfile=configfile,
        policy=policy, state=state)

#################################################
# include magic from lib/ansible/module_common.py
#<<INCLUDE_ANSIBLE_MODULE_COMMON>>

main()
203