Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on May 4th, 2012  |  syntax: None  |  size: 12.16 KB  |  hits: 13  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. #! /usr/bin/python
  2.  
  3. # ineptepub.pyw, version 2
  4.  
  5. # To run this program install Python 2.6 from http://www.python.org/download/
  6. # and PyCrypto from http://www.voidspace.org.uk/python/modules.shtml#pycrypto
  7. # (make sure to install the version for Python 2.6).  Save this script file as
  8. # ineptepub.pyw and double-click on it to run it.
  9.  
  10. # Revision history:
  11. #   1 - Initial release
  12. #   2 - Rename to INEPT, fix exit code
  13.  
  14. """
  15. Decrypt Adobe ADEPT-encrypted EPUB books.
  16. """
  17.  
  18. from __future__ import with_statement
  19.  
  20. __license__ = 'GPL v3'
  21.  
  22. import sys
  23. import os
  24. import zlib
  25. import zipfile
  26. from zipfile import ZipFile, ZIP_STORED, ZIP_DEFLATED
  27. from contextlib import closing
  28. import xml.etree.ElementTree as etree
  29. import Tkinter
  30. import Tkconstants
  31. import tkFileDialog
  32. import tkMessageBox
  33.  
  34. try:
  35.     from Crypto.Cipher import AES
  36.     from Crypto.PublicKey import RSA
  37. except ImportError:
  38.     AES = None
  39.     RSA = None
  40.  
  41. META_NAMES = ('mimetype', 'META-INF/rights.xml', 'META-INF/encryption.xml')
  42. NSMAP = {'adept': 'http://ns.adobe.com/adept',
  43.          'enc': 'http://www.w3.org/2001/04/xmlenc#'}
  44.  
  45.  
  46. # ASN.1 parsing code from tlslite
  47.  
  48. def bytesToNumber(bytes):
  49.     total = 0L
  50.     multiplier = 1L
  51.     for count in range(len(bytes)-1, -1, -1):
  52.         byte = bytes[count]
  53.         total += multiplier * byte
  54.         multiplier *= 256
  55.     return total
  56.  
  57. class ASN1Error(Exception):
  58.     pass
  59.  
  60. class ASN1Parser(object):
  61.     class Parser(object):
  62.         def __init__(self, bytes):
  63.             self.bytes = bytes
  64.             self.index = 0
  65.  
  66.         def get(self, length):
  67.             if self.index + length > len(self.bytes):
  68.                 raise ASN1Error("Error decoding ASN.1")
  69.             x = 0
  70.             for count in range(length):
  71.                 x <<= 8
  72.                 x |= self.bytes[self.index]
  73.                 self.index += 1
  74.             return x
  75.  
  76.         def getFixBytes(self, lengthBytes):
  77.             bytes = self.bytes[self.index : self.index+lengthBytes]
  78.             self.index += lengthBytes
  79.             return bytes
  80.  
  81.         def getVarBytes(self, lengthLength):
  82.             lengthBytes = self.get(lengthLength)
  83.             return self.getFixBytes(lengthBytes)
  84.  
  85.         def getFixList(self, length, lengthList):
  86.             l = [0] * lengthList
  87.             for x in range(lengthList):
  88.                 l[x] = self.get(length)
  89.             return l
  90.  
  91.         def getVarList(self, length, lengthLength):
  92.             lengthList = self.get(lengthLength)
  93.             if lengthList % length != 0:
  94.                 raise ASN1Error("Error decoding ASN.1")
  95.             lengthList = int(lengthList/length)
  96.             l = [0] * lengthList
  97.             for x in range(lengthList):
  98.                 l[x] = self.get(length)
  99.             return l
  100.  
  101.         def startLengthCheck(self, lengthLength):
  102.             self.lengthCheck = self.get(lengthLength)
  103.             self.indexCheck = self.index
  104.  
  105.         def setLengthCheck(self, length):
  106.             self.lengthCheck = length
  107.             self.indexCheck = self.index
  108.  
  109.         def stopLengthCheck(self):
  110.             if (self.index - self.indexCheck) != self.lengthCheck:
  111.                 raise ASN1Error("Error decoding ASN.1")
  112.  
  113.         def atLengthCheck(self):
  114.             if (self.index - self.indexCheck) < self.lengthCheck:
  115.                 return False
  116.             elif (self.index - self.indexCheck) == self.lengthCheck:
  117.                 return True
  118.             else:
  119.                 raise ASN1Error("Error decoding ASN.1")
  120.  
  121.     def __init__(self, bytes):
  122.         p = self.Parser(bytes)
  123.         p.get(1)
  124.         self.length = self._getASN1Length(p)
  125.         self.value = p.getFixBytes(self.length)
  126.  
  127.     def getChild(self, which):
  128.         p = self.Parser(self.value)
  129.         for x in range(which+1):
  130.             markIndex = p.index
  131.             p.get(1)
  132.             length = self._getASN1Length(p)
  133.             p.getFixBytes(length)
  134.         return ASN1Parser(p.bytes[markIndex:p.index])
  135.  
  136.     def _getASN1Length(self, p):
  137.         firstLength = p.get(1)
  138.         if firstLength<=127:
  139.             return firstLength
  140.         else:
  141.             lengthLength = firstLength & 0x7F
  142.             return p.get(lengthLength)
  143.  
  144.  
  145. class ZipInfo(zipfile.ZipInfo):
  146.     def __init__(self, *args, **kwargs):
  147.         if 'compress_type' in kwargs:
  148.             compress_type = kwargs.pop('compress_type')
  149.         super(ZipInfo, self).__init__(*args, **kwargs)
  150.         self.compress_type = compress_type
  151.  
  152.  
  153. class Decryptor(object):
  154.     def __init__(self, bookkey, encryption):
  155.         enc = lambda tag: '{%s}%s' % (NSMAP['enc'], tag)
  156.         self._aes = AES.new(bookkey, AES.MODE_CBC)
  157.         encryption = etree.fromstring(encryption)
  158.         self._encrypted = encrypted = set()
  159.         expr = './%s/%s/%s' % (enc('EncryptedData'), enc('CipherData'),
  160.                                enc('CipherReference'))
  161.         for elem in encryption.findall(expr):
  162.             path = elem.get('URI', None)
  163.             if path is not None:
  164.                 encrypted.add(path)
  165.  
  166.     def decompress(self, bytes):
  167.         dc = zlib.decompressobj(-15)
  168.         bytes = dc.decompress(bytes)
  169.         ex = dc.decompress('Z') + dc.flush()
  170.         if ex:
  171.             bytes = bytes + ex
  172.         return bytes
  173.  
  174.     def decrypt(self, path, data):
  175.         if path in self._encrypted:
  176.             data = self._aes.decrypt(data)[16:]
  177.             data = data[:-ord(data[-1])]
  178.             data = self.decompress(data)
  179.         return data
  180.  
  181.  
  182. class ADEPTError(Exception):
  183.     pass
  184.  
  185. def cli_main(argv=sys.argv):
  186.     progname = os.path.basename(argv[0])
  187.     if AES is None:
  188.         print "%s: This script requires PyCrypto, which must be installed " \
  189.               "separately.  Read the top-of-script comment for details." % \
  190.               (progname,)
  191.         return 1
  192.     if len(argv) != 4:
  193.         print "usage: %s KEYFILE INBOOK OUTBOOK" % (progname,)
  194.         return 1
  195.     keypath, inpath, outpath = argv[1:]
  196.     with open(keypath, 'rb') as f:
  197.         keyder = f.read()
  198.     key = ASN1Parser([ord(x) for x in keyder])
  199.     key = [bytesToNumber(key.getChild(x).value) for x in xrange(1, 4)]
  200.     rsa = RSA.construct(key)
  201.     with closing(ZipFile(open(inpath, 'rb'))) as inf:
  202.         namelist = set(inf.namelist())
  203.         if 'META-INF/rights.xml' not in namelist or \
  204.            'META-INF/encryption.xml' not in namelist:
  205.             raise ADEPTError('%s: not an ADEPT EPUB' % (inpath,))
  206.         for name in META_NAMES:
  207.             namelist.remove(name)
  208.         rights = etree.fromstring(inf.read('META-INF/rights.xml'))
  209.         adept = lambda tag: '{%s}%s' % (NSMAP['adept'], tag)
  210.         expr = './/%s' % (adept('encryptedKey'),)
  211.         bookkey = ''.join(rights.findtext(expr))
  212.         bookkey = rsa.decrypt(bookkey.decode('base64'))
  213.         # Padded as per RSAES-PKCS1-v1_5
  214.         if bookkey[-17] != '\x00':
  215.             raise ADEPTError('problem decrypting session key')
  216.         encryption = inf.read('META-INF/encryption.xml')
  217.         decryptor = Decryptor(bookkey[-16:], encryption)
  218.         kwds = dict(compression=ZIP_DEFLATED, allowZip64=False)
  219.         with closing(ZipFile(open(outpath, 'wb'), 'w', **kwds)) as outf:
  220.             zi = ZipInfo('mimetype', compress_type=ZIP_STORED)
  221.             outf.writestr(zi, inf.read('mimetype'))
  222.             for path in namelist:
  223.                 data = inf.read(path)
  224.                 outf.writestr(path, decryptor.decrypt(path, data))
  225.     return 0
  226.  
  227.  
  228. class DecryptionDialog(Tkinter.Frame):
  229.     def __init__(self, root):
  230.         Tkinter.Frame.__init__(self, root, border=5)
  231.         self.status = Tkinter.Label(self, text='Select files for decryption')
  232.         self.status.pack(fill=Tkconstants.X, expand=1)
  233.         body = Tkinter.Frame(self)
  234.         body.pack(fill=Tkconstants.X, expand=1)
  235.         sticky = Tkconstants.E + Tkconstants.W
  236.         body.grid_columnconfigure(1, weight=2)
  237.         Tkinter.Label(body, text='Key file').grid(row=0)
  238.         self.keypath = Tkinter.Entry(body, width=30)
  239.         self.keypath.grid(row=0, column=1, sticky=sticky)
  240.         if os.path.exists('adeptkey.der'):
  241.             self.keypath.insert(0, 'adeptkey.der')
  242.         button = Tkinter.Button(body, text="...", command=self.get_keypath)
  243.         button.grid(row=0, column=2)
  244.         Tkinter.Label(body, text='Input file').grid(row=1)
  245.         self.inpath = Tkinter.Entry(body, width=30)
  246.         self.inpath.grid(row=1, column=1, sticky=sticky)
  247.         button = Tkinter.Button(body, text="...", command=self.get_inpath)
  248.         button.grid(row=1, column=2)
  249.         Tkinter.Label(body, text='Output file').grid(row=2)
  250.         self.outpath = Tkinter.Entry(body, width=30)
  251.         self.outpath.grid(row=2, column=1, sticky=sticky)
  252.         button = Tkinter.Button(body, text="...", command=self.get_outpath)
  253.         button.grid(row=2, column=2)
  254.         buttons = Tkinter.Frame(self)
  255.         buttons.pack()
  256.         botton = Tkinter.Button(
  257.             buttons, text="Decrypt", width=10, command=self.decrypt)
  258.         botton.pack(side=Tkconstants.LEFT)
  259.         Tkinter.Frame(buttons, width=10).pack(side=Tkconstants.LEFT)
  260.         button = Tkinter.Button(
  261.             buttons, text="Quit", width=10, command=self.quit)
  262.         button.pack(side=Tkconstants.RIGHT)
  263.  
  264.     def get_keypath(self):
  265.         keypath = tkFileDialog.askopenfilename(
  266.             parent=None, title='Select ADEPT key file',
  267.             defaultextension='.der', filetypes=[('DER-encoded files', '.der'),
  268.                                                 ('All Files', '.*')])
  269.         if keypath:
  270.             keypath = os.path.normpath(keypath)
  271.             self.keypath.delete(0, Tkconstants.END)
  272.             self.keypath.insert(0, keypath)
  273.         return
  274.  
  275.     def get_inpath(self):
  276.         inpath = tkFileDialog.askopenfilename(
  277.             parent=None, title='Select ADEPT-encrypted EPUB file to decrypt',
  278.             defaultextension='.epub', filetypes=[('EPUB files', '.epub'),
  279.                                                  ('All files', '.*')])
  280.         if inpath:
  281.             inpath = os.path.normpath(inpath)
  282.             self.inpath.delete(0, Tkconstants.END)
  283.             self.inpath.insert(0, inpath)
  284.         return
  285.  
  286.     def get_outpath(self):
  287.         outpath = tkFileDialog.asksaveasfilename(
  288.             parent=None, title='Select unencrypted EPUB file to produce',
  289.             defaultextension='.epub', filetypes=[('EPUB files', '.epub'),
  290.                                                  ('All files', '.*')])
  291.         if outpath:
  292.             outpath = os.path.normpath(outpath)
  293.             self.outpath.delete(0, Tkconstants.END)
  294.             self.outpath.insert(0, outpath)
  295.         return
  296.  
  297.     def decrypt(self):
  298.         keypath = self.keypath.get()
  299.         inpath = self.inpath.get()
  300.         outpath = self.outpath.get()
  301.         if not keypath or not os.path.exists(keypath):
  302.             self.status['text'] = 'Specified key file does not exist'
  303.             return
  304.         if not inpath or not os.path.exists(inpath):
  305.             self.status['text'] = 'Specified input file does not exist'
  306.             return
  307.         if not outpath:
  308.             self.status['text'] = 'Output file not specified'
  309.             return
  310.         if inpath == outpath:
  311.             self.status['text'] = 'Must have different input and output files'
  312.             return
  313.         argv = [sys.argv[0], keypath, inpath, outpath]
  314.         self.status['text'] = 'Decrypting...'
  315.         try:
  316.             cli_main(argv)
  317.         except Exception, e:
  318.             self.status['text'] = 'Error: ' + str(e)
  319.             return
  320.         self.status['text'] = 'File successfully decrypted'
  321.  
  322. def gui_main():
  323.     root = Tkinter.Tk()
  324.     if AES is None:
  325.         root.withdraw()
  326.         tkMessageBox.showerror(
  327.             "INEPT EPUB Decrypter",
  328.             "This script requires PyCrypto, which must be installed "
  329.             "separately.  Read the top-of-script comment for details.")
  330.         return 1
  331.     root.title('INEPT EPUB Decrypter')
  332.     root.resizable(True, False)
  333.     root.minsize(300, 0)
  334.     DecryptionDialog(root).pack(fill=Tkconstants.X, expand=1)
  335.     root.mainloop()
  336.     return 0
  337.  
  338. if __name__ == '__main__':
  339.     if len(sys.argv) > 1:
  340.         sys.exit(cli_main())
  341.     sys.exit(gui_main())