Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 41
Expand file tree
/
Copy pathcryptolens_python2.py
More file actions
Latest commit
599 lines (483 loc) · 20.6 KB
/
Copy pathcryptolens_python2.py
File metadata and controls
599 lines (483 loc) · 20.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
importdatetime
importsocket
importjson
importos
"""
The code below should not be changed.
"""
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 23 10:12:13 2019
@author: Artem Los
"""
importbase64
importurllib2
importurllib
importhashlib
fromsubprocessimportPopen, PIPE
fromurllib2importURLError, HTTPError
classHelperMethods:
server_address="https://app.cryptolens.io/api/"
ironpython2730_legacy=False
@staticmethod
defget_SHA256(string):
"""
Compute the SHA256 signature of a string.
"""
returnhashlib.sha256(string.encode("utf-8")).hexdigest()
@staticmethod
defI2OSP(x, xLen):
ifx> (1<< (8*xLen)):
returnNone
Xrev= []
for_inxrange(0, xLen):
x, m=divmod(x, 256)
Xrev.append(chr(m))
return"".join(reversed(Xrev))
@staticmethod
defOS2IP(X):
returnint(X.encode("hex"), 16)
@staticmethod
def_OS2IP(X):
x=0
a=1
l=len(X)
foriinxrange(1, l+1):
x+=ord(X[l-i])*a
a*=256
returnx
@staticmethod
defRSAVP1((n,e), s):
ifs<0orn-1<s:
returnNone
returnpow(s, e, n)
@staticmethod
defEMSA_PKCS1_V15_ENCODE(M, emLen):
importhashlib
h=hashlib.sha256()
h.update(M)
H=h.digest()
T="".join([chr(x) forxin [0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05, 0x00, 0x04, 0x20]]) +H
tLen=len(T)
ifemLen<tLen+11:
returnNone
PS="".join([chr(0xff) for_inrange(emLen-tLen-3)])
return"".join([chr(0x0), chr(0x1), PS, chr(0x0), T])
@staticmethod
defRSAASSA_PKCS1_V15_VERIFY((n,e), M, S):
s=HelperMethods.OS2IP(S)
m=HelperMethods.RSAVP1((n,e), s)
ifmisNone: returnFalse
EM=HelperMethods.I2OSP(m, 256)
ifEMisNone: returnFalse
EM2=HelperMethods.EMSA_PKCS1_V15_ENCODE(M, 256)
ifEM2isNone: returnFalse
try:
importhmac
returnhmac.compare_digest(EM, EM2)
except (ImportError, AttributeError):
returnEM==EM2
@staticmethod
defverify_signature(response, rsaPublicKey):
"""
Verifies a signature from .NET RSACryptoServiceProvider.
"""
modulus=base64.b64decode(rsaPublicKey.modulus)
exponent=base64.b64decode(rsaPublicKey.exponent)
message=base64.b64decode(response.license_key)
signature=base64.b64decode(response.signature)
n=HelperMethods.OS2IP(modulus)
e=HelperMethods.OS2IP(exponent)
returnHelperMethods.RSAASSA_PKCS1_V15_VERIFY((n,e), message, signature)
@staticmethod
defint2base64(num):
returnbase64.b64encode(int.to_bytes(num), byteorder='big')
@staticmethod
defbase642int(string):
returnint.from_bytes(base64.b64decode((string)), byteorder='big')
@staticmethod
defsend_request(method, params):
"""
Send a POST request to method in the Web API with the specified
params and return the response string.
method: the path of the method, eg. key/activate
params: a dictionary of parameters
"""
ifHelperMethods.ironpython2730_legacy:
returnHelperMethods.send_request_ironpythonlegacy(HelperMethods.server_address+method, \
urllib.urlencode(params))
else:
returnurllib2.urlopen(HelperMethods.server_address+method, \
urllib.urlencode(params)).read().decode("utf-8")
@staticmethod
defsend_request_ironpythonlegacy(uri, parameters):
"""
IronPython 2.7.3 and earlier has a built in problem with
urlib2 library when verifying certificates. This code calls a .NET
library instead.
"""
fromSystem.NetimportWebRequest
fromSystem.IOimportStreamReader
fromSystem.TextimportEncoding
request=WebRequest.Create(uri)
request.ContentType="application/x-www-form-urlencoded"
request.Method="POST"#work for post
bytes=Encoding.ASCII.GetBytes(parameters)
request.ContentLength=bytes.Length
reqStream=request.GetRequestStream()
reqStream.Write(bytes, 0, bytes.Length)
reqStream.Close()
response=request.GetResponse()
result=StreamReader(response.GetResponseStream()).ReadToEnd()
returnresult
@staticmethod
defstart_process(command):
process=Popen(command, stdout=PIPE)
(output, err) =process.communicate()
exit_code=process.wait()
returnoutput.decode("utf-8")
@staticmethod
defget_dbus_machine_id():
try:
withopen("/etc/machine-id") asf:
returnf.read().strip()
except:
pass
try:
withopen("/var/lib/dbus/machine-id") asf:
returnf.read().strip()
except:
pass
return""
@staticmethod
defget_inodes():
importos
files= ["/bin", "/etc", "/lib", "/root", "/sbin", "/usr", "/var"]
inodes= []
forfileinfiles:
try:
inodes.append(os.stat(file).st_ino)
except:
pass
return"".join([str(x) forxininodes])
@staticmethod
defcompute_machine_code():
returnHelperMethods.get_dbus_machine_id() +HelperMethods.get_inodes()
importplatform
importuuid
importsys
importjson
classKey:
"""
License key related methods. More docs: https://app.cryptolens.io/docs/api/v3/Key.
"""
@staticmethod
defactivate(token, rsa_pub_key, product_id, key, machine_code, fields_to_return=0,\
metadata=False, floating_time_interval=0,\
max_overdraft=0, friendly_name=None):
"""
Calls the Activate method in Web API 3 and returns a tuple containing
(LicenseKey, Message). If an error occurs, LicenseKey will be None. If
everything went well, no message will be returned.
More docs: https://app.cryptolens.io/docs/api/v3/Activate
"""
response=Response("","",0,"")
try:
response=Response.from_string(HelperMethods.send_request("key/activate", {"token":token,\
"ProductId":product_id,\
"key":key,\
"MachineCode":machine_code,\
"FieldsToReturn":fields_to_return,\
"metadata":metadata,\
"FloatingTimeInterval": floating_time_interval,\
"MaxOverdraft": max_overdraft,\
"FriendlyName" : friendly_name,\
"ModelVersion" : 2,\
"Sign":"True",\
"SignMethod":1}))
exceptHTTPErrorase:
response=Response.from_string(e.read())
exceptURLErrorase:
return (None, "Could not contact the server. Error message: "+str(e))
exceptException:
return (None, "Could not contact the server.")
pubkey=RSAPublicKey.from_string(rsa_pub_key)
ifresponse.result==1:
return (None, response.message)
else:
try:
ifHelperMethods.verify_signature(response, pubkey):
return (LicenseKey.from_response(response), response.message)
else:
return (None, "The signature check failed.")
exceptException:
return (None, "The signature check failed.")
@staticmethod
defget_key(token, rsa_pub_key, product_id, key, fields_to_return=0,\
metadata=False, floating_time_interval=0):
"""
Calls the GetKey method in Web API 3 and returns a tuple containing
(LicenseKey, Message). If an error occurs, LicenseKey will be None. If
everything went well, no message will be returned.
More docs: https://app.cryptolens.io/docs/api/v3/GetKey
"""
response=Response("","",0,"")
try:
response=Response.from_string(HelperMethods.send_request("key/getkey", {"token":token,\
"ProductId":product_id,\
"key":key,\
"FieldsToReturn":fields_to_return,\
"metadata":metadata,\
"FloatingTimeInterval": floating_time_interval,\
"Sign":"True",\
"SignMethod":1}))
exceptHTTPErrorase:
response=Response.from_string(e.read())
exceptURLErrorase:
return (None, "Could not contact the server. Error message: "+str(e))
exceptException:
return (None, "Could not contact the server.")
pubkey=RSAPublicKey.from_string(rsa_pub_key)
ifresponse.result==1:
return (None, response.message)
else:
try:
ifHelperMethods.verify_signature(response, pubkey):
return (LicenseKey.from_response(response), response.message)
else:
return (None, "The signature check failed.")
exceptException:
return (None, "The signature check failed.")
@staticmethod
defcreate_trial_key(token, product_id, machine_code):
"""
Calls the CreateTrialKey method in Web API 3 and returns a tuple containing
(LicenseKeyString, Message). If an error occurs, LicenseKeyString will be None. If
everything went well, no message will be returned.
More docs: https://app.cryptolens.io/docs/api/v3/CreateTrialKey
"""
response=""
try:
response=HelperMethods.send_request("key/createtrialkey", {"token":token,\
"ProductId":product_id,\
"MachineCode":machine_code})
exceptHTTPErrorase:
response=e.read()
exceptURLErrorase:
return (None, "Could not contact the server. Error message: "+str(e))
exceptException:
return (None, "Could not contact the server.")
jobj=json.loads(response)
ifjobj==Noneornot("result"injobj) orjobj["result"] ==1:
ifjobj!=None:
return (None, jobj["message"])
else:
return (None, "Could not contact the server.")
try:
return (jobj["key"], "")
except:
return (None, "An unexpected error occurred")
@staticmethod
defdeactivate(token, product_id, key, machine_code, floating=False):
"""
Calls the Deactivate method in Web API 3 and returns a tuple containing
(Success, Message). If an error occurs, Success will be False. If
everything went well, Sucess is true and no message will be returned.
More docs: https://app.cryptolens.io/docs/api/v3/Deactivate
"""
response=""
try:
response=HelperMethods.send_request("key/deactivate", {"token":token,\
"ProductId":product_id,\
"Key" : key,\
"Floating" : floating,\
"MachineCode":machine_code})
exceptHTTPErrorase:
response=e.read()
exceptURLErrorase:
return (None, "Could not contact the server. Error message: "+str(e))
exceptException:
return (None, "Could not contact the server.")
jobj=json.loads(response)
ifjobj==Noneornot("result"injobj) orjobj["result"] ==1:
ifjobj!=None:
return (False, jobj["message"])
else:
return (False, "Could not contact the server.")
return (True, "")
classHelpers:
@staticmethod
defGetMachineCode():
"""
Get a unique identifier for this device.
"""
if"windows"inplatform.platform().lower():
returnHelperMethods.get_SHA256(HelperMethods.start_process(["cmd.exe", "/C", "wmic","csproduct", "get", "uuid"]))
elif"darwin"inplatform.platform().lower():
res=HelperMethods.start_process(["system_profiler","SPHardwareDataType"]).decode('utf-8')
returnHelperMethods.get_SHA256(res[res.index("UUID"):].strip())
elif"linux"inplatform.platform(HelperMethods.compute_machine_code()):
returnHelperMethods.get_SHA256(HelperMethods.compute_machine_code())
else:
returnHelperMethods.get_SHA256(HelperMethods.compute_machine_code())
@staticmethod
defIsOnRightMachine(license_key, is_floating_license=False, allow_overdraft=False, custom_machine_code=None):
"""
Check if the device is registered with the license key.
"""
current_mid=""
ifcustom_machine_code==None:
current_mid=Helpers.GetMachineCode()
else:
current_mid=custom_machine_code
iflicense_key.activated_machines==None:
returnFalse
ifis_floating_license:
iflen(license_key.activated_machines) ==1and \
(license_key.activated_machines[0].Mid[9:] ==current_midor \
allow_overdraftandlicense_key.activated_machines[0].Mid[19:] ==current_mid):
returnTrue
else:
foract_machineinlicense_key.activated_machines:
ifcurrent_mid==act_machine.Mid:
returnTrue
returnFalse
importxml.etree.ElementTree
importjson
importbase64
importdatetime
importcopy
importtime
classActivatedMachine:
def__init__(self, IP, Mid, Time, FriendlyName=""):
self.IP=IP
self.Mid=Mid
# TODO: check if time is int, and convert to datetime in this case.
self.Time=Time
self.FriendlyName=FriendlyName
classLicenseKey:
def__init__(self, ProductId, ID, Key, Created, Expires, Period, F1, F2,\
F3, F4, F5, F6, F7, F8, Notes, Block, GlobalId, Customer, \
ActivatedMachines, TrialActivation, MaxNoOfMachines, \
AllowedMachines, DataObjects, SignDate, RawResponse):
self.product_id=ProductId
self.id=ID
self.key=Key
self.created=Created
self.expires=Expires
self.period=Period
self.f1=F1
self.f2=F2
self.f3=F3
self.f4=F4
self.f5=F5
self.f6=F6
self.f7=F7
self.f8=F8
self.notes=Notes
self.block=Block
self.global_id=GlobalId
self.customer=Customer
self.activated_machines=ActivatedMachines
self.trial_activation=TrialActivation
self.max_no_of_machines=MaxNoOfMachines
self.allowed_machines=AllowedMachines
self.data_objects=DataObjects
self.sign_date=SignDate
self.raw_response=RawResponse
@staticmethod
deffrom_response(response):
ifresponse.result=="1":
raiseValueError("The response did not contain any license key object since it was unsuccessful. Message '{0}'.".format(response.message))
obj=json.loads(base64.b64decode(response.license_key).decode('utf-8'))
returnLicenseKey(obj["ProductId"], obj["ID"], obj["Key"], datetime.datetime.fromtimestamp(obj["Created"]),\
datetime.datetime.fromtimestamp(obj["Expires"]), obj["Period"], obj["F1"], obj["F2"], \
obj["F3"], obj["F4"],obj["F5"],obj["F6"], obj["F7"], \
obj["F8"], obj["Notes"], obj["Block"], obj["GlobalId"],\
obj["Customer"], LicenseKey.__load_activated_machines(obj["ActivatedMachines"]), obj["TrialActivation"], \
obj["MaxNoOfMachines"], obj["AllowedMachines"], obj["DataObjects"], \
datetime.datetime.fromtimestamp(obj["SignDate"]), response)
defsave_as_string(self):
"""
Save the license as a string that can later be read by load_from_string.
"""
res=copy.copy(self.raw_response.__dict__)
res["licenseKey"] =res["license_key"]
res.pop("license_key", None)
returnjson.dumps(res)
@staticmethod
defload_from_string(rsa_pub_key, string, signature_expiration_interval=-1):
"""
Loads a license from a string generated by save_as_string.
Note: if an error occurs, None will be returned. An error can occur
if the license string has been tampered with or if the public key is
incorrectly formatted.
:param signature_expiration_interval: If the license key was signed,
this method will check so that no more than "signatureExpirationInterval"
days have passed since the last activation.
"""
response=Response("","","","")
try:
response=Response.from_string(string)
exceptExceptionasex:
returnNone
ifresponse.result=="1":
returnNone
else:
try:
pubKey=RSAPublicKey.from_string(rsa_pub_key)
ifHelperMethods.verify_signature(response, pubKey):
licenseKey=LicenseKey.from_response(response)
ifsignature_expiration_interval>0and \
(licenseKey.sign_date+datetime.timedelta(days=1*signature_expiration_interval) <datetime.datetime.utcnow()):
returnNone
returnlicenseKey
else:
returnNone
exceptException:
returnNone
@staticmethod
def__load_activated_machines(obj):
ifobj==None:
returnNone
arr= []
foriteminobj:
arr.append(ActivatedMachine(**item))
returnarr
classResponse:
def__init__(self, license_key, signature, result, message):
self.license_key=license_key
self.signature=signature
self.result=result
self.message=message
@staticmethod
deffrom_string(responseString):
obj=json.loads(responseString)
licenseKey=""
signature=""
result=0
message=""
if"licenseKey"inobj:
licenseKey=obj["licenseKey"]
if"signature"inobj:
signature=obj["signature"]
if"message"inobj:
message=obj["message"]
if"result"inobj:
result=obj["result"]
else:
result=1
returnResponse(licenseKey, signature, result, message)
classRSAPublicKey:
def__init__(self, modulus, exponent):
self.modulus=modulus
self.exponent=exponent
@staticmethod
deffrom_string(rsaPubKeyString):
"""
The rsaPubKeyString can be found at https://app.cryptolens.io/User/Security.
It should be of the following format:
<RSAKeyValue><Modulus>...</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>
"""
rsaKey=xml.etree.ElementTree.fromstring(rsaPubKeyString)
returnRSAPublicKey(rsaKey.find('Modulus').text, rsaKey.find('Exponent').text)