clawsmail-passdecrypt.py 4.94 KB
Newer Older
1 2 3
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
#
4
# Copyright (C) 2013-2016 Colomban Wendling <ban@herbesfolles.org>
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
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
#   notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
#   copyright notice, this list of conditions and the following disclaimer
#   in the documentation and/or other materials provided with the
#   distribution.
# * Neither the name of the author nor the names of its contributors may
#   be used to endorse or promote products derived from this software
#   without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.


from Crypto.Cipher import DES
from base64 import standard_b64decode as b64decode
Andreas Nüßlein's avatar
Andreas Nüßlein committed
35 36 37 38
try:
    from ConfigParser import ConfigParser
except ImportError:
    from configparser import ConfigParser
39 40 41 42 43


PASSCRYPT_KEY = b'passkey0'


44 45
def pass_decrypt(p, key=PASSCRYPT_KEY, mode=DES.MODE_CFB):
    """ Decrypts a password from ClawsMail. """
46
    if p[0] == '!':  # encrypted password
47 48 49 50 51 52 53 54 55
        buf = b64decode(p[1:])

        """
        If mode is ECB or CBC and the length of the data is wrong, do nothing
        as would the libc algorithms (as they fail early).  Yes, this means the
        password wasn't actually encrypted but only base64-ed.
        """
        if (mode in (DES.MODE_ECB, DES.MODE_CBC)) and ((len(buf) % 8) != 0 or
                                                       len(buf) > 8192):
56 57 58 59
            d = buf
        else:
            c = DES.new(key, mode=mode, IV=b'\0'*8)
            d = c.decrypt(buf)
60

61 62 63 64
        try:
            return d.decode()
        except UnicodeDecodeError:
            return d
65 66 67 68
    else:  # raw password
        return p


69
def accountrc_decrypt(filename, key=PASSCRYPT_KEY, mode=DES.MODE_CFB):
70 71 72 73 74 75 76 77
    """ Reads passwords from ClawsMail's accountrc file """
    p = ConfigParser()
    p.read(filename)

    for s in p.sections():
        try:
            try:
                address = p.get(s, 'address')
Mike Evans's avatar
Mike Evans committed
78
                account = p.get(s, 'account_name')
79 80
            except:
                address = '<unknown>'
Mike Evans's avatar
Mike Evans committed
81
                account = '<unknown>'
82

83
            password = pass_decrypt(p.get(s, 'password'), key, mode=mode)
Mike Evans's avatar
Mike Evans committed
84
            print('password for %s, %s is "%s"' % (account, address, password))
85 86 87 88 89 90
        except Exception as e:
            print('Error resolving password for account "%s": %s' % (s, e))


if __name__ == '__main__':
    import os
91 92 93 94 95 96 97
    from optparse import OptionParser, OptionValueError

    def mode_callback(option, opt, value, parser):
        try:
            parser.values.mode = getattr(DES, 'MODE_'+value.upper())
        except AttributeError:
            raise OptionValueError('Invalid mode "%s"' % value)
98 99 100 101 102 103 104

    usage = 'Usage: %prog [OPTIONS] ENCRYPTED_PASS1...|FILE...'
    parser = OptionParser(usage=usage)
    parser.add_option('-k', '--key', dest='key', default=PASSCRYPT_KEY,
                      help='Use KEY to decode passwords (8 byte string) '
                           '[%default]',
                      metavar='KEY')
105 106 107 108 109 110 111 112 113 114
    parser.add_option('-m', '--mode', dest='mode', default=DES.MODE_CFB,
                      type='string', action='callback', callback=mode_callback,
                      help='Use MODE to decrypt DES passwords.  Choose ECB to '
                           'decrypt passwords from FreeBSD installations, CFB '
                           'otherwise [CFB]',
                      metavar='MODE')
    parser.add_option('--freebsd', dest='mode',
                      action='store_const', const=DES.MODE_ECB,
                      help='Use ECB mode as needed for passwords from FreeBSD '
                           '(alias for --mode=ECB)')
115 116 117 118 119 120 121
    (options, args) = parser.parse_args()

    if len(args) < 1:
        parser.error('missing file or string to decrypt')
    else:
        for a in args:
            if os.path.exists(a):
122
                accountrc_decrypt(a, key=options.key, mode=options.mode)
123
            else:
124
                password = pass_decrypt(a, key=options.key, mode=options.mode)
125
                print('password "%s" is "%s"' % (a, password))