~chris-gondolin/charms/trusty/samhain/trunk

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
#!/usr/bin/python
#
# Copyright 2014 Canonical Ltd.  All rights reserved
# Author: Chris Stratford <chris.stratford@canonical.com>

import os
import sys
import subprocess
import shutil
import tempfile

sys.path.insert(0, os.path.join(os.environ['CHARM_DIR'], 'lib'))

from charmhelpers.core import hookenv, host
from charmhelpers.fetch import apt_install, apt_update
from charmhelpers.contrib.charmsupport.nrpe import NRPE

from Cheetah.Template import Template
from Config import Config

hooks = hookenv.Hooks()
log = hookenv.log
conf = Config()

SERVICE = 'samhain'

requiredPkgs = [
    "samhain",
]

scriptsToCopy = [
    "check-safe-for-update.sh",
    "samhain-summary.py",
]

APT_CONF = "/etc/apt/apt.conf.d/91samhain"

# This should list any files affected by the charm that may trigger an alert
samhainFiles = [
    "/etc",
    "/etc/samhain",
    "/etc/samhain/samhainrc",
    "/etc/apt/apt.conf.d",
    APT_CONF,
    "/etc/cron.d",
    "/etc/cron.d/count-samhain-violations",
]

def jujuHeader():
    header = ("#-------------------------------------------------#\n"
              "# This file is Juju managed - do not edit by hand #\n"
              "#-------------------------------------------------#\n")
    return header


def fileFromTemplate(tmpl, dest, searchList):
    template_file = os.path.join(hookenv.charm_dir(), "templates", tmpl)
    t = Template(file=template_file, searchList=searchList)
    with open(dest, "w") as f:
        f.write(jujuHeader())
        f.write(str(t))
    os.chmod(dest, 0444)


def copyScripts():
    if not os.path.exists(conf.scriptDir()):
        host.mkdir(conf.scriptDir())
    for script in scriptsToCopy:
        src = os.path.join(hookenv.charm_dir(), "files", script)
        dest = os.path.join(conf.scriptDir(), script)
        shutil.copyfile(src, dest)
        os.chmod(dest, 0755)


def updateLogrotate():
    relation_data = {}
    relation_data["logfiles"] = '{"samhain":{"path":"/var/log/samhain/samhain.log","when":"daily"}}'
    if hookenv.relation_id():
        hookenv.relation_set(None, relation_data)
    else:
        for r in hookenv.relation_ids("logrotate"):
            hookenv.relation_set(r, relation_data)


def installPackages():
    apt_update()
    apt_install(requiredPkgs, options=['--force-yes'])


# Note: We can't enable the check on install, as that prevents other
# charms installed alongside it from installing packages (any config
# file changes would make the system unclean), so this has to be set
# manually after the system is up and running.
# Note also, there is no option to disable it.  This is intentional.
def updateAptConf():
    if conf.enableAptCheck() == "yes":
        src = os.path.join(hookenv.charm_dir(), "files", "apt.conf")
        shutil.copyfile(src, APT_CONF)
        os.chmod(APT_CONF, 0644)
        updateSamhain("partial")

def writeConfig():
    tmpl_data = {}
    tmpl_data["attributesDirs"] = conf.attributesDirs()
    tmpl_data["attributesFiles"] = conf.attributesFiles()
    tmpl_data["eventSeverity"] = conf.eventSeverity()
    tmpl_data["growingLogfiles"] = conf.growingLogfiles()
    tmpl_data["ignoreAdded"] = conf.ignoreAdded()
    tmpl_data["ignoreMissing"] = conf.ignoreMissing()
    tmpl_data["ignoreModified"] = conf.ignoreModified()
    tmpl_data["ignoreAllDirs"] = conf.ignoreAllDirs()
    tmpl_data["ignoreAllFiles"] = conf.ignoreAllFiles()
    tmpl_data["ignoreNoneDirs"] = conf.ignoreNoneDirs()
    tmpl_data["ignoreNoneFiles"] = conf.ignoreNoneFiles()
    tmpl_data["logging"] = conf.logging()
    tmpl_data["logfiles"] = conf.logfiles()
    tmpl_data["mailRecipient"] = conf.mailRecipient()
    tmpl_data["prelinkDirs"] = conf.prelinkDirs()
    tmpl_data["prelinkFiles"] = conf.prelinkFiles()
    tmpl_data["readOnlyDirs"] = conf.readOnlyDirs()
    tmpl_data["readOnlyFiles"] = conf.readOnlyFiles()

    config_path = "/etc/samhain/samhainrc"
    fileFromTemplate("samhainrc.tmpl", config_path, tmpl_data)
    os.chmod(config_path, 0444)


# The samhain init scripts don't seem to work well
# so we'll control it directly
def controlSamhain(cmd):
    log("CHARM: samhain {}".format(cmd))
    validCmds = ["start", "stop", "restart", "reload", "status"]
    if cmd not in validCmds:
        log("CHARM: {} is not a valid samhain option".format(cmd))
        sys.exit(1)

    # Restart doesn't apear to work
    if cmd == "restart":
        controlSamhain("stop")
        controlSamhain("start")

    # If it's not started when we call reload, start it instead
    if cmd == "reload":
        if subprocess.call(["samhain", "status"]) != 0:
            cmd = "start"

    command = ["samhain", cmd]
    if subprocess.call(command, shell=False) != 0:
        log("CHARM: Error running samhain {} command".format(cmd))
        sys.exit(1)


# Update samhain's DB
def updateSamhain(type="full"):
    command = ['samhain', '-t', 'update', '--foreground', '-m', 'none', '-l', 'none', '-s', 'none']

    with tempfile.NamedTemporaryFile() as f:
        for filename in samhainFiles:
            f.write(filename + "\n")
        f.flush()
        if type == "partial":
            command += ["--listfile={}".format(f.name)]
        if subprocess.call(command, shell=False) != 0:
            log("CHARM: Error updating samhain")
            sys.exit(1)

def configureNrpe():
    checkScript = "samhain-policy-violations.py"
    nrpePath = "/usr/local/lib/nagios/plugins"

    with open("/etc/cron.d/count-samhain-violations", "w") as f:
        f.write("*/{} * * * * root /usr/local/sbin/check-safe-for-update.sh > /var/lib/nagios/samhain-policy-violations.txt\n".format(conf.nagiosCheckFrequency()))

    src = os.path.join(hookenv.charm_dir(), "files", checkScript)
    shutil.copyfile(src, os.path.join(nrpePath, checkScript))
    os.chmod(os.path.join(nrpePath, checkScript), 0755)

    nrpe_compat = NRPE()
    nrpe_compat.add_check(
        shortname="samhain-violations",
        description="Check for Samhain policy violations",
        check_cmd="{} -w {} -c {}".format(
            os.path.join(nrpePath, checkScript),
            conf.nagiosWarnLevel(),
            conf.nagiosCritLevel())
    )
    nrpe_compat.write()


@hooks.hook("logrotate-relation-changed")
def logrotateRelationChanged():
    log("CHARM: Changing logrotate relation for {}".format(conf.appName()))
    updateLogrotate()


@hooks.hook("nrpe-external-master-relation-changed")
def nrpeExternalMasterRelationChanged():
    log("CHARM: Changing nrpe-external-master relation for {}".format(conf.appName()))
    configureNrpe()


@hooks.hook('install')
def install():
    log("CHARM: Installing {}".format(conf.appName()))
    installPackages()
    copyScripts()
    updateSamhain()

    # Fix samhain log permissions to be world-readable
    # (otherwise logstash can't get to them)
    if not os.path.exists("/var/log/samhain"):
        mkdir("/var/log/samhain")
    if not os.path.exists("/var/log/samhain/samhain.log"):
        with open("/var/log/samhain/samhain.log", "w") as f:
            os.chmod("/var/log/samhain/samhain.log", 0644)


@hooks.hook('config-changed')
def config_changed():
    config = hookenv.config()

    for key in config:
        if config.changed(key):
            log("config['{}'] changed from {} to {}".format(
                key, config.previous(key), config[key]))

    config.save()
    writeConfig()
    controlSamhain("restart")
    updateAptConf()


@hooks.hook('upgrade-charm')
def upgrade_charm():
    log("CHARM: Upgrading {}".format(conf.appName()))
    copyScripts()
    updateAptConf()

@hooks.hook('start')
def start():
    controlSamhain("start")

@hooks.hook('stop')
def stop():
    controlSamhain("stop")


if __name__ == "__main__":
    # execute a hook based on the name the program is called by
    hooks.execute(sys.argv)