|
1
|
|
|
import binascii |
|
2
|
|
|
from ige import SecurityException, log |
|
3
|
|
|
import hashlib |
|
4
|
|
|
import os |
|
5
|
|
|
import rsa |
|
6
|
|
|
import time |
|
7
|
|
|
|
|
8
|
|
|
defaultMethod = "rsa" |
|
9
|
|
|
|
|
10
|
|
|
# support for RSA keys |
|
11
|
|
|
publicKey = None |
|
12
|
|
|
privateKey = None |
|
13
|
|
|
|
|
14
|
|
|
def init(authMethod, size=2048): |
|
15
|
|
|
# RSA needs init |
|
16
|
|
|
if authMethod == "rsa": |
|
17
|
|
|
initRSAKeys(size) |
|
18
|
|
|
|
|
19
|
|
|
def _generateKeys(size): |
|
20
|
|
|
global publicKey, privateKey |
|
21
|
|
|
# no keys, let's generate them |
|
22
|
|
|
log.message("Generating RSA keys of size {0}, please wait...".format(size)) |
|
23
|
|
|
publicKey, privateKey = rsa.newkeys(size) |
|
24
|
|
|
|
|
25
|
|
|
def initRSAKeys(size): |
|
26
|
|
|
"""Load or generate and save RSA keys""" |
|
27
|
|
|
_generateKeys(size) |
|
28
|
|
|
|
|
29
|
|
|
def getPublicKey(): |
|
30
|
|
|
"""Get current RSA public key""" |
|
31
|
|
|
assert publicKey is not None |
|
32
|
|
|
return publicKey |
|
33
|
|
|
|
|
34
|
|
|
def getPrivateKey(): |
|
35
|
|
|
"""Get current RSA private key""" |
|
36
|
|
|
assert privateKey is not None |
|
37
|
|
|
return privateKey |
|
38
|
|
|
|
|
39
|
|
|
# |
|
40
|
|
|
def getMethod(challenge): |
|
41
|
|
|
return challenge.split(":")[0] |
|
42
|
|
|
|
|
43
|
|
|
def getWelcomeString(method = "rsa"): |
|
44
|
|
|
"""Return welcome string (typically a challenge)""" |
|
45
|
|
|
if method == "sha256": |
|
46
|
|
|
return "sha256:" + hashlib.sha256(str(time.time())).hexdigest() |
|
47
|
|
|
elif method == "rsa": |
|
48
|
|
|
publicKey = getPublicKey() |
|
49
|
|
|
return "rsa:%s:%s" % (publicKey.n, publicKey.e) |
|
50
|
|
|
raise SecurityException("Unsupported authentication method %s" % str(method)) |
|
51
|
|
|
|
|
52
|
|
|
def encode(password, challenge): |
|
53
|
|
|
"""Encode password using auth method specified in the challenge""" |
|
54
|
|
|
method = getMethod(challenge) |
|
55
|
|
|
if method == "sha256": |
|
56
|
|
|
return hashlib.sha256(password + challenge).hexdigest() |
|
57
|
|
|
elif method == "rsa": |
|
58
|
|
|
dummy, n, e = challenge.split(":") |
|
59
|
|
|
key = rsa.PublicKey(int(n), int(e)) |
|
60
|
|
|
return binascii.hexlify(rsa.encrypt(password.encode('utf-8'), key)) |
|
61
|
|
|
raise SecurityException("Unsupported authentication method %s" % str(method)) |
|
62
|
|
|
|
|
63
|
|
|
def unwrapUserPassword(password, challenge): |
|
64
|
|
|
"""Decode password according to auth method (if possible)""" |
|
65
|
|
|
method = getMethod(challenge) |
|
66
|
|
|
if method == "sha256": |
|
67
|
|
|
return password |
|
68
|
|
|
elif method == "rsa": |
|
69
|
|
|
return rsa.decrypt(binascii.unhexlify(password), getPrivateKey()) |
|
70
|
|
|
raise SecurityException("Unsupported authentication method %s" % str(method)) |
|
71
|
|
|
|
|
72
|
|
|
|