Guest User

Untitled

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