Compare commits

..

3 Commits

Author SHA1 Message Date
Giovanni Carvelli
482dbbc232 Merge 7673503228 into 3373d93874 2024-07-14 20:08:57 -04:00
Giovanni Carvelli
7673503228 remove print statement 2024-07-05 17:23:31 -04:00
Giovanni Carvelli
763ddb81e2 Support multiple keys on MacOS 2024-05-19 18:55:13 -04:00
10 changed files with 68 additions and 93 deletions

View File

@@ -14,7 +14,7 @@ jobs:
run: python3 make_release.py
- name: Upload
uses: actions/upload-artifact@v4
uses: actions/upload-artifact@v2
with:
name: plugin
path: |

View File

@@ -105,9 +105,4 @@ This is v10.0.9, a release candidate for v10.1.0. I don't expect there to be maj
- Fix some bugs (Python 2 and Python 3) in erdr2pml.py (untested).
- Fix file lock bug in androidkindlekey.py on Windows with Calibre >= 7 (untested).
- A bunch of updates to the external FileOpen ineptpdf script, might fix #442 (untested).
- Fix exception handling on decrypt in ion.py (#662, thanks @C0rn3j).
- Fix SHA1 hash function for erdr2pml.py script (#608, thanks @unwiredben).
- Make Kobo DRM removal not fail when there are undownloaded ebooks (#384, thanks @precondition).
- Fix Obok import failing in Calibre flatpak due to missing ip command (#586 and #585, thanks @jcotton42).
- Don't re-pack EPUB if there's no DRM to remove and no postprocessing done (fixes #555).

View File

@@ -22,8 +22,6 @@ li {margin-top: 0.5em}
<p>If you have upgraded from an earlier version of the plugin, any existing Kindle for Mac/PC keys will have been automatically imported, so you might not need to do any more configuration. In addition, on Windows and Mac, the default Kindle for Mac/PC key is added the first time the plugin is run. Continue reading for key generation and management instructions.</p>
<p>Note that for best results, you should run Calibre / this plugin on the same machine where Kindle 4 PC / Kindle 4 Mac is running. It is possible to export/import the keys to another machine, but this may not always work, particularly with the newer DRM versions.</p>
<h3>Creating New Keys:</h3>
<p>On the right-hand side of the plugins customization dialog, you will see a button with an icon that looks like a green plus sign (+). Clicking this button will open a new dialog prompting you to enter a key name for the default Kindle for Mac/PC key. </p>

View File

@@ -216,16 +216,12 @@ class DeDRM(FileTypePlugin):
traceback.print_exc()
raise
def postProcessEPUB(self, path_to_ebook, path_to_original_ebook = None):
def postProcessEPUB(self, path_to_ebook):
# This is called after the DRM is removed (or if no DRM was present)
# It does stuff like de-obfuscating fonts (by calling checkFonts)
# or removing watermarks.
postProcessStart = time.time()
postProcessingNeeded = False
# Save a backup of the EPUB path after DRM removal but before any postprocessing is done.
pre_postprocessing_EPUB_path = path_to_ebook
try:
import prefs
@@ -252,15 +248,6 @@ class DeDRM(FileTypePlugin):
postProcessEnd = time.time()
print("{0} v{1}: Post-processing took {2:.1f} seconds".format(PLUGIN_NAME, PLUGIN_VERSION, postProcessEnd-postProcessStart))
# If the EPUB is DRM-free (path_to_original_ebook will only be set in this case),
# and the post-processing hasn't changed anything in the EPUB,
# return the raw original file from path_to_original_ebook from before the
# zipfix code was executed.
if ((path_to_ebook == pre_postprocessing_EPUB_path) and path_to_original_ebook is not None):
print("{0} v{1}: Post-processing didn't do anything on DRM-free EPUB, returning original file".format(PLUGIN_NAME, PLUGIN_VERSION))
return path_to_original_ebook
return path_to_ebook
except:
@@ -312,9 +299,9 @@ class DeDRM(FileTypePlugin):
# import the LCP handler
import lcpdedrm
if (lcpdedrm.isLCPbook(inf.name)):
if (lcpdedrm.isLCPbook(path_to_ebook)):
try:
retval = lcpdedrm.decryptLCPbook(inf.name, dedrmprefs['lcp_passphrases'], self)
retval = lcpdedrm.decryptLCPbook(path_to_ebook, dedrmprefs['lcp_passphrases'], self)
except:
print("Looks like that didn't work:")
raise
@@ -641,7 +628,7 @@ class DeDRM(FileTypePlugin):
# Not a Barnes & Noble nor an Adobe Adept
# Probably a DRM-free EPUB, but we should still check for fonts.
return self.postProcessEPUB(inf.name, path_to_ebook)
return self.postProcessEPUB(inf.name)
def PDFIneptDecrypt(self, path_to_ebook):

View File

@@ -379,40 +379,45 @@ elif isosx:
return None
def adeptkeys():
# TODO: All the code to support extracting multiple activation keys
# TODO: seems to be Windows-only currently, still needs to be added for Mac.
actpath = findActivationDat()
if actpath is None:
raise ADEPTError("Could not find ADE activation.dat file.")
tree = etree.parse(actpath)
adept = lambda tag: '{%s}%s' % (NSMAP['adept'], tag)
expr = '//%s/%s' % (adept('credentials'), adept('privateLicenseKey'))
userkey = tree.findtext(expr)
userkeyelems = tree.findall(expr)
exprUUID = '//%s/%s' % (adept('credentials'), adept('user'))
keyName = ""
try:
keyName = tree.findtext(exprUUID)[9:] + "_"
except:
pass
userkeys = []
keynames = []
for userkeyelem in userkeyelems:
userkey = userkeyelem.text
try:
exprMail = '//%s/%s' % (adept('credentials'), adept('username'))
keyName = keyName + tree.find(exprMail).attrib["method"] + "_"
keyName = keyName + tree.findtext(exprMail) + "_"
except:
pass
exprUUID = '//%s/%s' % (adept('credentials'), adept('user'))
keyName = ""
try:
keyName = tree.findtext(exprUUID)[9:] + "_"
except:
pass
if keyName == "":
keyName = "Unknown"
else:
keyName = keyName[:-1]
try:
exprMail = '//%s/%s' % (adept('credentials'), adept('username'))
keyName = keyName + tree.find(exprMail).attrib["method"] + "_"
keyName = keyName + tree.findtext(exprMail) + "_"
except:
pass
if keyName == "":
keyName = "Unknown"
else:
keyName = keyName[:-1]
userkey = b64decode(userkey)
userkey = userkey[26:]
userkey = b64decode(userkey)
userkey = userkey[26:]
return [userkey], [keyName]
userkeys.append(userkey)
keynames.append(keyName)
return userkeys, keynames
else:
def adeptkeys():

View File

@@ -255,7 +255,7 @@ class EreaderProcessor(object):
encrypted_key = r[172:172+8]
encrypted_key_sha = r[56:56+20]
self.content_key = des.decrypt(encrypted_key)
if hashlib.sha1(self.content_key).digest() != encrypted_key_sha:
if sha1(self.content_key).digest() != encrypted_key_sha:
raise ValueError('Incorrect Name and/or Credit Card')
def getNumImages(self):

View File

@@ -1,19 +1,24 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""ion.py: Decrypt Kindle KFX files.
# ion.py
# Copyright © 2013-2020 Apprentice Harper et al.
Revision history:
Pascal implementation by lulzkabulz.
BinaryIon.pas + DrmIon.pas + IonSymbols.pas
1.0 - Python translation by apprenticenaomi.
1.1 - DeDRM integration by anon.
1.2 - Added pylzma import fallback
1.3 - Fixed lzma support for calibre 4.6+
2.0 - VoucherEnvelope v2/v3 support by apprenticesakuya.
3.0 - Added Python 3 compatibility for calibre 5.0
__license__ = 'GPL v3'
__version__ = '3.0'
Copyright © 2013-2020 Apprentice Harper et al.
# Revision history:
# Pascal implementation by lulzkabulz.
# BinaryIon.pas + DrmIon.pas + IonSymbols.pas
# 1.0 - Python translation by apprenticenaomi.
# 1.1 - DeDRM integration by anon.
# 1.2 - Added pylzma import fallback
# 1.3 - Fixed lzma support for calibre 4.6+
# 2.0 - VoucherEnvelope v2/v3 support by apprenticesakuya.
# 3.0 - Added Python 3 compatibility for calibre 5.0
"""
Decrypt Kindle KFX files.
"""
import collections
@@ -25,9 +30,6 @@ import struct
from io import BytesIO
__license__ = 'GPL v3'
__version__ = '3.0'
#@@CALIBRE_COMPAT_CODE@@
@@ -1094,11 +1096,11 @@ def process_V9888(st):
ws.sbox(d0x6a0bf4d0,d0x6a0dab50,[1,2])
ws.sbox(d0x6a0ba4d0,d0x6a0dab50,[1,2])
ws.shuffle(repl)
ws.shuffle(repl)
ws.shuffle(repl)
ws.shuffle(repl)
ws.sbox(d0x6a0bf4d0,d0x6a0dab50,[1,2])
ws.sbox(d0x6a0ba4d0,d0x6a0dab50,[1,2])
ws.exlookup(d0x6a0be4d0)
ws.exlookup(d0x6a0be4d0)
dat=ws.mask(st[sto:sto+16])
out+=dat
sto+=16
@@ -1122,7 +1124,7 @@ def process_V4648(st):
ws.sbox(d0x6a0c51a8,d0x6a0dab50,[1,3])
ws.shuffle(repl)
ws.shuffle(repl)
ws.exlookup(d0x6a0c91a8)
ws.exlookup(d0x6a0c91a8)
dat=ws.mask(st[sto:sto+16])
out+=dat
sto+=16
@@ -1146,7 +1148,7 @@ def process_V5683(st):
ws.shuffle(repl)
ws.sbox(d0x6a0cfe80,d0x6a0dab50,[])
ws.shuffle(repl)
ws.exlookup(d0x6a0d3e80)
ws.exlookup(d0x6a0d3e80)
dat=ws.mask(st[sto:sto+16])
out+=dat
sto+=16
@@ -1161,12 +1163,12 @@ def process_V5683(st):
# if a<0: a=256+a
# ax.append(ha[(a>>4)]+ha[a%16])
# return "".join(ax)
#
#
# def memhex(adr,sz):
# emu=EmulatorHelper(currentProgram)
# arr=emu.readMemory(getAddress(adr),sz)
# return a2hex(arr)
#
#
@@ -1252,7 +1254,7 @@ def scramble3(st,magic):
iVar5 = iVar5 - magic
index -= 1
if uVar4<=-1: break
else:
else:
if (offset < magic):
iVar3 = 0
else :
@@ -1272,9 +1274,9 @@ def scramble3(st,magic):
index=index-1
iVar5 = iVar5 + magic;
cntr += 1;
if iVar3>=divs: break
if iVar3>=divs: break
offset = offset + 1
if offset >= ((magic - 1) + divs) :break
if offset >= ((magic - 1) + divs) :break
return ret
#not sure if the third variant is used anywhere, but it is in Kindle, so I tried to add it
@@ -1340,14 +1342,14 @@ class DrmIonVoucher(object):
_assert(False, "Unknown lock parameter: %s" % param)
# i know that version maps to scramble pretty much 1 to 1, but there was precendent where they changed it, so...
# i know that version maps to scramble pretty much 1 to 1, but there was precendent where they changed it, so...
sharedsecrets = [obfuscate(shared, self.version),obfuscate2(shared, self.version),obfuscate3(shared, self.version),
process_V9708(shared), process_V1031(shared), process_V2069(shared), process_V9041(shared),
process_V3646(shared), process_V6052(shared), process_V9479(shared), process_V9888(shared),
process_V4648(shared), process_V5683(shared)]
decrypted=False
lastexception = None # type: Exception | None
ex=None
for sharedsecret in sharedsecrets:
key = hmac.new(sharedsecret, b"PIDv3", digestmod=hashlib.sha256).digest()
aes = AES.new(key[:32], AES.MODE_CBC, self.cipheriv[:16])
@@ -1359,15 +1361,14 @@ class DrmIonVoucher(object):
_assert(self.drmkey.hasnext() and self.drmkey.next() == TID_LIST and self.drmkey.gettypename() == "com.amazon.drm.KeySet@1.0",
"Expected KeySet, got %s" % self.drmkey.gettypename())
decrypted=True
decrypted=True
print("Decryption succeeded")
break
except Exception as ex:
lastexception = ex
print("Decryption failed, trying next fallback ")
if not decrypted:
raise lastexception
raise ex
self.drmkey.stepin()
while self.drmkey.hasnext():

View File

@@ -374,11 +374,7 @@ class InterfacePluginAction(InterfaceAction):
result['success'] = False
result['fileobj'] = None
try:
zin = zipfile.ZipFile(book.filename, 'r')
except FileNotFoundError:
print (_('{0} - File "{1}" not found. Make sure the eBook has been properly downloaded in the Kobo app.').format(PLUGIN_NAME, book.filename))
return result
zin = zipfile.ZipFile(book.filename, 'r')
#print ('Kobo library filename: {0}'.format(book.filename))
for userkey in self.userkeys:
print (_('Trying key: '), codecs.encode(userkey, 'hex'))

View File

@@ -449,15 +449,9 @@ class KoboLibrary(object):
for m in matches:
# print "m:{0}".format(m[0])
macaddrs.append(m[0].upper())
elif sys.platform.startswith('linux'):
for interface in os.listdir('/sys/class/net'):
with open('/sys/class/net/' + interface + '/address', 'r') as f:
mac = f.read().strip().upper()
# some interfaces, like Tailscale's VPN interface, do not have a MAC address
if mac != '':
macaddrs.append(mac)
else:
# final fallback
# probably linux
# let's try ip
c = re.compile('\s(' + '[0-9a-f]{2}:' * 5 + '[0-9a-f]{2})(\s|$)', re.IGNORECASE)
for line in os.popen('ip -br link'):

View File

@@ -8,8 +8,6 @@ Installation
------------
Open calibre's Preferences dialog. Click on the "Plugins" button. Next, click on the button, "Load plugin from file". Navigate to the unzipped DeDRM_tools folder, find the file "obok_plugin.zip". Click to select the file and select "Open". Click "Yes" in the "Are you sure?" dialog box. Click the "OK" button in the "Success" dialog box.
Note: This plugin requires the "wmic" component on Windows. On Windows 10 and below this will be available by default, on Windows 11 it needs to be explicitly enabled. Make sure that on your Windows 11 machine, under Settings -> System -> Optional features -> Add an optional feature -> View features, "WMIC" is enabled / activated, otherwise this plugin may not work correctly.
Customization
-------------
@@ -18,6 +16,7 @@ No customization is required, except choosing which menus will show the plugin.
Using the plugin
----------------
Select the plugin's menu or icon from whichever part of the calibre interface you have chosen to have it. Follow the instructions in the dialog that appears.
@@ -30,5 +29,5 @@ If you find that the DeDRM plugin is not working for you (imported ebooks still
- Once calibre has re-started, import the problem ebook.
- Now close calibre.
A log will appear that you can copy and paste into a GitHub issue at noDRM's repository, https://github.com/noDRM/DeDRM_tools/issues . You should also give details of your computer, and how you obtained the ebook file.
A log will appear that you can copy and paste into a comment at Apprentice Alf's blog, http://apprenticealf.wordpress.com/ or an issue at Apprentice Harper's repository, https://github.com/apprenticeharper/DeDRM_tools/issues . You should also give details of your computer, and how you obtained the ebook file.