2020-09-27 04:54:49 -06:00
|
|
|
#!/usr/bin/env python3
|
2015-03-13 01:18:16 -06:00
|
|
|
# -*- coding: utf-8 -*-
|
2015-03-13 01:16:59 -06:00
|
|
|
|
2022-07-13 09:21:49 -06:00
|
|
|
# Version 10.0.3 July 2022
|
|
|
|
# Fix Calibre 6
|
|
|
|
#
|
2022-02-22 16:16:03 -07:00
|
|
|
# Version 10.0.1 February 2022
|
|
|
|
# Remove OpenSSL support to only support PyCryptodome; clean up the code.
|
|
|
|
#
|
2021-11-16 13:22:09 -07:00
|
|
|
# Version 10.0.0 November 2021
|
|
|
|
# Merge https://github.com/apprenticeharper/DeDRM_tools/pull/1691 to fix
|
|
|
|
# key fetch issues on some machines.
|
|
|
|
#
|
2021-02-07 19:21:03 -07:00
|
|
|
# Version 4.1.0 February 2021
|
|
|
|
# Add detection for Kobo directory location on Linux
|
2021-11-16 13:22:09 -07:00
|
|
|
#
|
2020-09-26 14:22:47 -06:00
|
|
|
# Version 4.0.0 September 2020
|
|
|
|
# Python 3.0
|
|
|
|
#
|
2016-12-20 23:33:34 -07:00
|
|
|
# Version 3.2.5 December 2016
|
|
|
|
# Improve detection of good text decryption.
|
|
|
|
#
|
2016-12-19 23:27:08 -07:00
|
|
|
# Version 3.2.4 December 2016
|
|
|
|
# Remove incorrect support for Kobo Desktop under Wine
|
|
|
|
#
|
2016-10-20 00:12:37 -06:00
|
|
|
# Version 3.2.3 October 2016
|
|
|
|
# Fix for windows network user and more xml fixes
|
|
|
|
#
|
2016-10-07 00:06:22 -06:00
|
|
|
# Version 3.2.2 October 2016
|
|
|
|
# Change to the way the new database version is handled.
|
|
|
|
#
|
2016-09-28 00:14:16 -06:00
|
|
|
# Version 3.2.1 September 2016
|
|
|
|
# Update for v4.0 of Windows Desktop app.
|
|
|
|
#
|
2016-01-14 10:15:43 -07:00
|
|
|
# Version 3.2.0 January 2016
|
2015-12-25 17:13:16 -07:00
|
|
|
# Update for latest version of Windows Desktop app.
|
2015-12-27 17:35:29 -07:00
|
|
|
# Support Kobo devices in the command line version.
|
2015-12-25 17:13:16 -07:00
|
|
|
#
|
2016-01-10 23:40:15 -07:00
|
|
|
# Version 3.1.9 November 2015
|
|
|
|
# Handle Kobo Desktop under wine on Linux
|
|
|
|
#
|
2015-10-29 01:47:49 -06:00
|
|
|
# Version 3.1.8 November 2015
|
|
|
|
# Handle the case of Kobo Arc or Vox device (i.e. don't crash).
|
|
|
|
#
|
2015-10-13 01:05:34 -06:00
|
|
|
# Version 3.1.7 October 2015
|
|
|
|
# Handle the case of no device or database more gracefully.
|
|
|
|
#
|
2015-09-30 00:39:29 -06:00
|
|
|
# Version 3.1.6 September 2015
|
|
|
|
# Enable support for Kobo devices
|
|
|
|
# More character encoding fixes (unicode strings)
|
|
|
|
#
|
2015-09-07 00:52:23 -06:00
|
|
|
# Version 3.1.5 September 2015
|
|
|
|
# Removed requirement that a purchase has been made.
|
2015-09-07 01:11:18 -06:00
|
|
|
# Also add in character encoding fixes
|
2015-09-07 00:52:23 -06:00
|
|
|
#
|
2015-09-03 00:49:09 -06:00
|
|
|
# Version 3.1.4 September 2015
|
|
|
|
# Updated for version 3.17 of the Windows Desktop app.
|
|
|
|
#
|
2015-08-04 11:18:44 -06:00
|
|
|
# Version 3.1.3 August 2015
|
|
|
|
# Add translations for Portuguese and Arabic
|
|
|
|
#
|
2015-03-13 01:18:16 -06:00
|
|
|
# Version 3.1.2 January 2015
|
|
|
|
# Add coding, version number and version announcement
|
|
|
|
#
|
2015-03-13 01:16:59 -06:00
|
|
|
# Version 3.05 October 2014
|
|
|
|
# Identifies DRM-free books in the dialog
|
|
|
|
#
|
|
|
|
# Version 3.04 September 2014
|
2015-03-13 01:18:16 -06:00
|
|
|
# Handles DRM-free books as well (sometimes Kobo Library doesn't
|
2015-03-13 01:16:59 -06:00
|
|
|
# show download link for DRM-free books)
|
|
|
|
#
|
|
|
|
# Version 3.03 August 2014
|
|
|
|
# If PyCrypto is unavailable try to use libcrypto for AES_ECB.
|
|
|
|
#
|
|
|
|
# Version 3.02 August 2014
|
|
|
|
# Relax checking of application/xhtml+xml and image/jpeg content.
|
|
|
|
#
|
|
|
|
# Version 3.01 June 2014
|
|
|
|
# Check image/jpeg as well as application/xhtml+xml content. Fix typo
|
|
|
|
# in Windows ipconfig parsing.
|
|
|
|
#
|
|
|
|
# Version 3.0 June 2014
|
|
|
|
# Made portable for Mac and Windows, and the only module dependency
|
|
|
|
# not part of python core is PyCrypto. Major code cleanup/rewrite.
|
|
|
|
# No longer tries the first MAC address; tries them all if it detects
|
|
|
|
# the decryption failed.
|
|
|
|
#
|
|
|
|
# Updated September 2013 by Anon
|
|
|
|
# Version 2.02
|
|
|
|
# Incorporated minor fixes posted at Apprentice Alf's.
|
|
|
|
#
|
|
|
|
# Updates July 2012 by Michael Newton
|
|
|
|
# PWSD ID is no longer a MAC address, but should always
|
|
|
|
# be stored in the registry. Script now works with OS X
|
|
|
|
# and checks plist for values instead of registry. Must
|
|
|
|
# have biplist installed for OS X support.
|
|
|
|
#
|
|
|
|
# Original comments left below; note the "AUTOPSY" is inaccurate. See
|
|
|
|
# KoboLibrary.userkeys and KoboFile.decrypt()
|
|
|
|
#
|
|
|
|
##########################################################
|
|
|
|
# KOBO DRM CRACK BY #
|
|
|
|
# PHYSISTICATED #
|
|
|
|
##########################################################
|
|
|
|
# This app was made for Python 2.7 on Windows 32-bit
|
|
|
|
#
|
|
|
|
# This app needs pycrypto - get from here:
|
|
|
|
# http://www.voidspace.org.uk/python/modules.shtml
|
|
|
|
#
|
|
|
|
# Usage: obok.py
|
|
|
|
# Choose the book you want to decrypt
|
|
|
|
#
|
|
|
|
# Shouts to my krew - you know who you are - and one in
|
|
|
|
# particular who gave me a lot of help with this - thank
|
|
|
|
# you so much!
|
|
|
|
#
|
|
|
|
# Kopimi /K\
|
|
|
|
# Keep sharing, keep copying, but remember that nothing is
|
|
|
|
# for free - make sure you compensate your favorite
|
|
|
|
# authors - and cut out the middle man whenever possible
|
|
|
|
# ;) ;) ;)
|
|
|
|
#
|
|
|
|
# DRM AUTOPSY
|
|
|
|
# The Kobo DRM was incredibly easy to crack, but it took
|
|
|
|
# me months to get around to making this. Here's the
|
|
|
|
# basics of how it works:
|
|
|
|
# 1: Get MAC address of first NIC in ipconfig (sometimes
|
|
|
|
# stored in registry as pwsdid)
|
|
|
|
# 2: Get user ID (stored in tons of places, this gets it
|
|
|
|
# from HKEY_CURRENT_USER\Software\Kobo\Kobo Desktop
|
|
|
|
# Edition\Browser\cookies)
|
|
|
|
# 3: Concatenate and SHA256, take the second half - this
|
|
|
|
# is your master key
|
|
|
|
# 4: Open %LOCALAPPDATA%\Kobo Desktop Editions\Kobo.sqlite
|
|
|
|
# and dump content_keys
|
|
|
|
# 5: Unbase64 the keys, then decode these with the master
|
|
|
|
# key - these are your page keys
|
|
|
|
# 6: Unzip EPUB of your choice, decrypt each page with its
|
|
|
|
# page key, then zip back up again
|
|
|
|
#
|
|
|
|
# WHY USE THIS WHEN INEPT WORKS FINE? (adobe DRM stripper)
|
|
|
|
# Inept works very well, but authors on Kobo can choose
|
|
|
|
# what DRM they want to use - and some have chosen not to
|
|
|
|
# let people download them with Adobe Digital Editions -
|
|
|
|
# they would rather lock you into a single platform.
|
|
|
|
#
|
|
|
|
# With Obok, you can sync Kobo Desktop, decrypt all your
|
|
|
|
# ebooks, and then use them on whatever device you want
|
|
|
|
# - you bought them, you own them, you can do what you
|
|
|
|
# like with them.
|
|
|
|
#
|
|
|
|
# Obok is Kobo backwards, but it is also means "next to"
|
|
|
|
# in Polish.
|
|
|
|
# When you buy a real book, it is right next to you. You
|
|
|
|
# can read it at home, at work, on a train, you can lend
|
|
|
|
# it to a friend, you can scribble on it, and add your own
|
|
|
|
# explanations/translations.
|
|
|
|
#
|
|
|
|
# Obok gives you this power over your ebooks - no longer
|
|
|
|
# are you restricted to one device. This allows you to
|
|
|
|
# embed foreign fonts into your books, as older Kobo's
|
|
|
|
# can't display them properly. You can read your books
|
|
|
|
# on your phones, in different PC readers, and different
|
|
|
|
# ereader devices. You can share them with your friends
|
|
|
|
# too, if you like - you can do that with a real book
|
|
|
|
# after all.
|
|
|
|
#
|
|
|
|
"""Manage all Kobo books, either encrypted or DRM-free."""
|
2019-06-24 10:49:38 -06:00
|
|
|
from __future__ import print_function
|
2015-03-13 01:18:16 -06:00
|
|
|
|
2023-08-01 23:39:35 -06:00
|
|
|
__version__ = '10.0.9'
|
|
|
|
__about__ = "Obok v{0}\nCopyright © 2012-2023 Physisticated et al.".format(__version__)
|
2015-03-13 01:18:16 -06:00
|
|
|
|
2015-03-13 01:16:59 -06:00
|
|
|
import sys
|
|
|
|
import os
|
|
|
|
import subprocess
|
2016-10-07 00:06:22 -06:00
|
|
|
import sqlite3
|
2015-03-13 01:16:59 -06:00
|
|
|
import base64
|
|
|
|
import binascii
|
|
|
|
import re
|
|
|
|
import zipfile
|
|
|
|
import hashlib
|
|
|
|
import xml.etree.ElementTree as ET
|
|
|
|
import string
|
|
|
|
import shutil
|
2015-12-27 17:35:29 -07:00
|
|
|
import argparse
|
2016-10-07 00:06:22 -06:00
|
|
|
import tempfile
|
2015-12-27 17:35:29 -07:00
|
|
|
|
2022-02-22 16:16:03 -07:00
|
|
|
try:
|
|
|
|
from Cryptodome.Cipher import AES
|
|
|
|
except ImportError:
|
|
|
|
from Crypto.Cipher import AES
|
2022-03-19 03:14:45 -06:00
|
|
|
|
|
|
|
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]
|
|
|
|
|
2022-02-22 16:16:03 -07:00
|
|
|
|
2015-12-27 17:35:29 -07:00
|
|
|
can_parse_xml = True
|
|
|
|
try:
|
|
|
|
from xml.etree import ElementTree as ET
|
2020-09-27 04:54:49 -06:00
|
|
|
# print "using xml.etree for xml parsing"
|
2015-12-27 17:35:29 -07:00
|
|
|
except ImportError:
|
|
|
|
can_parse_xml = False
|
2020-09-27 04:54:49 -06:00
|
|
|
# print "Cannot find xml.etree, disabling extraction of serial numbers"
|
2015-03-13 01:16:59 -06:00
|
|
|
|
2015-12-25 17:13:16 -07:00
|
|
|
# List of all known hash keys
|
2016-09-28 00:14:16 -06:00
|
|
|
KOBO_HASH_KEYS = ['88b3a2e13', 'XzUhGYdFp', 'NoCanLook','QJhwzAtXL']
|
2015-12-25 17:13:16 -07:00
|
|
|
|
2015-03-13 01:16:59 -06:00
|
|
|
class ENCRYPTIONError(Exception):
|
|
|
|
pass
|
|
|
|
|
2015-09-07 01:11:18 -06:00
|
|
|
# Wrap a stream so that output gets flushed immediately
|
|
|
|
# and also make sure that any unicode strings get
|
|
|
|
# encoded using "replace" before writing them.
|
|
|
|
class SafeUnbuffered:
|
|
|
|
def __init__(self, stream):
|
|
|
|
self.stream = stream
|
|
|
|
self.encoding = stream.encoding
|
|
|
|
if self.encoding == None:
|
|
|
|
self.encoding = "utf-8"
|
|
|
|
def write(self, data):
|
2022-08-06 11:57:20 -06:00
|
|
|
if isinstance(data,str) or isinstance(data,unicode):
|
|
|
|
# str for Python3, unicode for Python2
|
2015-09-07 01:11:18 -06:00
|
|
|
data = data.encode(self.encoding,"replace")
|
2022-08-06 11:57:20 -06:00
|
|
|
try:
|
|
|
|
buffer = getattr(self.stream, 'buffer', self.stream)
|
|
|
|
# self.stream.buffer for Python3, self.stream for Python2
|
|
|
|
buffer.write(data)
|
|
|
|
buffer.flush()
|
|
|
|
except:
|
|
|
|
# We can do nothing if a write fails
|
|
|
|
raise
|
2015-09-07 01:11:18 -06:00
|
|
|
def __getattr__(self, attr):
|
|
|
|
return getattr(self.stream, attr)
|
|
|
|
|
|
|
|
|
2015-03-13 01:16:59 -06:00
|
|
|
class KoboLibrary(object):
|
|
|
|
"""The Kobo library.
|
|
|
|
|
|
|
|
This class represents all the information available from the data
|
|
|
|
written by the Kobo Desktop Edition application, including the list
|
|
|
|
of books, their titles, and the user's encryption key(s)."""
|
|
|
|
|
2019-07-05 21:01:28 -06:00
|
|
|
def __init__ (self, serials = [], device_path = None, desktopkobodir = u""):
|
2019-06-24 10:49:38 -06:00
|
|
|
print(__about__)
|
2015-09-30 00:39:29 -06:00
|
|
|
self.kobodir = u""
|
|
|
|
kobodb = u""
|
2015-09-17 18:10:06 -06:00
|
|
|
|
2015-12-27 17:35:29 -07:00
|
|
|
# Order of checks
|
|
|
|
# 1. first check if a device_path has been passed in, and whether
|
|
|
|
# we can find the sqlite db in the respective place
|
|
|
|
# 2. if 1., and we got some serials passed in (from saved
|
|
|
|
# settings in calibre), just use it
|
|
|
|
# 3. if 1. worked, but we didn't get serials, try to parse them
|
|
|
|
# from the device, if this didn't work, unset everything
|
|
|
|
# 4. if by now we don't have kobodir set, give up on device and
|
|
|
|
# try to use the Desktop app.
|
|
|
|
|
|
|
|
# step 1. check whether this looks like a real device
|
|
|
|
if (device_path):
|
|
|
|
# we got a device path
|
2020-09-27 04:54:49 -06:00
|
|
|
self.kobodir = os.path.join(device_path, ".kobo")
|
2015-09-17 18:10:06 -06:00
|
|
|
# devices use KoboReader.sqlite
|
2020-09-27 04:54:49 -06:00
|
|
|
kobodb = os.path.join(self.kobodir, "KoboReader.sqlite")
|
2015-10-07 19:59:34 -06:00
|
|
|
if (not(os.path.isfile(kobodb))):
|
2015-12-27 17:35:29 -07:00
|
|
|
# device path seems to be wrong, unset it
|
|
|
|
device_path = u""
|
2015-09-30 00:39:29 -06:00
|
|
|
self.kobodir = u""
|
|
|
|
kobodb = u""
|
2015-09-17 18:10:06 -06:00
|
|
|
|
2015-12-27 17:35:29 -07:00
|
|
|
if (self.kobodir):
|
|
|
|
# step 3. we found a device but didn't get serials, try to get them
|
|
|
|
if (len(serials) == 0):
|
|
|
|
# we got a device path but no saved serial
|
|
|
|
# try to get the serial from the device
|
2020-09-27 04:54:49 -06:00
|
|
|
# print "get_device_settings - device_path = {0}".format(device_path)
|
2015-12-27 17:35:29 -07:00
|
|
|
# get serial from device_path/.adobe-digital-editions/device.xml
|
|
|
|
if can_parse_xml:
|
|
|
|
devicexml = os.path.join(device_path, '.adobe-digital-editions', 'device.xml')
|
2020-09-27 04:54:49 -06:00
|
|
|
# print "trying to load {0}".format(devicexml)
|
2015-12-27 17:35:29 -07:00
|
|
|
if (os.path.exists(devicexml)):
|
2020-09-27 04:54:49 -06:00
|
|
|
# print "trying to parse {0}".format(devicexml)
|
2015-12-27 17:35:29 -07:00
|
|
|
xmltree = ET.parse(devicexml)
|
|
|
|
for node in xmltree.iter():
|
|
|
|
if "deviceSerial" in node.tag:
|
|
|
|
serial = node.text
|
2020-09-27 04:54:49 -06:00
|
|
|
# print "found serial {0}".format(serial)
|
2015-12-27 17:35:29 -07:00
|
|
|
serials.append(serial)
|
|
|
|
break
|
|
|
|
else:
|
2020-09-27 04:54:49 -06:00
|
|
|
# print "cannot get serials from device."
|
2015-12-27 17:35:29 -07:00
|
|
|
device_path = u""
|
|
|
|
self.kobodir = u""
|
|
|
|
kobodb = u""
|
|
|
|
|
2015-09-30 00:39:29 -06:00
|
|
|
if (self.kobodir == u""):
|
2015-12-27 17:35:29 -07:00
|
|
|
# step 4. we haven't found a device with serials, so try desktop apps
|
2019-07-05 21:01:28 -06:00
|
|
|
if desktopkobodir != u'':
|
|
|
|
self.kobodir = desktopkobodir
|
|
|
|
|
|
|
|
if (self.kobodir == u""):
|
|
|
|
if sys.platform.startswith('win'):
|
2021-02-24 18:54:39 -07:00
|
|
|
try:
|
|
|
|
import winreg
|
|
|
|
except ImportError:
|
|
|
|
import _winreg as winreg
|
2019-07-05 21:01:28 -06:00
|
|
|
if sys.getwindowsversion().major > 5:
|
|
|
|
if 'LOCALAPPDATA' in os.environ.keys():
|
|
|
|
# Python 2.x does not return unicode env. Use Python 3.x
|
2022-12-29 11:58:29 -07:00
|
|
|
if sys.version_info[0] == 2:
|
|
|
|
self.kobodir = winreg.ExpandEnvironmentStrings(u"%LOCALAPPDATA%")
|
|
|
|
else:
|
|
|
|
self.kobodir = winreg.ExpandEnvironmentStrings("%LOCALAPPDATA%")
|
2019-07-05 21:01:28 -06:00
|
|
|
if (self.kobodir == u""):
|
|
|
|
if 'USERPROFILE' in os.environ.keys():
|
|
|
|
# Python 2.x does not return unicode env. Use Python 3.x
|
2022-12-29 11:58:29 -07:00
|
|
|
if sys.version_info[0] == 2:
|
|
|
|
self.kobodir = os.path.join(winreg.ExpandEnvironmentStrings(u"%USERPROFILE%"), "Local Settings", "Application Data")
|
|
|
|
else:
|
|
|
|
self.kobodir = os.path.join(winreg.ExpandEnvironmentStrings("%USERPROFILE%"), "Local Settings", "Application Data")
|
2020-09-27 04:54:49 -06:00
|
|
|
self.kobodir = os.path.join(self.kobodir, "Kobo", "Kobo Desktop Edition")
|
2019-07-05 21:01:28 -06:00
|
|
|
elif sys.platform.startswith('darwin'):
|
2020-09-27 04:54:49 -06:00
|
|
|
self.kobodir = os.path.join(os.environ['HOME'], "Library", "Application Support", "Kobo", "Kobo Desktop Edition")
|
2021-02-07 19:21:03 -07:00
|
|
|
elif sys.platform.startswith('linux'):
|
|
|
|
|
|
|
|
#sets ~/.config/calibre as the location to store the kobodir location info file and creates this directory if necessary
|
|
|
|
kobodir_cache_dir = os.path.join(os.environ['HOME'], ".config", "calibre")
|
|
|
|
if not os.path.isdir(kobodir_cache_dir):
|
|
|
|
os.mkdir(kobodir_cache_dir)
|
|
|
|
|
|
|
|
#appends the name of the file we're storing the kobodir location info to the above path
|
|
|
|
kobodir_cache_file = str(kobodir_cache_dir) + "/" + "kobo location"
|
|
|
|
|
|
|
|
"""if the above file does not exist, recursively searches from the root
|
|
|
|
of the filesystem until kobodir is found and stores the location of kobodir
|
|
|
|
in that file so this loop can be skipped in the future"""
|
|
|
|
original_stdout = sys.stdout
|
|
|
|
if not os.path.isfile(kobodir_cache_file):
|
|
|
|
for root, dirs, files in os.walk('/'):
|
|
|
|
for file in files:
|
|
|
|
if file == 'Kobo.sqlite':
|
|
|
|
kobo_linux_path = str(root)
|
|
|
|
with open(kobodir_cache_file, 'w') as f:
|
|
|
|
sys.stdout = f
|
|
|
|
print(kobo_linux_path, end='')
|
|
|
|
sys.stdout = original_stdout
|
|
|
|
|
|
|
|
f = open(kobodir_cache_file, 'r' )
|
|
|
|
self.kobodir = f.read()
|
|
|
|
|
2015-09-17 18:10:06 -06:00
|
|
|
# desktop versions use Kobo.sqlite
|
2020-09-27 04:54:49 -06:00
|
|
|
kobodb = os.path.join(self.kobodir, "Kobo.sqlite")
|
2015-10-07 19:59:34 -06:00
|
|
|
# check for existence of file
|
|
|
|
if (not(os.path.isfile(kobodb))):
|
|
|
|
# give up here, we haven't found anything useful
|
|
|
|
self.kobodir = u""
|
|
|
|
kobodb = u""
|
|
|
|
|
2015-09-30 00:39:29 -06:00
|
|
|
if (self.kobodir != u""):
|
2020-09-27 04:54:49 -06:00
|
|
|
self.bookdir = os.path.join(self.kobodir, "kepub")
|
2016-10-07 00:06:22 -06:00
|
|
|
# make a copy of the database in a temporary file
|
|
|
|
# so we can ensure it's not using WAL logging which sqlite3 can't do.
|
|
|
|
self.newdb = tempfile.NamedTemporaryFile(mode='wb', delete=False)
|
2019-06-24 10:49:38 -06:00
|
|
|
print(self.newdb.name)
|
2016-10-07 00:06:22 -06:00
|
|
|
olddb = open(kobodb, 'rb')
|
|
|
|
self.newdb.write(olddb.read(18))
|
2020-09-26 14:22:47 -06:00
|
|
|
self.newdb.write(b'\x01\x01')
|
2016-10-07 00:06:22 -06:00
|
|
|
olddb.read(2)
|
|
|
|
self.newdb.write(olddb.read())
|
|
|
|
olddb.close()
|
|
|
|
self.newdb.close()
|
|
|
|
self.__sqlite = sqlite3.connect(self.newdb.name)
|
2022-01-29 23:23:23 -07:00
|
|
|
self.__sqlite.text_factory = lambda b: b.decode("utf-8", errors="ignore")
|
2015-09-16 08:01:29 -06:00
|
|
|
self.__cursor = self.__sqlite.cursor()
|
|
|
|
self._userkeys = []
|
|
|
|
self._books = []
|
|
|
|
self._volumeID = []
|
|
|
|
self._serials = serials
|
2015-03-13 01:16:59 -06:00
|
|
|
|
|
|
|
def close (self):
|
|
|
|
"""Closes the database used by the library."""
|
|
|
|
self.__cursor.close()
|
|
|
|
self.__sqlite.close()
|
2016-10-07 00:06:22 -06:00
|
|
|
# delete the temporary copy of the database
|
|
|
|
os.remove(self.newdb.name)
|
2015-03-13 01:16:59 -06:00
|
|
|
|
|
|
|
@property
|
|
|
|
def userkeys (self):
|
|
|
|
"""The list of potential userkeys being used by this library.
|
|
|
|
Only one of these will be valid.
|
|
|
|
"""
|
|
|
|
if len(self._userkeys) != 0:
|
|
|
|
return self._userkeys
|
|
|
|
for macaddr in self.__getmacaddrs():
|
2015-09-03 00:49:09 -06:00
|
|
|
self._userkeys.extend(self.__getuserkeys(macaddr))
|
2015-03-13 01:16:59 -06:00
|
|
|
return self._userkeys
|
|
|
|
|
|
|
|
@property
|
|
|
|
def books (self):
|
|
|
|
"""The list of KoboBook objects in the library."""
|
|
|
|
if len(self._books) != 0:
|
|
|
|
return self._books
|
|
|
|
"""Drm-ed kepub"""
|
|
|
|
for row in self.__cursor.execute('SELECT DISTINCT volumeid, Title, Attribution, Series FROM content_keys, content WHERE contentid = volumeid'):
|
|
|
|
self._books.append(KoboBook(row[0], row[1], self.__bookfile(row[0]), 'kepub', self.__cursor, author=row[2], series=row[3]))
|
|
|
|
self._volumeID.append(row[0])
|
|
|
|
"""Drm-free"""
|
|
|
|
for f in os.listdir(self.bookdir):
|
|
|
|
if(f not in self._volumeID):
|
2016-10-07 00:06:22 -06:00
|
|
|
row = self.__cursor.execute("SELECT Title, Attribution, Series FROM content WHERE ContentID = '" + f + "'").fetchone()
|
|
|
|
if row is not None:
|
2015-03-13 01:16:59 -06:00
|
|
|
fTitle = row[0]
|
|
|
|
self._books.append(KoboBook(f, fTitle, self.__bookfile(f), 'drm-free', self.__cursor, author=row[1], series=row[2]))
|
|
|
|
self._volumeID.append(f)
|
|
|
|
"""Sort"""
|
|
|
|
self._books.sort(key=lambda x: x.title)
|
|
|
|
return self._books
|
|
|
|
|
|
|
|
def __bookfile (self, volumeid):
|
|
|
|
"""The filename needed to open a given book."""
|
2020-09-27 04:54:49 -06:00
|
|
|
return os.path.join(self.kobodir, "kepub", volumeid)
|
2015-03-13 01:16:59 -06:00
|
|
|
|
|
|
|
def __getmacaddrs (self):
|
|
|
|
"""The list of all MAC addresses on this machine."""
|
|
|
|
macaddrs = []
|
|
|
|
if sys.platform.startswith('win'):
|
2021-03-01 13:15:20 -07:00
|
|
|
c = re.compile('\s?(' + '[0-9a-f]{2}[:\-]' * 5 + '[0-9a-f]{2})(\s|$)', re.IGNORECASE)
|
2021-04-26 04:24:57 -06:00
|
|
|
try:
|
|
|
|
output = subprocess.Popen('ipconfig /all', shell=True, stdout=subprocess.PIPE, text=True).stdout
|
|
|
|
for line in output:
|
|
|
|
m = c.search(line)
|
|
|
|
if m:
|
|
|
|
macaddrs.append(re.sub("-", ":", m.group(1)).upper())
|
|
|
|
except:
|
|
|
|
output = subprocess.Popen('wmic nic where PhysicalAdapter=True get MACAddress', shell=True, stdout=subprocess.PIPE, text=True).stdout
|
|
|
|
for line in output:
|
|
|
|
m = c.search(line)
|
|
|
|
if m:
|
|
|
|
macaddrs.append(re.sub("-", ":", m.group(1)).upper())
|
2015-03-13 01:16:59 -06:00
|
|
|
elif sys.platform.startswith('darwin'):
|
|
|
|
c = re.compile('\s(' + '[0-9a-f]{2}:' * 5 + '[0-9a-f]{2})(\s|$)', re.IGNORECASE)
|
2021-03-05 14:54:53 -07:00
|
|
|
output = subprocess.check_output('/sbin/ifconfig -a', shell=True, encoding='utf-8')
|
2015-03-13 01:16:59 -06:00
|
|
|
matches = c.findall(output)
|
|
|
|
for m in matches:
|
2020-09-27 04:54:49 -06:00
|
|
|
# print "m:{0}".format(m[0])
|
2015-03-13 01:16:59 -06:00
|
|
|
macaddrs.append(m[0].upper())
|
2024-11-10 06:14:59 -07:00
|
|
|
elif sys.platform.startswith('linux'):
|
|
|
|
for interface in os.listdir('/sys/class/net'):
|
|
|
|
with open('/sys/class/net/' + interface + '/address', 'r') as f:
|
|
|
|
mac = f.read().strip().upper()
|
|
|
|
# some interfaces, like Tailscale's VPN interface, do not have a MAC address
|
|
|
|
if mac != '':
|
|
|
|
macaddrs.append(mac)
|
2016-01-10 23:40:15 -07:00
|
|
|
else:
|
2024-11-10 06:14:59 -07:00
|
|
|
# final fallback
|
2019-07-05 21:01:28 -06:00
|
|
|
# let's try ip
|
|
|
|
c = re.compile('\s(' + '[0-9a-f]{2}:' * 5 + '[0-9a-f]{2})(\s|$)', re.IGNORECASE)
|
|
|
|
for line in os.popen('ip -br link'):
|
|
|
|
m = c.search(line)
|
|
|
|
if m:
|
|
|
|
macaddrs.append(m.group(1).upper())
|
|
|
|
|
|
|
|
# let's try ipconfig under wine
|
2016-01-10 23:40:15 -07:00
|
|
|
c = re.compile('\s(' + '[0-9a-f]{2}-' * 5 + '[0-9a-f]{2})(\s|$)', re.IGNORECASE)
|
|
|
|
for line in os.popen('ipconfig /all'):
|
|
|
|
m = c.search(line)
|
|
|
|
if m:
|
|
|
|
macaddrs.append(re.sub("-", ":", m.group(1)).upper())
|
2015-09-16 08:01:29 -06:00
|
|
|
|
|
|
|
# extend the list of macaddrs in any case with the serials
|
|
|
|
# cannot hurt ;-)
|
|
|
|
macaddrs.extend(self._serials)
|
2015-09-13 23:12:22 -06:00
|
|
|
|
2015-03-13 01:16:59 -06:00
|
|
|
return macaddrs
|
|
|
|
|
2015-09-03 00:49:09 -06:00
|
|
|
def __getuserids (self):
|
|
|
|
userids = []
|
2015-09-07 00:52:23 -06:00
|
|
|
cursor = self.__cursor.execute('SELECT UserID FROM user')
|
2016-10-07 00:06:22 -06:00
|
|
|
row = cursor.fetchone()
|
|
|
|
while row is not None:
|
|
|
|
try:
|
|
|
|
userid = row[0]
|
|
|
|
userids.append(userid)
|
|
|
|
except:
|
|
|
|
pass
|
|
|
|
row = cursor.fetchone()
|
2015-09-03 00:49:09 -06:00
|
|
|
return userids
|
2020-09-26 14:22:47 -06:00
|
|
|
|
2015-09-03 00:49:09 -06:00
|
|
|
def __getuserkeys (self, macaddr):
|
|
|
|
userids = self.__getuserids()
|
|
|
|
userkeys = []
|
2015-12-25 17:13:16 -07:00
|
|
|
for hash in KOBO_HASH_KEYS:
|
2020-09-26 14:22:47 -06:00
|
|
|
deviceid = hashlib.sha256((hash + macaddr).encode('ascii')).hexdigest()
|
2015-12-25 17:13:16 -07:00
|
|
|
for userid in userids:
|
2020-09-26 14:22:47 -06:00
|
|
|
userkey = hashlib.sha256((deviceid + userid).encode('ascii')).hexdigest()
|
2015-12-25 17:13:16 -07:00
|
|
|
userkeys.append(binascii.a2b_hex(userkey[32:]))
|
2015-09-03 00:49:09 -06:00
|
|
|
return userkeys
|
2015-03-13 01:16:59 -06:00
|
|
|
|
|
|
|
class KoboBook(object):
|
|
|
|
"""A Kobo book.
|
|
|
|
|
|
|
|
A Kobo book contains a number of unencrypted and encrypted files.
|
|
|
|
This class provides a list of the encrypted files.
|
|
|
|
|
|
|
|
Each book has the following instance variables:
|
|
|
|
volumeid - a UUID which uniquely refers to the book in this library.
|
|
|
|
title - the human-readable book title.
|
|
|
|
filename - the complete path and filename of the book.
|
|
|
|
type - either kepub or drm-free"""
|
|
|
|
def __init__ (self, volumeid, title, filename, type, cursor, author=None, series=None):
|
|
|
|
self.volumeid = volumeid
|
|
|
|
self.title = title
|
|
|
|
self.author = author
|
|
|
|
self.series = series
|
|
|
|
self.series_index = None
|
|
|
|
self.filename = filename
|
|
|
|
self.type = type
|
|
|
|
self.__cursor = cursor
|
|
|
|
self._encryptedfiles = {}
|
|
|
|
|
|
|
|
@property
|
|
|
|
def encryptedfiles (self):
|
|
|
|
"""A dictionary of KoboFiles inside the book.
|
|
|
|
|
|
|
|
The dictionary keys are the relative pathnames, which are
|
|
|
|
the same as the pathnames inside the book 'zip' file."""
|
|
|
|
if (self.type == 'drm-free'):
|
|
|
|
return self._encryptedfiles
|
|
|
|
if len(self._encryptedfiles) != 0:
|
|
|
|
return self._encryptedfiles
|
|
|
|
# Read the list of encrypted files from the DB
|
|
|
|
for row in self.__cursor.execute('SELECT elementid,elementkey FROM content_keys,content WHERE volumeid = ? AND volumeid = contentid',(self.volumeid,)):
|
|
|
|
self._encryptedfiles[row[0]] = KoboFile(row[0], None, base64.b64decode(row[1]))
|
|
|
|
|
|
|
|
# Read the list of files from the kepub OPF manifest so that
|
|
|
|
# we can get their proper MIME type.
|
|
|
|
# NOTE: this requires that the OPF file is unencrypted!
|
|
|
|
zin = zipfile.ZipFile(self.filename, "r")
|
|
|
|
xmlns = {
|
|
|
|
'ocf': 'urn:oasis:names:tc:opendocument:xmlns:container',
|
|
|
|
'opf': 'http://www.idpf.org/2007/opf'
|
|
|
|
}
|
|
|
|
ocf = ET.fromstring(zin.read('META-INF/container.xml'))
|
|
|
|
opffile = ocf.find('.//ocf:rootfile', xmlns).attrib['full-path']
|
|
|
|
basedir = re.sub('[^/]+$', '', opffile)
|
|
|
|
opf = ET.fromstring(zin.read(opffile))
|
|
|
|
zin.close()
|
|
|
|
|
|
|
|
c = re.compile('/')
|
|
|
|
for item in opf.findall('.//opf:item', xmlns):
|
|
|
|
mimetype = item.attrib['media-type']
|
|
|
|
|
|
|
|
# Convert relative URIs
|
|
|
|
href = item.attrib['href']
|
|
|
|
if not c.match(href):
|
2020-09-26 14:22:47 -06:00
|
|
|
href = ''.join((basedir, href))
|
2015-03-13 01:16:59 -06:00
|
|
|
|
|
|
|
# Update books we've found from the DB.
|
|
|
|
if href in self._encryptedfiles:
|
|
|
|
self._encryptedfiles[href].mimetype = mimetype
|
|
|
|
return self._encryptedfiles
|
|
|
|
|
|
|
|
@property
|
|
|
|
def has_drm (self):
|
|
|
|
return not self.type == 'drm-free'
|
|
|
|
|
|
|
|
|
|
|
|
class KoboFile(object):
|
|
|
|
"""An encrypted file in a KoboBook.
|
|
|
|
|
|
|
|
Each file has the following instance variables:
|
|
|
|
filename - the relative pathname inside the book zip file.
|
|
|
|
mimetype - the file's MIME type, e.g. 'image/jpeg'
|
|
|
|
key - the encrypted page key."""
|
|
|
|
|
|
|
|
def __init__ (self, filename, mimetype, key):
|
|
|
|
self.filename = filename
|
|
|
|
self.mimetype = mimetype
|
|
|
|
self.key = key
|
|
|
|
def decrypt (self, userkey, contents):
|
|
|
|
"""
|
|
|
|
Decrypt the contents using the provided user key and the
|
|
|
|
file page key. The caller must determine if the decrypted
|
|
|
|
data is correct."""
|
|
|
|
# The userkey decrypts the page key (self.key)
|
2022-02-22 16:16:03 -07:00
|
|
|
decryptedkey = AES.new(userkey, AES.MODE_ECB).decrypt(self.key)
|
|
|
|
# The decrypted page key decrypts the content. Padding is PKCS#7
|
|
|
|
return unpad(AES.new(decryptedkey, AES.MODE_ECB).decrypt(contents), 16)
|
2015-03-13 01:16:59 -06:00
|
|
|
|
|
|
|
def check (self, contents):
|
|
|
|
"""
|
|
|
|
If the contents uses some known MIME types, check if it
|
|
|
|
conforms to the type. Throw a ValueError exception if not.
|
|
|
|
If the contents uses an uncheckable MIME type, don't check
|
|
|
|
it and don't throw an exception.
|
|
|
|
Returns True if the content was checked, False if it was not
|
|
|
|
checked."""
|
|
|
|
if self.mimetype == 'application/xhtml+xml':
|
2016-12-20 23:33:34 -07:00
|
|
|
# assume utf-8 with no BOM
|
|
|
|
textoffset = 0
|
|
|
|
stride = 1
|
2020-09-27 04:54:49 -06:00
|
|
|
print("Checking text:{0}:".format(contents[:10]))
|
2016-12-20 23:33:34 -07:00
|
|
|
# check for byte order mark
|
2020-09-26 14:22:47 -06:00
|
|
|
if contents[:3]==b"\xef\xbb\xbf":
|
2016-12-20 23:33:34 -07:00
|
|
|
# seems to be utf-8 with BOM
|
2020-09-27 04:54:49 -06:00
|
|
|
print("Could be utf-8 with BOM")
|
2016-12-20 23:33:34 -07:00
|
|
|
textoffset = 3
|
2020-09-26 14:22:47 -06:00
|
|
|
elif contents[:2]==b"\xfe\xff":
|
2016-12-20 23:33:34 -07:00
|
|
|
# seems to be utf-16BE
|
2020-09-27 04:54:49 -06:00
|
|
|
print("Could be utf-16BE")
|
2016-12-20 23:33:34 -07:00
|
|
|
textoffset = 3
|
|
|
|
stride = 2
|
2020-09-26 14:22:47 -06:00
|
|
|
elif contents[:2]==b"\xff\xfe":
|
2016-12-20 23:33:34 -07:00
|
|
|
# seems to be utf-16LE
|
2020-09-27 04:54:49 -06:00
|
|
|
print("Could be utf-16LE")
|
2016-12-20 23:33:34 -07:00
|
|
|
textoffset = 2
|
|
|
|
stride = 2
|
|
|
|
else:
|
2020-09-27 04:54:49 -06:00
|
|
|
print("Perhaps utf-8 without BOM")
|
2020-09-26 14:22:47 -06:00
|
|
|
|
2016-12-20 23:33:34 -07:00
|
|
|
# now check that the first few characters are in the ASCII range
|
2020-09-26 14:22:47 -06:00
|
|
|
for i in range(textoffset,textoffset+5*stride,stride):
|
|
|
|
if contents[i]<32 or contents[i]>127:
|
2016-12-20 23:33:34 -07:00
|
|
|
# Non-ascii, so decryption probably failed
|
2020-09-27 04:54:49 -06:00
|
|
|
print("Bad character at {0}, value {1}".format(i,contents[i]))
|
2016-12-20 23:33:34 -07:00
|
|
|
raise ValueError
|
2020-09-27 04:54:49 -06:00
|
|
|
print("Seems to be good text")
|
2016-12-20 23:33:34 -07:00
|
|
|
return True
|
2020-09-26 14:22:47 -06:00
|
|
|
if contents[:5]==b"<?xml" or contents[:8]==b"\xef\xbb\xbf<?xml":
|
2016-09-28 00:14:16 -06:00
|
|
|
# utf-8
|
|
|
|
return True
|
2020-09-26 14:22:47 -06:00
|
|
|
elif contents[:14]==b"\xfe\xff\x00<\x00?\x00x\x00m\x00l":
|
2016-09-28 00:14:16 -06:00
|
|
|
# utf-16BE
|
|
|
|
return True
|
2020-09-26 14:22:47 -06:00
|
|
|
elif contents[:14]==b"\xff\xfe<\x00?\x00x\x00m\x00l\x00":
|
2016-09-28 00:14:16 -06:00
|
|
|
# utf-16LE
|
2015-03-13 01:16:59 -06:00
|
|
|
return True
|
2020-09-26 14:22:47 -06:00
|
|
|
elif contents[:9]==b"<!DOCTYPE" or contents[:12]==b"\xef\xbb\xbf<!DOCTYPE":
|
2016-10-20 00:12:37 -06:00
|
|
|
# utf-8 of weird <!DOCTYPE start
|
|
|
|
return True
|
2020-09-26 14:22:47 -06:00
|
|
|
elif contents[:22]==b"\xfe\xff\x00<\x00!\x00D\x00O\x00C\x00T\x00Y\x00P\x00E":
|
2016-10-20 00:12:37 -06:00
|
|
|
# utf-16BE of weird <!DOCTYPE start
|
|
|
|
return True
|
2020-09-26 14:22:47 -06:00
|
|
|
elif contents[:22]==b"\xff\xfe<\x00!\x00D\x00O\x00C\x00T\x00Y\x00P\x00E\x00":
|
2016-10-20 00:12:37 -06:00
|
|
|
# utf-16LE of weird <!DOCTYPE start
|
|
|
|
return True
|
2015-03-13 01:16:59 -06:00
|
|
|
else:
|
2020-09-27 04:54:49 -06:00
|
|
|
print("Bad XML: {0}".format(contents[:8]))
|
2015-03-13 01:16:59 -06:00
|
|
|
raise ValueError
|
2016-09-28 00:14:16 -06:00
|
|
|
elif self.mimetype == 'image/jpeg':
|
2020-09-26 14:22:47 -06:00
|
|
|
if contents[:3] == b'\xff\xd8\xff':
|
2015-03-13 01:16:59 -06:00
|
|
|
return True
|
|
|
|
else:
|
2020-09-27 04:54:49 -06:00
|
|
|
print("Bad JPEG: {0}".format(contents[:3].hex()))
|
2015-03-13 01:16:59 -06:00
|
|
|
raise ValueError()
|
|
|
|
return False
|
|
|
|
|
|
|
|
|
2017-06-26 23:50:24 -06:00
|
|
|
def decrypt_book(book, lib):
|
2020-09-27 04:54:49 -06:00
|
|
|
print("Converting {0}".format(book.title))
|
2015-03-13 01:16:59 -06:00
|
|
|
zin = zipfile.ZipFile(book.filename, "r")
|
|
|
|
# make filename out of Unicode alphanumeric and whitespace equivalents from title
|
2020-09-27 04:54:49 -06:00
|
|
|
outname = "{0}.epub".format(re.sub('[^\s\w]', '_', book.title, 0, re.UNICODE))
|
2015-03-13 01:16:59 -06:00
|
|
|
if (book.type == 'drm-free'):
|
2020-09-27 04:54:49 -06:00
|
|
|
print("DRM-free book, conversion is not needed")
|
2015-03-13 01:16:59 -06:00
|
|
|
shutil.copyfile(book.filename, outname)
|
2020-09-27 04:54:49 -06:00
|
|
|
print("Book saved as {0}".format(os.path.join(os.getcwd(), outname)))
|
2017-06-26 23:50:24 -06:00
|
|
|
return 0
|
2015-03-13 01:16:59 -06:00
|
|
|
result = 1
|
|
|
|
for userkey in lib.userkeys:
|
2020-09-27 04:54:49 -06:00
|
|
|
print("Trying key: {0}".format(userkey.hex()))
|
2015-03-13 01:16:59 -06:00
|
|
|
try:
|
|
|
|
zout = zipfile.ZipFile(outname, "w", zipfile.ZIP_DEFLATED)
|
|
|
|
for filename in zin.namelist():
|
|
|
|
contents = zin.read(filename)
|
|
|
|
if filename in book.encryptedfiles:
|
|
|
|
file = book.encryptedfiles[filename]
|
|
|
|
contents = file.decrypt(userkey, contents)
|
|
|
|
# Parse failures mean the key is probably wrong.
|
2015-09-30 00:39:29 -06:00
|
|
|
file.check(contents)
|
2015-03-13 01:16:59 -06:00
|
|
|
zout.writestr(filename, contents)
|
|
|
|
zout.close()
|
2020-09-27 04:54:49 -06:00
|
|
|
print("Decryption succeeded.")
|
|
|
|
print("Book saved as {0}".format(os.path.join(os.getcwd(), outname)))
|
2015-03-13 01:16:59 -06:00
|
|
|
result = 0
|
|
|
|
break
|
|
|
|
except ValueError:
|
2020-09-27 04:54:49 -06:00
|
|
|
print("Decryption failed.")
|
2015-03-13 01:16:59 -06:00
|
|
|
zout.close()
|
|
|
|
os.remove(outname)
|
|
|
|
zin.close()
|
2017-06-26 23:50:24 -06:00
|
|
|
return result
|
|
|
|
|
|
|
|
|
|
|
|
def cli_main():
|
|
|
|
description = __about__
|
2020-09-27 04:54:49 -06:00
|
|
|
epilog = "Parsing of arguments failed."
|
2017-06-26 23:50:24 -06:00
|
|
|
parser = argparse.ArgumentParser(prog=sys.argv[0], description=description, epilog=epilog)
|
|
|
|
parser.add_argument('--devicedir', default='/media/KOBOeReader', help="directory of connected Kobo device")
|
|
|
|
parser.add_argument('--all', action='store_true', help="flag for converting all books on device")
|
|
|
|
args = vars(parser.parse_args())
|
|
|
|
serials = []
|
|
|
|
devicedir = u""
|
|
|
|
if args['devicedir']:
|
|
|
|
devicedir = args['devicedir']
|
|
|
|
|
|
|
|
lib = KoboLibrary(serials, devicedir)
|
|
|
|
|
|
|
|
if args['all']:
|
|
|
|
books = lib.books
|
|
|
|
else:
|
|
|
|
for i, book in enumerate(lib.books):
|
2020-09-27 04:54:49 -06:00
|
|
|
print("{0}: {1}".format(i + 1, book.title))
|
|
|
|
print("Or 'all'")
|
2017-06-26 23:50:24 -06:00
|
|
|
|
2020-09-27 04:54:49 -06:00
|
|
|
choice = input("Convert book number... ")
|
|
|
|
if choice == "all":
|
2017-06-26 23:50:24 -06:00
|
|
|
books = list(lib.books)
|
|
|
|
else:
|
|
|
|
try:
|
|
|
|
num = int(choice)
|
|
|
|
books = [lib.books[num - 1]]
|
|
|
|
except (ValueError, IndexError):
|
2020-09-27 04:54:49 -06:00
|
|
|
print("Invalid choice. Exiting...")
|
2021-12-29 03:36:59 -07:00
|
|
|
sys.exit()
|
2017-06-26 23:50:24 -06:00
|
|
|
|
|
|
|
results = [decrypt_book(book, lib) for book in books]
|
2015-03-13 01:16:59 -06:00
|
|
|
lib.close()
|
2017-06-26 23:50:24 -06:00
|
|
|
overall_result = all(result != 0 for result in results)
|
|
|
|
if overall_result != 0:
|
2020-09-27 04:54:49 -06:00
|
|
|
print("Could not decrypt book with any of the keys found.")
|
2017-06-26 23:50:24 -06:00
|
|
|
return overall_result
|
|
|
|
|
2015-09-07 01:11:18 -06:00
|
|
|
|
|
|
|
if __name__ == '__main__':
|
|
|
|
sys.stdout=SafeUnbuffered(sys.stdout)
|
|
|
|
sys.stderr=SafeUnbuffered(sys.stderr)
|
|
|
|
sys.exit(cli_main())
|