Merge remote-tracking branch 'upstream/master' into master
commit
e726be2ed0
@ -1,33 +0,0 @@
|
||||
---
|
||||
name: Question
|
||||
about: Questions for DeDRM Project
|
||||
title: "[QUESTION] Title"
|
||||
labels: Question
|
||||
---
|
||||
|
||||
## CheckList
|
||||
<!-- Check with `[x]` -->
|
||||
- [ ] `The Title` and The `Log Title` are setted correctly.
|
||||
- [ ] Clarified about `my environment`.
|
||||
- [ ] Code block is used for `the log`.
|
||||
<!-- If you don't know the version, please specify 'Unknown'. -->
|
||||
<!-- In case of markdown To use the code block, enclose it in ```. -->
|
||||
<!-- If you don't need Log, please delete the log section. -->
|
||||
|
||||
---
|
||||
|
||||
## Title
|
||||
<!-- content -->
|
||||
|
||||
## My Environment
|
||||
### Calibre: `Version`
|
||||
### Kindle: `Version`
|
||||
### DeDRM: `Version`
|
||||
|
||||
## Log
|
||||
<details><summary>Log Title</summary>
|
||||
|
||||
```log
|
||||
PUT YOUR LOG
|
||||
```
|
||||
</details>
|
@ -0,0 +1,41 @@
|
||||
name: Question
|
||||
description: Questions for DeDRM Project
|
||||
body:
|
||||
- type: textarea
|
||||
id: question
|
||||
attributes:
|
||||
label: Question / bug report
|
||||
description: Please enter your question / your bug report.
|
||||
- type: input
|
||||
id: calibre-version
|
||||
attributes:
|
||||
label: Which version of Calibre are you running?
|
||||
description: "Example: 5.32"
|
||||
placeholder: "5.32"
|
||||
validations:
|
||||
required: true
|
||||
- type: input
|
||||
id: plugin-version
|
||||
attributes:
|
||||
label: Which version of the DeDRM plugin are you running?
|
||||
description: "Example: v10.0.0"
|
||||
placeholder: "v10.0.0"
|
||||
validations:
|
||||
required: true
|
||||
- type: input
|
||||
id: kindle-version
|
||||
attributes:
|
||||
label: If applicable, which version of the Kindle software are you running?
|
||||
description: "Example: 1.24"
|
||||
placeholder: "Leave empty if unrelated to Kindle books"
|
||||
validations:
|
||||
required: false
|
||||
- type: textarea
|
||||
id: log
|
||||
attributes:
|
||||
label: Log output
|
||||
description: If applicable, please post your log output here - into the code block.
|
||||
value: |
|
||||
```log
|
||||
Paste log output here.
|
||||
```
|
@ -1,39 +0,0 @@
|
||||
name: Python code format
|
||||
on:
|
||||
push:
|
||||
branches: master
|
||||
jobs:
|
||||
Format:
|
||||
if: "contains(github.event.head_commit.message, '!format')"
|
||||
runs-on: ubuntu-20.04
|
||||
strategy:
|
||||
fail-fast: false
|
||||
steps:
|
||||
- uses: actions/checkout@main
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@main
|
||||
with:
|
||||
python-version: 3.x
|
||||
- uses: actions/cache@main
|
||||
with:
|
||||
path: ~/.cache/pip
|
||||
key: ${{ runner.os }}-pip-format
|
||||
restore-keys: |
|
||||
${{ runner.os }}-pip-format
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
python -m pip install --upgrade pip
|
||||
python -m pip install autopep8 pycodestyle
|
||||
- name: Format by autopep8 then Push
|
||||
env:
|
||||
GIT_EMAIL: github-actions[bot]@users.noreply.github.com
|
||||
GIT_ACTOR: github-actions[bot]
|
||||
run: |
|
||||
export HASH_SHORT=$(git rev-parse --short HEAD)
|
||||
git checkout -b format--${HASH_SHORT}
|
||||
git config --global user.email $GIT_EMAIL
|
||||
git config --global user.name $GIT_ACTOR
|
||||
python -m autopep8 --in-place --aggressive --aggressive --experimental -r ./
|
||||
git add -A
|
||||
git commit -m 'Format by autopep8' -m From: -m $(git rev-parse HEAD)
|
||||
git push --set-upstream origin format--${HASH_SHORT}
|
@ -1,26 +0,0 @@
|
||||
name: Python code review
|
||||
on: [push, pull_request]
|
||||
jobs:
|
||||
Test:
|
||||
runs-on: ubuntu-20.04
|
||||
strategy:
|
||||
fail-fast: false
|
||||
steps:
|
||||
- uses: actions/checkout@main
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@main
|
||||
with:
|
||||
python-version: 3.x
|
||||
- uses: actions/cache@main
|
||||
with:
|
||||
path: ~/.cache/pip
|
||||
key: ${{ runner.os }}-pip-lint
|
||||
restore-keys: |
|
||||
${{ runner.os }}-pip-lint
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
python -m pip install --upgrade pip
|
||||
pip install flake8
|
||||
- name: Lint with flake8
|
||||
run: |
|
||||
python -m flake8 . --builtins=_,I --ignore=E501 --count --benchmark --show-source --statistics
|
@ -0,0 +1,20 @@
|
||||
name: Package plugin
|
||||
on:
|
||||
push:
|
||||
branches: [ master ]
|
||||
|
||||
jobs:
|
||||
package:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v2
|
||||
- name: Package
|
||||
run: python3 make_release.py
|
||||
- name: Upload
|
||||
uses: actions/upload-artifact@v2
|
||||
with:
|
||||
name: plugin
|
||||
path: |
|
||||
DeDRM_tools_*.zip
|
||||
DeDRM_tools.zip
|
@ -1 +1,9 @@
|
||||
# Mac files
|
||||
.DS_Store
|
||||
|
||||
# local test data
|
||||
/user_data/
|
||||
|
||||
# Cache
|
||||
/DeDRM_plugin/__pycache__
|
||||
/DeDRM_plugin/standalone/__pycache__
|
@ -0,0 +1,87 @@
|
||||
# Changelog
|
||||
|
||||
List of changes since the fork of Apprentice Harper's repository:
|
||||
|
||||
## Fixes in v10.0.0 (2021-11-17):
|
||||
|
||||
- CI testing / linting removed as that always failed anyways. The CI now "just" packages the plugin.
|
||||
- ~Support for the Readium LCP DRM (also known as "CARE DRM" or "TEA DRM"). This supports EPUB and PDF files. It does not yet support Readium LCPDF/LPF/LCPA/LCPAU/LCPDI files, as I don't have access to any of these. If you have an LCP-protected file in one of these formats that this plugin does not work with, please open [an issue](https://github.com/noDRM/DeDRM_tools/issues) and attach the file to the report.~ (removed due to a DMCA request, see #18 )
|
||||
- Add new Github issue report form which forces the user to include stuff like their Calibre version to hopefully increase the quality of bug reports.
|
||||
- Issues with PDF files in Calibre 5 should be fixed (merged [apprenticeharper/DeDRM_tools#1689](https://github.com/apprenticeharper/DeDRM_tools/pull/1689) ).
|
||||
- Fixed tons of issues with the B&N PDF DRM removal script ignoblepdf.py. It looks like that has never been tested since the move to Python3. I have integrated the B&N-specific code into ineptpdf.py, the original ignoblepdf.py is now unused. Fairly untested as I don't have any PDFs with B&N DRM.
|
||||
- Issues with Obok key retrieval fixed (merged [apprenticeharper/DeDRM_tools#1691](https://github.com/apprenticeharper/DeDRM_tools/pull/1691) ).
|
||||
- Issues with obfuscated Adobe fonts fixed (fixes [apprenticeharper/DeDRM_tools#1828](https://github.com/apprenticeharper/DeDRM_tools/issues/1828) ).
|
||||
- Deobfuscate font files in EPUBs by default (can be disabled in the plugin settings).
|
||||
- The standalone adobekey.py script now includes the account UUID in the key file name.
|
||||
- When extracting the default key from an ADE install, include the account UUID in the key name.
|
||||
- Adobe key management window size increased to account for longer key names due to the UUID.
|
||||
- Verify that the decrypted book key has the correct format. This makes it way less likely for issue [apprenticeharper/DeDRM_tools#1862](https://github.com/apprenticeharper/DeDRM_tools/issues/1862) to cause trouble.
|
||||
- If the Adobe owner UUID of a book being imported happens to be included in a particular key's name, try this key first before trying all the others. This completely fixes [apprenticeharper/DeDRM_tools#1862](https://github.com/apprenticeharper/DeDRM_tools/issues/1862), but only if the key name contains the correct UUID (not always the case, especially for keys imported with older versions of the plugin). It also makes DRM removal faster as the plugin no longer has to attempt all possible keys.
|
||||
- Remove some additional DRM remnants in Amazon MOBI files (merged [apprenticeharper/DeDRM_tools#23](https://github.com/apprenticeharper/DeDRM_tools/pull/23) ).
|
||||
- Just in case it's necessary, added a setting to the B&N key generation script to optionally allow the user to select the old key generation algorithm. Who knows, they might want to remove DRM from old books with the old key scheme.
|
||||
- Add a more verbose error message when trying to remove DRM from a book with the new, not-yet-cracked version of the Adobe ADEPT DRM.
|
||||
- Added back support for Python2 (Calibre 2.0+). Only tested with ADEPT (PDF & EPUB) and Readium LCP so far, please open an issue if there's errors with other book types.
|
||||
- Begin work on removing some kinds of watermarks from files after DRM removal. This isn't tested a lot, and is disabled by default. You can enable it in the plugin settings.
|
||||
- If you're using the [ACSM Input Plugin / DeACSM](https://www.mobileread.com/forums/showthread.php?t=341975), the encryption key will automatically be extracted from that plugin if necessary.
|
||||
|
||||
## Fixes in v10.0.1 (2021-11-19):
|
||||
|
||||
- Hotfix update to fix broken EPUB DRM removal due to a typo.
|
||||
|
||||
## Fixes in v10.0.2 (2021-11-29):
|
||||
|
||||
- Fix Kindle for Mac key retrieval (merged [apprenticeharper/DeDRM_tools#1936](https://github.com/apprenticeharper/DeDRM_tools/pull/1936) ), fixing #1.
|
||||
- Fix Adobe key retrieval in case the username has been changed (merged [apprenticeharper/DeDRM_tools#1946](https://github.com/apprenticeharper/DeDRM_tools/pull/1946) ). This should fix the error "failed to decrypt user key key".
|
||||
- Fix small issue with elibri watermark removal.
|
||||
- Adobe key name will now contain account email.
|
||||
|
||||
## Fixes in v10.0.3 (2022-07-13):
|
||||
|
||||
- Fix issue where importing a key from Adobe Digital Editions would fail in Python2 (Calibre < 5) if there were non-ASCII characters in the username.
|
||||
- Add code to support importing multiple decryption keys from ADE.
|
||||
- Improve epubtest.py to also detect Kobo & Apple DRM.
|
||||
- ~Small updates to the LCP DRM error messages.~ (removed due to a DMCA request, see #18 ).
|
||||
- Merge ignobleepub into ineptepub so there's no duplicate code.
|
||||
- Support extracting the B&N / Nook key from the NOOK Microsoft Store application (based on [this script](https://github.com/noDRM/DeDRM_tools/discussions/9) by fesiwi).
|
||||
- Support extracting the B&N / Nook key from a data dump of the NOOK Android application.
|
||||
- Support adding an existing PassHash / B&N key base64 string without having to write it to a file first.
|
||||
- Support extracting PassHash keys from Adobe Digital Editions.
|
||||
- Fix a bug that might have stopped the eReader PDB DRM removal from working (untested, I don't have any PDB books)
|
||||
- Fix a bug where the watermark removal code wouldn't run for DRM-free files.
|
||||
- ineptpdf: Add code to plugin to support "Standard" (tested) and "Adobe.APS" (untested) encrypted PDFs using the ineptpdf implementation (PDF passwords can be entered in the plugin settings)
|
||||
- ineptpdf: Support for decrypting PDF with owner password instead of user password.
|
||||
- ineptpdf: Add function to return Filter name.
|
||||
- ineptpdf: Support for V=5, R=5 and R=6 PDF files, and for AES256-encrypted PDFs.
|
||||
- ineptpdf: Disable cross-reference streams in the output file. This may make PDFs slightly larger, but the current code for cross-reference streams seems to be buggy and sometimes creates corrupted PDFs.
|
||||
- Drop support for importing key data from the ancient, pre "DeDRM" Calibre plugins ("Ignoble Epub DeDRM", "eReader PDB 2 PML" and "K4MobiDeDRM"). These are from 2011, I doubt anyone still has these installed, I can't even find a working link for these to test them. If you still have encryption keys in one of these plugins, you will need to update to DeDRM v10.0.2 or older (to convert the keys) before updating to DeDRM v10.0.3 or newer.
|
||||
- Some Python3 bugfixes for Amazon books (merged #10 by ableeker).
|
||||
- Fix a bug where extracting an Adobe key from ADE on Linux through Wine did fail when using the OpenSSL backend (instead of PyCrypto). See #13 and #14 for details, thanks acaloiaro for the bugfix.
|
||||
- Fix IndexError when DeDRMing some Amazon eBooks.
|
||||
- Add support for books with the new ADE3.0+ DRM by merging #48 by a980e066a01. Thanks a lot! (Also fixes #96 on MacOS)
|
||||
- Remove OpenSSL support, now the plugin will always use the Python crypto libraries.
|
||||
- Obok: Fix issues with invalid UTF-8 characters by merging #26 by baby-bell.
|
||||
- ineptpdf: Fix broken V=3 key obfuscation algorithm.
|
||||
- ineptpdf: (Hopefully) fix issues with some B&N PDF files.
|
||||
- Fix broken Amazon K4PC key retrieval (fixes #38)
|
||||
- Fix bug that corrupts output file for Print-Replica Amazon books (fixes #30).
|
||||
- Fix Nook Study key retrieval code (partially fixes #50).
|
||||
- Make the plugin work on Calibre 6 (Qt 6). (fixes #54 and #98) If you're running Calibre 6 and you notice any issues, please open a bug report.
|
||||
|
||||
## Fixes on master (not yet released):
|
||||
|
||||
- Fix a bug introduced with #48 that breaks DeDRM'ing on Calibre 4 (fixes #101).
|
||||
- Fix some more Calibre-6 bugs in the Obok plugin (should fix #114).
|
||||
- Fix a bug where invalid Adobe keys could cause the plugin to stop trying subsequent keys (partially fixes #109).
|
||||
- Fix DRM removal sometimes resetting the ZIP's internal "external_attr" value on Calibre 5 and newer.
|
||||
- Fix tons of PDF decryption issues (hopefully fixes #104 and other PDF-related issues).
|
||||
- Small Python 2 / Calibre 4 bugfix for Obok.
|
||||
- Removing ancient AlfCrypto machine code libraries, moving all encryption / decryption to Python code.
|
||||
- General cleanup and removal of dead code.
|
||||
- Fix a bug where ADE account keys weren't automatically imported from the DeACSM plugin when importing a PDF file.
|
||||
- Re-enable Xrefs in exported PDF files since the file corruption bug is hopefully fixed. Please open bug reports if you encounter new issues with PDF files.
|
||||
- Fix a bug that would sometimes cause corrupted keys to be added when adding them through the config dialog (fixes #145, #134, #119, #116, #115, #109).
|
||||
- Update the README (fixes #136) to indicate that Apprentice Harper's version is no longer being updated.
|
||||
- Fix a bug where PDFs with empty arrays (`<>`) in a PDF object failed to decrypt, fixes #183.
|
||||
- Automatically strip whitespace from entered Amazon Kindle serial numbers, should fix #158.
|
||||
- Obok: Add new setting option "Add new entry" for duplicate books to always add them to the Calibre database as a new book. Untested. Should fix #148.
|
||||
- Obok: Fix where changing the Calibre UI language to some languages would cause the "duplicate book" setting to reset. Untested.
|
@ -0,0 +1,20 @@
|
||||
|
||||
#@@CALIBRE_COMPAT_CODE_START@@
|
||||
import sys, os
|
||||
|
||||
# Explicitly allow importing everything ...
|
||||
if os.path.dirname(os.path.dirname(os.path.abspath(__file__))) not in sys.path:
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
if os.path.dirname(os.path.abspath(__file__)) not in sys.path:
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
# Bugfix for Calibre < 5:
|
||||
if "calibre" in sys.modules and sys.version_info[0] == 2:
|
||||
from calibre.utils.config import config_dir
|
||||
if os.path.join(config_dir, "plugins", "DeDRM.zip") not in sys.path:
|
||||
sys.path.insert(0, os.path.join(config_dir, "plugins", "DeDRM.zip"))
|
||||
|
||||
# Explicitly set the package identifier so we are allowed to import stuff ...
|
||||
#__package__ = "DeDRM_plugin"
|
||||
|
||||
#@@CALIBRE_COMPAT_CODE_END@@
|
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,23 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# __main__.py for DeDRM_plugin
|
||||
# (CLI interface without Calibre)
|
||||
# Copyright © 2021 NoDRM
|
||||
|
||||
__license__ = 'GPL v3'
|
||||
__docformat__ = 'restructuredtext en'
|
||||
|
||||
# For revision history see __init__.py
|
||||
|
||||
"""
|
||||
Run DeDRM plugin without Calibre.
|
||||
"""
|
||||
|
||||
# Import __init__.py from the standalone folder so we can have all the
|
||||
# standalone / non-Calibre code in that subfolder.
|
||||
|
||||
import standalone.__init__ as mdata
|
||||
import sys
|
||||
|
||||
mdata.main(sys.argv)
|
@ -0,0 +1,12 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
#@@CALIBRE_COMPAT_CODE@@
|
||||
|
||||
PLUGIN_NAME = "DeDRM"
|
||||
__version__ = '10.0.3'
|
||||
|
||||
PLUGIN_VERSION_TUPLE = tuple([int(x) for x in __version__.split(".")])
|
||||
PLUGIN_VERSION = ".".join([str(x)for x in PLUGIN_VERSION_TUPLE])
|
||||
# Include an html helpfile in the plugin's zipfile with the following name.
|
||||
RESOURCE_NAME = PLUGIN_NAME + '_Help.htm'
|
@ -1,75 +0,0 @@
|
||||
import sys
|
||||
import tkinter
|
||||
import tkinter.constants
|
||||
|
||||
class ActivityBar(tkinter.Frame):
|
||||
|
||||
def __init__(self, master, length=300, height=20, barwidth=15, interval=50, bg='white', fillcolor='orchid1',\
|
||||
bd=2, relief=tkinter.constants.GROOVE, *args, **kw):
|
||||
tkinter.Frame.__init__(self, master, bg=bg, width=length, height=height, *args, **kw)
|
||||
self._master = master
|
||||
self._interval = interval
|
||||
self._maximum = length
|
||||
self._startx = 0
|
||||
self._barwidth = barwidth
|
||||
self._bardiv = length / barwidth
|
||||
if self._bardiv < 10:
|
||||
self._bardiv = 10
|
||||
stopx = self._startx + self._barwidth
|
||||
if stopx > self._maximum:
|
||||
stopx = self._maximum
|
||||
# self._canv = Tkinter.Canvas(self, bg=self['bg'], width=self['width'], height=self['height'],\
|
||||
# highlightthickness=0, relief='flat', bd=0)
|
||||
self._canv = tkinter.Canvas(self, bg=self['bg'], width=self['width'], height=self['height'],\
|
||||
highlightthickness=0, relief=relief, bd=bd)
|
||||
self._canv.pack(fill='both', expand=1)
|
||||
self._rect = self._canv.create_rectangle(0, 0, self._canv.winfo_reqwidth(), self._canv.winfo_reqheight(), fill=fillcolor, width=0)
|
||||
|
||||
self._set()
|
||||
self.bind('<Configure>', self._update_coords)
|
||||
self._running = False
|
||||
|
||||
def _update_coords(self, event):
|
||||
'''Updates the position of the rectangle inside the canvas when the size of
|
||||
the widget gets changed.'''
|
||||
# looks like we have to call update_idletasks() twice to make sure
|
||||
# to get the results we expect
|
||||
self._canv.update_idletasks()
|
||||
self._maximum = self._canv.winfo_width()
|
||||
self._startx = 0
|
||||
self._barwidth = self._maximum / self._bardiv
|
||||
if self._barwidth < 2:
|
||||
self._barwidth = 2
|
||||
stopx = self._startx + self._barwidth
|
||||
if stopx > self._maximum:
|
||||
stopx = self._maximum
|
||||
self._canv.coords(self._rect, 0, 0, stopx, self._canv.winfo_height())
|
||||
self._canv.update_idletasks()
|
||||
|
||||
def _set(self):
|
||||
if self._startx < 0:
|
||||
self._startx = 0
|
||||
if self._startx > self._maximum:
|
||||
self._startx = self._startx % self._maximum
|
||||
stopx = self._startx + self._barwidth
|
||||
if stopx > self._maximum:
|
||||
stopx = self._maximum
|
||||
self._canv.coords(self._rect, self._startx, 0, stopx, self._canv.winfo_height())
|
||||
self._canv.update_idletasks()
|
||||
|
||||
def start(self):
|
||||
self._running = True
|
||||
self.after(self._interval, self._step)
|
||||
|
||||
def stop(self):
|
||||
self._running = False
|
||||
self._set()
|
||||
|
||||
def _step(self):
|
||||
if self._running:
|
||||
stepsize = self._barwidth / 4
|
||||
if stepsize < 2:
|
||||
stepsize = 2
|
||||
self._startx += stepsize
|
||||
self._set()
|
||||
self.after(self._interval, self._step)
|
@ -0,0 +1,179 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# adobekey_get_passhash.py, version 1
|
||||
# based on adobekey.pyw, version 7.2
|
||||
# Copyright © 2009-2021 i♥cabbages, Apprentice Harper et al.
|
||||
# Copyright © 2021 noDRM
|
||||
|
||||
# Released under the terms of the GNU General Public Licence, version 3
|
||||
# <http://www.gnu.org/licenses/>
|
||||
|
||||
# Revision history:
|
||||
# 1 - Initial release
|
||||
|
||||
"""
|
||||
Retrieve Adobe ADEPT user passhash keys
|
||||
"""
|
||||
|
||||
__license__ = 'GPL v3'
|
||||
__version__ = '1'
|
||||
|
||||
import sys, os, time
|
||||
import base64, hashlib
|
||||
try:
|
||||
from Cryptodome.Cipher import AES
|
||||
except ImportError:
|
||||
from Crypto.Cipher import AES
|
||||
|
||||
|
||||
def unpad(data, padding=16):
|
||||
if sys.version_info[0] == 2:
|
||||
pad_len = ord(data[-1])
|
||||
else:
|
||||
pad_len = data[-1]
|
||||
|
||||
return data[:-pad_len]
|
||||
|
||||
PASS_HASH_SECRET = "9ca588496a1bc4394553d9e018d70b9e"
|
||||
|
||||
|
||||
try:
|
||||
from calibre.constants import iswindows, isosx
|
||||
except:
|
||||
iswindows = sys.platform.startswith('win')
|
||||
isosx = sys.platform.startswith('darwin')
|
||||
|
||||
|
||||
class ADEPTError(Exception):
|
||||
pass
|
||||
|
||||
def decrypt_passhash(passhash, fp):
|
||||
|
||||
serial_number = base64.b64decode(fp).hex()
|
||||
|
||||
hash_key = hashlib.sha1(bytearray.fromhex(serial_number + PASS_HASH_SECRET)).digest()[:16]
|
||||
|
||||
encrypted_cc_hash = base64.b64decode(passhash)
|
||||
cc_hash = unpad(AES.new(hash_key, AES.MODE_CBC, encrypted_cc_hash[:16]).decrypt(encrypted_cc_hash[16:]))
|
||||
return base64.b64encode(cc_hash).decode("ascii")
|
||||
|
||||
|
||||
if iswindows:
|
||||
try:
|
||||
import winreg
|
||||
except ImportError:
|
||||
import _winreg as winreg
|
||||
|
||||
PRIVATE_LICENCE_KEY_PATH = r'Software\Adobe\Adept\Activation'
|
||||
|
||||
def passhash_keys():
|
||||
cuser = winreg.HKEY_CURRENT_USER
|
||||
keys = []
|
||||
names = []
|
||||
try:
|
||||
plkroot = winreg.OpenKey(cuser, PRIVATE_LICENCE_KEY_PATH)
|
||||
except WindowsError:
|
||||
raise ADEPTError("Could not locate ADE activation")
|
||||
except FileNotFoundError:
|
||||
raise ADEPTError("Could not locate ADE activation")
|
||||
|
||||
idx = 1
|
||||
|
||||
fp = None
|
||||
|
||||
i = -1
|
||||
while True:
|
||||
i = i + 1 # start with 0
|
||||
try:
|
||||
plkparent = winreg.OpenKey(plkroot, "%04d" % (i,))
|
||||
except:
|
||||
# No more keys
|
||||
break
|
||||
|
||||
ktype = winreg.QueryValueEx(plkparent, None)[0]
|
||||
|
||||
if ktype == "activationToken":
|
||||
# find fingerprint for hash decryption
|
||||
j = -1
|
||||
while True:
|
||||
j = j + 1 # start with 0
|
||||
try:
|
||||
plkkey = winreg.OpenKey(plkparent, "%04d" % (j,))
|
||||
except WindowsError:
|
||||
break
|
||||
except FileNotFoundError:
|
||||
break
|
||||
ktype = winreg.QueryValueEx(plkkey, None)[0]
|
||||
if ktype == 'fingerprint':
|
||||
fp = winreg.QueryValueEx(plkkey, 'value')[0]
|
||||
#print("Found fingerprint: " + fp)
|
||||
|
||||
|
||||
# Note: There can be multiple lists, with multiple entries each.
|
||||
if ktype == 'passHashList':
|
||||
|
||||
# Find operator (used in key name)
|
||||
j = -1
|
||||
lastOperator = "Unknown"
|
||||
while True:
|
||||
j = j + 1 # start with 0
|
||||
try:
|
||||
plkkey = winreg.OpenKey(plkparent, "%04d" % (j,))
|
||||
except WindowsError:
|
||||
break
|
||||
except FileNotFoundError:
|
||||
break
|
||||
ktype = winreg.QueryValueEx(plkkey, None)[0]
|
||||
if ktype == 'operatorURL':
|
||||
operatorURL = winreg.QueryValueEx(plkkey, 'value')[0]
|
||||
try:
|
||||
lastOperator = operatorURL.split('//')[1].split('/')[0]
|
||||
except:
|
||||
pass
|
||||
|
||||
|
||||
# Find hashes
|
||||
j = -1
|
||||
while True:
|
||||
j = j + 1 # start with 0
|
||||
try:
|
||||
plkkey = winreg.OpenKey(plkparent, "%04d" % (j,))
|
||||
except WindowsError:
|
||||
break
|
||||
except FileNotFoundError:
|
||||
break
|
||||
ktype = winreg.QueryValueEx(plkkey, None)[0]
|
||||
|
||||
if ktype == "passHash":
|
||||
passhash_encrypted = winreg.QueryValueEx(plkkey, 'value')[0]
|
||||
names.append("ADE_key_" + lastOperator + "_" + str(int(time.time())) + "_" + str(idx))
|
||||
idx = idx + 1
|
||||
keys.append(passhash_encrypted)
|
||||
|
||||
if fp is None:
|
||||
#print("Didn't find fingerprint for decryption ...")
|
||||
return [], []
|
||||
|
||||
print("Found {0:d} passhashes".format(len(keys)), file=sys.stderr)
|
||||
|
||||
keys_decrypted = []
|
||||
|
||||
for key in keys:
|
||||
decrypted = decrypt_passhash(key, fp)
|
||||
#print("Input key: " + key)
|
||||
#print("Output key: " + decrypted)
|
||||
keys_decrypted.append(decrypted)
|
||||
|
||||
return keys_decrypted, names
|
||||
|
||||
|
||||
else:
|
||||
def passhash_keys():
|
||||
raise ADEPTError("This script only supports Windows.")
|
||||
#TODO: Add MacOS support by parsing the activation.xml file.
|
||||
return [], []
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
print("This is a python calibre plugin. It can't be directly executed.")
|
@ -0,0 +1,271 @@
|
||||
# This is based on https://github.com/DanielStutzbach/winreg_unicode
|
||||
# The original _winreg in Python2 doesn't support unicode.
|
||||
# This causes issues if there's unicode chars in the username needed to decrypt the key.
|
||||
|
||||
'''
|
||||
Copyright 2010 Stutzbach Enterprises, LLC (daniel@stutzbachenterprises.com)
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are
|
||||
met:
|
||||
|
||||
1. Redistributions of source code must retain the above copyright
|
||||
notice, this list of conditions and the following disclaimer.
|
||||
2. 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.
|
||||
3. The name of the author may not be used to endorse or promote
|
||||
products derived from this software without specific prior written
|
||||
permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
|
||||
'''
|
||||
|
||||
import ctypes, ctypes.wintypes
|
||||
|
||||
ERROR_SUCCESS = 0
|
||||
ERROR_MORE_DATA = 234
|
||||
|
||||
KEY_READ = 0x20019
|
||||
|
||||
REG_NONE = 0
|
||||
REG_SZ = 1
|
||||
REG_EXPAND_SZ = 2
|
||||
REG_BINARY = 3
|
||||
REG_DWORD = 4
|
||||
REG_DWORD_BIG_ENDIAN = 5
|
||||
REG_DWORD_LITTLE_ENDIAN = 4
|
||||
REG_LINK = 6
|
||||
REG_MULTI_SZ = 7
|
||||
REG_RESOURCE_LIST = 8
|
||||
REG_FULL_RESOURCE_DESCRIPTOR = 9
|
||||
REG_RESOURCE_REQUIREMENTS_LIST = 10
|
||||
|
||||
c_HKEY = ctypes.c_void_p
|
||||
DWORD = ctypes.wintypes.DWORD
|
||||
BYTE = ctypes.wintypes.BYTE
|
||||
LPDWORD = ctypes.POINTER(DWORD)
|
||||
LPBYTE = ctypes.POINTER(BYTE)
|
||||
|
||||
advapi32 = ctypes.windll.advapi32
|
||||
|
||||
class FILETIME(ctypes.Structure):
|
||||
_fields_ = [("dwLowDateTime", DWORD),
|
||||
("dwHighDateTime", DWORD)]
|
||||
|
||||
RegCloseKey = advapi32.RegCloseKey
|
||||
RegCloseKey.restype = ctypes.c_long
|
||||
RegCloseKey.argtypes = [c_HKEY]
|
||||
|
||||
RegOpenKeyEx = advapi32.RegOpenKeyExW
|
||||
RegOpenKeyEx.restype = ctypes.c_long
|
||||
RegOpenKeyEx.argtypes = [c_HKEY, ctypes.c_wchar_p, ctypes.c_ulong,
|
||||
ctypes.c_ulong, ctypes.POINTER(c_HKEY)]
|
||||
|
||||
RegQueryInfoKey = advapi32.RegQueryInfoKeyW
|
||||
RegQueryInfoKey.restype = ctypes.c_long
|
||||
RegQueryInfoKey.argtypes = [c_HKEY, ctypes.c_wchar_p, LPDWORD, LPDWORD,
|
||||
LPDWORD, LPDWORD, LPDWORD, LPDWORD,
|
||||
LPDWORD, LPDWORD, LPDWORD,
|
||||
ctypes.POINTER(FILETIME)]
|
||||
|
||||
RegEnumValue = advapi32.RegEnumValueW
|
||||
RegEnumValue.restype = ctypes.c_long
|
||||
RegEnumValue.argtypes = [c_HKEY, DWORD, ctypes.c_wchar_p, LPDWORD,
|
||||
LPDWORD, LPDWORD, LPBYTE, LPDWORD]
|
||||
|
||||
RegEnumKeyEx = advapi32.RegEnumKeyExW
|
||||
RegEnumKeyEx.restype = ctypes.c_long
|
||||
RegEnumKeyEx.argtypes = [c_HKEY, DWORD, ctypes.c_wchar_p, LPDWORD,
|
||||
LPDWORD, ctypes.c_wchar_p, LPDWORD,
|
||||
ctypes.POINTER(FILETIME)]
|
||||
|
||||
RegQueryValueEx = advapi32.RegQueryValueExW
|
||||
RegQueryValueEx.restype = ctypes.c_long
|
||||
RegQueryValueEx.argtypes = [c_HKEY, ctypes.c_wchar_p, LPDWORD, LPDWORD,
|
||||
LPBYTE, LPDWORD]
|
||||
|
||||
def check_code(code):
|
||||
if code == ERROR_SUCCESS:
|
||||
return
|
||||
raise ctypes.WinError(2)
|
||||
|
||||
class HKEY(object):
|
||||
def __init__(self):
|
||||
self.hkey = c_HKEY()
|
||||
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, exc_type=None, exc_val=None, exc_tb=None):
|
||||
self.Close()
|
||||
return False
|
||||
|
||||
def Detach(self):
|
||||
rv = self.cast(self.hkey, self.c_ulong).value
|
||||
self.hkey = c_HKEY()
|
||||
return rv
|
||||
|
||||
def __nonzero__(self):
|
||||
return bool(self.hkey)
|
||||
|
||||
def Close(self):
|
||||
if not self.hkey:
|
||||
return
|
||||
if RegCloseKey is None or check_code is None or c_HKEY is None:
|
||||
return # globals become None during exit
|
||||
rc = RegCloseKey(self.hkey)
|
||||
self.hkey = c_HKEY()
|
||||
check_code(rc)
|
||||
|
||||
def __del__(self):
|
||||
self.Close()
|
||||
|
||||
class RootHKEY(ctypes.Structure):
|
||||
def __init__(self, value):
|
||||
self.hkey = c_HKEY(value)
|
||||
|
||||
def Close(self):
|
||||
pass
|
||||
|
||||
HKEY_CLASSES_ROOT = RootHKEY(0x80000000)
|
||||
HKEY_CURRENT_USER = RootHKEY(0x80000001)
|
||||
HKEY_LOCAL_MACHINE = RootHKEY(0x80000002)
|
||||
HKEY_USERS = RootHKEY(0x80000003)
|
||||
HKEY_PERFORMANCE_DATA = RootHKEY(0x80000004)
|
||||
HKEY_CURRENT_CONFIG = RootHKEY(0x80000005)
|
||||
HKEY_DYN_DATA = RootHKEY(0x80000006)
|
||||
|
||||
def OpenKey(key, sub_key):
|
||||
new_key = HKEY()
|
||||
rc = RegOpenKeyEx(key.hkey, sub_key, 0, KEY_READ,
|
||||
ctypes.cast(ctypes.byref(new_key.hkey),
|
||||
ctypes.POINTER(c_HKEY)))
|
||||
check_code(rc)
|
||||
return new_key
|
||||
|
||||
def QueryInfoKey(key):
|
||||
null = LPDWORD()
|
||||
num_sub_keys = DWORD()
|
||||
num_values = DWORD()
|
||||
ft = FILETIME()
|
||||
rc = RegQueryInfoKey(key.hkey, ctypes.c_wchar_p(), null, null,
|
||||
ctypes.byref(num_sub_keys), null, null,
|
||||
ctypes.byref(num_values), null, null, null,
|
||||
ctypes.byref(ft))
|
||||
check_code(rc)
|
||||
return (num_sub_keys.value, num_values.value,
|
||||
ft.dwLowDateTime | (ft.dwHighDateTime << 32))
|
||||
|
||||
def EnumValue(key, index):
|
||||
null = LPDWORD()
|
||||
value_size = DWORD()
|
||||
data_size = DWORD()
|
||||
rc = RegQueryInfoKey(key.hkey, ctypes.c_wchar_p(), null, null, null,
|
||||
null, null, null,
|
||||
ctypes.byref(value_size), ctypes.byref(data_size),
|
||||
null, ctypes.POINTER(FILETIME)())
|
||||
check_code(rc)
|
||||
value_size.value += 1
|
||||
data_size.value += 1
|
||||
|
||||
value = ctypes.create_unicode_buffer(value_size.value)
|
||||
|
||||
while True:
|
||||
data = ctypes.create_string_buffer(data_size.value)
|
||||
|
||||
tmp_value_size = DWORD(value_size.value)
|
||||
tmp_data_size = DWORD(data_size.value)
|
||||
typ = DWORD()
|
||||
rc = RegEnumValue(key.hkey, index,
|
||||
ctypes.cast(value, ctypes.c_wchar_p),
|
||||
ctypes.byref(tmp_value_size), null,
|
||||
ctypes.byref(typ),
|
||||
ctypes.cast(data, LPBYTE),
|
||||
ctypes.byref(tmp_data_size))
|
||||
|
||||
if rc != ERROR_MORE_DATA:
|
||||
break
|
||||
|
||||
data_size.value *= 2
|
||||
|
||||
check_code(rc)
|
||||
return (value.value, Reg2Py(data, tmp_data_size.value, typ.value),
|
||||
typ.value)
|
||||
|
||||
def split_multi_sz(data, size):
|
||||
if size == 0:
|
||||
return []
|
||||
Q = size
|
||||
P = 0
|
||||
rv = []
|
||||
while P < Q and data[P].value != u'\0':
|
||||
rv.append[P]
|
||||
while P < Q and data[P].value != u'\0':
|
||||
P += 1
|
||||
P += 1
|
||||
rv.append(size)
|
||||
return [ctypes.wstring_at(ctypes.pointer(data[rv[i]]),
|
||||
rv[i+1] - rv[i]).rstrip(u'\x00')
|
||||
for i in range(len(rv)-1)]
|
||||
|
||||
def Reg2Py(data, size, typ):
|
||||
if typ == REG_DWORD:
|
||||
if size == 0:
|
||||
return 0
|
||||
return ctypes.cast(data, ctypes.POINTER(ctypes.c_int)).contents.value
|
||||
elif typ == REG_SZ or typ == REG_EXPAND_SZ:
|
||||
return ctypes.wstring_at(data, size // 2).rstrip(u'\x00')
|
||||
elif typ == REG_MULTI_SZ:
|
||||
return split_multi_sz(ctypes.cast(data, ctypes.c_wchar_p), size // 2)
|
||||
else:
|
||||
if size == 0:
|
||||
return None
|
||||
return ctypes.string_at(data, size)
|
||||
|
||||
def EnumKey(key, index):
|
||||
tmpbuf = ctypes.create_unicode_buffer(257)
|
||||
length = DWORD(257)
|
||||
rc = RegEnumKeyEx(key.hkey, index,
|
||||
ctypes.cast(tmpbuf, ctypes.c_wchar_p),
|
||||
ctypes.byref(length),
|
||||
LPDWORD(), ctypes.c_wchar_p(), LPDWORD(),
|
||||
ctypes.POINTER(FILETIME)())
|
||||
check_code(rc)
|
||||
return ctypes.wstring_at(tmpbuf, length.value).rstrip(u'\x00')
|
||||
|
||||
def QueryValueEx(key, value_name):
|
||||
size = 256
|
||||
typ = DWORD()
|
||||
while True:
|
||||
tmp_size = DWORD(size)
|
||||
buf = ctypes.create_string_buffer(size)
|
||||
rc = RegQueryValueEx(key.hkey, value_name, LPDWORD(),
|
||||
ctypes.byref(typ),
|
||||
ctypes.cast(buf, LPBYTE), ctypes.byref(tmp_size))
|
||||
if rc != ERROR_MORE_DATA:
|
||||
break
|
||||
|
||||
size *= 2
|
||||
check_code(rc)
|
||||
return (Reg2Py(buf, tmp_size.value, typ.value), typ.value)
|
||||
|
||||
__all__ = ['OpenKey', 'QueryInfoKey', 'EnumValue', 'EnumKey', 'QueryValueEx',
|
||||
'HKEY_CLASSES_ROOT', 'HKEY_CURRENT_USER', 'HKEY_LOCAL_MACHINE',
|
||||
'HKEY_USERS', 'HKEY_PERFORMANCE_DATA', 'HKEY_CURRENT_CONFIG',
|
||||
'HKEY_DYN_DATA', 'REG_NONE', 'REG_SZ', 'REG_EXPAND_SZ',
|
||||
'REG_BINARY', 'REG_DWORD', 'REG_DWORD_BIG_ENDIAN',
|
||||
'REG_DWORD_LITTLE_ENDIAN', 'REG_LINK', 'REG_MULTI_SZ',
|
||||
'REG_RESOURCE_LIST', 'REG_FULL_RESOURCE_DESCRIPTOR',
|
||||
'REG_RESOURCE_REQUIREMENTS_LIST']
|
Binary file not shown.
Binary file not shown.
Binary file not shown.
@ -1,213 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
# vim:ts=4:sw=4:softtabstop=4:smarttab:expandtab
|
||||
|
||||
# to work around tk_chooseDirectory not properly returning unicode paths on Windows
|
||||
# need to use a dialog that can be hacked up to actually return full unicode paths
|
||||
# originally based on AskFolder from EasyDialogs for Windows but modified to fix it
|
||||
# to actually use unicode for path
|
||||
|
||||
# The original license for EasyDialogs is as follows
|
||||
#
|
||||
# Copyright (c) 2003-2005 Jimmy Retzlaff
|
||||
#
|
||||
# Permission is hereby granted, free of charge, to any person obtaining a
|
||||
# copy of this software and associated documentation files (the "Software"),
|
||||
# to deal in the Software without restriction, including without limitation
|
||||
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
|
||||
# and/or sell copies of the Software, and to permit persons to whom the
|
||||
# Software is furnished to do so, subject to the following conditions:
|
||||
#
|
||||
# The above copyright notice and this permission notice shall be included in
|
||||
# all copies or substantial portions of the Software.
|
||||
#
|
||||
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
|
||||
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
||||
# DEALINGS IN THE SOFTWARE.
|
||||
|
||||
# Adjusted for Python 3, September 2020
|
||||
|
||||
"""
|
||||
AskFolder(...) -- Ask the user to select a folder Windows specific
|
||||
"""
|
||||
|
||||
import os
|
||||
|
||||
import ctypes
|
||||
from ctypes import POINTER, byref, cdll, c_int, windll
|
||||
from ctypes.wintypes import LPCWSTR, LPWSTR
|
||||
import ctypes.wintypes as wintypes
|
||||
|
||||
|
||||
__all__ = ['AskFolder']
|
||||
|
||||
# Load required Windows DLLs
|
||||
ole32 = ctypes.windll.ole32
|
||||
shell32 = ctypes.windll.shell32
|
||||
user32 = ctypes.windll.user32
|
||||
|
||||
|
||||
# Windows Constants
|
||||
BFFM_INITIALIZED = 1
|
||||
BFFM_SETOKTEXT = 1129
|
||||
BFFM_SETSELECTIONA = 1126
|
||||
BFFM_SETSELECTIONW = 1127
|
||||
BIF_EDITBOX = 16
|
||||
BS_DEFPUSHBUTTON = 1
|
||||
CB_ADDSTRING = 323
|
||||
CB_GETCURSEL = 327
|
||||
CB_SETCURSEL = 334
|
||||
CDM_SETCONTROLTEXT = 1128
|
||||
EM_GETLINECOUNT = 186
|
||||
EM_GETMARGINS = 212
|
||||
EM_POSFROMCHAR = 214
|
||||
EM_SETSEL = 177
|
||||
GWL_STYLE = -16
|
||||
IDC_STATIC = -1
|
||||
IDCANCEL = 2
|
||||
IDNO = 7
|
||||
IDOK = 1
|
||||
IDYES = 6
|
||||
MAX_PATH = 260
|
||||
OFN_ALLOWMULTISELECT = 512
|
||||
OFN_ENABLEHOOK = 32
|
||||
OFN_ENABLESIZING = 8388608
|
||||
OFN_ENABLETEMPLATEHANDLE = 128
|
||||
OFN_EXPLORER = 524288
|
||||
OFN_OVERWRITEPROMPT = 2
|
||||
OPENFILENAME_SIZE_VERSION_400 = 76
|
||||
PBM_GETPOS = 1032
|
||||
PBM_SETMARQUEE = 1034
|
||||
PBM_SETPOS = 1026
|
||||
PBM_SETRANGE = 1025
|
||||
PBM_SETRANGE32 = 1030
|
||||
PBS_MARQUEE = 8
|
||||
PM_REMOVE = 1
|
||||
SW_HIDE = 0
|
||||
SW_SHOW = 5
|
||||
SW_SHOWNORMAL = 1
|
||||
SWP_NOACTIVATE = 16
|
||||
SWP_NOMOVE = 2
|
||||
SWP_NOSIZE = 1
|
||||
SWP_NOZORDER = 4
|
||||
VER_PLATFORM_WIN32_NT = 2
|
||||
WM_COMMAND = 273
|
||||
WM_GETTEXT = 13
|
||||
WM_GETTEXTLENGTH = 14
|
||||
WM_INITDIALOG = 272
|
||||
WM_NOTIFY = 78
|
||||
|
||||
# Windows function prototypes
|
||||
BrowseCallbackProc = ctypes.WINFUNCTYPE(ctypes.c_int, wintypes.HWND, ctypes.c_uint, wintypes.LPARAM, wintypes.LPARAM)
|
||||
|
||||
# Windows types
|
||||
LPCTSTR = ctypes.c_char_p
|
||||
LPTSTR = ctypes.c_char_p
|
||||
LPVOID = ctypes.c_voidp
|
||||
TCHAR = ctypes.c_char
|
||||
|
||||
class BROWSEINFO(ctypes.Structure):
|
||||
_fields_ = [
|
||||
("hwndOwner", wintypes.HWND),
|
||||
("pidlRoot", LPVOID),
|
||||
("pszDisplayName", LPTSTR),
|
||||
("lpszTitle", LPCTSTR),
|
||||
("ulFlags", ctypes.c_uint),
|
||||
("lpfn", BrowseCallbackProc),
|
||||
("lParam", wintypes.LPARAM),
|
||||
("iImage", ctypes.c_int)
|
||||
]
|
||||
|
||||
|
||||
# Utilities
|
||||
def CenterWindow(hwnd):
|
||||
desktopRect = GetWindowRect(user32.GetDesktopWindow())
|
||||
myRect = GetWindowRect(hwnd)
|
||||
x = width(desktopRect) // 2 - width(myRect) // 2
|
||||
y = height(desktopRect) // 2 - height(myRect) // 2
|
||||
user32.SetWindowPos(hwnd, 0,
|
||||
desktopRect.left + x,
|
||||
desktopRect.top + y,
|
||||
0, 0,
|
||||
SWP_NOACTIVATE | SWP_NOSIZE | SWP_NOZORDER
|
||||
)
|
||||
|
||||
|
||||
def GetWindowRect(hwnd):
|
||||
rect = wintypes.RECT()
|
||||
user32.GetWindowRect(hwnd, ctypes.byref(rect))
|
||||
return rect
|
||||
|
||||
def width(rect):
|
||||
return rect.right-rect.left
|
||||
|
||||
def height(rect):
|
||||
return rect.bottom-rect.top
|
||||
|
||||
|
||||
def AskFolder(
|
||||
message=None,
|
||||
version=None,
|
||||
defaultLocation=None,
|
||||
location=None,
|
||||
windowTitle=None,
|
||||
actionButtonLabel=None,
|
||||
cancelButtonLabel=None,
|
||||
multiple=None):
|
||||
"""Display a dialog asking the user for select a folder.
|
||||
modified to use unicode strings as much as possible
|
||||
returns unicode path
|
||||
"""
|
||||
|
||||
def BrowseCallback(hwnd, uMsg, lParam, lpData):
|
||||
if uMsg == BFFM_INITIALIZED:
|
||||
if actionButtonLabel:
|
||||
label = str(actionButtonLabel, errors='replace')
|
||||
user32.SendMessageW(hwnd, BFFM_SETOKTEXT, 0, label)
|
||||
if cancelButtonLabel:
|
||||
label = str(cancelButtonLabel, errors='replace')
|
||||
cancelButton = user32.GetDlgItem(hwnd, IDCANCEL)
|
||||
if cancelButton:
|
||||
user32.SetWindowTextW(cancelButton, label)
|
||||
if windowTitle:
|
||||
title = str(windowTitle, errors='replace')
|
||||
user32.SetWindowTextW(hwnd, title)
|
||||
if defaultLocation:
|
||||
user32.SendMessageW(hwnd, BFFM_SETSELECTIONW, 1, defaultLocation.replace('/', '\\'))
|
||||
if location:
|
||||
x, y = location
|
||||
desktopRect = wintypes.RECT()
|
||||
user32.GetWindowRect(0, ctypes.byref(desktopRect))
|
||||
user32.SetWindowPos(hwnd, 0,
|
||||
desktopRect.left + x,
|
||||
desktopRect.top + y, 0, 0,
|
||||
SWP_NOACTIVATE | SWP_NOSIZE | SWP_NOZORDER)
|
||||
else:
|
||||
CenterWindow(hwnd)
|
||||
return 0
|
||||
|
||||
# This next line is needed to prevent gc of the callback
|
||||
callback = BrowseCallbackProc(BrowseCallback)
|
||||
|
||||
browseInfo = BROWSEINFO()
|
||||
browseInfo.pszDisplayName = ctypes.c_char_p('\0' * (MAX_PATH+1))
|
||||
browseInfo.lpszTitle = message
|
||||
browseInfo.lpfn = callback
|
||||
|
||||
pidl = shell32.SHBrowseForFolder(ctypes.byref(browseInfo))
|
||||
if not pidl:
|
||||
result = None
|
||||
else:
|
||||
path = LPCWSTR(" " * (MAX_PATH+1))
|
||||
shell32.SHGetPathFromIDListW(pidl, path)
|
||||
ole32.CoTaskMemFree(pidl)
|
||||
result = path.value
|
||||
return result
|
||||
|
||||
|
||||
|
||||
|
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,328 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# epubfontdecrypt.py
|
||||
# Copyright © 2021 by noDRM
|
||||
|
||||
# Released under the terms of the GNU General Public Licence, version 3
|
||||
# <http://www.gnu.org/licenses/>
|
||||
|
||||
|
||||
# Revision history:
|
||||
# 1 - Initial release
|
||||
|
||||
"""
|
||||
Decrypts / deobfuscates font files in EPUB files
|
||||
"""
|
||||
|
||||
from __future__ import print_function
|
||||
|
||||
__license__ = 'GPL v3'
|
||||
__version__ = "1"
|
||||
|
||||
import os
|
||||
import traceback
|
||||
import zlib
|
||||
import zipfile
|
||||
from zipfile import ZipInfo, ZipFile, ZIP_STORED, ZIP_DEFLATED
|
||||
from zeroedzipinfo import ZeroedZipInfo
|
||||
from contextlib import closing
|
||||
from lxml import etree
|
||||
import itertools
|
||||
import hashlib
|
||||
import binascii
|
||||
|
||||
|
||||
class Decryptor(object):
|
||||
def __init__(self, obfuscationkeyIETF, obfuscationkeyAdobe, encryption):
|
||||
enc = lambda tag: '{%s}%s' % ('http://www.w3.org/2001/04/xmlenc#', tag)
|
||||
dsig = lambda tag: '{%s}%s' % ('http://www.w3.org/2000/09/xmldsig#', tag)
|
||||
self.obfuscation_key_Adobe = obfuscationkeyAdobe
|
||||
self.obfuscation_key_IETF = obfuscationkeyIETF
|
||||
|
||||
self._encryption = etree.fromstring(encryption)
|
||||
# This loops through all entries in the "encryption.xml" file
|
||||
# to figure out which files need to be decrypted.
|
||||
self._obfuscatedIETF = obfuscatedIETF = set()
|
||||
self._obfuscatedAdobe = obfuscatedAdobe = set()
|
||||
self._other = other = set()
|
||||
|
||||
self._json_elements_to_remove = json_elements_to_remove = set()
|
||||
self._has_remaining_xml = False
|
||||
expr = './%s/%s/%s' % (enc('EncryptedData'), enc('CipherData'),
|
||||
enc('CipherReference'))
|
||||
for elem in self._encryption.findall(expr):
|
||||
path = elem.get('URI', None)
|
||||
encryption_type_url = (elem.getparent().getparent().find("./%s" % (enc('EncryptionMethod'))).get('Algorithm', None))
|
||||
if path is not None:
|
||||
|
||||
if encryption_type_url == "http://www.idpf.org/2008/embedding":
|
||||
# Font files obfuscated with the IETF algorithm
|
||||
path = path.encode('utf-8')
|
||||
obfuscatedIETF.add(path)
|
||||
if (self.obfuscation_key_IETF is None):
|
||||
self._has_remaining_xml = True
|
||||
else:
|
||||
json_elements_to_remove.add(elem.getparent().getparent())
|
||||
|
||||
elif encryption_type_url == "http://ns.adobe.com/pdf/enc#RC":
|
||||
# Font files obfuscated with the Adobe algorithm.
|
||||
path = path.encode('utf-8')
|
||||
obfuscatedAdobe.add(path)
|
||||
if (self.obfuscation_key_Adobe is None):
|
||||
self._has_remaining_xml = True
|
||||
else:
|
||||
json_elements_to_remove.add(elem.getparent().getparent())
|
||||
|
||||
else:
|
||||
path = path.encode('utf-8')
|
||||
other.add(path)
|
||||
self._has_remaining_xml = True
|
||||
# Other unsupported type.
|
||||
|
||||
for elem in json_elements_to_remove:
|
||||
elem.getparent().remove(elem)
|
||||
|
||||
def check_if_remaining(self):
|
||||
return self._has_remaining_xml
|
||||
|
||||
def get_xml(self):
|
||||
return "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + etree.tostring(self._encryption, encoding="utf-8", pretty_print=True, xml_declaration=False).decode("utf-8")
|
||||
|
||||
def decompress(self, bytes):
|
||||
dc = zlib.decompressobj(-15)
|
||||
try:
|
||||
decompressed_bytes = dc.decompress(bytes)
|
||||
ex = dc.decompress(b'Z') + dc.flush()
|
||||
if ex:
|
||||
decompressed_bytes = decompressed_bytes + ex
|
||||
except:
|
||||
# possibly not compressed by zip - just return bytes
|
||||
return bytes, False
|
||||
return decompressed_bytes , True
|
||||
|
||||
def decrypt(self, path, data):
|
||||
if path.encode('utf-8') in self._obfuscatedIETF and self.obfuscation_key_IETF is not None:
|
||||
# de-obfuscate according to the IETF standard
|
||||
data, was_decomp = self.decompress(data)
|
||||
|
||||
if len(data) <= 1040:
|
||||
# de-obfuscate whole file
|
||||
out = self.deobfuscate_single_data(self.obfuscation_key_IETF, data)
|
||||
else:
|
||||
out = self.deobfuscate_single_data(self.obfuscation_key_IETF, data[:1040]) + data[1040:]
|
||||
|
||||
if (not was_decomp):
|
||||
out, was_decomp = self.decompress(out)
|
||||
return out
|
||||
|
||||
elif path.encode('utf-8') in self._obfuscatedAdobe and self.obfuscation_key_Adobe is not None:
|
||||
# de-obfuscate according to the Adobe standard
|
||||
data, was_decomp = self.decompress(data)
|
||||
|
||||
if len(data) <= 1024:
|
||||
# de-obfuscate whole file
|
||||
out = self.deobfuscate_single_data(self.obfuscation_key_Adobe, data)
|
||||
else:
|
||||
out = self.deobfuscate_single_data(self.obfuscation_key_Adobe, data[:1024]) + data[1024:]
|
||||
|
||||
if (not was_decomp):
|
||||
out, was_decomp = self.decompress(out)
|
||||
return out
|
||||
|
||||
else:
|
||||
# Not encrypted or obfuscated
|
||||
return data
|
||||
|
||||
def deobfuscate_single_data(self, key, data):
|
||||
try:
|
||||
msg = bytes([c^k for c,k in zip(data, itertools.cycle(key))])
|
||||
except TypeError:
|
||||
# Python 2
|
||||
msg = ''.join(chr(ord(c)^ord(k)) for c,k in itertools.izip(data, itertools.cycle(key)))
|
||||
return msg
|
||||
|
||||
|
||||
|
||||
def decryptFontsBook(inpath, outpath):
|
||||
|
||||
with closing(ZipFile(open(inpath, 'rb'))) as inf:
|
||||
namelist = inf.namelist()
|
||||
if 'META-INF/encryption.xml' not in namelist:
|
||||
return 1
|
||||
|
||||
# Font key handling:
|
||||
|
||||
font_master_key = None
|
||||
adobe_master_encryption_key = None
|
||||
|
||||
contNS = lambda tag: '{%s}%s' % ('urn:oasis:names:tc:opendocument:xmlns:container', tag)
|
||||
path = None
|
||||
|
||||
try:
|
||||
container = etree.fromstring(inf.read("META-INF/container.xml"))
|
||||
rootfiles = container.find(contNS("rootfiles")).findall(contNS("rootfile"))
|
||||
for rootfile in rootfiles:
|
||||
path = rootfile.get("full-path", None)
|
||||
if (path is not None):
|
||||
break
|
||||
except:
|
||||
pass
|
||||
|
||||
# If path is None, we didn't find an OPF, so we probably don't have a font key.
|
||||
# If path is set, it's the path to the main content OPF file.
|
||||
|
||||
if (path is None):
|
||||
print("FontDecrypt: No OPF for font obfuscation found")
|
||||
return 1
|
||||
else:
|
||||
packageNS = lambda tag: '{%s}%s' % ('http://www.idpf.org/2007/opf', tag)
|
||||
metadataDCNS = lambda tag: '{%s}%s' % ('http://purl.org/dc/elements/1.1/', tag)
|
||||
|
||||
try:
|
||||
container = etree.fromstring(inf.read(path))
|
||||
except:
|
||||
container = []
|
||||
|
||||
## IETF font key algorithm:
|
||||
print("FontDecrypt: Checking {0} for IETF font obfuscation keys ... ".format(path), end='')
|
||||
secret_key_name = None
|
||||
try:
|
||||
secret_key_name = container.get("unique-identifier")
|
||||
except:
|
||||
pass
|
||||
|
||||
try:
|
||||
identify_element = container.find(packageNS("metadata")).find(metadataDCNS("identifier"))
|
||||
if (secret_key_name is None or secret_key_name == identify_element.get("id")):
|
||||
font_master_key = identify_element.text
|
||||
except:
|
||||
pass
|
||||
|
||||
if (font_master_key is not None):
|
||||
if (secret_key_name is None):
|
||||
print("found '%s'" % (font_master_key))
|
||||
else:
|
||||
print("found '%s' (%s)" % (font_master_key, secret_key_name))
|
||||
|
||||
# Trim / remove forbidden characters from the key, then hash it:
|
||||
font_master_key = font_master_key.replace(' ', '')
|
||||
font_master_key = font_master_key.replace('\t', '')
|
||||
font_master_key = font_master_key.replace('\r', '')
|
||||
font_master_key = font_master_key.replace('\n', '')
|
||||
font_master_key = font_master_key.encode('utf-8')
|
||||
font_master_key = hashlib.sha1(font_master_key).digest()
|
||||
else:
|
||||
print("not found")
|
||||
|
||||
## Adobe font key algorithm
|
||||
print("FontDecrypt: Checking {0} for Adobe font obfuscation keys ... ".format(path), end='')
|
||||
|
||||
try:
|
||||
metadata = container.find(packageNS("metadata"))
|
||||
identifiers = metadata.findall(metadataDCNS("identifier"))
|
||||
|
||||
uid = None
|
||||
uidMalformed = False
|
||||
|
||||
for identifier in identifiers:
|
||||
if identifier.get(packageNS("scheme")) == "UUID":
|
||||
if identifier.text[:9] == "urn:uuid:":
|
||||
uid = identifier.text[9:]
|
||||
else:
|
||||
uid = identifier.text
|
||||
break
|
||||
if identifier.text[:9] == "urn:uuid:":
|
||||
uid = identifier.text[9:]
|
||||
break
|
||||
|
||||
|
||||
if uid is not None:
|
||||
uid = uid.replace(chr(0x20),'').replace(chr(0x09),'')
|
||||
uid = uid.replace(chr(0x0D),'').replace(chr(0x0A),'').replace('-','')
|
||||
|
||||
if len(uid) < 16:
|
||||
uidMalformed = True
|
||||
if not all(c in "0123456789abcdefABCDEF" for c in uid):
|
||||
uidMalformed = True
|
||||
|
||||
|
||||
if not uidMalformed:
|
||||
print("found '{0}'".format(uid))
|
||||
uid = uid + uid
|
||||
adobe_master_encryption_key = binascii.unhexlify(uid[:32])
|
||||
|
||||
if adobe_master_encryption_key is None:
|
||||
print("not found")
|
||||
|
||||
except:
|
||||
print("exception")
|
||||
pass
|
||||
|
||||
# Begin decrypting.
|
||||
|
||||
try:
|
||||
encryption = inf.read('META-INF/encryption.xml')
|
||||
decryptor = Decryptor(font_master_key, adobe_master_encryption_key, encryption)
|
||||
kwds = dict(compression=ZIP_DEFLATED, allowZip64=False)
|
||||
with closing(ZipFile(open(outpath, 'wb'), 'w', **kwds)) as outf:
|
||||
|
||||
# Mimetype needs to be the first entry, so remove it from the list
|
||||
# whereever it is, then add it at the beginning.
|
||||
namelist.remove("mimetype")
|
||||
|
||||
for path in (["mimetype"] + namelist):
|
||||
data = inf.read(path)
|
||||
zi = ZipInfo(path)
|
||||
zi.compress_type=ZIP_DEFLATED
|
||||
|
||||
if path == "mimetype":
|
||||
# mimetype must not be compressed
|
||||
zi.compress_type = ZIP_STORED
|
||||
|
||||
elif path == "META-INF/encryption.xml":
|
||||
# Check if there's still other entries not related to fonts
|
||||
if (decryptor.check_if_remaining()):
|
||||
data = decryptor.get_xml()
|
||||
print("FontDecrypt: There's remaining entries in encryption.xml, adding file ...")
|
||||
else:
|
||||
# No remaining entries, no need for that file.
|
||||
continue
|
||||
|
||||
try:
|
||||
# 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.volume = oldzi.volume
|
||||
zi.create_system = oldzi.create_system
|
||||
zi.create_version = oldzi.create_version
|
||||
|
||||
if any(ord(c) >= 128 for c in path) or any(ord(c) >= 128 for c in zi.comment):
|
||||
# If the file name or the comment contains any non-ASCII char, set the UTF8-flag
|
||||
zi.flag_bits |= 0x800
|
||||
except:
|
||||
pass
|
||||
|
||||
# Python 3 has a bug where the external_attr is reset to `0o600 << 16`
|
||||
# if it's NULL, so we need a workaround:
|
||||
if zi.external_attr == 0:
|
||||
zi = ZeroedZipInfo(zi)
|
||||
|
||||
if path == "mimetype":
|
||||
outf.writestr(zi, inf.read('mimetype'))
|
||||
elif path == "META-INF/encryption.xml":
|
||||
outf.writestr(zi, data)
|
||||
else:
|
||||
outf.writestr(zi, decryptor.decrypt(path, data))
|
||||
except:
|
||||
print("FontDecrypt: Could not decrypt fonts in {0:s} because of an exception:\n{1:s}".format(os.path.basename(inpath), traceback.format_exc()))
|
||||
traceback.print_exc()
|
||||
return 2
|
||||
return 0
|
||||
|
@ -0,0 +1,344 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# epubwatermark.py
|
||||
# Copyright © 2021 NoDRM
|
||||
|
||||
# Revision history:
|
||||
# 1.0 - Initial version
|
||||
|
||||
# Released under the terms of the GNU General Public Licence, version 3
|
||||
# <http://www.gnu.org/licenses/>
|
||||
|
||||
"""
|
||||
Removes various watermarks from EPUB files
|
||||
"""
|
||||
|
||||
import traceback
|
||||
from zipfile import ZipInfo, ZipFile, ZIP_STORED, ZIP_DEFLATED
|
||||
from zeroedzipinfo import ZeroedZipInfo
|
||||
from contextlib import closing
|
||||
from lxml import etree
|
||||
import re
|
||||
|
||||
# Runs a RegEx over all HTML/XHTML files to remove watermakrs.
|
||||
def removeHTMLwatermarks(object, path_to_ebook):
|
||||
try:
|
||||
inf = ZipFile(open(path_to_ebook, 'rb'))
|
||||
namelist = inf.namelist()
|
||||
|
||||
modded_names = []
|
||||
modded_contents = []
|
||||
|
||||
count_adept = 0
|
||||
count_pocketbook = 0
|
||||
count_lemonink_invisible = 0
|
||||
count_lemonink_visible = 0
|
||||
lemonink_trackingID = None
|
||||
|
||||
for file in namelist:
|
||||
if not (file.endswith('.html') or file.endswith('.xhtml') or file.endswith('.xml')):
|
||||
continue
|
||||
|
||||
try:
|
||||
file_str = inf.read(file).decode("utf-8")
|
||||
str_new = file_str
|
||||
|
||||
# Remove Adobe ADEPT watermarks
|
||||
# Match optional newline at the beginning, then a "meta" tag with name = "Adept.expected.resource" or "Adept.resource"
|
||||
# and either a "value" or a "content" element with an Adobe UUID
|
||||
pre_remove = str_new
|
||||
str_new = re.sub(r'((\r\n|\r|\n)\s*)?\<meta\s+name=\"(Adept\.resource|Adept\.expected\.resource)\"\s+(content|value)=\"urn:uuid:[0-9a-fA-F\-]+\"\s*\/>', '', str_new)
|
||||
str_new = re.sub(r'((\r\n|\r|\n)\s*)?\<meta\s+(content|value)=\"urn:uuid:[0-9a-fA-F\-]+\"\s+name=\"(Adept\.resource|Adept\.expected\.resource)\"\s*\/>', '', str_new)
|
||||
|
||||
if (str_new != pre_remove):
|
||||
count_adept += 1
|
||||
|
||||
# Remove Pocketbook watermarks
|
||||
pre_remove = str_new
|
||||
str_new = re.sub(r'\<div style\=\"padding\:0\;border\:0\;text\-indent\:0\;line\-height\:normal\;margin\:0 1cm 0.5cm 1cm\;[^\"]*opacity:0.0\;[^\"]*text\-decoration\:none\;[^\"]*background\:none\;[^\"]*\"\>(.*?)\<\/div\>', '', str_new)
|
||||
|
||||
if (str_new != pre_remove):
|
||||
count_pocketbook += 1
|
||||
|
||||
|
||||
# Remove eLibri / LemonInk watermark
|
||||
# Run this in a loop, as it is possible a file has been watermarked twice ...
|
||||
while True:
|
||||
pre_remove = str_new
|
||||
unique_id = re.search(r'<body[^>]+class="[^"]*(t0x[0-9a-fA-F]{25})[^"]*"[^>]*>', str_new)
|
||||
if (unique_id):
|
||||
lemonink_trackingID = unique_id.groups()[0]
|
||||
count_lemonink_invisible += 1
|
||||
str_new = re.sub(lemonink_trackingID, '', str_new)
|
||||
pre_remove = str_new
|
||||
pm = r'(<body[^>]+class="[^"]*"[^>]*>)'
|
||||
pm += r'\<div style\=\'padding\:0\;border\:0\;text\-indent\:0\;line\-height\:normal\;margin\:0 1cm 0.5cm 1cm\;[^\']*text\-decoration\:none\;[^\']*background\:none\;[^\']*\'\>(.*?)</div>'
|
||||
pm += r'\<div style\=\'padding\:0\;border\:0\;text\-indent\:0\;line\-height\:normal\;margin\:0 1cm 0.5cm 1cm\;[^\']*text\-decoration\:none\;[^\']*background\:none\;[^\']*\'\>(.*?)</div>'
|
||||
str_new = re.sub(pm, r'\1', str_new)
|
||||
|
||||
if (str_new != pre_remove):
|
||||
count_lemonink_visible += 1
|
||||
else:
|
||||
break
|
||||
|
||||
except:
|
||||
traceback.print_exc()
|
||||
continue
|
||||
|
||||
if (file_str == str_new):
|
||||
continue
|
||||
|
||||
modded_names.append(file)
|
||||
modded_contents.append(str_new)
|
||||
|
||||
|
||||
if len(modded_names) == 0:
|
||||
# No file modified, return original
|
||||
return path_to_ebook
|
||||
|
||||
if len(modded_names) != len(modded_contents):
|
||||
# Something went terribly wrong, return original
|
||||
print("Watermark: Error during watermark removal")
|
||||
return path_to_ebook
|
||||
|
||||
# Re-package with modified files:
|
||||
namelist.remove("mimetype")
|
||||
|
||||
try:
|
||||
output = object.temporary_file(".epub").name
|
||||
kwds = dict(compression=ZIP_DEFLATED, allowZip64=False)
|
||||
with closing(ZipFile(open(output, 'wb'), 'w', **kwds)) as outf:
|
||||
for path in (["mimetype"] + namelist):
|
||||
|
||||
data = inf.read(path)
|
||||
|
||||
try:
|
||||
modded_index = None
|
||||
modded_index = modded_names.index(path)
|
||||
except:
|
||||
pass
|
||||
|
||||
if modded_index is not None:
|
||||
# Found modified file - replace contents
|
||||
data = modded_contents[modded_index]
|
||||
|
||||
zi = ZipInfo(path)
|
||||
oldzi = inf.getinfo(path)
|
||||
try:
|
||||
zi.compress_type = oldzi.compress_type
|
||||
if path == "mimetype":
|
||||
zi.compress_type = ZIP_STORED
|
||||
zi.date_time = oldzi.date_time
|
||||
zi.comment = oldzi.comment
|
||||
zi.extra = oldzi.extra
|
||||
zi.internal_attr = oldzi.internal_attr
|
||||
zi.external_attr = oldzi.external_attr
|
||||
zi.volume = oldzi.volume
|
||||
zi.create_system = oldzi.create_system
|
||||
zi.create_version = oldzi.create_version
|
||||
|
||||
if any(ord(c) >= 128 for c in path) or any(ord(c) >= 128 for c in zi.comment):
|
||||
# If the file name or the comment contains any non-ASCII char, set the UTF8-flag
|
||||
zi.flag_bits |= 0x800
|
||||
except:
|
||||
pass
|
||||
|
||||
# Python 3 has a bug where the external_attr is reset to `0o600 << 16`
|
||||
# if it's NULL, so we need a workaround:
|
||||
if zi.external_attr == 0:
|
||||
zi = ZeroedZipInfo(zi)
|
||||
|
||||
|
||||
outf.writestr(zi, data)
|
||||
except:
|
||||
traceback.print_exc()
|
||||
return path_to_ebook
|
||||
|
||||
if (count_adept > 0):
|
||||
print("Watermark: Successfully stripped {0} ADEPT watermark(s) from ebook.".format(count_adept))
|
||||
|
||||
if (count_lemonink_invisible > 0 or count_lemonink_visible > 0):
|
||||
print("Watermark: Successfully stripped {0} visible and {1} invisible LemonInk watermark(s) (\"{2}\") from ebook."
|
||||
.format(count_lemonink_visible, count_lemonink_invisible, lemonink_trackingID))
|
||||
|
||||
if (count_pocketbook > 0):
|
||||
print("Watermark: Successfully stripped {0} Pocketbook watermark(s) from ebook.".format(count_pocketbook))
|
||||
|
||||
return output
|
||||
|
||||
except:
|
||||
traceback.print_exc()
|
||||
return path_to_ebook
|
||||
|
||||
|
||||
|
||||
|
||||
# Finds the main OPF file, then uses RegEx to remove watermarks
|
||||
def removeOPFwatermarks(object, path_to_ebook):
|
||||
contNS = lambda tag: '{%s}%s' % ('urn:oasis:names:tc:opendocument:xmlns:container', tag)
|
||||
opf_path = None
|
||||
|
||||
try:
|
||||
inf = ZipFile(open(path_to_ebook, 'rb'))
|
||||
container = etree.fromstring(inf.read("META-INF/container.xml"))
|
||||
rootfiles = container.find(contNS("rootfiles")).findall(contNS("rootfile"))
|
||||
for rootfile in rootfiles:
|
||||
opf_path = rootfile.get("full-path", None)
|
||||
if (opf_path is not None):
|
||||
break
|
||||
except:
|
||||
traceback.print_exc()
|
||||
return path_to_ebook
|
||||
|
||||
# If path is None, we didn't find an OPF, so we probably don't have a font key.
|
||||
# If path is set, it's the path to the main content OPF file.
|
||||
|
||||
if (opf_path is None):
|
||||
# No OPF found - no watermark
|
||||
return path_to_ebook
|
||||
else:
|
||||
try:
|
||||
container_str = inf.read(opf_path).decode("utf-8")
|
||||
container_str_new = container_str
|
||||
|
||||
had_amazon = False
|
||||
had_elibri = False
|
||||
|
||||
# Remove Amazon hex watermarks
|
||||
# Match optional newline at the beginning, then spaces, then a "meta" tag with name = "Watermark" or "Watermark_(hex)" and a "content" element.
|
||||
# This regex also matches DuMont watermarks with meta name="watermark", with the case-insensitive match on the "w" in watermark.
|
||||
pre_remove = container_str_new
|
||||
container_str_new = re.sub(r'((\r\n|\r|\n)\s*)?\<meta\s+name=\"[Ww]atermark(_\(hex\))?\"\s+content=\"[0-9a-fA-F]+\"\s*\/>', '', container_str_new)
|
||||
container_str_new = re.sub(r'((\r\n|\r|\n)\s*)?\<meta\s+content=\"[0-9a-fA-F]+\"\s+name=\"[Ww]atermark(_\(hex\))?\"\s*\/>', '', container_str_new)
|
||||
if pre_remove != container_str_new:
|
||||
had_amazon = True
|
||||
|
||||
# Remove elibri / lemonink watermark
|
||||
# Lemonink replaces all "id" fields in the opf with "idX_Y", with X being the watermark and Y being a number for that particular ID.
|
||||
# This regex replaces all "idX_Y" IDs with "id_Y", removing the watermark IDs.
|
||||
pre_remove = container_str_new
|
||||
container_str_new = re.sub(r'((\r\n|\r|\n)\s*)?\<\!\-\-\s*Wygenerowane przez elibri dla zamówienia numer [0-9a-fA-F]+\s*\-\-\>', '', container_str_new)
|
||||
if pre_remove != container_str_new:
|
||||
# To prevent this Regex from applying to books without that watermark, only do that if the watermark above was found.
|
||||
container_str_new = re.sub(r'\=\"id[0-9]+_([0-9]+)\"', r'="id_\1"', container_str_new)
|
||||
if pre_remove != container_str_new:
|
||||
had_elibri = True
|
||||
|
||||
except:
|
||||
traceback.print_exc()
|
||||
return path_to_ebook
|
||||
|
||||
if (container_str == container_str_new):
|
||||
# container didn't change - no watermark
|
||||
return path_to_ebook
|
||||
|
||||
# Re-package without watermark
|
||||
namelist = inf.namelist()
|
||||
namelist.remove("mimetype")
|
||||
|
||||
try:
|
||||
output = object.temporary_file(".epub").name
|
||||
kwds = dict(compression=ZIP_DEFLATED, allowZip64=False)
|
||||
with closing(ZipFile(open(output, 'wb'), 'w', **kwds)) as outf:
|
||||
for path in (["mimetype"] + namelist):
|
||||
|
||||
data = inf.read(path)
|
||||
if path == opf_path:
|
||||
# Found OPF, replacing ...
|
||||
data = container_str_new
|
||||
|
||||
zi = ZipInfo(path)
|
||||
oldzi = inf.getinfo(path)
|
||||
try:
|
||||
zi.compress_type = oldzi.compress_type
|
||||
if path == "mimetype":
|
||||
zi.compress_type = ZIP_STORED
|
||||
zi.date_time = oldzi.date_time
|
||||
zi.comment = oldzi.comment
|
||||
zi.extra = oldzi.extra
|
||||
zi.internal_attr = oldzi.internal_attr
|
||||
zi.external_attr = oldzi.external_attr
|
||||
zi.volume = oldzi.volume
|
||||
zi.create_system = oldzi.create_system
|
||||
zi.create_version = oldzi.create_version
|
||||
|
||||
if any(ord(c) >= 128 for c in path) or any(ord(c) >= 128 for c in zi.comment):
|
||||
# If the file name or the comment contains any non-ASCII char, set the UTF8-flag
|
||||
zi.flag_bits |= 0x800
|
||||
except:
|
||||
pass
|
||||
|
||||
# Python 3 has a bug where the external_attr is reset to `0o600 << 16`
|
||||
# if it's NULL, so we need a workaround:
|
||||
if zi.external_attr == 0:
|
||||
zi = ZeroedZipInfo(zi)
|
||||
|
||||
outf.writestr(zi, data)
|
||||
except:
|
||||
traceback.print_exc()
|
||||
return path_to_ebook
|
||||
|
||||
if had_elibri:
|
||||
print("Watermark: Successfully stripped eLibri watermark from OPF file.")
|
||||
if had_amazon:
|
||||
print("Watermark: Successfully stripped Amazon watermark from OPF file.")
|
||||
|
||||
return output
|
||||
|
||||
|
||||
|
||||
def removeCDPwatermark(object, path_to_ebook):
|
||||
# "META-INF/cdp.info" is a watermark file used by some Tolino vendors.
|
||||
# We don't want that in our eBooks, so lets remove that file.
|
||||
try:
|
||||
infile = ZipFile(open(path_to_ebook, 'rb'))
|
||||
namelist = infile.namelist()
|
||||
if 'META-INF/cdp.info' not in namelist:
|
||||
return path_to_ebook
|
||||
|
||||
namelist.remove("mimetype")
|
||||
namelist.remove("META-INF/cdp.info")
|
||||
|
||||
output = object.temporary_file(".epub").name
|
||||
|
||||
kwds = dict(compression=ZIP_DEFLATED, allowZip64=False)
|
||||
with closing(ZipFile(open(output, 'wb'), 'w', **kwds)) as outf:
|
||||
for path in (["mimetype"] + namelist):
|
||||
|
||||
data = infile.read(path)
|
||||
|
||||
zi = ZipInfo(path)
|
||||
oldzi = infile.getinfo(path)
|
||||
try:
|
||||
zi.compress_type = oldzi.compress_type
|
||||
if path == "mimetype":
|
||||
zi.compress_type = ZIP_STORED
|
||||
zi.date_time = oldzi.date_time
|
||||
zi.comment = oldzi.comment
|
||||
zi.extra = oldzi.extra
|
||||
zi.internal_attr = oldzi.internal_attr
|
||||
zi.external_attr = oldzi.external_attr
|
||||
zi.volume = oldzi.volume
|
||||
zi.create_system = oldzi.create_system
|
||||
zi.create_version = oldzi.create_version
|
||||
|
||||
if any(ord(c) >= 128 for c in path) or any(ord(c) >= 128 for c in zi.comment):
|
||||
# If the file name or the comment contains any non-ASCII char, set the UTF8-flag
|
||||
zi.flag_bits |= 0x800
|
||||
except:
|
||||
pass
|
||||
|
||||
# Python 3 has a bug where the external_attr is reset to `0o600 << 16`
|
||||
# if it's NULL, so we need a workaround:
|
||||
if zi.external_attr == 0:
|
||||
zi = ZeroedZipInfo(zi)
|
||||
|
||||
outf.writestr(zi, data)
|
||||
|
||||
print("Watermark: Successfully removed cdp.info watermark")
|
||||
return output
|
||||
|
||||
except:
|
||||
traceback.print_exc()
|
||||
return path_to_ebook
|
@ -1,441 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# ignobleepub.py
|
||||
# Copyright © 2009-2020 by i♥cabbages, Apprentice Harper et al.
|
||||
|
||||
# Released under the terms of the GNU General Public Licence, version 3
|
||||
# <http://www.gnu.org/licenses/>
|
||||
|
||||
#
|
||||
# Revision history:
|
||||
# 1 - Initial release
|
||||
# 2 - Added OS X support by using OpenSSL when available
|
||||
# 3 - screen out improper key lengths to prevent segfaults on Linux
|
||||
# 3.1 - Allow Windows versions of libcrypto to be found
|
||||
# 3.2 - add support for encoding to 'utf-8' when building up list of files to decrypt from encryption.xml
|
||||
# 3.3 - On Windows try PyCrypto first, OpenSSL next
|
||||
# 3.4 - Modify interface to allow use with import
|
||||
# 3.5 - Fix for potential problem with PyCrypto
|
||||
# 3.6 - Revised to allow use in calibre plugins to eliminate need for duplicate code
|
||||
# 3.7 - Tweaked to match ineptepub more closely
|
||||
# 3.8 - Fixed to retain zip file metadata (e.g. file modification date)
|
||||
# 3.9 - moved unicode_argv call inside main for Windows DeDRM compatibility
|
||||
# 4.0 - Work if TkInter is missing
|
||||
# 4.1 - Import tkFileDialog, don't assume something else will import it.
|
||||
# 5.0 - Python 3 for calibre 5.0
|
||||
|
||||
"""
|
||||
Decrypt Barnes & Noble encrypted ePub books.
|
||||
"""
|
||||
|
||||
__license__ = 'GPL v3'
|
||||
__version__ = "5.0"
|
||||
|
||||
import sys
|
||||
import os
|
||||
import traceback
|
||||
import base64
|
||||
import zlib
|
||||
import zipfile
|
||||
from zipfile import ZipInfo, ZipFile, ZIP_STORED, ZIP_DEFLATED
|
||||
from contextlib import closing
|
||||
import xml.etree.ElementTree as etree
|
||||
|
||||
# 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,str):
|
||||
data = data.encode(self.encoding,"replace")
|
||||
self.stream.buffer.write(data)
|
||||
self.stream.buffer.flush()
|
||||
def __getattr__(self, attr):
|
||||
return getattr(self.stream, attr)
|
||||
|
||||
try:
|
||||
from calibre.constants import iswindows, isosx
|
||||
except:
|
||||
iswindows = sys.platform.startswith('win')
|
||||
isosx = sys.platform.startswith('darwin')
|
||||
|
||||
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
|
||||
range(start, argc.value)]
|
||||
return ["ineptepub.py"]
|
||||
else:
|
||||
argvencoding = sys.stdin.encoding or "utf-8"
|
||||
return [arg if isinstance(arg, str) else str(arg, argvencoding) for arg in sys.argv]
|
||||
|
||||
|
||||
class IGNOBLEError(Exception):
|
||||
pass
|
||||
|
||||
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
|
||||
|
||||
if iswindows:
|
||||
libcrypto = find_library('libeay32')
|
||||
else:
|
||||
libcrypto = find_library('crypto')
|
||||
|
||||
if libcrypto is None:
|
||||
raise IGNOBLEError('libcrypto not found')
|
||||
libcrypto = CDLL(libcrypto)
|
||||
|
||||
AES_MAXNR = 14
|
||||
|
||||
c_char_pp = POINTER(c_char_p)
|
||||
c_int_p = POINTER(c_int)
|
||||
|
||||
class AES_KEY(Structure):
|
||||
_fields_ = [('rd_key', c_long * (4 * (AES_MAXNR + 1))),
|
||||
('rounds', c_int)]
|
||||
AES_KEY_p = POINTER(AES_KEY)
|
||||
|
||||
def F(restype, name, argtypes):
|
||||
func = getattr(libcrypto, name)
|
||||
func.restype = restype
|
||||
func.argtypes = argtypes
|
||||
return func
|
||||
|
||||
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])
|
||||
|
||||
class AES(object):
|
||||
def __init__(self, userkey):
|
||||
self._blocksize = len(userkey)
|
||||
if (self._blocksize != 16) and (self._blocksize != 24) and (self._blocksize != 32) :
|
||||
raise IGNOBLEError('AES improper key used')
|
||||
return
|
||||
key = self._key = AES_KEY()
|
||||
rv = AES_set_decrypt_key(userkey, len(userkey) * 8, key)
|
||||
if rv < 0:
|
||||
raise IGNOBLEError('Failed to initialize AES key')
|
||||
|
||||
def decrypt(self, data):
|
||||
out = create_string_buffer(len(data))
|
||||
iv = (b'\x00' * self._blocksize)
|
||||
rv = AES_cbc_encrypt(data, out, len(data), self._key, iv, 0)
|
||||
if rv == 0:
|
||||
raise IGNOBLEError('AES decryption failed')
|
||||
return out.raw
|
||||
|
||||
return AES
|
||||
|
||||
def _load_crypto_pycrypto():
|
||||
from Crypto.Cipher import AES as _AES
|
||||
|
||||
class AES(object):
|
||||
def __init__(self, key):
|
||||
self._aes = _AES.new(key, _AES.MODE_CBC, b'\x00'*16)
|
||||
|
||||
def decrypt(self, data):
|
||||
return self._aes.decrypt(data)
|
||||
|
||||
return AES
|
||||
|
||||
def _load_crypto():
|
||||
AES = None
|
||||
cryptolist = (_load_crypto_libcrypto, _load_crypto_pycrypto)
|
||||
if sys.platform.startswith('win'):
|
||||
cryptolist = (_load_crypto_pycrypto, _load_crypto_libcrypto)
|
||||
for loader in cryptolist:
|
||||
try:
|
||||
AES = loader()
|
||||
break
|
||||
except (ImportError, IGNOBLEError):
|
||||
pass
|
||||
return AES
|
||||
|
||||
AES = _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(b'Z') + dc.flush()
|
||||
if ex:
|
||||
bytes = bytes + ex
|
||||
return bytes
|
||||
|
||||
def decrypt(self, path, data):
|
||||
if bytes(path,'utf-8') in self._encrypted:
|
||||
data = self._aes.decrypt(data)[16:]
|
||||
data = data[:-data[-1]]
|
||||
data = self.decompress(data)
|
||||
return data
|
||||
|
||||
# check file to make check whether it's probably an Adobe Adept encrypted ePub
|
||||
def ignobleBook(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
|
||||
try:
|
||||
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) == 64:
|
||||
return True
|
||||
except:
|
||||
# if we couldn't check, assume it is
|
||||
return True
|
||||
return False
|
||||
|
||||
def decryptBook(keyb64, inpath, outpath):
|
||||
if AES is None:
|
||||
raise IGNOBLEError("PyCrypto or OpenSSL must be installed.")
|
||||
key = base64.b64decode(keyb64)[:16]
|
||||
aes = AES(key)
|
||||
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("{0:s} is DRM-free.".format(os.path.basename(inpath)))
|
||||
return 1
|
||||
for name in META_NAMES:
|
||||
namelist.remove(name)
|
||||
try:
|
||||
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) != 64:
|
||||
print("{0:s} is not a secure Barnes & Noble ePub.".format(os.path.basename(inpath)))
|
||||
return 1
|
||||
bookkey = aes.decrypt(base64.b64decode(bookkey))
|
||||
bookkey = bookkey[:-bookkey[-1]]
|
||||
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
|
||||
try:
|
||||
# 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
|
||||
except:
|
||||
pass
|
||||
outf.writestr(zi, inf.read('mimetype'))
|
||||
for path in namelist:
|
||||
data = inf.read(path)
|
||||
zi = ZipInfo(path)
|
||||
zi.compress_type=ZIP_DEFLATED
|
||||
try:
|
||||
# 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:
|
||||
pass
|
||||
outf.writestr(zi, decryptor.decrypt(path, data))
|
||||
except:
|
||||
print("Could not decrypt {0:s} because of an exception:\n{1:s}".format(os.path.basename(inpath), traceback.format_exc()))
|
||||
return 2
|
||||
return 0
|
||||
|
||||
|
||||
def cli_main():
|
||||
sys.stdout=SafeUnbuffered(sys.stdout)
|
||||
sys.stderr=SafeUnbuffered(sys.stderr)
|
||||
argv=unicode_argv()
|
||||
progname = os.path.basename(argv[0])
|
||||
if len(argv) != 4:
|
||||
print("usage: {0} <keyfile.b64> <inbook.epub> <outbook.epub>".format(progname))
|
||||
return 1
|
||||
keypath, inpath, outpath = argv[1:]
|
||||
userkey = open(keypath,'rb').read()
|
||||
result = decryptBook(userkey, inpath, outpath)
|
||||
if result == 0:
|
||||
print("Successfully decrypted {0:s} as {1:s}".format(os.path.basename(inpath),os.path.basename(outpath)))
|
||||
return result
|
||||
|
||||
def gui_main():
|
||||
try:
|
||||
import tkinter
|
||||
import tkinter.constants
|
||||
import tkinter.filedialog
|
||||
import tkinter.messagebox
|
||||
import traceback
|
||||
except:
|
||||
return cli_main()
|
||||
|
||||
class DecryptionDialog(tkinter.Frame):
|
||||
def __init__(self, root):
|
||||
tkinter.Frame.__init__(self, root, border=5)
|
||||
self.status = tkinter.Label(self, text="Select files for decryption")
|
||||
self.status.pack(fill=tkinter.constants.X, expand=1)
|
||||
body = tkinter.Frame(self)
|
||||
body.pack(fill=tkinter.constants.X, expand=1)
|
||||
sticky = tkinter.constants.E + tkinter.constants.W
|
||||
body.grid_columnconfigure(1, weight=2)
|
||||
tkinter.Label(body, text="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("bnepubkey.b64"):
|
||||
self.keypath.insert(0, "bnepubkey.b64")
|
||||
button = tkinter.Button(body, text="...", command=self.get_keypath)
|
||||
button.grid(row=0, column=2)
|
||||
tkinter.Label(body, text="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="...", command=self.get_inpath)
|
||||
button.grid(row=1, column=2)
|
||||
tkinter.Label(body, text="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="...", command=self.get_outpath)
|
||||
button.grid(row=2, column=2)
|
||||
buttons = tkinter.Frame(self)
|
||||
buttons.pack()
|
||||
botton = tkinter.Button(
|
||||
buttons, text="Decrypt", width=10, command=self.decrypt)
|
||||
botton.pack(side=tkinter.constants.LEFT)
|
||||
tkinter.Frame(buttons, width=10).pack(side=tkinter.constants.LEFT)
|
||||
button = tkinter.Button(
|
||||
buttons, text="Quit", width=10, command=self.quit)
|
||||
button.pack(side=tkinter.constants.RIGHT)
|
||||
|
||||
def get_keypath(self):
|
||||
keypath = tkinter.filedialog.askopenfilename(
|
||||
parent=None, title="Select Barnes & Noble \'.b64\' key file",
|
||||
defaultextension=".b64",
|
||||
filetypes=[('base64-encoded files', '.b64'),
|
||||
('All Files', '.*')])
|
||||
if keypath:
|
||||
keypath = os.path.normpath(keypath)
|
||||
self.keypath.delete(0, tkinter.constants.END)
|
||||
self.keypath.insert(0, keypath)
|
||||
return
|
||||
|
||||
def get_inpath(self):
|
||||
inpath = tkinter.filedialog.askopenfilename(
|
||||
parent=None, title="Select B&N-encrypted ePub file to decrypt",
|
||||
defaultextension=".epub", filetypes=[('ePub files', '.epub')])
|
||||
if inpath:
|
||||
inpath = os.path.normpath(inpath)
|
||||
self.inpath.delete(0, tkinter.constants.END)
|
||||
self.inpath.insert(0, inpath)
|
||||
return
|
||||
|
||||
def get_outpath(self):
|
||||
outpath = tkinter.filedialog.asksaveasfilename(
|
||||
parent=None, title="Select unencrypted ePub file to produce",
|
||||
defaultextension=".epub", filetypes=[('ePub files', '.epub')])
|
||||
if outpath:
|
||||
outpath = os.path.normpath(outpath)
|
||||
self.outpath.delete(0, tkinter.constants.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'] = "Specified key file does not exist"
|
||||
return
|
||||
if not inpath or not os.path.exists(inpath):
|
||||
self.status['text'] = "Specified input file does not exist"
|
||||
return
|
||||
if not outpath:
|
||||
self.status['text'] = "Output file not specified"
|
||||
return
|
||||
if inpath == outpath:
|
||||
self.status['text'] = "Must have different input and output files"
|
||||
return
|
||||
userkey = open(keypath,'rb').read()
|
||||
self.status['text'] = "Decrypting..."
|
||||
try:
|
||||
decrypt_status = decryptBook(userkey, inpath, outpath)
|
||||
except Exception as e:
|
||||
self.status['text'] = "Error: {0}".format(e.args[0])
|
||||
return
|
||||
if decrypt_status == 0:
|
||||
self.status['text'] = "File successfully decrypted"
|
||||
else:
|
||||
self.status['text'] = "The was an error decrypting the file."
|
||||
|
||||
root = tkinter.Tk()
|
||||
root.title("Barnes & Noble ePub Decrypter v.{0}".format(__version__))
|
||||
root.resizable(True, False)
|
||||
root.minsize(300, 0)
|
||||
DecryptionDialog(root).pack(fill=tkinter.constants.X, expand=1)
|
||||
root.mainloop()
|
||||
return 0
|
||||
|
||||
if __name__ == '__main__':
|
||||
if len(sys.argv) > 1:
|
||||
sys.exit(cli_main())
|
||||
sys.exit(gui_main())
|
@ -0,0 +1,68 @@
|
||||
'''
|
||||
Extracts the user's ccHash from an .adobe-digital-editions folder
|
||||
typically included in the Nook Android app's data folder.
|
||||
|
||||
Based on ignoblekeyWindowsStore.py, updated for Android by noDRM.
|
||||
'''
|
||||
|
||||
import sys
|
||||
import os
|
||||
import base64
|
||||
try:
|
||||
from Cryptodome.Cipher import AES
|
||||
except ImportError:
|
||||
from Crypto.Cipher import AES
|
||||
import hashlib
|
||||
from lxml import etree
|
||||
|
||||
def unpad(data, padding=16):
|
||||
if sys.version_info[0] == 2:
|
||||
pad_len = ord(data[-1])
|
||||
else:
|
||||
pad_len = data[-1]
|
||||
|
||||
return data[:-pad_len]
|
||||
|
||||
|
||||
PASS_HASH_SECRET = "9ca588496a1bc4394553d9e018d70b9e"
|
||||
|
||||
|
||||
def dump_keys(path_to_adobe_folder):
|
||||
|
||||
activation_path = os.path.join(path_to_adobe_folder, "activation.xml")
|
||||
device_path = os.path.join(path_to_adobe_folder, "device.xml")
|
||||
|
||||
if not os.path.isfile(activation_path):
|
||||
print("Nook activation file is missing: %s\n" % activation_path)
|
||||
return []
|
||||
if not os.path.isfile(device_path):
|
||||
print("Nook device file is missing: %s\n" % device_path)
|
||||
return []
|
||||
|
||||
# Load files:
|
||||
activation_xml = etree.parse(activation_path)
|
||||
device_xml = etree.parse(device_path)
|
||||
|
||||
# Get fingerprint:
|
||||
device_fingerprint = device_xml.findall(".//{http://ns.adobe.com/adept}fingerprint")[0].text
|
||||
device_fingerprint = base64.b64decode(device_fingerprint).hex()
|
||||
|
||||
hash_key = hashlib.sha1(bytearray.fromhex(device_fingerprint + PASS_HASH_SECRET)).digest()[:16]
|
||||
|
||||
hashes = []
|
||||
|
||||
for pass_hash in activation_xml.findall(".//{http://ns.adobe.com/adept}passHash"):
|
||||
try:
|
||||
encrypted_cc_hash = base64.b64decode(pass_hash.text)
|
||||
cc_hash = unpad(AES.new(hash_key, AES.MODE_CBC, encrypted_cc_hash[:16]).decrypt(encrypted_cc_hash[16:]))
|
||||
hashes.append(base64.b64encode(cc_hash).decode("ascii"))
|
||||
#print("Nook ccHash is %s" % (base64.b64encode(cc_hash).decode("ascii")))
|
||||
except:
|
||||
pass
|
||||
|
||||
return hashes
|
||||
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
print("No standalone version available.")
|
@ -0,0 +1,78 @@
|
||||
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
|
||||
|
||||
'''
|
||||
Obtain the user's ccHash from the Barnes & Noble Nook Windows Store app.
|
||||
https://www.microsoft.com/en-us/p/nook-books-magazines-newspapers-comics/9wzdncrfj33h
|
||||
(Requires a recent Windows version in a supported region (US).)
|
||||
This procedure has been tested with Nook app version 1.11.0.4 under Windows 11.
|
||||
|
||||
Based on experimental standalone python script created by fesiwi at
|
||||
https://github.com/noDRM/DeDRM_tools/discussions/9
|
||||
'''
|
||||
|
||||
import sys, os
|
||||
import apsw
|
||||
import base64
|
||||
import traceback
|
||||
try:
|
||||
from Cryptodome.Cipher import AES
|
||||
except:
|
||||
from Crypto.Cipher import AES
|
||||
import hashlib
|
||||
from lxml import etree
|
||||
|
||||
def unpad(data, padding=16):
|
||||
if sys.version_info[0] == 2:
|
||||
pad_len = ord(data[-1])
|
||||
else:
|
||||
pad_len = data[-1]
|
||||
|
||||
return data[:-pad_len]
|
||||
|
||||
|
||||
NOOK_DATA_FOLDER = "%LOCALAPPDATA%\\Packages\\BarnesNoble.Nook_ahnzqzva31enc\\LocalState"
|
||||
PASS_HASH_SECRET = "9ca588496a1bc4394553d9e018d70b9e"
|
||||
|
||||
|
||||
def dump_keys(print_result=False):
|
||||
db_filename = os.path.expandvars(NOOK_DATA_FOLDER + "\\NookDB.db3")
|
||||
|
||||
|
||||
if not os.path.isfile(db_filename):
|
||||
print("Database file not found. Is the Nook Windows Store app installed?")
|
||||
return []
|
||||
|
||||
|
||||
# Python2 has no fetchone() so we have to use fetchall() and discard everything but the first result.
|
||||
# There should only be one result anyways.
|
||||
serial_number = apsw.Connection(db_filename).cursor().execute(
|
||||
"SELECT value FROM bn_internal_key_value_table WHERE key = 'serialNumber';").fetchall()[0][0]
|
||||
|
||||
|
||||
hash_key = hashlib.sha1(bytearray.fromhex(serial_number + PASS_HASH_SECRET)).digest()[:16]
|
||||
|
||||
activation_file_name = os.path.expandvars(NOOK_DATA_FOLDER + "\\settings\\activation.xml")
|
||||
|
||||
if not os.path.isfile(activation_file_name):
|
||||
print("Activation file not found. Are you logged in to your Nook account?")
|
||||
return []
|
||||
|
||||
|
||||
activation_xml = etree.parse(activation_file_name)
|
||||
|
||||
decrypted_hashes = []
|
||||
|
||||
for pass_hash in activation_xml.findall(".//{http://ns.adobe.com/adept}passHash"):
|
||||
try:
|
||||
encrypted_cc_hash = base64.b64decode(pass_hash.text)
|
||||
cc_hash = unpad(AES.new(hash_key, AES.MODE_CBC, encrypted_cc_hash[:16]).decrypt(encrypted_cc_hash[16:]), 16)
|
||||
decrypted_hashes.append((base64.b64encode(cc_hash).decode("ascii")))
|
||||
if print_result:
|
||||
print("Nook ccHash is %s" % (base64.b64encode(cc_hash).decode("ascii")))
|
||||
except:
|
||||
traceback.print_exc()
|
||||
|
||||
return decrypted_hashes
|
||||
|
||||
if __name__ == "__main__":
|
||||
dump_keys(True)
|
@ -1,254 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# ignoblekeyfetch.py
|
||||
# Copyright © 2015-2020 Apprentice Harper et al.
|
||||
|
||||
# Released under the terms of the GNU General Public Licence, version 3
|
||||
# <http://www.gnu.org/licenses/>
|
||||
|
||||
# Based on discoveries by "Nobody You Know"
|
||||
# Code partly based on ignoblekeygen.py by several people.
|
||||
|
||||
# Windows users: Before running this program, you must first install Python.
|
||||
# We recommend ActiveState Python 2.7.X for Windows from
|
||||
# http://www.activestate.com/activepython/downloads.
|
||||
# Then save this script file as ignoblekeyfetch.pyw and double-click on it to run it.
|
||||
#
|
||||
# Mac OS X users: Save this script file as ignoblekeyfetch.pyw. You can run this
|
||||
# program from the command line (python ignoblekeyfetch.pyw) or by double-clicking
|
||||
# it when it has been associated with PythonLauncher.
|
||||
|
||||
# Revision history:
|
||||
# 1.0 - Initial version
|
||||
# 1.1 - Try second URL if first one fails
|
||||
# 2.0 - Python 3 for calibre 5.0
|
||||
|
||||
"""
|
||||
Fetch Barnes & Noble EPUB user key from B&N servers using email and password
|
||||
"""
|
||||
|
||||
__license__ = 'GPL v3'
|
||||
__version__ = "2.0"
|
||||
|
||||
import sys
|
||||
import os
|
||||
|
||||
# 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, str):
|
||||
data = data.encode(self.encoding,"replace")
|
||||
self.stream.buffer.write(data)
|
||||
self.stream.buffer.flush()
|
||||
|
||||
def __getattr__(self, attr):
|
||||
return getattr(self.stream, attr)
|
||||
|
||||
try:
|
||||
from calibre.constants import iswindows, isosx
|
||||
except:
|
||||
iswindows = sys.platform.startswith('win')
|
||||
isosx = sys.platform.startswith('darwin')
|
||||
|
||||
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 '?'. So use shell32.GetCommandLineArgvW to get sys.argv
|
||||
# as a list of Unicode strings and encode them as utf-8
|
||||
|
||||
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
|
||||
range(start, argc.value)]
|
||||
# if we don't have any arguments at all, just pass back script name
|
||||
# this should never happen
|
||||
return ["ignoblekeyfetch.py"]
|
||||
else:
|
||||
argvencoding = sys.stdin.encoding or "utf-8"
|
||||
return [arg if isinstance(arg, str) else str(arg, argvencoding) for arg in sys.argv]
|
||||
|
||||
|
||||
class IGNOBLEError(Exception):
|
||||
pass
|
||||
|
||||
def fetch_key(email, password):
|
||||
# change email and password to utf-8 if unicode
|
||||
if type(email)==str:
|
||||
email = email.encode('utf-8')
|
||||
if type(password)==str:
|
||||
password = password.encode('utf-8')
|
||||
|
||||
import random
|
||||
random = "%030x" % random.randrange(16**30)
|
||||
|
||||
import urllib.parse, urllib.request, re
|
||||
|
||||
# try the URL from nook for PC
|
||||
fetch_url = "https://cart4.barnesandnoble.com/services/service.aspx?Version=2&acctPassword="
|
||||
fetch_url += urllib.parse.quote(password,'')+"&devID=PC_BN_2.5.6.9575_"+random+"&emailAddress="
|
||||
fetch_url += urllib.parse.quote(email,"")+"&outFormat=5&schema=1&service=1&stage=deviceHashB"
|
||||
#print fetch_url
|
||||
|
||||
found = ''
|
||||
try:
|
||||
response = urllib.request.urlopen(fetch_url)
|
||||
the_page = response.read()
|
||||
#print the_page
|
||||
found = re.search('ccHash>(.+?)</ccHash', the_page).group(1)
|
||||
except:
|
||||
found = ''
|
||||
if len(found)!=28:
|
||||
# try the URL from android devices
|
||||
fetch_url = "https://cart4.barnesandnoble.com/services/service.aspx?Version=2&acctPassword="
|
||||
fetch_url += urllib.parse.quote(password,'')+"&devID=hobbes_9.3.50818_"+random+"&emailAddress="
|
||||
fetch_url += urllib.parse.quote(email,"")+"&outFormat=5&schema=1&service=1&stage=deviceHashB"
|
||||
#print fetch_url
|
||||
|
||||
found = ''
|
||||
try:
|
||||
response = urllib.request.urlopen(fetch_url)
|
||||
the_page = response.read()
|
||||
#print the_page
|
||||
found = re.search('ccHash>(.+?)</ccHash', the_page).group(1)
|
||||
except:
|
||||
found = ''
|
||||
|
||||
return found
|
||||
|
||||
|
||||
|
||||
|
||||
def cli_main():
|
||||
sys.stdout=SafeUnbuffered(sys.stdout)
|
||||
sys.stderr=SafeUnbuffered(sys.stderr)
|
||||
argv=unicode_argv()
|
||||
progname = os.path.basename(argv[0])
|
||||
if len(argv) != 4:
|
||||
print("usage: {0} <email> <password> <keyfileout.b64>".format(progname))
|
||||
return 1
|
||||
email, password, keypath = argv[1:]
|
||||
userkey = fetch_key(email, password)
|
||||
if len(userkey) == 28:
|
||||
open(keypath,'wb').write(userkey)
|
||||
return 0
|
||||
print("Failed to fetch key.")
|
||||
return 1
|
||||
|
||||
|
||||
def gui_main():
|
||||
try:
|
||||
import tkinter
|
||||
import tkinter.filedialog
|
||||
import tkinter.constants
|
||||
import tkinter.messagebox
|
||||
import traceback
|
||||
except:
|
||||
return cli_main()
|
||||
|
||||
class DecryptionDialog(tkinter.Frame):
|
||||
def __init__(self, root):
|
||||
tkinter.Frame.__init__(self, root, border=5)
|
||||
self.status = tkinter.Label(self, text="Enter parameters")
|
||||
self.status.pack(fill=tkinter.constants.X, expand=1)
|
||||
body = tkinter.Frame(self)
|
||||
body.pack(fill=tkinter.constants.X, expand=1)
|
||||
sticky = tkinter.constants.E + tkinter.constants.W
|
||||
body.grid_columnconfigure(1, weight=2)
|
||||
tkinter.Label(body, text="Account email address").grid(row=0)
|
||||
self.name = tkinter.Entry(body, width=40)
|
||||
self.name.grid(row=0, column=1, sticky=sticky)
|
||||
tkinter.Label(body, text="Account password").grid(row=1)
|
||||
self.ccn = tkinter.Entry(body, width=40)
|
||||
self.ccn.grid(row=1, column=1, sticky=sticky)
|
||||
tkinter.Label(body, text="Output file").grid(row=2)
|
||||
self.keypath = tkinter.Entry(body, width=40)
|
||||
self.keypath.grid(row=2, column=1, sticky=sticky)
|
||||
self.keypath.insert(2, "bnepubkey.b64")
|
||||
button = tkinter.Button(body, text="...", command=self.get_keypath)
|
||||
button.grid(row=2, column=2)
|
||||
buttons = tkinter.Frame(self)
|
||||
buttons.pack()
|
||||
botton = tkinter.Button(
|
||||
buttons, text="Fetch", width=10, command=self.generate)
|
||||
botton.pack(side=tkinter.constants.LEFT)
|
||||
tkinter.Frame(buttons, width=10).pack(side=tkinter.constants.LEFT)
|
||||
button = tkinter.Button(
|
||||
buttons, text="Quit", width=10, command=self.quit)
|
||||
button.pack(side=tkinter.constants.RIGHT)
|
||||
|
||||
def get_keypath(self):
|
||||
keypath = tkinter.filedialog.asksaveasfilename(
|
||||
parent=None, title="Select B&N ePub key file to produce",
|
||||
defaultextension=".b64",
|
||||
filetypes=[('base64-encoded files', '.b64'),
|
||||
('All Files', '.*')])
|
||||
if keypath:
|
||||
keypath = os.path.normpath(keypath)
|
||||
self.keypath.delete(0, tkinter.constants.END)
|
||||
self.keypath.insert(0, keypath)
|
||||
return
|
||||
|
||||
def generate(self):
|
||||
email = self.name.get()
|
||||
password = self.ccn.get()
|
||||
keypath = self.keypath.get()
|
||||
if not email:
|
||||
self.status['text'] = "Email address not given"
|
||||
return
|
||||
if not password:
|
||||
self.status['text'] = "Account password not given"
|
||||
return
|
||||
if not keypath:
|
||||
self.status['text'] = "Output keyfile path not set"
|
||||
return
|
||||
self.status['text'] = "Fetching..."
|
||||
try:
|
||||
userkey = fetch_key(email, password)
|
||||
except Exception as e:
|
||||
self.status['text'] = "Error: {0}".format(e.args[0])
|
||||
return
|
||||
if len(userkey) == 28:
|
||||
open(keypath,'wb').write(userkey)
|
||||
self.status['text'] = "Keyfile fetched successfully"
|
||||
else:
|
||||
self.status['text'] = "Keyfile fetch failed."
|
||||
|
||||
root = tkinter.Tk()
|
||||
root.title("Barnes & Noble ePub Keyfile Fetch v.{0}".format(__version__))
|
||||
root.resizable(True, False)
|
||||
root.minsize(300, 0)
|
||||
DecryptionDialog(root).pack(fill=tkinter.constants.X, expand=1)
|
||||
root.mainloop()
|
||||
return 0
|
||||
|
||||
if __name__ == '__main__':
|
||||
if len(sys.argv) > 1:
|
||||
sys.exit(cli_main())
|
||||
sys.exit(gui_main())
|
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,70 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# lcpdedrm.py
|
||||
# Copyright © 2021-2022 NoDRM
|
||||
|
||||
# Released under the terms of the GNU General Public Licence, version 3
|
||||
# <http://www.gnu.org/licenses/>
|
||||
|
||||
|
||||
# Revision history:
|
||||
# 1 - Initial release
|
||||
# 2 - LCP DRM code removed due to a DMCA takedown.
|
||||
|
||||
"""
|
||||
This file used to contain code to remove the Readium LCP DRM
|
||||
from eBooks. Unfortunately, Readium has issued a DMCA takedown
|
||||
request, so I was forced to remove that code:
|
||||
|
||||
https://github.com/github/dmca/blob/master/2022/01/2022-01-04-readium.md
|
||||
|
||||
This file now just returns an error message when asked to remove LCP DRM.
|
||||
For more information, see this issue:
|
||||
https://github.com/noDRM/DeDRM_tools/issues/18
|
||||
"""
|
||||
|
||||
__license__ = 'GPL v3'
|
||||
__version__ = "2"
|
||||
|
||||
import json
|
||||
from zipfile import ZipFile
|
||||
from contextlib import closing
|
||||
|
||||
|
||||
class LCPError(Exception):
|
||||
pass
|
||||
|
||||
# Check file to see if this is an LCP-protected file
|
||||
def isLCPbook(inpath):
|
||||
try:
|
||||
with closing(ZipFile(open(inpath, 'rb'))) as lcpbook:
|
||||
if ("META-INF/license.lcpl" not in lcpbook.namelist() or
|
||||
"META-INF/encryption.xml" not in lcpbook.namelist() or
|
||||
b"EncryptedContentKey" not in lcpbook.read("META-INF/encryption.xml")):
|
||||
return False
|
||||
|
||||
license = json.loads(lcpbook.read('META-INF/license.lcpl'))
|
||||
|
||||
if "id" in license and "encryption" in license and "profile" in license["encryption"]:
|
||||
return True
|
||||
|
||||
except:
|
||||
return False
|
||||
|
||||
return False
|
||||
|
||||
|
||||
# Takes a file and a list of passphrases
|
||||
def decryptLCPbook(inpath, passphrases, parent_object):
|
||||
|
||||
if not isLCPbook(inpath):
|
||||
raise LCPError("This is not an LCP-encrypted book")
|
||||
|
||||
print("LCP: LCP DRM removal no longer supported due to a DMCA takedown request.")
|
||||
print("LCP: The takedown request can be found here: ")
|
||||
print("LCP: https://github.com/github/dmca/blob/master/2022/01/2022-01-04-readium.md ")
|
||||
print("LCP: More information can be found in the Github repository: ")
|
||||
print("LCP: https://github.com/noDRM/DeDRM_tools/issues/18 ")
|
||||
|
||||
raise LCPError("LCP DRM removal no longer supported")
|
Binary file not shown.
Binary file not shown.
Binary file not shown.
@ -1,89 +0,0 @@
|
||||
#!/usr/bin/env python
|
||||
# vim:ts=4:sw=4:softtabstop=4:smarttab:expandtab
|
||||
|
||||
# implement just enough of des from openssl to make erdr2pml.py happy
|
||||
|
||||
def load_libcrypto():
|
||||
from ctypes import CDLL, POINTER, c_void_p, c_char_p, c_char, c_int, c_long, \
|
||||
Structure, c_ulong, create_string_buffer, cast
|
||||
from ctypes.util import find_library
|
||||
import sys
|
||||
|
||||
if sys.platform.startswith('win'):
|
||||
libcrypto = find_library('libeay32')
|
||||
else:
|
||||
libcrypto = find_library('crypto')
|
||||
|
||||
if libcrypto is None:
|
||||
return None
|
||||
|
||||
libcrypto = CDLL(libcrypto)
|
||||
|
||||
# typedef struct DES_ks
|
||||
# {
|
||||
# union
|
||||
# {
|
||||
# DES_cblock cblock;
|
||||
# /* make sure things are correct size on machines with
|
||||
# * 8 byte longs */
|
||||
# DES_LONG deslong[2];
|
||||
# } ks[16];
|
||||
# } DES_key_schedule;
|
||||
|
||||
# just create a big enough place to hold everything
|
||||
# it will have alignment of structure so we should be okay (16 byte aligned?)
|
||||
class DES_KEY_SCHEDULE(Structure):
|
||||
_fields_ = [('DES_cblock1', c_char * 16),
|
||||
('DES_cblock2', c_char * 16),
|
||||
('DES_cblock3', c_char * 16),
|
||||
('DES_cblock4', c_char * 16),
|
||||
('DES_cblock5', c_char * 16),
|
||||
('DES_cblock6', c_char * 16),
|
||||
('DES_cblock7', c_char * 16),
|
||||
('DES_cblock8', c_char * 16),
|
||||
('DES_cblock9', c_char * 16),
|
||||
('DES_cblock10', c_char * 16),
|
||||
('DES_cblock11', c_char * 16),
|
||||
('DES_cblock12', c_char * 16),
|
||||
('DES_cblock13', c_char * 16),
|
||||
('DES_cblock14', c_char * 16),
|
||||
('DES_cblock15', c_char * 16),
|
||||
('DES_cblock16', c_char * 16)]
|
||||
|
||||
DES_KEY_SCHEDULE_p = POINTER(DES_KEY_SCHEDULE)
|
||||
|
||||
def F(restype, name, argtypes):
|
||||
func = getattr(libcrypto, name)
|
||||
func.restype = restype
|
||||
func.argtypes = argtypes
|
||||
return func
|
||||
|
||||
DES_set_key = F(None, 'DES_set_key',[c_char_p, DES_KEY_SCHEDULE_p])
|
||||
DES_ecb_encrypt = F(None, 'DES_ecb_encrypt',[c_char_p, c_char_p, DES_KEY_SCHEDULE_p, c_int])
|
||||
|
||||
|
||||
class DES(object):
|
||||
def __init__(self, key):
|
||||
if len(key) != 8 :
|
||||
raise Exception('DES improper key used')
|
||||
return
|
||||
self.key = key
|
||||
self.keyschedule = DES_KEY_SCHEDULE()
|
||||
DES_set_key(self.key, self.keyschedule)
|
||||
def desdecrypt(self, data):
|
||||
ob = create_string_buffer(len(data))
|
||||
DES_ecb_encrypt(data, ob, self.keyschedule, 0)
|
||||
return ob.raw
|
||||
def decrypt(self, data):
|
||||
if not data:
|
||||
return b''
|
||||
i = 0
|
||||
result = []
|
||||
while i < len(data):
|
||||
block = data[i:i+8]
|
||||
processed_block = self.desdecrypt(block)
|
||||
result.append(processed_block)
|
||||
i += 8
|
||||
return b''.join(result)
|
||||
|
||||
return DES
|
@ -1,30 +0,0 @@
|
||||
#!/usr/bin/env python
|
||||
# vim:ts=4:sw=4:softtabstop=4:smarttab:expandtab
|
||||
|
||||
|
||||
def load_pycrypto():
|
||||
try :
|
||||
from Crypto.Cipher import DES as _DES
|
||||
except:
|
||||
return None
|
||||
|
||||
class DES(object):
|
||||
def __init__(self, key):
|
||||
if len(key) != 8 :
|
||||
raise ValueError('DES improper key used')
|
||||
self.key = key
|
||||
self._des = _DES.new(key,_DES.MODE_ECB)
|
||||
def desdecrypt(self, data):
|
||||
return self._des.decrypt(data)
|
||||
def decrypt(self, data):
|
||||
if not data:
|
||||
return ''
|
||||
i = 0
|
||||
result = []
|
||||
while i < len(data):
|
||||
block = data[i:i+8]
|
||||
processed_block = self.desdecrypt(block)
|
||||
result.append(processed_block)
|
||||
i += 8
|
||||
return ''.join(result)
|
||||
return DES
|
@ -1,220 +0,0 @@
|
||||
#!/usr/bin/env python
|
||||
# vim:ts=4:sw=4:softtabstop=4:smarttab:expandtab
|
||||
import sys
|
||||
|
||||
ECB = 0
|
||||
CBC = 1
|
||||
class Des(object):
|
||||
__pc1 = [56, 48, 40, 32, 24, 16, 8, 0, 57, 49, 41, 33, 25, 17,
|
||||
9, 1, 58, 50, 42, 34, 26, 18, 10, 2, 59, 51, 43, 35,
|
||||
62, 54, 46, 38, 30, 22, 14, 6, 61, 53, 45, 37, 29, 21,
|
||||
13, 5, 60, 52, 44, 36, 28, 20, 12, 4, 27, 19, 11, 3]
|
||||
__left_rotations = [1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1]
|
||||
__pc2 = [13, 16, 10, 23, 0, 4,2, 27, 14, 5, 20, 9,
|
||||
22, 18, 11, 3, 25, 7, 15, 6, 26, 19, 12, 1,
|
||||
40, 51, 30, 36, 46, 54, 29, 39, 50, 44, 32, 47,
|
||||
43, 48, 38, 55, 33, 52, 45, 41, 49, 35, 28, 31]
|
||||
__ip = [57, 49, 41, 33, 25, 17, 9, 1, 59, 51, 43, 35, 27, 19, 11, 3,
|
||||
61, 53, 45, 37, 29, 21, 13, 5, 63, 55, 47, 39, 31, 23, 15, 7,
|
||||
56, 48, 40, 32, 24, 16, 8, 0, 58, 50, 42, 34, 26, 18, 10, 2,
|
||||
60, 52, 44, 36, 28, 20, 12, 4, 62, 54, 46, 38, 30, 22, 14, 6]
|
||||
__expansion_table = [31, 0, 1, 2, 3, 4, 3, 4, 5, 6, 7, 8,
|
||||
7, 8, 9, 10, 11, 12,11, 12, 13, 14, 15, 16,
|
||||
15, 16, 17, 18, 19, 20,19, 20, 21, 22, 23, 24,
|
||||
23, 24, 25, 26, 27, 28,27, 28, 29, 30, 31, 0]
|
||||
__sbox = [[14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7,
|
||||
0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8,
|
||||
4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0,
|
||||
15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13],
|
||||
[15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10,
|
||||
3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5,
|
||||
0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15,
|
||||
13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9],
|
||||
[10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8,
|
||||
13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1,
|
||||
13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7,
|
||||
1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12],
|
||||
[7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15,
|
||||
13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9,
|
||||
10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4,
|
||||
3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14],
|
||||
[2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9,
|
||||
14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6,
|
||||
4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14,
|
||||
11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3],
|
||||
[12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11,
|
||||
10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8,
|
||||
9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6,
|
||||
4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13],
|
||||
[4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1,
|
||||
13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6,
|
||||
1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2,
|
||||
6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12],
|
||||
[13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7,
|
||||
1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2,
|
||||
7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8,
|
||||
2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11],]
|
||||
__p = [15, 6, 19, 20, 28, 11,27, 16, 0, 14, 22, 25,
|
||||
4, 17, 30, 9, 1, 7,23,13, 31, 26, 2, 8,18, 12, 29, 5, 21, 10,3, 24]
|
||||
__fp = [39, 7, 47, 15, 55, 23, 63, 31,38, 6, 46, 14, 54, 22, 62, 30,
|
||||
37, 5, 45, 13, 53, 21, 61, 29,36, 4, 44, 12, 52, 20, 60, 28,
|
||||
35, 3, 43, 11, 51, 19, 59, 27,34, 2, 42, 10, 50, 18, 58, 26,
|
||||
33, 1, 41, 9, 49, 17, 57, 25,32, 0, 40, 8, 48, 16, 56, 24]
|
||||
# Type of crypting being done
|
||||
ENCRYPT = 0x00
|
||||
DECRYPT = 0x01
|
||||
def __init__(self, key, mode=ECB, IV=None):
|
||||
if len(key) != 8:
|
||||
raise ValueError("Invalid DES key size. Key must be exactly 8 bytes long.")
|
||||
self.block_size = 8
|
||||
self.key_size = 8
|
||||
self.__padding = ''
|
||||
self.setMode(mode)
|
||||
if IV:
|
||||
self.setIV(IV)
|
||||
self.L = []
|
||||
self.R = []
|
||||
self.Kn = [ [0] * 48 ] * 16 # 16 48-bit keys (K1 - K16)
|
||||
self.final = []
|
||||
self.setKey(key)
|
||||
def getKey(self):
|
||||
return self.__key
|
||||
def setKey(self, key):
|
||||
self.__key = key
|
||||
self.__create_sub_keys()
|
||||
def getMode(self):
|
||||
return self.__mode
|
||||
def setMode(self, mode):
|
||||
self.__mode = mode
|
||||
def getIV(self):
|
||||
return self.__iv
|
||||
def setIV(self, IV):
|
||||
if not IV or len(IV) != self.block_size:
|
||||
raise ValueError("Invalid Initial Value (IV), must be a multiple of " + str(self.block_size) + " bytes")
|
||||
self.__iv = IV
|
||||
def getPadding(self):
|
||||
return self.__padding
|
||||
def __String_to_BitList(self, data):
|
||||
l = len(data) * 8
|
||||
result = [0] * l
|
||||
pos = 0
|
||||
for c in data:
|
||||
i = 7
|
||||
ch = ord(c)
|
||||
while i >= 0:
|
||||
if ch & (1 << i) != 0:
|
||||
result[pos] = 1
|
||||
else:
|
||||
result[pos] = 0
|
||||
pos += 1
|
||||
i -= 1
|
||||
return result
|
||||
def __BitList_to_String(self, data):
|
||||
result = ''
|
||||
pos = 0
|
||||
c = 0
|
||||
while pos < len(data):
|
||||
c += data[pos] << (7 - (pos % 8))
|
||||
if (pos % 8) == 7:
|
||||
result += chr(c)
|
||||
c = 0
|
||||
pos += 1
|
||||
return result
|
||||
def __permutate(self, table, block):
|
||||
return [block[x] for x in table]
|
||||
def __create_sub_keys(self):
|
||||
key = self.__permutate(Des.__pc1, self.__String_to_BitList(self.getKey()))
|
||||
i = 0
|
||||
self.L = key[:28]
|
||||
self.R = key[28:]
|
||||
while i < 16:
|
||||
j = 0
|
||||
while j < Des.__left_rotations[i]:
|
||||
self.L.append(self.L[0])
|
||||
del self.L[0]
|
||||
self.R.append(self.R[0])
|
||||
del self.R[0]
|
||||
j += 1
|
||||
self.Kn[i] = self.__permutate(Des.__pc2, self.L + self.R)
|
||||
i += 1
|
||||
def __des_crypt(self, block, crypt_type):
|
||||
block = self.__permutate(Des.__ip, block)
|
||||
self.L = block[:32]
|
||||
self.R = block[32:]
|
||||
if crypt_type == Des.ENCRYPT:
|
||||
iteration = 0
|
||||
iteration_adjustment = 1
|
||||
else:
|
||||
iteration = 15
|
||||
iteration_adjustment = -1
|
||||
i = 0
|
||||
while i < 16:
|
||||
tempR = self.R[:]
|
||||
self.R = self.__permutate(Des.__expansion_table, self.R)
|
||||
self.R = [x ^ y for x,y in zip(self.R, self.Kn[iteration])]
|
||||
B = [self.R[:6], self.R[6:12], self.R[12:18], self.R[18:24], self.R[24:30], self.R[30:36], self.R[36:42], self.R[42:]]
|
||||
j = 0
|
||||
Bn = [0] * 32
|
||||
pos = 0
|
||||
while j < 8:
|
||||
m = (B[j][0] << 1) + B[j][5]
|
||||
n = (B[j][1] << 3) + (B[j][2] << 2) + (B[j][3] << 1) + B[j][4]
|
||||
v = Des.__sbox[j][(m << 4) + n]
|
||||
Bn[pos] = (v & 8) >> 3
|
||||
Bn[pos + 1] = (v & 4) >> 2
|
||||
Bn[pos + 2] = (v & 2) >> 1
|
||||
Bn[pos + 3] = v & 1
|
||||
pos += 4
|
||||
j += 1
|
||||
self.R = self.__permutate(Des.__p, Bn)
|
||||
self.R = [x ^ y for x, y in zip(self.R, self.L)]
|
||||
self.L = tempR
|
||||
i += 1
|
||||
iteration += iteration_adjustment
|
||||
self.final = self.__permutate(Des.__fp, self.R + self.L)
|
||||
return self.final
|
||||
def crypt(self, data, crypt_type):
|
||||
if not data:
|
||||
return ''
|
||||
if len(data) % self.block_size != 0:
|
||||
if crypt_type == Des.DECRYPT: # Decryption must work on 8 byte blocks
|
||||
raise ValueError("Invalid data length, data must be a multiple of " + str(self.block_size) + " bytes\n.")
|
||||
if not self.getPadding():
|
||||
raise ValueError("Invalid data length, data must be a multiple of " + str(self.block_size) + " bytes\n. Try setting the optional padding character")
|
||||
else:
|
||||
data += (self.block_size - (len(data) % self.block_size)) * self.getPadding()
|
||||
if self.getMode() == CBC:
|
||||
if self.getIV():
|
||||
iv = self.__String_to_BitList(self.getIV())
|
||||
else:
|
||||
raise ValueError("For CBC mode, you must supply the Initial Value (IV) for ciphering")
|
||||
i = 0
|
||||
dict = {}
|
||||
result = []
|
||||
while i < len(data):
|
||||
block = self.__String_to_BitList(data[i:i+8])
|
||||
if self.getMode() == CBC:
|
||||
if crypt_type == Des.ENCRYPT:
|
||||
block = [x ^ y for x, y in zip(block, iv)]
|
||||
processed_block = self.__des_crypt(block, crypt_type)
|
||||
if crypt_type == Des.DECRYPT:
|
||||
processed_block = [x ^ y for x, y in zip(processed_block, iv)]
|
||||
iv = block
|
||||
else:
|
||||
iv = processed_block
|
||||
else:
|
||||
processed_block = self.__des_crypt(block, crypt_type)
|
||||
result.append(self.__BitList_to_String(processed_block))
|
||||
i += 8
|
||||
if crypt_type == Des.DECRYPT and self.getPadding():
|
||||
s = result[-1]
|
||||
while s[-1] == self.getPadding():
|
||||
s = s[:-1]
|
||||
result[-1] = s
|
||||
return ''.join(result)
|
||||
def encrypt(self, data, pad=''):
|
||||
self.__padding = pad
|
||||
return self.crypt(data, Des.ENCRYPT)
|
||||
def decrypt(self, data, pad=''):
|
||||
self.__padding = pad
|
||||
return self.crypt(data, Des.DECRYPT)
|
@ -1,27 +0,0 @@
|
||||
#!/usr/bin/env python
|
||||
# vim:ts=4:sw=4:softtabstop=4:smarttab:expandtab
|
||||
|
||||
import tkinter
|
||||
import tkinter.constants
|
||||
|
||||
# basic scrolled text widget
|
||||
class ScrolledText(tkinter.Text):
|
||||
def __init__(self, master=None, **kw):
|
||||
self.frame = tkinter.Frame(master)
|
||||
self.vbar = tkinter.Scrollbar(self.frame)
|
||||
self.vbar.pack(side=tkinter.constants.RIGHT, fill=tkinter.constants.Y)
|
||||
kw.update({'yscrollcommand': self.vbar.set})
|
||||
tkinter.Text.__init__(self, self.frame, **kw)
|
||||
self.pack(side=tkinter.constants.LEFT, fill=tkinter.constants.BOTH, expand=True)
|
||||
self.vbar['command'] = self.yview
|
||||
# Copy geometry methods of self.frame without overriding Text
|
||||
# methods = hack!
|
||||
text_meths = list(vars(tkinter.Text).keys())
|
||||
methods = list(vars(tkinter.Pack).keys()) + list(vars(tkinter.Grid).keys()) + list(vars(tkinter.Place).keys())
|
||||
methods = set(methods).difference(text_meths)
|
||||
for m in methods:
|
||||
if m[0] != '_' and m != 'config' and m != 'configure':
|
||||
setattr(self, m, getattr(self.frame, m))
|
||||
|
||||
def __str__(self):
|
||||
return str(self.frame)
|
@ -1,78 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
# vim:ts=4:sw=4:softtabstop=4:smarttab:expandtab
|
||||
|
||||
import sys
|
||||
import os, os.path
|
||||
import shutil
|
||||
|
||||
class SimplePrefsError(Exception):
|
||||
pass
|
||||
|
||||
class SimplePrefs(object):
|
||||
def __init__(self, target, description):
|
||||
self.prefs = {}
|
||||
self.key2file={}
|
||||
self.file2key={}
|
||||
for keyfilemap in description:
|
||||
[key, filename] = keyfilemap
|
||||
self.key2file[key] = filename
|
||||
self.file2key[filename] = key
|
||||
self.target = target + 'Prefs'
|
||||
if sys.platform.startswith('win'):
|
||||
import winreg
|
||||
regkey = winreg.OpenKey(winreg.HKEY_CURRENT_USER, "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders\\")
|
||||
path = winreg.QueryValueEx(regkey, 'Local AppData')[0]
|
||||
prefdir = path + os.sep + self.target
|
||||
elif sys.platform.startswith('darwin'):
|
||||
home = os.getenv('HOME')
|
||||
prefdir = os.path.join(home,'Library','Preferences','org.' + self.target)
|
||||
else:
|
||||
# linux and various flavors of unix
|
||||
home = os.getenv('HOME')
|
||||
prefdir = os.path.join(home,'.' + self.target)
|
||||
if not os.path.exists(prefdir):
|
||||
os.makedirs(prefdir)
|
||||
self.prefdir = prefdir
|
||||
self.prefs['dir'] = self.prefdir
|
||||
self._loadPreferences()
|
||||
|
||||
def _loadPreferences(self):
|
||||
filenames = os.listdir(self.prefdir)
|
||||
for filename in filenames:
|
||||
if filename in self.file2key:
|
||||
key = self.file2key[filename]
|
||||
filepath = os.path.join(self.prefdir,filename)
|
||||
if os.path.isfile(filepath):
|
||||
try :
|
||||
data = file(filepath,'rb').read()
|
||||
self.prefs[key] = data
|
||||
except Exception as e:
|
||||
pass
|
||||
|
||||
def getPreferences(self):
|
||||
return self.prefs
|
||||
|
||||
def setPreferences(self, newprefs={}):
|
||||
if 'dir' not in newprefs:
|
||||
raise SimplePrefsError('Error: Attempt to Set Preferences in unspecified directory')
|
||||
if newprefs['dir'] != self.prefs['dir']:
|
||||
raise SimplePrefsError('Error: Attempt to Set Preferences in unspecified directory')
|
||||
for key in newprefs:
|
||||
if key != 'dir':
|
||||
if key in self.key2file:
|
||||
filename = self.key2file[key]
|
||||
filepath = os.path.join(self.prefdir,filename)
|
||||
data = newprefs[key]
|
||||
if data != None:
|
||||
data = str(data)
|
||||
if data == None or data == '':
|
||||
if os.path.exists(filepath):
|
||||
os.remove(filepath)
|
||||
else:
|
||||
try:
|
||||
file(filepath,'wb').write(data)
|
||||
except Exception as e:
|
||||
pass
|
||||
self.prefs = newprefs
|
||||
return
|
@ -0,0 +1,278 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# CLI interface for the DeDRM plugin (useable without Calibre, too)
|
||||
|
||||
from __future__ import absolute_import, print_function
|
||||
|
||||
# Copyright © 2021 NoDRM
|
||||
|
||||
OPT_SHORT_TO_LONG = [
|
||||
["c", "config"],
|
||||
["e", "extract"],
|
||||
["f", "force"],
|
||||
["h", "help"],
|
||||
["i", "import"],
|
||||
["o", "output"],
|
||||
["p", "password"],
|
||||
["q", "quiet"],
|
||||
["t", "test"],
|
||||
["u", "username"],
|
||||
["v", "verbose"],
|
||||
]
|
||||
|
||||
#@@CALIBRE_COMPAT_CODE@@
|
||||
|
||||
import os, sys
|
||||
|
||||
|
||||
global _additional_data
|
||||
global _additional_params
|
||||
global _function
|
||||
_additional_data = []
|
||||
_additional_params = []
|
||||
_function = None
|
||||
|
||||
global config_file_path
|
||||
config_file_path = "dedrm.json"
|
||||
|
||||
def print_fname(f, info):
|
||||
print(" " + f.ljust(15) + " " + info)
|
||||
|
||||
def print_opt(short, long, info):
|
||||
if short is None:
|
||||
short = " "
|
||||
else:
|
||||
short = " -" + short
|
||||
|
||||
if long is None:
|
||||
long = " "
|
||||
else:
|
||||
long = "--" + long.ljust(16)
|
||||
|
||||
print(short + " " + long + " " + info, file=sys.stderr)
|
||||
|
||||
def print_std_usage(name, param_string):
|
||||
print("Usage: ", file=sys.stderr)
|
||||
if "calibre" in sys.modules:
|
||||
print(" calibre-debug -r \"DeDRM\" -- "+name+" " + param_string, file=sys.stderr)
|
||||
else:
|
||||
print(" python3 DeDRM_plugin.zip "+name+" "+param_string, file=sys.stderr)
|
||||
|
||||
def print_err_header():
|
||||
from __init__ import PLUGIN_NAME, PLUGIN_VERSION # type: ignore
|
||||
|
||||
print(PLUGIN_NAME + " v" + PLUGIN_VERSION + " - DRM removal plugin by noDRM")
|
||||
print()
|
||||
|
||||
def print_help():
|
||||
from __version import PLUGIN_NAME, PLUGIN_VERSION
|
||||
print(PLUGIN_NAME + " v" + PLUGIN_VERSION + " - DRM removal plugin by noDRM")
|
||||
print("Based on DeDRM Calibre plugin by Apprentice Harper, Apprentice Alf and others.")
|
||||
print("See https://github.com/noDRM/DeDRM_tools for more information.")
|
||||
print()
|
||||
if "calibre" in sys.modules:
|
||||
print("This plugin can be run through Calibre - like you are doing right now - ")
|
||||
print("but it can also be executed with a standalone Python interpreter.")
|
||||
else:
|
||||
print("This plugin can either be imported into Calibre, or be executed directly")
|
||||
print("through Python like you are doing right now.")
|
||||
print()
|
||||
print("Available functions:")
|
||||
print_fname("passhash", "Manage Adobe PassHashes")
|
||||
print_fname("remove_drm", "Remove DRM from one or multiple books")
|
||||
print()
|
||||
|
||||
# TODO: All parameters that are global should be listed here.
|
||||
|
||||
def print_credits():
|
||||
from __version import PLUGIN_NAME, PLUGIN_VERSION
|
||||
print(PLUGIN_NAME + " v" + PLUGIN_VERSION + " - Calibre DRM removal plugin by noDRM")
|
||||
print("Based on DeDRM Calibre plugin by Apprentice Harper, Apprentice Alf and others.")
|
||||
print("See https://github.com/noDRM/DeDRM_tools for more information.")
|
||||
print()
|
||||
print("Credits:")
|
||||
print(" - noDRM for the current release of the DeDRM plugin")
|
||||
print(" - Apprentice Alf and Apprentice Harper for the previous versions of the DeDRM plugin")
|
||||
print(" - The Dark Reverser for the Mobipocket and eReader script")
|
||||
print(" - i ♥ cabbages for the Adobe Digital Editions scripts")
|
||||
print(" - Skindle aka Bart Simpson for the Amazon Kindle for PC script")
|
||||
print(" - CMBDTC for Amazon Topaz DRM removal script")
|
||||
print(" - some_updates, clarknova and Bart Simpson for Amazon Topaz conversion scripts")
|
||||
print(" - DiapDealer for the first calibre plugin versions of the tools")
|
||||
print(" - some_updates, DiapDealer, Apprentice Alf and mdlnx for Amazon Kindle/Mobipocket tools")
|
||||
print(" - some_updates for the DeDRM all-in-one Python tool")
|
||||
print(" - Apprentice Alf for the DeDRM all-in-one AppleScript tool")
|
||||
|
||||
|
||||
def handle_single_argument(arg, next):
|
||||
used_up = 0
|
||||
global _additional_params
|
||||
global config_file_path
|
||||
|
||||
if arg in ["--username", "--password", "--output", "--outputdir"]:
|
||||
used_up = 1
|
||||
_additional_params.append(arg)
|
||||
if next is None or len(next) == 0:
|
||||
print_err_header()
|
||||
print("Missing parameter for argument " + arg, file=sys.stderr)
|
||||
sys.exit(1)
|
||||
else:
|
||||
_additional_params.append(next[0])
|
||||
|
||||
elif arg == "--config":
|
||||
if next is None or len(next) == 0:
|
||||
print_err_header()
|
||||
print("Missing parameter for argument " + arg, file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
config_file_path = next[0]
|
||||
used_up = 1
|
||||
|
||||
elif arg in ["--help", "--credits", "--verbose", "--quiet", "--extract", "--import", "--overwrite", "--force"]:
|
||||
_additional_params.append(arg)
|
||||
|
||||
|
||||
else:
|
||||
print_err_header()
|
||||
print("Unknown argument: " + arg, file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
# Used up 0 additional arguments
|
||||
return used_up
|
||||
|
||||
|
||||
|
||||
def handle_data(data):
|
||||
global _function
|
||||
global _additional_data
|
||||
|
||||
if _function is None:
|
||||
_function = str(data)
|
||||
else:
|
||||
_additional_data.append(str(data))
|
||||
|
||||
def execute_action(action, filenames, params):
|
||||
print("Executing '{0}' on file(s) {1} with parameters {2}".format(action, str(filenames), str(params)), file=sys.stderr)
|
||||
|
||||
if action == "help":
|
||||
print_help()
|
||||
sys.exit(0)
|
||||
|
||||
elif action == "passhash":
|
||||
from standalone.passhash import perform_action
|
||||
perform_action(params, filenames)
|
||||
|
||||
elif action == "remove_drm":
|
||||
if not os.path.isfile(os.path.abspath(config_file_path)):
|
||||
print("Config file missing ...")
|
||||
|
||||
from standalone.remove_drm import perform_action
|
||||
perform_action(params, filenames)
|
||||
|
||||
elif action == "config":
|
||||
import prefs
|
||||
config = prefs.DeDRM_Prefs(os.path.abspath(config_file_path))
|
||||
print(config["adeptkeys"])
|
||||
|
||||
else:
|
||||
print("Command '"+action+"' is unknown.", file=sys.stderr)
|
||||
|
||||
|
||||
def main(argv):
|
||||
arguments = argv
|
||||
skip_opts = False
|
||||
|
||||
# First element is always the ZIP name, remove that.
|
||||
if not arguments[0].lower().endswith(".zip") and not "calibre" in sys.modules:
|
||||
print("Warning: File name does not end in .zip ...")
|
||||
print(arguments)
|
||||
arguments.pop(0)
|
||||
|
||||
while len(arguments) > 0:
|
||||
arg = arguments.pop(0)
|
||||
|
||||
if arg == "--":
|
||||
skip_opts = True
|
||||
continue
|
||||
|
||||
if not skip_opts:
|
||||
if arg.startswith("--"):
|
||||
# Give the current arg, plus all remaining ones.
|
||||
# Return the number of additional args we used.
|
||||
used = handle_single_argument(arg, arguments)
|
||||
for _ in range(used):
|
||||
# Function returns number of additional arguments that were
|
||||
# "used up" by that argument.
|
||||
# Remove that amount of arguments from the list.
|
||||
try:
|
||||
arguments.pop(0)
|
||||
except:
|
||||
pass
|
||||
continue
|
||||
elif arg.startswith("-"):
|
||||
single_args = list(arg[1:])
|
||||
# single_args is now a list of single chars, for when you call the program like "ls -alR"
|
||||
# with multiple single-letter options combined.
|
||||
while len(single_args) > 0:
|
||||
c = single_args.pop(0)
|
||||
|
||||
# See if we have a long name for that option.
|
||||
for wrapper in OPT_SHORT_TO_LONG:
|
||||
if wrapper[0] == c:
|
||||
c = "--" + wrapper[1]
|
||||
break
|
||||
else:
|
||||
c = "-" + c
|
||||
# c is now the long term (unless there is no long version, then it's the short version).
|
||||
|
||||
if len(single_args) > 0:
|
||||
# If we have more short arguments, the argument for this one must be None.
|
||||
handle_single_argument(c, None)
|
||||
used = 0
|
||||
else:
|
||||
# If not, then there might be parameters for this short argument.
|
||||
used = handle_single_argument(c, arguments)
|
||||
|
||||
for _ in range(used):
|
||||
# Function returns number of additional arguments that were
|
||||
# "used up" by that argument.
|
||||
# Remove that amount of arguments from the list.
|
||||
try:
|
||||
arguments.pop(0)
|
||||
except:
|
||||
pass
|
||||
|
||||
continue
|
||||
|
||||
handle_data(arg)
|
||||
|
||||
|
||||
if _function is None and "--credits" in _additional_params:
|
||||
print_credits()
|
||||
sys.exit(0)
|
||||
|
||||
if _function is None and "--help" in _additional_params:
|
||||
print_help()
|
||||
sys.exit(0)
|
||||
|
||||
if _function is None:
|
||||
print_help()
|
||||
sys.exit(1)
|
||||
|
||||
# Okay, now actually begin doing stuff.
|
||||
# This function gets told what to do and gets additional data (filenames).
|
||||
# It also receives additional parameters.
|
||||
# The rest of the code will be in different Python files.
|
||||
execute_action(_function.lower(), _additional_data, _additional_params)
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
# NOTE: This MUST not do anything else other than calling main()
|
||||
# All the code must be in main(), not in here.
|
||||
import sys
|
||||
main(sys.argv)
|
@ -0,0 +1,140 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# CLI interface for the DeDRM plugin (useable without Calibre, too)
|
||||
# Config implementation
|
||||
|
||||
from __future__ import absolute_import, print_function
|
||||
|
||||
# Taken from Calibre code - Copyright © 2008, Kovid Goyal kovid@kovidgoyal.net, GPLv3
|
||||
|
||||
#@@CALIBRE_COMPAT_CODE@@
|
||||
|
||||
import sys, os, codecs, json
|
||||
|
||||
config_dir = "/"
|
||||
CONFIG_DIR_MODE = 0o700
|
||||
iswindows = sys.platform.startswith('win')
|
||||
|
||||
|
||||
filesystem_encoding = sys.getfilesystemencoding()
|
||||
if filesystem_encoding is None:
|
||||
filesystem_encoding = 'utf-8'
|
||||
else:
|
||||
try:
|
||||
if codecs.lookup(filesystem_encoding).name == 'ascii':
|
||||
filesystem_encoding = 'utf-8'
|
||||
# On linux, unicode arguments to os file functions are coerced to an ascii
|
||||
# bytestring if sys.getfilesystemencoding() == 'ascii', which is
|
||||
# just plain dumb. This is fixed by the icu.py module which, when
|
||||
# imported changes ascii to utf-8
|
||||
except Exception:
|
||||
filesystem_encoding = 'utf-8'
|
||||
|
||||
|
||||
class JSONConfig(dict):
|
||||
|
||||
EXTENSION = '.json'
|
||||
|
||||
|
||||
def __init__(self, rel_path_to_cf_file, base_path=config_dir):
|
||||
dict.__init__(self)
|
||||
self.no_commit = False
|
||||
self.defaults = {}
|
||||
self.file_path = os.path.join(base_path,
|
||||
*(rel_path_to_cf_file.split('/')))
|
||||
self.file_path = os.path.abspath(self.file_path)
|
||||
if not self.file_path.endswith(self.EXTENSION):
|
||||
self.file_path += self.EXTENSION
|
||||
|
||||
self.refresh()
|
||||
|
||||
def mtime(self):
|
||||
try:
|
||||
return os.path.getmtime(self.file_path)
|
||||
except OSError:
|
||||
return 0
|
||||
|
||||
def touch(self):
|
||||
try:
|
||||
os.utime(self.file_path, None)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def decouple(self, prefix):
|
||||
self.file_path = os.path.join(os.path.dirname(self.file_path), prefix + os.path.basename(self.file_path))
|
||||
self.refresh()
|
||||
|
||||
def refresh(self, clear_current=True):
|
||||
d = {}
|
||||
if os.path.exists(self.file_path):
|
||||
with open(self.file_path, "rb") as f:
|
||||
raw = f.read()
|
||||
try:
|
||||
d = self.raw_to_object(raw) if raw.strip() else {}
|
||||
except SystemError:
|
||||
pass
|
||||
except:
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
d = {}
|
||||
if clear_current:
|
||||
self.clear()
|
||||
self.update(d)
|
||||
|
||||
def has_key(self, key):
|
||||
return dict.__contains__(self, key)
|
||||
|
||||
def set(self, key, val):
|
||||
self.__setitem__(key, val)
|
||||
|
||||
def __delitem__(self, key):
|
||||
try:
|
||||
dict.__delitem__(self, key)
|
||||
except KeyError:
|
||||
pass # ignore missing keys
|
||||
else:
|
||||
self.commit()
|
||||
|
||||
def commit(self):
|
||||
if self.no_commit:
|
||||
return
|
||||
if hasattr(self, 'file_path') and self.file_path:
|
||||
dpath = os.path.dirname(self.file_path)
|
||||
if not os.path.exists(dpath):
|
||||
os.makedirs(dpath, mode=CONFIG_DIR_MODE)
|
||||
with open(self.file_path, "w") as f:
|
||||
raw = self.to_raw()
|
||||
f.seek(0)
|
||||
f.truncate()
|
||||
f.write(raw)
|
||||
|
||||
def __enter__(self):
|
||||
self.no_commit = True
|
||||
|
||||
def __exit__(self, *args):
|
||||
self.no_commit = False
|
||||
self.commit()
|
||||
|
||||
def raw_to_object(self, raw):
|
||||
return json.loads(raw)
|
||||
|
||||
def to_raw(self):
|
||||
return json.dumps(self, ensure_ascii=False)
|
||||
|
||||
def __getitem__(self, key):
|
||||
try:
|
||||
return dict.__getitem__(self, key)
|
||||
except KeyError:
|
||||
return self.defaults[key]
|
||||
|
||||
def get(self, key, default=None):
|
||||
try:
|
||||
return dict.__getitem__(self, key)
|
||||
except KeyError:
|
||||
return self.defaults.get(key, default)
|
||||
|
||||
def __setitem__(self, key, val):
|
||||
dict.__setitem__(self, key, val)
|
||||
self.commit()
|
@ -0,0 +1,122 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# CLI interface for the DeDRM plugin (useable without Calibre, too)
|
||||
# Adobe PassHash implementation
|
||||
|
||||
from __future__ import absolute_import, print_function
|
||||
|
||||
# Copyright © 2021 NoDRM
|
||||
|
||||
#@@CALIBRE_COMPAT_CODE@@
|
||||
|
||||
import os, sys
|
||||
|
||||
from standalone.__init__ import print_opt, print_std_usage
|
||||
|
||||
iswindows = sys.platform.startswith('win')
|
||||
isosx = sys.platform.startswith('darwin')
|
||||
|
||||
def print_passhash_help():
|
||||
from __version import PLUGIN_NAME, PLUGIN_VERSION
|
||||
print(PLUGIN_NAME + " v" + PLUGIN_VERSION + " - Calibre DRM removal plugin by noDRM")
|
||||
print()
|
||||
print("passhash: Manage Adobe PassHashes")
|
||||
print()
|
||||
print_std_usage("passhash", "[ -u username -p password | -b base64str ] [ -i ] ")
|
||||
|
||||
print()
|
||||
print("Options: ")
|
||||
print_opt("u", "username", "Generate a PassHash with the given username")
|
||||
print_opt("p", "password", "Generate a PassHash with the given password")
|
||||
print_opt("e", "extract", "Display PassHashes found on this machine")
|
||||
print_opt("i", "import", "Import hashes into the JSON config file")
|
||||
|
||||
def perform_action(params, files):
|
||||
user = None
|
||||
pwd = None
|
||||
|
||||
if len(params) == 0:
|
||||
print_passhash_help()
|
||||
return 0
|
||||
|
||||
extract = False
|
||||
import_to_json = True
|
||||
|
||||
while len(params) > 0:
|
||||
p = params.pop(0)
|
||||
if p == "--username":
|
||||
user = params.pop(0)
|
||||
elif p == "--password":
|
||||
pwd = params.pop(0)
|
||||
elif p == "--extract":
|
||||
extract = True
|
||||
elif p == "--help":
|
||||
print_passhash_help()
|
||||
return 0
|
||||
elif p == "--import":
|
||||
import_to_json = True
|
||||
|
||||
if not extract and not import_to_json:
|
||||
if user is None:
|
||||
print("Missing parameter: --username", file=sys.stderr)
|
||||
if pwd is None:
|
||||
print("Missing parameter: --password", file=sys.stderr)
|
||||
if user is None or pwd is None:
|
||||
return 1
|
||||
|
||||
if user is None and pwd is not None:
|
||||
print("Parameter --password also requires --username", file=sys.stderr)
|
||||
return 1
|
||||
if user is not None and pwd is None:
|
||||
print("Parameter --username also requires --password", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
if user is not None and pwd is not None:
|
||||
from ignoblekeyGenPassHash import generate_key
|
||||
key = generate_key(user, pwd)
|
||||
if import_to_json:
|
||||
# TODO: Import the key to the JSON
|
||||
pass
|
||||
|
||||
print(key.decode("utf-8"))
|
||||
|
||||
if extract or import_to_json:
|
||||
if not iswindows and not isosx:
|
||||
print("Extracting PassHash keys not supported on Linux.", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
keys = []
|
||||
|
||||
from ignoblekeyNookStudy import nookkeys
|
||||
keys.extend(nookkeys())
|
||||
|
||||
if iswindows:
|
||||
from ignoblekeyWindowsStore import dump_keys
|
||||
keys.extend(dump_keys())
|
||||
|
||||
from adobekey_get_passhash import passhash_keys
|
||||
ade_keys, ade_names = passhash_keys()
|
||||
keys.extend(ade_keys)
|
||||
|
||||
# Trim duplicates
|
||||
newkeys = []
|
||||
for k in keys:
|
||||
if not k in newkeys:
|
||||
newkeys.append(k)
|
||||
|
||||
# Print all found keys
|
||||
for k in newkeys:
|
||||
if import_to_json:
|
||||
# TODO: Add keys to json
|
||||
pass
|
||||
|
||||
if extract:
|
||||
print(k)
|
||||
|
||||
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
print("This code is not intended to be executed directly!", file=sys.stderr)
|
@ -0,0 +1,209 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# CLI interface for the DeDRM plugin (useable without Calibre, too)
|
||||
# DRM removal
|
||||
|
||||
from __future__ import absolute_import, print_function
|
||||
|
||||
# Copyright © 2021 NoDRM
|
||||
|
||||
#@@CALIBRE_COMPAT_CODE@@
|
||||
|
||||
import os, sys
|
||||
|
||||
from zipfile import ZipInfo, ZipFile, ZIP_STORED, ZIP_DEFLATED
|
||||
from contextlib import closing
|
||||
|
||||
from standalone.__init__ import print_opt, print_std_usage
|
||||
|
||||
iswindows = sys.platform.startswith('win')
|
||||
isosx = sys.platform.startswith('darwin')
|
||||
|
||||
def print_removedrm_help():
|
||||
from __init__ import PLUGIN_NAME, PLUGIN_VERSION
|
||||
print(PLUGIN_NAME + " v" + PLUGIN_VERSION + " - Calibre DRM removal plugin by noDRM")
|
||||
print()
|
||||
print("remove_drm: Remove DRM from one or multiple files")
|
||||
print()
|
||||
print_std_usage("remove_drm", "<filename> ... [ -o <filename> ] [ -f ]")
|
||||
|
||||
print()
|
||||
print("Options: ")
|
||||
print_opt(None, "outputdir", "Folder to export the file(s) to")
|
||||
print_opt("o", "output", "File name to export the file to")
|
||||
print_opt("f", "force", "Overwrite output file if it already exists")
|
||||
print_opt(None, "overwrite", "Replace DRMed file with DRM-free file (implies --force)")
|
||||
|
||||
|
||||
def determine_file_type(file):
|
||||
# Returns a file type:
|
||||
# "PDF", "PDB", "MOBI", "TPZ", "LCP", "ADEPT", "ADEPT-PassHash", "KFX-ZIP", "ZIP" or None
|
||||
|
||||
f = open(file, "rb")
|
||||
fdata = f.read(100)
|
||||
f.close()
|
||||
|
||||
if fdata.startswith(b"PK\x03\x04"):
|
||||
pass
|
||||
# Either LCP, Adobe, or Amazon
|
||||
elif fdata.startswith(b"%PDF"):
|
||||
return "PDF"
|
||||
elif fdata[0x3c:0x3c+8] == b"PNRdPPrs" or fdata[0x3c:0x3c+8] == b"PDctPPrs":
|
||||
return "PDB"
|
||||
elif fdata[0x3c:0x3c+8] == b"BOOKMOBI" or fdata[0x3c:0x3c+8] == b"TEXtREAd":
|
||||
return "MOBI"
|
||||
elif fdata.startswith(b"TPZ"):
|
||||
return "TPZ"
|
||||
else:
|
||||
return None
|
||||
# Unknown file type
|
||||
|
||||
|
||||
# If it's a ZIP, determine the type.
|
||||
|
||||
from lcpdedrm import isLCPbook
|
||||
if isLCPbook(file):
|
||||
return "LCP"
|
||||
|
||||
from ineptepub import adeptBook, isPassHashBook
|
||||
if adeptBook(file):
|
||||
if isPassHashBook(file):
|
||||
return "ADEPT-PassHash"
|
||||
else:
|
||||
return "ADEPT"
|
||||
|
||||
try:
|
||||
# Amazon / KFX-ZIP has a file that starts with b'\xeaDRMION\xee' in the ZIP.
|
||||
with closing(ZipFile(open(file, "rb"))) as book:
|
||||
for subfilename in book.namelist():
|
||||
with book.open(subfilename) as subfile:
|
||||
data = subfile.read(8)
|
||||
if data == b'\xeaDRMION\xee':
|
||||
return "KFX-ZIP"
|
||||
except:
|
||||
pass
|
||||
|
||||
return "ZIP"
|
||||
|
||||
|
||||
|
||||
|
||||
def dedrm_single_file(input_file, output_file):
|
||||
# When this runs, all the stupid file handling is done.
|
||||
# Just take the file at the absolute path "input_file"
|
||||
# and export it, DRM-free, to "output_file".
|
||||
|
||||
# Use a temp file as input_file and output_file
|
||||
# might be identical.
|
||||
|
||||
# The output directory might not exist yet.
|
||||
|
||||
print("File " + input_file + " to " + output_file)
|
||||
|
||||
# Okay, first check the file type and don't rely on the extension.
|
||||
try:
|
||||
ftype = determine_file_type(input_file)
|
||||
except:
|
||||
print("Can't determine file type for this file.")
|
||||
ftype = None
|
||||
|
||||
if ftype is None:
|
||||
return
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
def perform_action(params, files):
|
||||
output = None
|
||||
outputdir = None
|
||||
force = False
|
||||
overwrite_original = False
|
||||
|
||||
|
||||
if len(files) == 0:
|
||||
print_removedrm_help()
|
||||
return 0
|
||||
|
||||
while len(params) > 0:
|
||||
p = params.pop(0)
|
||||
if p == "--output":
|
||||
output = params.pop(0)
|
||||
elif p == "--outputdir":
|
||||
outputdir = params.pop(0)
|
||||
elif p == "--force":
|
||||
force = True
|
||||
elif p == "--overwrite":
|
||||
overwrite_original = True
|
||||
force = True
|
||||
elif p == "--help":
|
||||
print_removedrm_help()
|
||||
return 0
|
||||
|
||||
if overwrite_original and (output is not None or outputdir is not None):
|
||||
print("Can't use --overwrite together with --output or --outputdir.", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
if output is not None and os.path.isfile(output) and not force:
|
||||
print("Output file already exists. Use --force to overwrite.", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
|
||||
if output is not None and len(files) > 1:
|
||||
print("Cannot set output file name if there's multiple input files.", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
if outputdir is not None and output is not None and os.path.isabs(output):
|
||||
print("--output parameter is absolute path despite --outputdir being set.", file=sys.stderr)
|
||||
print("Remove --outputdir, or give a relative path to --output.", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
|
||||
|
||||
for file in files:
|
||||
|
||||
file = os.path.abspath(file)
|
||||
|
||||
if not os.path.isfile(file):
|
||||
print("Skipping file " + file + " - not found.", file=sys.stderr)
|
||||
continue
|
||||
|
||||
if overwrite_original:
|
||||
output_filename = file
|
||||
else:
|
||||
if output is not None:
|
||||
# Due to the check above, we DO only have one file here.
|
||||
if outputdir is not None and not os.path.isabs(output):
|
||||
output_filename = os.path.join(outputdir, output)
|
||||
else:
|
||||
output_filename = os.path.abspath(output)
|
||||
else:
|
||||
if outputdir is None:
|
||||
outputdir = os.getcwd()
|
||||
output_filename = os.path.join(outputdir, os.path.basename(file))
|
||||
output_filename = os.path.abspath(output_filename)
|
||||
|
||||
if output_filename == file:
|
||||
# If we export to the import folder, add a suffix to the file name.
|
||||
fn, f_ext = os.path.splitext(output_filename)
|
||||
output_filename = fn + "_nodrm" + f_ext
|
||||
|
||||
|
||||
|
||||
if os.path.isfile(output_filename) and not force:
|
||||
print("Skipping file " + file + " because output file already exists (use --force).", file=sys.stderr)
|
||||
continue
|
||||
|
||||
|
||||
|
||||
dedrm_single_file(file, output_filename)
|
||||
|
||||
|
||||
|
||||
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
print("This code is not intended to be executed directly!", file=sys.stderr)
|
@ -1,148 +0,0 @@
|
||||
#!/usr/bin/env python
|
||||
# vim:ts=4:sw=4:softtabstop=4:smarttab:expandtab
|
||||
|
||||
import os, sys
|
||||
import signal
|
||||
import threading
|
||||
import subprocess
|
||||
from subprocess import Popen, PIPE, STDOUT
|
||||
|
||||
# **heavily** chopped up and modfied version of asyncproc.py
|
||||
# to make it actually work on Windows as well as Mac/Linux
|
||||
# For the original see:
|
||||
# "http://www.lysator.liu.se/~bellman/download/"
|
||||
# author is "Thomas Bellman <bellman@lysator.liu.se>"
|
||||
# available under GPL version 3 or Later
|
||||
|
||||
# create an asynchronous subprocess whose output can be collected in
|
||||
# a non-blocking manner
|
||||
|
||||
# What a mess! Have to use threads just to get non-blocking io
|
||||
# in a cross-platform manner
|
||||
|
||||
# luckily all thread use is hidden within this class
|
||||
|
||||
class Process(object):
|
||||
def __init__(self, *params, **kwparams):
|
||||
if len(params) <= 3:
|
||||
kwparams.setdefault('stdin', subprocess.PIPE)
|
||||
if len(params) <= 4:
|
||||
kwparams.setdefault('stdout', subprocess.PIPE)
|
||||
if len(params) <= 5:
|
||||
kwparams.setdefault('stderr', subprocess.PIPE)
|
||||
self.__pending_input = []
|
||||
self.__collected_outdata = []
|
||||
self.__collected_errdata = []
|
||||
self.__exitstatus = None
|
||||
self.__lock = threading.Lock()
|
||||
self.__inputsem = threading.Semaphore(0)
|
||||
self.__quit = False
|
||||
|
||||
self.__process = subprocess.Popen(*params, **kwparams)
|
||||
|
||||
if self.__process.stdin:
|
||||
self.__stdin_thread = threading.Thread(
|
||||
name="stdin-thread",
|
||||
target=self.__feeder, args=(self.__pending_input,
|
||||
self.__process.stdin))
|
||||
self.__stdin_thread.setDaemon(True)
|
||||
self.__stdin_thread.start()
|
||||
|
||||
if self.__process.stdout:
|
||||
self.__stdout_thread = threading.Thread(
|
||||
name="stdout-thread",
|
||||
target=self.__reader, args=(self.__collected_outdata,
|
||||
self.__process.stdout))
|
||||
self.__stdout_thread.setDaemon(True)
|
||||
self.__stdout_thread.start()
|
||||
|
||||
if self.__process.stderr:
|
||||
self.__stderr_thread = threading.Thread(
|
||||
name="stderr-thread",
|
||||
target=self.__reader, args=(self.__collected_errdata,
|
||||
self.__process.stderr))
|
||||
self.__stderr_thread.setDaemon(True)
|
||||
self.__stderr_thread.start()
|
||||
|
||||
def pid(self):
|
||||
return self.__process.pid
|
||||
|
||||
def kill(self, signal):
|
||||
self.__process.send_signal(signal)
|
||||
|
||||
# check on subprocess (pass in 'nowait') to act like poll
|
||||
def wait(self, flag):
|
||||
if flag.lower() == 'nowait':
|
||||
rc = self.__process.poll()
|
||||
else:
|
||||
rc = self.__process.wait()
|
||||
if rc != None:
|
||||
if self.__process.stdin:
|
||||
self.closeinput()
|
||||
if self.__process.stdout:
|
||||
self.__stdout_thread.join()
|
||||
if self.__process.stderr:
|
||||
self.__stderr_thread.join()
|
||||
return self.__process.returncode
|
||||
|
||||
def terminate(self):
|
||||
if self.__process.stdin:
|
||||
self.closeinput()
|
||||
self.__process.terminate()
|
||||
|
||||
# thread gets data from subprocess stdout
|
||||
def __reader(self, collector, source):
|
||||
while True:
|
||||
data = os.read(source.fileno(), 65536)
|
||||
self.__lock.acquire()
|
||||
collector.append(data)
|
||||
self.__lock.release()
|
||||
if data == "":
|
||||
source.close()
|
||||
break
|
||||
return
|
||||
|
||||
# thread feeds data to subprocess stdin
|
||||
def __feeder(self, pending, drain):
|
||||
while True:
|
||||
self.__inputsem.acquire()
|
||||
self.__lock.acquire()
|
||||
if not pending and self.__quit:
|
||||
drain.close()
|
||||
self.__lock.release()
|
||||
break
|
||||
data = pending.pop(0)
|
||||
self.__lock.release()
|
||||
drain.write(data)
|
||||
|
||||
# non-blocking read of data from subprocess stdout
|
||||
def read(self):
|
||||
self.__lock.acquire()
|
||||
outdata = "".join(self.__collected_outdata)
|
||||
del self.__collected_outdata[:]
|
||||
self.__lock.release()
|
||||
return outdata
|
||||
|
||||
# non-blocking read of data from subprocess stderr
|
||||
def readerr(self):
|
||||
self.__lock.acquire()
|
||||
errdata = "".join(self.__collected_errdata)
|
||||
del self.__collected_errdata[:]
|
||||
self.__lock.release()
|
||||
return errdata
|
||||
|
||||
# non-blocking write to stdin of subprocess
|
||||
def write(self, data):
|
||||
if self.__process.stdin is None:
|
||||
raise ValueError("Writing to process with stdin not a pipe")
|
||||
self.__lock.acquire()
|
||||
self.__pending_input.append(data)
|
||||
self.__inputsem.release()
|
||||
self.__lock.release()
|
||||
|
||||
# close stdinput of subprocess
|
||||
def closeinput(self):
|
||||
self.__lock.acquire()
|
||||
self.__quit = True
|
||||
self.__inputsem.release()
|
||||
self.__lock.release()
|
@ -1,39 +1,49 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
from calibre_plugins.dedrm.ignoblekeygen import generate_key
|
||||
#@@CALIBRE_COMPAT_CODE@@
|
||||
|
||||
__license__ = 'GPL v3'
|
||||
import sys
|
||||
|
||||
DETAILED_MESSAGE = \
|
||||
'You have personal information stored in this plugin\'s customization '+ \
|
||||
'string from a previous version of this plugin.\n\n'+ \
|
||||
'This new version of the plugin can convert that info '+ \
|
||||
'into key data that the new plugin can then use (which doesn\'t '+ \
|
||||
'require personal information to be stored/displayed in an insecure '+ \
|
||||
'manner like the old plugin did).\n\nIf you choose NOT to migrate this data at this time '+ \
|
||||
'you will be prompted to save that personal data to a file elsewhere; and you\'ll have '+ \
|
||||
'to manually re-configure this plugin with your information.\n\nEither way... ' + \
|
||||
'this new version of the plugin will not be responsible for storing that personal '+ \
|
||||
'info in plain sight any longer.'
|
||||
__license__ = 'GPL v3'
|
||||
|
||||
def uStrCmp (s1, s2, caseless=False):
|
||||
import unicodedata as ud
|
||||
str1 = s1 if isinstance(s1, str) else str(s1)
|
||||
str2 = s2 if isinstance(s2, str) else str(s2)
|
||||
if sys.version_info[0] == 2:
|
||||
str1 = s1 if isinstance(s1, unicode) else unicode(s1)
|
||||
str2 = s2 if isinstance(s2, unicode) else unicode(s2)
|
||||
else:
|
||||
str1 = s1 if isinstance(s1, str) else str(s1)
|
||||
str2 = s2 if isinstance(s2, str) else str(s2)
|
||||
|
||||
if caseless:
|
||||
return ud.normalize('NFC', str1.lower()) == ud.normalize('NFC', str2.lower())
|
||||
else:
|
||||
return ud.normalize('NFC', str1) == ud.normalize('NFC', str2)
|
||||
|
||||
def parseCustString(keystuff):
|
||||
userkeys = []
|
||||
ar = keystuff.split(':')
|
||||
for i in ar:
|
||||
|
||||
|
||||
# Wrap a stream so that output gets flushed immediately
|
||||
# and also make sure that any unicode strings get safely
|
||||
# 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,str) or isinstance(data,unicode):
|
||||
# str for Python3, unicode for Python2
|
||||
data = data.encode(self.encoding,"replace")
|
||||
try:
|
||||
name, ccn = i.split(',')
|
||||
# Generate Barnes & Noble EPUB user key from name and credit card number.
|
||||
userkeys.append(generate_key(name, ccn))
|
||||
buffer = getattr(self.stream, 'buffer', self.stream)
|
||||
# self.stream.buffer for Python3, self.stream for Python2
|
||||
buffer.write(data)
|
||||
buffer.flush()
|
||||
except:
|
||||
pass
|
||||
return userkeys
|
||||
# We can do nothing if a write fails
|
||||
raise
|
||||
def __getattr__(self, attr):
|
||||
return getattr(self.stream, attr)
|
||||
|
@ -0,0 +1,30 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
|
||||
"""
|
||||
Python 3's "zipfile" has an annoying bug where the `external_attr` field
|
||||
of a ZIP file cannot be set to 0. However, if the original DRMed ZIP has
|
||||
that set to 0 then we want the DRM-free ZIP to have that as 0, too.
|
||||
See https://github.com/python/cpython/issues/87713
|
||||
|
||||
We cannot just set the "external_attr" to 0 as the code to save the ZIP
|
||||
resets that variable.
|
||||
|
||||
So, here's a class that inherits from ZipInfo and ensures that EVERY
|
||||
read access to that variable will return a 0 ...
|
||||
|
||||
"""
|
||||
|
||||
import zipfile
|
||||
|
||||
class ZeroedZipInfo(zipfile.ZipInfo):
|
||||
def __init__(self, zinfo):
|
||||
for k in self.__slots__:
|
||||
if hasattr(zinfo, k):
|
||||
setattr(self, k, getattr(zinfo, k))
|
||||
|
||||
def __getattribute__(self, name):
|
||||
if name == "external_attr":
|
||||
return 0
|
||||
return object.__getattribute__(self, name)
|
Loading…
Reference in New Issue