summaryrefslogtreecommitdiffstats
path: root/src/lib/Bcfg2/Server/Plugins/Cfg/CfgEncryptedGenshiGenerator.py
blob: f69ab8e5fb44e18310b310e349e63d3b2fa30d34 (plain)
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
""" Handle encrypted Genshi templates (.crypt.genshi or .genshi.crypt
files) """

from genshi.template import TemplateLoader
from Bcfg2.Compat import StringIO
from Bcfg2.Server.Plugin import PluginExecutionError
from Bcfg2.Server.Plugins.Cfg.CfgGenshiGenerator import CfgGenshiGenerator

try:
    from Bcfg2.Server.Encryption import bruteforce_decrypt
    HAS_CRYPTO = True
except ImportError:
    HAS_CRYPTO = False


class EncryptedTemplateLoader(TemplateLoader):
    """ Subclass :class:`genshi.template.TemplateLoader` to decrypt
    the data on the fly as it's read in using
    :func:`Bcfg2.Server.Encryption.bruteforce_decrypt` """
    def _instantiate(self, cls, fileobj, filepath, filename, encoding=None):
        plaintext = StringIO(bruteforce_decrypt(fileobj.read()))
        return TemplateLoader._instantiate(self, cls, plaintext, filepath,
                                           filename, encoding=encoding)


class CfgEncryptedGenshiGenerator(CfgGenshiGenerator):
    """ CfgEncryptedGenshiGenerator lets you encrypt your Genshi
    :ref:`server-plugins-generators-cfg` files on the server """

    #: handle .crypt.genshi or .genshi.crypt files
    __extensions__ = ['genshi.crypt', 'crypt.genshi']

    #: Override low priority from parent class
    __priority__ = 0

    #: Use a TemplateLoader class that decrypts the data on the fly
    #: when it's read in
    __loader_cls__ = EncryptedTemplateLoader

    def __init__(self, fname, spec):
        CfgGenshiGenerator.__init__(self, fname, spec)
        if not HAS_CRYPTO:
            raise PluginExecutionError("M2Crypto is not available")