summaryrefslogtreecommitdiffstats
path: root/src/sbin/bcfg2-crypt
blob: 17f90ca273c0ba0e8b3a638708be84cd4e5a44fc (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
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
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
#!/usr/bin/env python
""" helper for encrypting/decrypting Cfg and Properties files """

import os
import sys
import copy
import logging
import getpass
import lxml.etree
import Bcfg2.Logger
import Bcfg2.Options
import Bcfg2.Encryption

LOGGER = None

def get_logger(verbose=0):
    """ set up logging according to the verbose level given on the
    command line """
    global LOGGER
    if LOGGER is None:
        LOGGER = logging.getLogger(sys.argv[0])
        stderr = logging.StreamHandler()
        if verbose:
            level = logging.DEBUG
        else:
            level = logging.WARNING
        LOGGER.setLevel(level)
        LOGGER.addHandler(stderr)
        syslog = logging.handlers.SysLogHandler("/dev/log")
        syslog.setFormatter(logging.Formatter("%(name)s: %(message)s"))
        LOGGER.addHandler(syslog)
    return LOGGER


class Encryptor(object):
    def __init__(self, setup):
        self.setup = setup
        self.logger = get_logger()
        self.passphrase = None
        self.pname = None
        
    def get_encrypted_filename(self, plaintext_filename):
        return plaintext_filename

    def get_plaintext_filename(self, encrypted_filename):
        return encrypted_filename

    def encrypt(self, fname):
        if (not self.setup.cfp.has_section("encryption") or
            self.setup.cfp.options("encryption") == 0):
            self.logger.error("No passphrases available in %s" %
                              self.setup['configfile'])
            return False

        try:
            plaintext = open(fname).read()
        except IOError:
            err = sys.exc_info()[1]
            self.logger.error("Error reading %s, skipping: %s" (fname, err))
            return False

        if not self.passphrase:
            self.pname = self.get_passphrase(plaintext)
            if self.setup['passphrase']:
                if self.pname:
                    self.logger.warning("Passphrase given on command line "
                                        "differs from passphrase embedded in "
                                        "file, using command-line option")
                self.pname = self.setup['passphrase']
                
            if self.pname:
                if self.setup.cfp.has_option("encryption", self.pname):
                    self.passphrase = self.setup.cfp.get("encryption",
                                                         self.pname)
                else:
                    self.logger.error("Could not find passphrase %s in %s" %
                                      (self.pname, self.setup['configfile']))
            else:
                pnames = self.setup.cfp.options("encryption")
                if len(pnames) == 1:
                    self.passphrase = self.setup.cfp.get(pnames[0])
                    self.pname = pnames[0]
                    self.logger.info("Using passphrase %s" % pnames[0])
                else:
                    name = None
                    while (not name or
                           not self.setup.cfp.has_option("encryption", name)):
                        print("Available passphrases: ")
                        for pname in pnames:
                            print(pname)
                        name = raw_input("Passphrase: ")
                    self.passphrase = self.setup.cfp.get("encryption", name)
                    self.pname = name

        crypted = self._encrypt(plaintext, self.passphrase, name=self.pname)
        try:
            open(self.get_encrypted_filename(fname), "wb").write(crypted)
            self.logger.info("Wrote encrypted data to %s" % 
                        self.get_encrypted_filename(fname))
            return True
        except IOError:
            err = sys.exc_info()[1]
            self.logger.error("Error writing encrypted data from %s to %s: %s" %
                         (fname, self.get_encrypted_filename(fname), err))
            return False

    def _encrypt(self, plaintext, passphrase, name=None):
        return Bcfg2.Encryption.ssl_encrypt(plaintext, passphrase)

    def decrypt(self, fname):
        if (not self.setup.cfp.has_section("encryption") or
            self.setup.cfp.options("encryption") == 0):
            self.logger.error("No passphrases available in %s" %
                              self.setup['configfile'])
            return False

        try:
            crypted = open(fname).read()
        except IOError:
            err = sys.exc_info()[1]
            self.logger.error("Error reading %s, skipping: %s" (fname, err))
            return False

        plaintext = None
        pname = self.get_passphrase(crypted)
        if pname and self.setup['passphrase']:
            self.logger.warning("Passphrase given on command line differs from "
                                "passphrase embedded in file, using "
                                "passphrase in file")
            self.setup['passphrase'] = None
        if self.setup['passphrase']:
            pname = self.setup['passphrase']
        if not pname:
            for pname in self.setup.cfp.options('encryption'):
                self.logger.debug("Trying passphrase %s" % pname)
                passphrase = self.setup.cfp.get('encryption', pname)
                try:
                    plaintext = self._decrypt(crypted, passphrase)
                    break
                except Bcfg2.Encryption.EVPError:
                    pass
                except:
                    err = sys.exc_info()[1]
                    self.logger.error("Error decrypting %s: %s" % (fname, err))
            if not plaintext:
                self.logger.error("Could not decrypt %s with any passphrase in "
                                  "%s" % (fname, self.setup['configfile']))
                return False
        else:
            if not self.setup.cfp.has_option("encryption", pname):
                self.logger.error("Could not find passphrase %s in %s" %
                                  (pname,
                                   self.setup['configfile']))
                return False
            passphrase = self.setup.cfp.get("encryption", pname)
            try:
                plaintext = self._decrypt(crypted, passphrase)
            except Bcfg2.Encryption.EVPError:
                self.logger.error("Could not decrypt %s with the specified "
                                  "passphrase" % fname)
                return False
            except:
                err = sys.exc_info()[1]
                self.logger.error("Error decrypting %s: %s" % (fname, err))
                return False
                
        try:
            open(self.get_plaintext_filename(fname), "wb").write(plaintext)
            self.logger.info("Wrote decrypted data to %s" %
                             self.get_plaintext_filename(fname))
            return True
        except IOError:
            err = sys.exc_info()[1]
            self.logger.error("Error writing encrypted data from %s to %s: %s" %
                              (fname, self.get_plaintext_filename(fname), err))
            return False

    def get_passphrase(self, crypted):
        return None

    def _decrypt(self, crypted, passphrase):
        return Bcfg2.Encryption.ssl_decrypt(crypted, passphrase)


class CfgEncryptor(Encryptor):
    def get_encrypted_filename(self, plaintext_filename):
        return plaintext_filename + ".crypt"

    def get_plaintext_filename(self, encrypted_filename):
        if encrypted_filename.endswith(".crypt"):
            return encrypted_filename[:-6]
        else:
            return Encryptor.get_plaintext_filename(self, encrypted_filename)


class PropertiesEncryptor(Encryptor):
    def _encrypt(self, plaintext, passphrase, name=None):
        xdata = lxml.etree.XML(plaintext)
        if self.setup['xpath']:
            elements = xdata.xpath(self.setup['xpath'])
        else:
            elements = xdata.xpath('//*[@encrypted="true"]')
            if not elements:
                elements = list(xdata.getiterator())

        for el in elements:
            if el.text and el.text.strip():
                el.text = Bcfg2.Encryption.ssl_encrypt(el.text, passphrase)
                el.set("encrypted", "true")
        if name is None:
            xdata.set("encryption", "true")
        else:
            xdata.set("encryption", name)
        return lxml.etree.tostring(xdata)

    def get_passphrase(self, crypted):
        xdata = lxml.etree.XML(crypted)
        pname = xdata.get("encryption")
        if pname and pname.lower() != "true":
            return pname
        return None

    def _decrypt(self, crypted, passphrase):
        xdata = lxml.etree.XML(crypted)
        if self.setup['xpath']:
            elements = xdata.xpath(self.setup['xpath'])
        else:
            elements = xdata.xpath("//*[@encrypted='true']")
        if not elements:
            self.logger.info("No elements found to decrypt")
            return False
        for el in elements:
            if not el.text.strip():
                self.logger.warning("Skipping empty element %s" % el.tag)
                continue
            el.text = Bcfg2.Encryption.ssl_decrypt(el.text, passphrase)
        return lxml.etree.tostring(xdata)


def main():
    optinfo = dict()
    optinfo.update(Bcfg2.Options.CRYPT_OPTIONS)
    optinfo.update(Bcfg2.Options.CLI_COMMON_OPTIONS)
    setup = Bcfg2.Options.OptionParser(optinfo)
    setup.hm = "     bcfg2-crypt [options] <filename>\nOptions:\n%s" % \
        setup.buildHelpMessage()
    setup.parse(sys.argv[1:])

    if not setup['args']:
        print(setup.hm)
        raise SystemExit(1)
    elif setup['encrypt'] and setup['decrypt']:
        print("You cannot specify both --encrypt) and --decrypt")
        raise SystemExit(1)
    elif setup['cfg'] and setup['properties']:
        print("You cannot specify both --cfg and --properties")
        raise SystemExit(1)        
    elif setup['cfg'] and setup['properties']:
        print("Specifying --xpath with --cfg is nonsensical, ignoring --xpath")
        setup['xpath'] = Bcfg2.Options.CRYPT_XPATH.default
    elif setup['decrypt'] and setup['remove']:
        print("--remove cannot be used with --decrypt, ignoring")
        setup['remove'] = Bcfg2.Options.CRYPT_REMOVE.default

    logger = get_logger(setup['verbose'])

    props_crypt = PropertiesEncryptor(setup)
    cfg_crypt = CfgEncryptor(setup)

    for fname in setup['args']:
        if not os.path.exists(fname):
            logger.error("%s does not exist, skipping" % fname)
            continue
        
        # figure out if we need to encrypt this as a Properties file
        # or as a Cfg file
        props = False
        if setup['properties']:
            props = True
        elif setup['cfg']:
            props = False
        elif fname.endswith(".xml"):
            try:
                xroot = lxml.etree.parse(fname).getroot()
                if xroot.tag == "Properties":
                    props = True
                else:
                    props = False
            except IOError:
                err = sys.exc_info()[1]
                logger.error("Error reading %s, skipping: %s" (fname, err))
                continue
            except lxml.etree.XMLSyntaxError:
                props = False
        else:
            props = False

        if props:
            encryptor = props_crypt
        else:
            encryptor = cfg_crypt

        if setup['encrypt']:
            if not encryptor.encrypt(fname):
                continue
        elif setup['decrypt']:
            if not encryptor.decrypt(fname):
                continue
        else:
            logger.info("Neither --encrypt nor --decrypt specified, determining mode")
            if not encryptor.decrypt(fname):
                logger.info("Failed to decrypt %s, trying encryption" % fname)
                if not encryptor.encrypt(fname):
                    continue

        if setup['remove'] and encryptor.get_encrypted_filename(fname) != fname:
            try:
                os.unlink(fname)
            except IOError:
                err = sys.exc_info()[1]
                logger.error("Error removing %s: %s" (fname, err))
                continue

if __name__ == '__main__':
    sys.exit(main())