summaryrefslogtreecommitdiffstats
path: root/src/sbin/bcfg2-crypt
blob: 89dfe3e2a31335ea4e8852ed1f6fc1fb64a3c99a (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
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
#!/usr/bin/env python
""" helper for encrypting/decrypting Cfg and Properties files """

import os
import sys
import logging
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 chunk(self, data):
        yield data

    def unchunk(self, data, original):
        return data[0]

    def set_passphrase(self):
        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

        if self.passphrase:
            self.logger.debug("Using previously determined passphrase %s" %
                              self.pname)
            return True

        if self.setup['passphrase']:
            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)
                self.logger.debug("Using passphrase %s specified on command "
                                  "line" % self.pname)
                return True
            else:
                self.logger.error("Could not find passphrase %s in %s" %
                                  (self.pname, self.setup['configfile']))
                return False
        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])
                return True
        self.logger.info("No passphrase could be determined")
        return False

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

        self.set_passphrase()

        crypted = []
        for chunk in self.chunk(plaintext):
            try:
                passphrase, pname = self.get_passphrase(chunk)
            except TypeError:
                return False

            crypted.append(self._encrypt(chunk, passphrase, name=pname))

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

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

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

        self.set_passphrase()

        plaintext = []
        for chunk in self.chunk(crypted):
            try:
                passphrase, pname = self.get_passphrase(chunk)
                try:
                    plaintext.append(self._decrypt(chunk, passphrase))
                except Bcfg2.Encryption.EVPError:
                    self.logger.info("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
            except TypeError:
                pchunk = None
                for pname in self.setup.cfp.options('encryption'):
                    self.logger.debug("Trying passphrase %s" % pname)
                    passphrase = self.setup.cfp.get('encryption', pname)
                    try:
                        pchunk = self._decrypt(chunk, passphrase)
                        break
                    except Bcfg2.Encryption.EVPError:
                        pass
                    except:
                        err = sys.exc_info()[1]
                        self.logger.error("Error decrypting %s: %s" %
                                          (fname, err))
                if pchunk is not None:
                    plaintext.append(pchunk)
                else:
                    self.logger.error("Could not decrypt %s with any "
                                      "passphrase in %s" %
                                      (fname, self.setup['configfile']))
                    return False
                
        new_fname = self.get_plaintext_filename(fname)
        try:
            open(new_fname, "wb").write(self.unchunk(plaintext, crypted))
            self.logger.info("Wrote decrypted data to %s" % new_fname)
            return True
        except IOError:
            err = sys.exc_info()[1]
            self.logger.error("Error writing encrypted data from %s to %s: %s" %
                              (fname, new_fname, err))
            return False

    def get_passphrase(self, chunk):
        pname = self._get_passphrase(chunk)
        if not self.pname:
            if not pname:
                self.logger.info("No passphrase given on command line or "
                                 "found in file")
                return False
            elif self.setup.cfp.has_option("encryption", pname):
                passphrase = self.setup.cfp.get("encryption", pname)
            else:
                self.logger.error("Could not find passphrase %s in %s" %
                                  (pname, self.setup['configfile']))
                return False
        else:
            pname = self.pname
            passphrase = self.passphrase
            if self.pname != pname:
                self.logger.warning("Passphrase given on command line (%s) "
                                    "differs from passphrase embedded in "
                                    "file (%s), using command-line option" %
                                    (self.pname, pname))
        return (passphrase, pname)

    def _get_passphrase(self, chunk):
        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):
        # plaintext is an lxml.etree._Element
        if name is None:
            name = "true"
        if plaintext.text and plaintext.text.strip():
            plaintext.text = Bcfg2.Encryption.ssl_encrypt(plaintext.text,
                                                          passphrase)
            plaintext.set("encrypted", name)
        return plaintext

    def chunk(self, data):
        xdata = lxml.etree.XML(data)
        if self.setup['xpath']:
            elements = xdata.xpath(self.setup['xpath'])
        else:
            elements = xdata.xpath('//*[@encrypted]')
            if not elements:
                elements = list(xdata.getiterator())
        # this is not a good use of a generator, but we need to
        # generate the full list of elements in order to ensure that
        # some exist before we know what to return
        for elt in elements:
            yield elt

    def unchunk(self, data, original):
        # Properties elements are modified in-place, so we don't
        # actually need to unchunk anything
        xdata = data[0]
        # find root element
        while xdata.getparent() != None:
            xdata = xdata.getparent()
        xdata.set("encryption", "true")
        return lxml.etree.tostring(xdata)

    def _get_passphrase(self, chunk):
        pname = chunk.get("encrypted") or chunk.get("encryption")
        if pname and pname.lower() != "true":
            return pname
        return None

    def _decrypt(self, crypted, passphrase):
        # crypted is in lxml.etree._Element
        if not crypted.text or not crypted.text.strip():
            self.logger.warning("Skipping empty element %s" % crypted.tag)
            return crypted
        rv = Bcfg2.Encryption.ssl_decrypt(crypted.text, passphrase)
        crypted.text = rv
        return crypted


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):
                print("Failed to encrypt %s, skipping" % fname)
        elif setup['decrypt']:
            if not encryptor.decrypt(fname):
                print("Failed to decrypt %s, skipping" % fname)
        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):
                    print("Failed to encrypt %s, skipping" % fname)

        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())