2013-10-02 18:59:40 +00:00
|
|
|
|
#!/usr/bin/env python
|
2010-07-24 11:55:24 +00:00
|
|
|
|
# -*- coding: utf-8 -*-
|
2009-02-19 12:39:43 +00:00
|
|
|
|
|
2011-01-17 07:24:53 +00:00
|
|
|
|
from __future__ import with_statement
|
|
|
|
|
|
2013-10-02 18:59:40 +00:00
|
|
|
|
# ineptepub.pyw, version 6.1
|
2012-12-19 13:48:11 +00:00
|
|
|
|
# Copyright © 2009-2010 by i♥cabbages
|
2009-02-19 12:39:43 +00:00
|
|
|
|
|
2012-12-19 13:48:11 +00:00
|
|
|
|
# Released under the terms of the GNU General Public Licence, version 3
|
|
|
|
|
# <http://www.gnu.org/licenses/>
|
|
|
|
|
|
2013-10-02 18:59:40 +00:00
|
|
|
|
# Modified 2010–2013 by some_updates, DiapDealer and Apprentice Alf
|
2010-07-24 11:55:24 +00:00
|
|
|
|
|
|
|
|
|
# Windows users: Before running this program, you must first install Python 2.6
|
|
|
|
|
# from <http://www.python.org/download/> and PyCrypto from
|
|
|
|
|
# <http://www.voidspace.org.uk/python/modules.shtml#pycrypto> (make sure to
|
|
|
|
|
# install the version for Python 2.6). Save this script file as
|
2013-10-02 18:59:40 +00:00
|
|
|
|
# ineptepub.pyw and double-click on it to run it.
|
2010-07-24 11:55:24 +00:00
|
|
|
|
#
|
2013-10-02 18:59:40 +00:00
|
|
|
|
# Mac OS X users: Save this script file as ineptepub.pyw. You can run this
|
|
|
|
|
# program from the command line (pythonw ineptepub.pyw) or by double-clicking
|
2010-07-24 11:55:24 +00:00
|
|
|
|
# it when it has been associated with PythonLauncher.
|
2009-02-19 12:39:43 +00:00
|
|
|
|
|
|
|
|
|
# Revision history:
|
|
|
|
|
# 1 - Initial release
|
2013-10-02 18:59:40 +00:00
|
|
|
|
# 2 - Rename to INEPT, fix exit code
|
|
|
|
|
# 5 - Version bump to avoid (?) confusion;
|
|
|
|
|
# Improve OS X support by using OpenSSL when available
|
|
|
|
|
# 5.1 - Improve OpenSSL error checking
|
|
|
|
|
# 5.2 - Fix ctypes error causing segfaults on some systems
|
|
|
|
|
# 5.3 - add support for OpenSSL on Windows, fix bug with some versions of libcrypto 0.9.8 prior to path level o
|
|
|
|
|
# 5.4 - add support for encoding to 'utf-8' when building up list of files to decrypt from encryption.xml
|
|
|
|
|
# 5.5 - On Windows try PyCrypto first, OpenSSL next
|
|
|
|
|
# 5.6 - Modify interface to allow use with import
|
|
|
|
|
# 5.7 - Fix for potential problem with PyCrypto
|
|
|
|
|
# 5.8 - Revised to allow use in calibre plugins to eliminate need for duplicate code
|
|
|
|
|
# 5.9 - Fixed to retain zip file metadata (e.g. file modification date)
|
|
|
|
|
# 6.0 - moved unicode_argv call inside main for Windows DeDRM compatibility
|
|
|
|
|
# 6.1 - Work if TkInter is missing
|
2015-03-09 07:38:31 +00:00
|
|
|
|
# 6.2 - Handle UTF-8 file names inside an ePub, fix by Jose Luis
|
2012-11-07 13:14:25 +00:00
|
|
|
|
|
2009-02-19 12:39:43 +00:00
|
|
|
|
"""
|
2013-10-02 18:59:40 +00:00
|
|
|
|
Decrypt Adobe Digital Editions encrypted ePub books.
|
2009-02-19 12:39:43 +00:00
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
__license__ = 'GPL v3'
|
2015-03-09 07:38:31 +00:00
|
|
|
|
__version__ = "6.2"
|
2009-02-19 12:39:43 +00:00
|
|
|
|
|
|
|
|
|
import sys
|
|
|
|
|
import os
|
2013-10-02 18:59:40 +00:00
|
|
|
|
import traceback
|
2009-02-19 12:39:43 +00:00
|
|
|
|
import zlib
|
2013-10-02 18:59:40 +00:00
|
|
|
|
import zipfile
|
|
|
|
|
from zipfile import ZipInfo, ZipFile, ZIP_STORED, ZIP_DEFLATED
|
|
|
|
|
from contextlib import closing
|
2009-02-19 12:39:43 +00:00
|
|
|
|
import xml.etree.ElementTree as etree
|
2012-12-19 13:48:11 +00:00
|
|
|
|
|
|
|
|
|
# Wrap a stream so that output gets flushed immediately
|
|
|
|
|
# and also make sure that any unicode strings get
|
|
|
|
|
# encoded using "replace" before writing them.
|
|
|
|
|
class SafeUnbuffered:
|
|
|
|
|
def __init__(self, stream):
|
|
|
|
|
self.stream = stream
|
|
|
|
|
self.encoding = stream.encoding
|
|
|
|
|
if self.encoding == None:
|
|
|
|
|
self.encoding = "utf-8"
|
|
|
|
|
def write(self, data):
|
|
|
|
|
if isinstance(data,unicode):
|
|
|
|
|
data = data.encode(self.encoding,"replace")
|
|
|
|
|
self.stream.write(data)
|
|
|
|
|
self.stream.flush()
|
|
|
|
|
def __getattr__(self, attr):
|
|
|
|
|
return getattr(self.stream, attr)
|
|
|
|
|
|
2013-10-02 18:59:40 +00:00
|
|
|
|
try:
|
|
|
|
|
from calibre.constants import iswindows, isosx
|
|
|
|
|
except:
|
|
|
|
|
iswindows = sys.platform.startswith('win')
|
|
|
|
|
isosx = sys.platform.startswith('darwin')
|
2012-12-19 13:48:11 +00:00
|
|
|
|
|
|
|
|
|
def unicode_argv():
|
|
|
|
|
if iswindows:
|
|
|
|
|
# Uses shell32.GetCommandLineArgvW to get sys.argv as a list of Unicode
|
|
|
|
|
# strings.
|
|
|
|
|
|
|
|
|
|
# Versions 2.x of Python don't support Unicode in sys.argv on
|
|
|
|
|
# Windows, with the underlying Windows API instead replacing multi-byte
|
|
|
|
|
# characters with '?'.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
from ctypes import POINTER, byref, cdll, c_int, windll
|
|
|
|
|
from ctypes.wintypes import LPCWSTR, LPWSTR
|
|
|
|
|
|
|
|
|
|
GetCommandLineW = cdll.kernel32.GetCommandLineW
|
|
|
|
|
GetCommandLineW.argtypes = []
|
|
|
|
|
GetCommandLineW.restype = LPCWSTR
|
|
|
|
|
|
|
|
|
|
CommandLineToArgvW = windll.shell32.CommandLineToArgvW
|
|
|
|
|
CommandLineToArgvW.argtypes = [LPCWSTR, POINTER(c_int)]
|
|
|
|
|
CommandLineToArgvW.restype = POINTER(LPWSTR)
|
|
|
|
|
|
|
|
|
|
cmd = GetCommandLineW()
|
|
|
|
|
argc = c_int(0)
|
|
|
|
|
argv = CommandLineToArgvW(cmd, byref(argc))
|
|
|
|
|
if argc.value > 0:
|
|
|
|
|
# Remove Python executable and commands if present
|
|
|
|
|
start = argc.value - len(sys.argv)
|
|
|
|
|
return [argv[i] for i in
|
|
|
|
|
xrange(start, argc.value)]
|
2013-10-02 18:59:40 +00:00
|
|
|
|
return [u"ineptepub.py"]
|
2012-12-19 13:48:11 +00:00
|
|
|
|
else:
|
|
|
|
|
argvencoding = sys.stdin.encoding
|
|
|
|
|
if argvencoding == None:
|
|
|
|
|
argvencoding = "utf-8"
|
|
|
|
|
return [arg if (type(arg) == unicode) else unicode(arg,argvencoding) for arg in sys.argv]
|
|
|
|
|
|
2009-02-19 12:39:43 +00:00
|
|
|
|
|
2010-07-24 11:55:24 +00:00
|
|
|
|
class ADEPTError(Exception):
|
|
|
|
|
pass
|
2009-02-19 12:39:43 +00:00
|
|
|
|
|
2010-07-24 11:55:24 +00:00
|
|
|
|
def _load_crypto_libcrypto():
|
|
|
|
|
from ctypes import CDLL, POINTER, c_void_p, c_char_p, c_int, c_long, \
|
|
|
|
|
Structure, c_ulong, create_string_buffer, cast
|
|
|
|
|
from ctypes.util import find_library
|
2009-02-19 12:39:43 +00:00
|
|
|
|
|
2013-10-02 18:59:40 +00:00
|
|
|
|
if iswindows:
|
2010-11-11 22:11:36 +00:00
|
|
|
|
libcrypto = find_library('libeay32')
|
|
|
|
|
else:
|
|
|
|
|
libcrypto = find_library('crypto')
|
|
|
|
|
|
2010-07-24 11:55:24 +00:00
|
|
|
|
if libcrypto is None:
|
|
|
|
|
raise ADEPTError('libcrypto not found')
|
|
|
|
|
libcrypto = CDLL(libcrypto)
|
2009-02-19 12:39:43 +00:00
|
|
|
|
|
2013-04-05 16:44:48 +00:00
|
|
|
|
RSA_NO_PADDING = 3
|
2013-10-02 18:59:40 +00:00
|
|
|
|
AES_MAXNR = 14
|
2013-04-05 16:44:48 +00:00
|
|
|
|
|
2010-07-24 11:55:24 +00:00
|
|
|
|
c_char_pp = POINTER(c_char_p)
|
|
|
|
|
c_int_p = POINTER(c_int)
|
2009-02-19 12:39:43 +00:00
|
|
|
|
|
2010-07-24 11:55:24 +00:00
|
|
|
|
class RSA(Structure):
|
|
|
|
|
pass
|
|
|
|
|
RSA_p = POINTER(RSA)
|
2012-03-06 18:24:28 +00:00
|
|
|
|
|
2013-10-02 18:59:40 +00:00
|
|
|
|
class AES_KEY(Structure):
|
|
|
|
|
_fields_ = [('rd_key', c_long * (4 * (AES_MAXNR + 1))),
|
|
|
|
|
('rounds', c_int)]
|
|
|
|
|
AES_KEY_p = POINTER(AES_KEY)
|
|
|
|
|
|
2010-07-24 11:55:24 +00:00
|
|
|
|
def F(restype, name, argtypes):
|
|
|
|
|
func = getattr(libcrypto, name)
|
|
|
|
|
func.restype = restype
|
|
|
|
|
func.argtypes = argtypes
|
|
|
|
|
return func
|
2012-03-06 18:24:28 +00:00
|
|
|
|
|
2010-07-24 11:55:24 +00:00
|
|
|
|
d2i_RSAPrivateKey = F(RSA_p, 'd2i_RSAPrivateKey',
|
|
|
|
|
[RSA_p, c_char_pp, c_long])
|
|
|
|
|
RSA_size = F(c_int, 'RSA_size', [RSA_p])
|
|
|
|
|
RSA_private_decrypt = F(c_int, 'RSA_private_decrypt',
|
|
|
|
|
[c_int, c_char_p, c_char_p, RSA_p, c_int])
|
|
|
|
|
RSA_free = F(None, 'RSA_free', [RSA_p])
|
2013-10-02 18:59:40 +00:00
|
|
|
|
AES_set_decrypt_key = F(c_int, 'AES_set_decrypt_key',
|
|
|
|
|
[c_char_p, c_int, AES_KEY_p])
|
|
|
|
|
AES_cbc_encrypt = F(None, 'AES_cbc_encrypt',
|
|
|
|
|
[c_char_p, c_char_p, c_ulong, AES_KEY_p, c_char_p,
|
|
|
|
|
c_int])
|
2012-03-06 18:24:28 +00:00
|
|
|
|
|
2010-07-24 11:55:24 +00:00
|
|
|
|
class RSA(object):
|
|
|
|
|
def __init__(self, der):
|
|
|
|
|
buf = create_string_buffer(der)
|
|
|
|
|
pp = c_char_pp(cast(buf, c_char_p))
|
|
|
|
|
rsa = self._rsa = d2i_RSAPrivateKey(None, pp, len(der))
|
|
|
|
|
if rsa is None:
|
|
|
|
|
raise ADEPTError('Error parsing ADEPT user key DER')
|
2012-03-06 18:24:28 +00:00
|
|
|
|
|
2010-07-24 11:55:24 +00:00
|
|
|
|
def decrypt(self, from_):
|
|
|
|
|
rsa = self._rsa
|
|
|
|
|
to = create_string_buffer(RSA_size(rsa))
|
|
|
|
|
dlen = RSA_private_decrypt(len(from_), from_, to, rsa,
|
|
|
|
|
RSA_NO_PADDING)
|
|
|
|
|
if dlen < 0:
|
|
|
|
|
raise ADEPTError('RSA decryption failed')
|
2013-10-02 18:59:40 +00:00
|
|
|
|
return to[:dlen]
|
2012-03-06 18:24:28 +00:00
|
|
|
|
|
2010-07-24 11:55:24 +00:00
|
|
|
|
def __del__(self):
|
|
|
|
|
if self._rsa is not None:
|
|
|
|
|
RSA_free(self._rsa)
|
|
|
|
|
self._rsa = None
|
|
|
|
|
|
|
|
|
|
class AES(object):
|
2013-10-02 18:59:40 +00:00
|
|
|
|
def __init__(self, userkey):
|
2010-07-24 11:55:24 +00:00
|
|
|
|
self._blocksize = len(userkey)
|
2010-11-11 22:11:36 +00:00
|
|
|
|
if (self._blocksize != 16) and (self._blocksize != 24) and (self._blocksize != 32) :
|
|
|
|
|
raise ADEPTError('AES improper key used')
|
|
|
|
|
return
|
2013-10-02 18:59:40 +00:00
|
|
|
|
key = self._key = AES_KEY()
|
|
|
|
|
rv = AES_set_decrypt_key(userkey, len(userkey) * 8, key)
|
2010-07-24 11:55:24 +00:00
|
|
|
|
if rv < 0:
|
|
|
|
|
raise ADEPTError('Failed to initialize AES key')
|
2013-10-02 18:59:40 +00:00
|
|
|
|
|
2010-07-24 11:55:24 +00:00
|
|
|
|
def decrypt(self, data):
|
|
|
|
|
out = create_string_buffer(len(data))
|
2013-10-02 18:59:40 +00:00
|
|
|
|
iv = ("\x00" * self._blocksize)
|
|
|
|
|
rv = AES_cbc_encrypt(data, out, len(data), self._key, iv, 0)
|
2010-07-24 11:55:24 +00:00
|
|
|
|
if rv == 0:
|
|
|
|
|
raise ADEPTError('AES decryption failed')
|
|
|
|
|
return out.raw
|
|
|
|
|
|
2013-10-02 18:59:40 +00:00
|
|
|
|
return (AES, RSA)
|
2010-07-24 11:55:24 +00:00
|
|
|
|
|
|
|
|
|
def _load_crypto_pycrypto():
|
2013-04-05 16:44:48 +00:00
|
|
|
|
from Crypto.Cipher import AES as _AES
|
2013-10-02 18:59:40 +00:00
|
|
|
|
from Crypto.PublicKey import RSA as _RSA
|
2010-07-24 11:55:24 +00:00
|
|
|
|
|
|
|
|
|
# ASN.1 parsing code from tlslite
|
|
|
|
|
class ASN1Error(Exception):
|
|
|
|
|
pass
|
2012-03-06 18:24:28 +00:00
|
|
|
|
|
2010-07-24 11:55:24 +00:00
|
|
|
|
class ASN1Parser(object):
|
|
|
|
|
class Parser(object):
|
|
|
|
|
def __init__(self, bytes):
|
|
|
|
|
self.bytes = bytes
|
|
|
|
|
self.index = 0
|
2012-03-06 18:24:28 +00:00
|
|
|
|
|
2010-07-24 11:55:24 +00:00
|
|
|
|
def get(self, length):
|
|
|
|
|
if self.index + length > len(self.bytes):
|
|
|
|
|
raise ASN1Error("Error decoding ASN.1")
|
|
|
|
|
x = 0
|
|
|
|
|
for count in range(length):
|
|
|
|
|
x <<= 8
|
|
|
|
|
x |= self.bytes[self.index]
|
|
|
|
|
self.index += 1
|
|
|
|
|
return x
|
2012-03-06 18:24:28 +00:00
|
|
|
|
|
2010-07-24 11:55:24 +00:00
|
|
|
|
def getFixBytes(self, lengthBytes):
|
|
|
|
|
bytes = self.bytes[self.index : self.index+lengthBytes]
|
|
|
|
|
self.index += lengthBytes
|
|
|
|
|
return bytes
|
2012-03-06 18:24:28 +00:00
|
|
|
|
|
2010-07-24 11:55:24 +00:00
|
|
|
|
def getVarBytes(self, lengthLength):
|
|
|
|
|
lengthBytes = self.get(lengthLength)
|
|
|
|
|
return self.getFixBytes(lengthBytes)
|
2012-03-06 18:24:28 +00:00
|
|
|
|
|
2010-07-24 11:55:24 +00:00
|
|
|
|
def getFixList(self, length, lengthList):
|
|
|
|
|
l = [0] * lengthList
|
|
|
|
|
for x in range(lengthList):
|
|
|
|
|
l[x] = self.get(length)
|
|
|
|
|
return l
|
2012-03-06 18:24:28 +00:00
|
|
|
|
|
2010-07-24 11:55:24 +00:00
|
|
|
|
def getVarList(self, length, lengthLength):
|
|
|
|
|
lengthList = self.get(lengthLength)
|
|
|
|
|
if lengthList % length != 0:
|
|
|
|
|
raise ASN1Error("Error decoding ASN.1")
|
|
|
|
|
lengthList = int(lengthList/length)
|
|
|
|
|
l = [0] * lengthList
|
|
|
|
|
for x in range(lengthList):
|
|
|
|
|
l[x] = self.get(length)
|
|
|
|
|
return l
|
2012-03-06 18:24:28 +00:00
|
|
|
|
|
2010-07-24 11:55:24 +00:00
|
|
|
|
def startLengthCheck(self, lengthLength):
|
|
|
|
|
self.lengthCheck = self.get(lengthLength)
|
|
|
|
|
self.indexCheck = self.index
|
2012-03-06 18:24:28 +00:00
|
|
|
|
|
2010-07-24 11:55:24 +00:00
|
|
|
|
def setLengthCheck(self, length):
|
|
|
|
|
self.lengthCheck = length
|
|
|
|
|
self.indexCheck = self.index
|
2012-03-06 18:24:28 +00:00
|
|
|
|
|
2010-07-24 11:55:24 +00:00
|
|
|
|
def stopLengthCheck(self):
|
|
|
|
|
if (self.index - self.indexCheck) != self.lengthCheck:
|
|
|
|
|
raise ASN1Error("Error decoding ASN.1")
|
2012-03-06 18:24:28 +00:00
|
|
|
|
|
2010-07-24 11:55:24 +00:00
|
|
|
|
def atLengthCheck(self):
|
|
|
|
|
if (self.index - self.indexCheck) < self.lengthCheck:
|
|
|
|
|
return False
|
|
|
|
|
elif (self.index - self.indexCheck) == self.lengthCheck:
|
|
|
|
|
return True
|
|
|
|
|
else:
|
|
|
|
|
raise ASN1Error("Error decoding ASN.1")
|
2012-03-06 18:24:28 +00:00
|
|
|
|
|
2010-07-24 11:55:24 +00:00
|
|
|
|
def __init__(self, bytes):
|
|
|
|
|
p = self.Parser(bytes)
|
2009-02-19 12:39:43 +00:00
|
|
|
|
p.get(1)
|
2010-07-24 11:55:24 +00:00
|
|
|
|
self.length = self._getASN1Length(p)
|
|
|
|
|
self.value = p.getFixBytes(self.length)
|
2012-03-06 18:24:28 +00:00
|
|
|
|
|
2010-07-24 11:55:24 +00:00
|
|
|
|
def getChild(self, which):
|
|
|
|
|
p = self.Parser(self.value)
|
|
|
|
|
for x in range(which+1):
|
|
|
|
|
markIndex = p.index
|
|
|
|
|
p.get(1)
|
|
|
|
|
length = self._getASN1Length(p)
|
|
|
|
|
p.getFixBytes(length)
|
|
|
|
|
return ASN1Parser(p.bytes[markIndex:p.index])
|
2012-03-06 18:24:28 +00:00
|
|
|
|
|
2010-07-24 11:55:24 +00:00
|
|
|
|
def _getASN1Length(self, p):
|
|
|
|
|
firstLength = p.get(1)
|
|
|
|
|
if firstLength<=127:
|
|
|
|
|
return firstLength
|
|
|
|
|
else:
|
|
|
|
|
lengthLength = firstLength & 0x7F
|
|
|
|
|
return p.get(lengthLength)
|
|
|
|
|
|
2013-04-05 16:44:48 +00:00
|
|
|
|
class AES(object):
|
2013-10-02 18:59:40 +00:00
|
|
|
|
def __init__(self, key):
|
|
|
|
|
self._aes = _AES.new(key, _AES.MODE_CBC, '\x00'*16)
|
|
|
|
|
|
2010-07-24 11:55:24 +00:00
|
|
|
|
def decrypt(self, data):
|
|
|
|
|
return self._aes.decrypt(data)
|
|
|
|
|
|
|
|
|
|
class RSA(object):
|
|
|
|
|
def __init__(self, der):
|
|
|
|
|
key = ASN1Parser([ord(x) for x in der])
|
|
|
|
|
key = [key.getChild(x).value for x in xrange(1, 4)]
|
|
|
|
|
key = [self.bytesToNumber(v) for v in key]
|
|
|
|
|
self._rsa = _RSA.construct(key)
|
|
|
|
|
|
|
|
|
|
def bytesToNumber(self, bytes):
|
|
|
|
|
total = 0L
|
|
|
|
|
for byte in bytes:
|
|
|
|
|
total = (total << 8) + byte
|
|
|
|
|
return total
|
2012-03-06 18:24:28 +00:00
|
|
|
|
|
2010-07-24 11:55:24 +00:00
|
|
|
|
def decrypt(self, data):
|
|
|
|
|
return self._rsa.decrypt(data)
|
2009-02-19 12:39:43 +00:00
|
|
|
|
|
2013-10-02 18:59:40 +00:00
|
|
|
|
return (AES, RSA)
|
2009-02-19 12:39:43 +00:00
|
|
|
|
|
2010-07-24 11:55:24 +00:00
|
|
|
|
def _load_crypto():
|
2013-10-02 18:59:40 +00:00
|
|
|
|
AES = RSA = None
|
2011-01-06 07:10:38 +00:00
|
|
|
|
cryptolist = (_load_crypto_libcrypto, _load_crypto_pycrypto)
|
|
|
|
|
if sys.platform.startswith('win'):
|
|
|
|
|
cryptolist = (_load_crypto_pycrypto, _load_crypto_libcrypto)
|
|
|
|
|
for loader in cryptolist:
|
2010-07-24 11:55:24 +00:00
|
|
|
|
try:
|
2013-10-02 18:59:40 +00:00
|
|
|
|
AES, RSA = loader()
|
2010-07-24 11:55:24 +00:00
|
|
|
|
break
|
|
|
|
|
except (ImportError, ADEPTError):
|
|
|
|
|
pass
|
2013-10-02 18:59:40 +00:00
|
|
|
|
return (AES, RSA)
|
|
|
|
|
|
|
|
|
|
AES, RSA = _load_crypto()
|
|
|
|
|
|
|
|
|
|
META_NAMES = ('mimetype', 'META-INF/rights.xml', 'META-INF/encryption.xml')
|
|
|
|
|
NSMAP = {'adept': 'http://ns.adobe.com/adept',
|
|
|
|
|
'enc': 'http://www.w3.org/2001/04/xmlenc#'}
|
|
|
|
|
|
|
|
|
|
class Decryptor(object):
|
|
|
|
|
def __init__(self, bookkey, encryption):
|
|
|
|
|
enc = lambda tag: '{%s}%s' % (NSMAP['enc'], tag)
|
|
|
|
|
self._aes = AES(bookkey)
|
|
|
|
|
encryption = etree.fromstring(encryption)
|
|
|
|
|
self._encrypted = encrypted = set()
|
|
|
|
|
expr = './%s/%s/%s' % (enc('EncryptedData'), enc('CipherData'),
|
|
|
|
|
enc('CipherReference'))
|
|
|
|
|
for elem in encryption.findall(expr):
|
|
|
|
|
path = elem.get('URI', None)
|
|
|
|
|
if path is not None:
|
|
|
|
|
path = path.encode('utf-8')
|
|
|
|
|
encrypted.add(path)
|
|
|
|
|
|
|
|
|
|
def decompress(self, bytes):
|
|
|
|
|
dc = zlib.decompressobj(-15)
|
|
|
|
|
bytes = dc.decompress(bytes)
|
|
|
|
|
ex = dc.decompress('Z') + dc.flush()
|
|
|
|
|
if ex:
|
|
|
|
|
bytes = bytes + ex
|
|
|
|
|
return bytes
|
|
|
|
|
|
|
|
|
|
def decrypt(self, path, data):
|
2015-03-09 07:38:31 +00:00
|
|
|
|
if path.encode('utf-8') in self._encrypted:
|
2013-10-02 18:59:40 +00:00
|
|
|
|
data = self._aes.decrypt(data)[16:]
|
|
|
|
|
data = data[:-ord(data[-1])]
|
|
|
|
|
data = self.decompress(data)
|
2013-04-05 16:44:48 +00:00
|
|
|
|
return data
|
2012-12-19 13:48:11 +00:00
|
|
|
|
|
2013-10-02 18:59:40 +00:00
|
|
|
|
# check file to make check whether it's probably an Adobe Adept encrypted ePub
|
|
|
|
|
def adeptBook(inpath):
|
|
|
|
|
with closing(ZipFile(open(inpath, 'rb'))) as inf:
|
|
|
|
|
namelist = set(inf.namelist())
|
|
|
|
|
if 'META-INF/rights.xml' not in namelist or \
|
|
|
|
|
'META-INF/encryption.xml' not in namelist:
|
|
|
|
|
return False
|
2012-12-19 13:48:11 +00:00
|
|
|
|
try:
|
2013-10-02 18:59:40 +00:00
|
|
|
|
rights = etree.fromstring(inf.read('META-INF/rights.xml'))
|
|
|
|
|
adept = lambda tag: '{%s}%s' % (NSMAP['adept'], tag)
|
|
|
|
|
expr = './/%s' % (adept('encryptedKey'),)
|
|
|
|
|
bookkey = ''.join(rights.findtext(expr))
|
|
|
|
|
if len(bookkey) == 172:
|
|
|
|
|
return True
|
|
|
|
|
except:
|
|
|
|
|
# if we couldn't check, assume it is
|
|
|
|
|
return True
|
|
|
|
|
return False
|
|
|
|
|
|
|
|
|
|
def decryptBook(userkey, inpath, outpath):
|
|
|
|
|
if AES is None:
|
|
|
|
|
raise ADEPTError(u"PyCrypto or OpenSSL must be installed.")
|
|
|
|
|
rsa = RSA(userkey)
|
|
|
|
|
with closing(ZipFile(open(inpath, 'rb'))) as inf:
|
|
|
|
|
namelist = set(inf.namelist())
|
|
|
|
|
if 'META-INF/rights.xml' not in namelist or \
|
|
|
|
|
'META-INF/encryption.xml' not in namelist:
|
|
|
|
|
print u"{0:s} is DRM-free.".format(os.path.basename(inpath))
|
|
|
|
|
return 1
|
|
|
|
|
for name in META_NAMES:
|
|
|
|
|
namelist.remove(name)
|
2013-04-05 16:44:48 +00:00
|
|
|
|
try:
|
2013-10-02 18:59:40 +00:00
|
|
|
|
rights = etree.fromstring(inf.read('META-INF/rights.xml'))
|
|
|
|
|
adept = lambda tag: '{%s}%s' % (NSMAP['adept'], tag)
|
|
|
|
|
expr = './/%s' % (adept('encryptedKey'),)
|
|
|
|
|
bookkey = ''.join(rights.findtext(expr))
|
|
|
|
|
if len(bookkey) != 172:
|
|
|
|
|
print u"{0:s} is not a secure Adobe Adept ePub.".format(os.path.basename(inpath))
|
|
|
|
|
return 1
|
|
|
|
|
bookkey = rsa.decrypt(bookkey.decode('base64'))
|
|
|
|
|
# Padded as per RSAES-PKCS1-v1_5
|
|
|
|
|
if bookkey[-17] != '\x00':
|
|
|
|
|
print u"Could not decrypt {0:s}. Wrong key".format(os.path.basename(inpath))
|
|
|
|
|
return 2
|
|
|
|
|
encryption = inf.read('META-INF/encryption.xml')
|
|
|
|
|
decryptor = Decryptor(bookkey[-16:], encryption)
|
|
|
|
|
kwds = dict(compression=ZIP_DEFLATED, allowZip64=False)
|
|
|
|
|
with closing(ZipFile(open(outpath, 'wb'), 'w', **kwds)) as outf:
|
|
|
|
|
zi = ZipInfo('mimetype')
|
|
|
|
|
zi.compress_type=ZIP_STORED
|
2013-03-20 10:23:54 +00:00
|
|
|
|
try:
|
2013-10-02 18:59:40 +00:00
|
|
|
|
# if the mimetype is present, get its info, including time-stamp
|
|
|
|
|
oldzi = inf.getinfo('mimetype')
|
|
|
|
|
# copy across fields to be preserved
|
|
|
|
|
zi.date_time = oldzi.date_time
|
|
|
|
|
zi.comment = oldzi.comment
|
|
|
|
|
zi.extra = oldzi.extra
|
|
|
|
|
zi.internal_attr = oldzi.internal_attr
|
|
|
|
|
# external attributes are dependent on the create system, so copy both.
|
|
|
|
|
zi.external_attr = oldzi.external_attr
|
|
|
|
|
zi.create_system = oldzi.create_system
|
2013-03-20 10:23:54 +00:00
|
|
|
|
except:
|
|
|
|
|
pass
|
2013-10-02 18:59:40 +00:00
|
|
|
|
outf.writestr(zi, inf.read('mimetype'))
|
|
|
|
|
for path in namelist:
|
|
|
|
|
data = inf.read(path)
|
|
|
|
|
zi = ZipInfo(path)
|
|
|
|
|
zi.compress_type=ZIP_DEFLATED
|
2013-03-20 10:23:54 +00:00
|
|
|
|
try:
|
2013-10-02 18:59:40 +00:00
|
|
|
|
# get the file info, including time-stamp
|
|
|
|
|
oldzi = inf.getinfo(path)
|
|
|
|
|
# copy across useful fields
|
|
|
|
|
zi.date_time = oldzi.date_time
|
|
|
|
|
zi.comment = oldzi.comment
|
|
|
|
|
zi.extra = oldzi.extra
|
|
|
|
|
zi.internal_attr = oldzi.internal_attr
|
|
|
|
|
# external attributes are dependent on the create system, so copy both.
|
|
|
|
|
zi.external_attr = oldzi.external_attr
|
|
|
|
|
zi.create_system = oldzi.create_system
|
|
|
|
|
except:
|
2013-03-20 10:23:54 +00:00
|
|
|
|
pass
|
2013-10-02 18:59:40 +00:00
|
|
|
|
outf.writestr(zi, decryptor.decrypt(path, data))
|
2012-12-19 13:48:11 +00:00
|
|
|
|
except:
|
2013-10-02 18:59:40 +00:00
|
|
|
|
print u"Could not decrypt {0:s} because of an exception:\n{1:s}".format(os.path.basename(inpath), traceback.format_exc())
|
2012-12-19 13:48:11 +00:00
|
|
|
|
return 2
|
2011-01-17 07:24:53 +00:00
|
|
|
|
return 0
|
|
|
|
|
|
|
|
|
|
|
2013-03-26 16:38:18 +00:00
|
|
|
|
def cli_main():
|
2013-04-05 16:44:48 +00:00
|
|
|
|
sys.stdout=SafeUnbuffered(sys.stdout)
|
|
|
|
|
sys.stderr=SafeUnbuffered(sys.stderr)
|
2013-03-26 16:38:18 +00:00
|
|
|
|
argv=unicode_argv()
|
2011-01-17 07:24:53 +00:00
|
|
|
|
progname = os.path.basename(argv[0])
|
|
|
|
|
if len(argv) != 4:
|
2013-10-02 18:59:40 +00:00
|
|
|
|
print u"usage: {0} <keyfile.der> <inbook.epub> <outbook.epub>".format(progname)
|
2011-01-17 07:24:53 +00:00
|
|
|
|
return 1
|
|
|
|
|
keypath, inpath, outpath = argv[1:]
|
2012-12-19 13:48:11 +00:00
|
|
|
|
userkey = open(keypath,'rb').read()
|
|
|
|
|
result = decryptBook(userkey, inpath, outpath)
|
|
|
|
|
if result == 0:
|
|
|
|
|
print u"Successfully decrypted {0:s} as {1:s}".format(os.path.basename(inpath),os.path.basename(outpath))
|
|
|
|
|
return result
|
2011-01-17 07:24:53 +00:00
|
|
|
|
|
2009-02-19 12:39:43 +00:00
|
|
|
|
def gui_main():
|
2013-04-05 16:44:48 +00:00
|
|
|
|
try:
|
|
|
|
|
import Tkinter
|
|
|
|
|
import Tkconstants
|
|
|
|
|
import tkMessageBox
|
|
|
|
|
import traceback
|
|
|
|
|
except:
|
|
|
|
|
return cli_main()
|
2012-12-19 13:48:11 +00:00
|
|
|
|
|
|
|
|
|
class DecryptionDialog(Tkinter.Frame):
|
|
|
|
|
def __init__(self, root):
|
|
|
|
|
Tkinter.Frame.__init__(self, root, border=5)
|
|
|
|
|
self.status = Tkinter.Label(self, text=u"Select files for decryption")
|
|
|
|
|
self.status.pack(fill=Tkconstants.X, expand=1)
|
|
|
|
|
body = Tkinter.Frame(self)
|
|
|
|
|
body.pack(fill=Tkconstants.X, expand=1)
|
|
|
|
|
sticky = Tkconstants.E + Tkconstants.W
|
|
|
|
|
body.grid_columnconfigure(1, weight=2)
|
|
|
|
|
Tkinter.Label(body, text=u"Key file").grid(row=0)
|
|
|
|
|
self.keypath = Tkinter.Entry(body, width=30)
|
|
|
|
|
self.keypath.grid(row=0, column=1, sticky=sticky)
|
|
|
|
|
if os.path.exists(u"adeptkey.der"):
|
|
|
|
|
self.keypath.insert(0, u"adeptkey.der")
|
|
|
|
|
button = Tkinter.Button(body, text=u"...", command=self.get_keypath)
|
|
|
|
|
button.grid(row=0, column=2)
|
|
|
|
|
Tkinter.Label(body, text=u"Input file").grid(row=1)
|
|
|
|
|
self.inpath = Tkinter.Entry(body, width=30)
|
|
|
|
|
self.inpath.grid(row=1, column=1, sticky=sticky)
|
|
|
|
|
button = Tkinter.Button(body, text=u"...", command=self.get_inpath)
|
|
|
|
|
button.grid(row=1, column=2)
|
|
|
|
|
Tkinter.Label(body, text=u"Output file").grid(row=2)
|
|
|
|
|
self.outpath = Tkinter.Entry(body, width=30)
|
|
|
|
|
self.outpath.grid(row=2, column=1, sticky=sticky)
|
|
|
|
|
button = Tkinter.Button(body, text=u"...", command=self.get_outpath)
|
|
|
|
|
button.grid(row=2, column=2)
|
|
|
|
|
buttons = Tkinter.Frame(self)
|
|
|
|
|
buttons.pack()
|
|
|
|
|
botton = Tkinter.Button(
|
|
|
|
|
buttons, text=u"Decrypt", width=10, command=self.decrypt)
|
|
|
|
|
botton.pack(side=Tkconstants.LEFT)
|
|
|
|
|
Tkinter.Frame(buttons, width=10).pack(side=Tkconstants.LEFT)
|
|
|
|
|
button = Tkinter.Button(
|
|
|
|
|
buttons, text=u"Quit", width=10, command=self.quit)
|
|
|
|
|
button.pack(side=Tkconstants.RIGHT)
|
|
|
|
|
|
|
|
|
|
def get_keypath(self):
|
|
|
|
|
keypath = tkFileDialog.askopenfilename(
|
|
|
|
|
parent=None, title=u"Select Adobe Adept \'.der\' key file",
|
|
|
|
|
defaultextension=u".der",
|
|
|
|
|
filetypes=[('Adobe Adept DER-encoded files', '.der'),
|
|
|
|
|
('All Files', '.*')])
|
|
|
|
|
if keypath:
|
|
|
|
|
keypath = os.path.normpath(keypath)
|
|
|
|
|
self.keypath.delete(0, Tkconstants.END)
|
|
|
|
|
self.keypath.insert(0, keypath)
|
|
|
|
|
return
|
|
|
|
|
|
|
|
|
|
def get_inpath(self):
|
|
|
|
|
inpath = tkFileDialog.askopenfilename(
|
2013-10-02 18:59:40 +00:00
|
|
|
|
parent=None, title=u"Select ADEPT-encrypted ePub file to decrypt",
|
|
|
|
|
defaultextension=u".epub", filetypes=[('ePub files', '.epub')])
|
2012-12-19 13:48:11 +00:00
|
|
|
|
if inpath:
|
|
|
|
|
inpath = os.path.normpath(inpath)
|
|
|
|
|
self.inpath.delete(0, Tkconstants.END)
|
|
|
|
|
self.inpath.insert(0, inpath)
|
|
|
|
|
return
|
|
|
|
|
|
|
|
|
|
def get_outpath(self):
|
|
|
|
|
outpath = tkFileDialog.asksaveasfilename(
|
2013-10-02 18:59:40 +00:00
|
|
|
|
parent=None, title=u"Select unencrypted ePub file to produce",
|
|
|
|
|
defaultextension=u".epub", filetypes=[('ePub files', '.epub')])
|
2012-12-19 13:48:11 +00:00
|
|
|
|
if outpath:
|
|
|
|
|
outpath = os.path.normpath(outpath)
|
|
|
|
|
self.outpath.delete(0, Tkconstants.END)
|
|
|
|
|
self.outpath.insert(0, outpath)
|
|
|
|
|
return
|
|
|
|
|
|
|
|
|
|
def decrypt(self):
|
|
|
|
|
keypath = self.keypath.get()
|
|
|
|
|
inpath = self.inpath.get()
|
|
|
|
|
outpath = self.outpath.get()
|
|
|
|
|
if not keypath or not os.path.exists(keypath):
|
|
|
|
|
self.status['text'] = u"Specified key file does not exist"
|
|
|
|
|
return
|
|
|
|
|
if not inpath or not os.path.exists(inpath):
|
|
|
|
|
self.status['text'] = u"Specified input file does not exist"
|
|
|
|
|
return
|
|
|
|
|
if not outpath:
|
|
|
|
|
self.status['text'] = u"Output file not specified"
|
|
|
|
|
return
|
|
|
|
|
if inpath == outpath:
|
|
|
|
|
self.status['text'] = u"Must have different input and output files"
|
|
|
|
|
return
|
|
|
|
|
userkey = open(keypath,'rb').read()
|
|
|
|
|
self.status['text'] = u"Decrypting..."
|
|
|
|
|
try:
|
|
|
|
|
decrypt_status = decryptBook(userkey, inpath, outpath)
|
|
|
|
|
except Exception, e:
|
2013-10-02 18:59:40 +00:00
|
|
|
|
self.status['text'] = u"Error: {0}".format(e.args[0])
|
2012-12-19 13:48:11 +00:00
|
|
|
|
return
|
|
|
|
|
if decrypt_status == 0:
|
|
|
|
|
self.status['text'] = u"File successfully decrypted"
|
|
|
|
|
else:
|
|
|
|
|
self.status['text'] = u"The was an error decrypting the file."
|
|
|
|
|
|
2009-02-19 12:39:43 +00:00
|
|
|
|
root = Tkinter.Tk()
|
2013-10-02 18:59:40 +00:00
|
|
|
|
root.title(u"Adobe Adept ePub Decrypter v.{0}".format(__version__))
|
2009-02-19 12:39:43 +00:00
|
|
|
|
root.resizable(True, False)
|
2013-10-02 18:59:40 +00:00
|
|
|
|
root.minsize(300, 0)
|
2009-02-19 12:39:43 +00:00
|
|
|
|
DecryptionDialog(root).pack(fill=Tkconstants.X, expand=1)
|
|
|
|
|
root.mainloop()
|
2009-09-01 16:02:35 +00:00
|
|
|
|
return 0
|
2009-02-19 12:39:43 +00:00
|
|
|
|
|
|
|
|
|
if __name__ == '__main__':
|
2010-02-14 15:47:48 +00:00
|
|
|
|
if len(sys.argv) > 1:
|
|
|
|
|
sys.exit(cli_main())
|
2009-02-19 12:39:43 +00:00
|
|
|
|
sys.exit(gui_main())
|