Guest User

ineptkey.pyw

a guest
Oct 31st, 2014
161
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 15.83 KB | None | 0 0
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
  43. 43
  44. 44
  45. 45
  46. 46
  47. 47
  48. 48
  49. 49
  50. 50
  51. 51
  52. 52
  53. 53
  54. 54
  55. 55
  56. 56
  57. 57
  58. 58
  59. 59
  60. 60
  61. 61
  62. 62
  63. 63
  64. 64
  65. 65
  66. 66
  67. 67
  68. 68
  69. 69
  70. 70
  71. 71
  72. 72
  73. 73
  74. 74
  75. 75
  76. 76
  77. 77
  78. 78
  79. 79
  80. 80
  81. 81
  82. 82
  83. 83
  84. 84
  85. 85
  86. 86
  87. 87
  88. 88
  89. 89
  90. 90
  91. 91
  92. 92
  93. 93
  94. 94
  95. 95
  96. 96
  97. 97
  98. 98
  99. 99
  100. 100
  101. 101
  102. 102
  103. 103
  104. 104
  105. 105
  106. 106
  107. 107
  108. 108
  109. 109
  110. 110
  111. 111
  112. 112
  113. 113
  114. 114
  115. 115
  116. 116
  117. 117
  118. 118
  119. 119
  120. 120
  121. 121
  122. 122
  123. 123
  124. 124
  125. 125
  126. 126
  127. 127
  128. 128
  129. 129
  130. 130
  131. 131
  132. 132
  133. 133
  134. 134
  135. 135
  136. 136
  137. 137
  138. 138
  139. 139
  140. 140
  141. 141
  142. 142
  143. 143
  144. 144
  145. 145
  146. 146
  147. 147
  148. 148
  149. 149
  150. 150
  151. 151
  152. 152
  153. 153
  154. 154
  155. 155
  156. 156
  157. 157
  158. 158
  159. 159
  160. 160
  161. 161
  162. 162
  163. 163
  164. 164
  165. 165
  166. 166
  167. 167
  168. 168
  169. 169
  170. 170
  171. 171
  172. 172
  173. 173
  174. 174
  175. 175
  176. 176
  177. 177
  178. 178
  179. 179
  180. 180
  181. 181
  182. 182
  183. 183
  184. 184
  185. 185
  186. 186
  187. 187
  188. 188
  189. 189
  190. 190
  191. 191
  192. 192
  193. 193
  194. 194
  195. 195
  196. 196
  197. 197
  198. 198
  199. 199
  200. 200
  201. 201
  202. 202
  203. 203
  204. 204
  205. 205
  206. 206
  207. 207
  208. 208
  209. 209
  210. 210
  211. 211
  212. 212
  213. 213
  214. 214
  215. 215
  216. 216
  217. 217
  218. 218
  219. 219
  220. 220
  221. 221
  222. 222
  223. 223
  224. 224
  225. 225
  226. 226
  227. 227
  228. 228
  229. 229
  230. 230
  231. 231
  232. 232
  233. 233
  234. 234
  235. 235
  236. 236
  237. 237
  238. 238
  239. 239
  240. 240
  241. 241
  242. 242
  243. 243
  244. 244
  245. 245
  246. 246
  247. 247
  248. 248
  249. 249
  250. 250
  251. 251
  252. 252
  253. 253
  254. 254
  255. 255
  256. 256
  257. 257
  258. 258
  259. 259
  260. 260
  261. 261
  262. 262
  263. 263
  264. 264
  265. 265
  266. 266
  267. 267
  268. 268
  269. 269
  270. 270
  271. 271
  272. 272
  273. 273
  274. 274
  275. 275
  276. 276
  277. 277
  278. 278
  279. 279
  280. 280
  281. 281
  282. 282
  283. 283
  284. 284
  285. 285
  286. 286
  287. 287
  288. 288
  289. 289
  290. 290
  291. 291
  292. 292
  293. 293
  294. 294
  295. 295
  296. 296
  297. 297
  298. 298
  299. 299
  300. 300
  301. 301
  302. 302
  303. 303
  304. 304
  305. 305
  306. 306
  307. 307
  308. 308
  309. 309
  310. 310
  311. 311
  312. 312
  313. 313
  314. 314
  315. 315
  316. 316
  317. 317
  318. 318
  319. 319
  320. 320
  321. 321
  322. 322
  323. 323
  324. 324
  325. 325
  326. 326
  327. 327
  328. 328
  329. 329
  330. 330
  331. 331
  332. 332
  333. 333
  334. 334
  335. 335
  336. 336
  337. 337
  338. 338
  339. 339
  340. 340
  341. 341
  342. 342
  343. 343
  344. 344
  345. 345
  346. 346
  347. 347
  348. 348
  349. 349
  350. 350
  351. 351
  352. 352
  353. 353
  354. 354
  355. 355
  356. 356
  357. 357
  358. 358
  359. 359
  360. 360
  361. 361
  362. 362
  363. 363
  364. 364
  365. 365
  366. 366
  367. 367
  368. 368
  369. 369
  370. 370
  371. 371
  372. 372
  373. 373
  374. 374
  375. 375
  376. 376
  377. 377
  378. #! /usr/bin/python
  379. # -*- coding: utf-8 -*-
  380.  
  381. # ineptkey.pyw, version 5
  382. # Copyright © 2009-2010 i♥cabbages
  383.  
  384. # Released under the terms of the GNU General Public Licence, version 3 or
  385. # later.  <http://www.gnu.org/licenses/>
  386.  
  387. # Windows users: Before running this program, you must first install Python 2.6
  388. #   from <http://www.python.org/download/> and PyCrypto from
  389. #   <http://www.voidspace.org.uk/python/modules.shtml#pycrypto> (make certain
  390. #   to install the version for Python 2.6).  Then save this script file as
  391. #   ineptkey.pyw and double-click on it to run it.  It will create a file named
  392. #   adeptkey.der in the same directory.  This is your ADEPT user key.
  393. #
  394. # Mac OS X users: Save this script file as ineptkey.pyw.  You can run this
  395. #   program from the command line (pythonw ineptkey.pyw) or by double-clicking
  396. #   it when it has been associated with PythonLauncher.  It will create a file
  397. #   named adeptkey.der in the same directory.  This is your ADEPT user key.
  398.  
  399. # Revision history:
  400. #   1 - Initial release, for Adobe Digital Editions 1.7
  401. #   2 - Better algorithm for finding pLK; improved error handling
  402. #   3 - Rename to INEPT
  403. #   4 - Series of changes by joblack (and others?) --
  404. #   4.1 - quick beta fix for ADE 1.7.2 (anon)
  405. #   4.2 - added old 1.7.1 processing
  406. #   4.3 - better key search
  407. #   4.4 - Make it working on 64-bit Python
  408. #   5 - Clean up and improve 4.x changes;
  409. #       Clean up and merge OS X support by unknown
  410.  
  411. """
  412. Retrieve Adobe ADEPT user key.
  413. """
  414.  
  415. from __future__ import with_statement
  416.  
  417. __license__ = 'GPL v3'
  418.  
  419. import sys
  420. import os
  421. import struct
  422. import Tkinter
  423. import Tkconstants
  424. import tkMessageBox
  425. import traceback
  426.  
  427. class ADEPTError(Exception):
  428.     pass
  429.  
  430. if sys.platform.startswith('win'):
  431.     from ctypes import windll, c_char_p, c_wchar_p, c_uint, POINTER, byref, \
  432.         create_unicode_buffer, create_string_buffer, CFUNCTYPE, addressof, \
  433.         string_at, Structure, c_void_p, cast, c_size_t, memmove
  434.     from ctypes.wintypes import LPVOID, DWORD, BOOL
  435.     import _winreg as winreg
  436.  
  437.     try:
  438.         from Crypto.Cipher import AES
  439.     except ImportError:
  440.         AES = None
  441.  
  442.     DEVICE_KEY_PATH = r'Software\Adobe\Adept\Device'
  443.     PRIVATE_LICENCE_KEY_PATH = r'Software\Adobe\Adept\Activation'
  444.  
  445.     MAX_PATH = 255
  446.  
  447.     kernel32 = windll.kernel32
  448.     advapi32 = windll.advapi32
  449.     crypt32 = windll.crypt32
  450.  
  451.     def GetSystemDirectory():
  452.         GetSystemDirectoryW = kernel32.GetSystemDirectoryW
  453.         GetSystemDirectoryW.argtypes = [c_wchar_p, c_uint]
  454.         GetSystemDirectoryW.restype = c_uint
  455.         def GetSystemDirectory():
  456.             buffer = create_unicode_buffer(MAX_PATH + 1)
  457.             GetSystemDirectoryW(buffer, len(buffer))
  458.             return buffer.value
  459.         return GetSystemDirectory
  460.     GetSystemDirectory = GetSystemDirectory()
  461.  
  462.     def GetVolumeSerialNumber():
  463.         GetVolumeInformationW = kernel32.GetVolumeInformationW
  464.         GetVolumeInformationW.argtypes = [c_wchar_p, c_wchar_p, c_uint,
  465.                                           POINTER(c_uint), POINTER(c_uint),
  466.                                           POINTER(c_uint), c_wchar_p, c_uint]
  467.         GetVolumeInformationW.restype = c_uint
  468.         def GetVolumeSerialNumber(path):
  469.             vsn = c_uint(0)
  470.             GetVolumeInformationW(
  471.                 path, None, 0, byref(vsn), None, None, None, 0)
  472.             return vsn.value
  473.         return GetVolumeSerialNumber
  474.     GetVolumeSerialNumber = GetVolumeSerialNumber()
  475.  
  476.     def GetUserName():
  477.         GetUserNameW = advapi32.GetUserNameW
  478.         GetUserNameW.argtypes = [c_wchar_p, POINTER(c_uint)]
  479.         GetUserNameW.restype = c_uint
  480.         def GetUserName():
  481.             buffer = create_unicode_buffer(32)
  482.             size = c_uint(len(buffer))
  483.             while not GetUserNameW(buffer, byref(size)):
  484.                 buffer = create_unicode_buffer(len(buffer) * 2)
  485.                 size.value = len(buffer)
  486.             return buffer.value.encode('utf-16-le')[::2]
  487.         return GetUserName
  488.     GetUserName = GetUserName()
  489.  
  490.     PAGE_EXECUTE_READWRITE = 0x40
  491.     MEM_COMMIT  = 0x1000
  492.     MEM_RESERVE = 0x2000
  493.  
  494.     def VirtualAlloc():
  495.         _VirtualAlloc = kernel32.VirtualAlloc
  496.         _VirtualAlloc.argtypes = [LPVOID, c_size_t, DWORD, DWORD]
  497.         _VirtualAlloc.restype = LPVOID
  498.         def VirtualAlloc(addr, size, alloctype=(MEM_COMMIT | MEM_RESERVE),
  499.                          protect=PAGE_EXECUTE_READWRITE):
  500.             return _VirtualAlloc(addr, size, alloctype, protect)
  501.         return VirtualAlloc
  502.     VirtualAlloc = VirtualAlloc()
  503.  
  504.     MEM_RELEASE = 0x8000
  505.  
  506.     def VirtualFree():
  507.         _VirtualFree = kernel32.VirtualFree
  508.         _VirtualFree.argtypes = [LPVOID, c_size_t, DWORD]
  509.         _VirtualFree.restype = BOOL
  510.         def VirtualFree(addr, size=0, freetype=MEM_RELEASE):
  511.             return _VirtualFree(addr, size, freetype)
  512.         return VirtualFree
  513.     VirtualFree = VirtualFree()
  514.  
  515.     class NativeFunction(object):
  516.         def __init__(self, restype, argtypes, insns):
  517.             self._buf = buf = VirtualAlloc(None, len(insns))
  518.             memmove(buf, insns, len(insns))
  519.             ftype = CFUNCTYPE(restype, *argtypes)
  520.             self._native = ftype(buf)
  521.  
  522.         def __call__(self, *args):
  523.             return self._native(*args)
  524.  
  525.         def __del__(self):
  526.             if self._buf is not None:
  527.                 VirtualFree(self._buf)
  528.                 self._buf = None
  529.  
  530.     if struct.calcsize("P") == 4:
  531.         CPUID0_INSNS = (
  532.             "\x53"             # push   %ebx
  533.             "\x31\xc0"         # xor    %eax,%eax
  534.             "\x0f\xa2"         # cpuid
  535.             "\x8b\x44\x24\x08" # mov    0x8(%esp),%eax
  536.             "\x89\x18"         # mov    %ebx,0x0(%eax)
  537.             "\x89\x50\x04"     # mov    %edx,0x4(%eax)
  538.             "\x89\x48\x08"     # mov    %ecx,0x8(%eax)
  539.             "\x5b"             # pop    %ebx
  540.             "\xc3"             # ret
  541.         )
  542.         CPUID1_INSNS = (
  543.             "\x53"             # push   %ebx
  544.             "\x31\xc0"         # xor    %eax,%eax
  545.             "\x40"             # inc    %eax
  546.             "\x0f\xa2"         # cpuid
  547.             "\x5b"             # pop    %ebx
  548.             "\xc3"             # ret
  549.         )
  550.     else:
  551.         CPUID0_INSNS = (
  552.             "\x49\x89\xd8"     # mov    %rbx,%r8
  553.             "\x49\x89\xc9"     # mov    %rcx,%r9
  554.             "\x48\x31\xc0"     # xor    %rax,%rax
  555.             "\x0f\xa2"         # cpuid
  556.             "\x4c\x89\xc8"     # mov    %r9,%rax
  557.             "\x89\x18"         # mov    %ebx,0x0(%rax)
  558.             "\x89\x50\x04"     # mov    %edx,0x4(%rax)
  559.             "\x89\x48\x08"     # mov    %ecx,0x8(%rax)
  560.             "\x4c\x89\xc3"     # mov    %r8,%rbx
  561.             "\xc3"             # retq
  562.         )
  563.         CPUID1_INSNS = (
  564.             "\x53"             # push   %rbx
  565.             "\x48\x31\xc0"     # xor    %rax,%rax
  566.             "\x48\xff\xc0"     # inc    %rax
  567.             "\x0f\xa2"         # cpuid
  568.             "\x5b"             # pop    %rbx
  569.             "\xc3"             # retq
  570.         )
  571.  
  572.     def cpuid0():
  573.         _cpuid0 = NativeFunction(None, [c_char_p], CPUID0_INSNS)
  574.         buf = create_string_buffer(12)
  575.         def cpuid0():
  576.             _cpuid0(buf)
  577.             return buf.raw
  578.         return cpuid0
  579.     cpuid0 = cpuid0()
  580.  
  581.     cpuid1 = NativeFunction(c_uint, [], CPUID1_INSNS)
  582.  
  583.     class DataBlob(Structure):
  584.         _fields_ = [('cbData', c_uint),
  585.                     ('pbData', c_void_p)]
  586.     DataBlob_p = POINTER(DataBlob)
  587.  
  588.     def CryptUnprotectData():
  589.         _CryptUnprotectData = crypt32.CryptUnprotectData
  590.         _CryptUnprotectData.argtypes = [DataBlob_p, c_wchar_p, DataBlob_p,
  591.                                        c_void_p, c_void_p, c_uint, DataBlob_p]
  592.         _CryptUnprotectData.restype = c_uint
  593.         def CryptUnprotectData(indata, entropy):
  594.             indatab = create_string_buffer(indata)
  595.             indata = DataBlob(len(indata), cast(indatab, c_void_p))
  596.             entropyb = create_string_buffer(entropy)
  597.             entropy = DataBlob(len(entropy), cast(entropyb, c_void_p))
  598.             outdata = DataBlob()
  599.             if not _CryptUnprotectData(byref(indata), None, byref(entropy),
  600.                                        None, None, 0, byref(outdata)):
  601.                 raise ADEPTError("Failed to decrypt user key key (sic)")
  602.             return string_at(outdata.pbData, outdata.cbData)
  603.         return CryptUnprotectData
  604.     CryptUnprotectData = CryptUnprotectData()
  605.  
  606.     def retrieve_key(keypath):
  607.         if AES is None:
  608.             tkMessageBox.showerror(
  609.                 "ADEPT Key",
  610.                 "This script requires PyCrypto, which must be installed "
  611.                 "separately.  Read the top-of-script comment for details.")
  612.             return False
  613.         root = GetSystemDirectory().split('\\')[0] + '\\'
  614.         serial = GetVolumeSerialNumber(root)
  615.         vendor = cpuid0()
  616.         signature = struct.pack('>I', cpuid1())[1:]
  617.         user = GetUserName()
  618.         entropy = struct.pack('>I12s3s13s', serial, vendor, signature, user)
  619.         cuser = winreg.HKEY_CURRENT_USER
  620.         try:
  621.             regkey = winreg.OpenKey(cuser, DEVICE_KEY_PATH)
  622.         except WindowsError:
  623.             raise ADEPTError("Adobe Digital Editions not activated")
  624.         device = winreg.QueryValueEx(regkey, 'key')[0]
  625.         keykey = CryptUnprotectData(device, entropy)
  626.         userkey = None
  627.         try:
  628.             plkroot = winreg.OpenKey(cuser, PRIVATE_LICENCE_KEY_PATH)
  629.         except WindowsError:
  630.             raise ADEPTError("Could not locate ADE activation")
  631.         for i in xrange(0, 16):
  632.             try:
  633.                 plkparent = winreg.OpenKey(plkroot, "%04d" % (i,))
  634.             except WindowsError:
  635.                 break
  636.             ktype = winreg.QueryValueEx(plkparent, None)[0]
  637.             if ktype != 'credentials':
  638.                 continue
  639.             for j in xrange(0, 16):
  640.                 try:
  641.                     plkkey = winreg.OpenKey(plkparent, "%04d" % (j,))
  642.                 except WindowsError:
  643.                     break
  644.                 ktype = winreg.QueryValueEx(plkkey, None)[0]
  645.                 if ktype != 'privateLicenseKey':
  646.                     continue
  647.                 userkey = winreg.QueryValueEx(plkkey, 'value')[0]
  648.                 break
  649.             if userkey is not None:
  650.                 break
  651.         if userkey is None:
  652.             raise ADEPTError('Could not locate privateLicenseKey')
  653.         userkey = userkey.decode('base64')
  654.         userkey = AES.new(keykey, AES.MODE_CBC).decrypt(userkey)
  655.         userkey = userkey[26:-ord(userkey[-1])]
  656.         with open(keypath, 'wb') as f:
  657.             f.write(userkey)
  658.         return True
  659.  
  660. elif sys.platform.startswith('darwin'):
  661.     import xml.etree.ElementTree as etree
  662.     import Carbon.File
  663.     import Carbon.Folder
  664.     import Carbon.Folders
  665.     import MacOS
  666.  
  667.     ACTIVATION_PATH = 'Adobe/Digital Editions/activation.dat'
  668.     NSMAP = {'adept': 'http://ns.adobe.com/adept',
  669.              'enc': 'http://www.w3.org/2001/04/xmlenc#'}
  670.  
  671.     def find_folder(domain, dtype):
  672.         try:
  673.             fsref = Carbon.Folder.FSFindFolder(domain, dtype, False)
  674.             return Carbon.File.pathname(fsref)
  675.         except MacOS.Error:
  676.             return None
  677.  
  678.     def find_app_support_file(subpath):
  679.         dtype = Carbon.Folders.kApplicationSupportFolderType
  680.         for domain in Carbon.Folders.kUserDomain, Carbon.Folders.kLocalDomain:
  681.             path = find_folder(domain, dtype)
  682.             if path is None:
  683.                 continue
  684.             path = os.path.join(path, subpath)
  685.             if os.path.isfile(path):
  686.                 return path
  687.         return None
  688.  
  689.     def retrieve_key(keypath):
  690.         actpath = find_app_support_file(ACTIVATION_PATH)
  691.         if actpath is None:
  692.             raise ADEPTError("Could not locate ADE activation")
  693.         tree = etree.parse(actpath)
  694.         adept = lambda tag: '{%s}%s' % (NSMAP['adept'], tag)
  695.         expr = '//%s/%s' % (adept('credentials'), adept('privateLicenseKey'))
  696.         userkey = tree.findtext(expr)
  697.         userkey = userkey.decode('base64')
  698.         userkey = userkey[26:]
  699.         with open(keypath, 'wb') as f:
  700.             f.write(userkey)
  701.         return True
  702.  
  703. elif sys.platform.startswith('cygwin'):
  704.     def retrieve_key(keypath):
  705.         tkMessageBox.showerror(
  706.             "ADEPT Key",
  707.             "This script requires a Windows-native Python, and cannot be run "
  708.             "under Cygwin.  Please install a Windows-native Python and/or "
  709.             "check your file associations.")
  710.         return False
  711.  
  712. else:
  713.     def retrieve_key(keypath):
  714.         tkMessageBox.showerror(
  715.             "ADEPT Key",
  716.             "This script only supports Windows and Mac OS X.  For Linux "
  717.             "you should be able to run ADE and this script under Wine (with "
  718.             "an appropriate version of Windows Python installed).")
  719.         return False
  720.  
  721. class ExceptionDialog(Tkinter.Frame):
  722.     def __init__(self, root, text):
  723.         Tkinter.Frame.__init__(self, root, border=5)
  724.         label = Tkinter.Label(self, text="Unexpected error:",
  725.                               anchor=Tkconstants.W, justify=Tkconstants.LEFT)
  726.         label.pack(fill=Tkconstants.X, expand=0)
  727.         self.text = Tkinter.Text(self)
  728.         self.text.pack(fill=Tkconstants.BOTH, expand=1)
  729.         self.text.insert(Tkconstants.END, text)
  730.  
  731. def main(argv=sys.argv):
  732.     root = Tkinter.Tk()
  733.     root.withdraw()
  734.     progname = os.path.basename(argv[0])
  735.     keypath = 'adeptkey.der'
  736.     success = False
  737.     try:
  738.         success = retrieve_key(keypath)
  739.     except ADEPTError, e:
  740.         tkMessageBox.showerror("ADEPT Key", "Error: " + str(e))
  741.     except Exception:
  742.         root.wm_state('normal')
  743.         root.title('ADEPT Key')
  744.         text = traceback.format_exc()
  745.         ExceptionDialog(root, text).pack(fill=Tkconstants.BOTH, expand=1)
  746.         root.mainloop()
  747.     if not success:
  748.         return 1
  749.     tkMessageBox.showinfo(
  750.         "ADEPT Key", "Key successfully retrieved to %s" % (keypath))
  751.     return 0
  752.  
  753. if __name__ == '__main__':
  754.     sys.exit(main())
Add Comment
Please, Sign In to add comment