1 import os |
1 import os |
2 from binascii import hexlify |
2 #from binascii import hexlify |
|
3 from runtime.spawn_subprocess import call |
3 |
4 |
4 restart_stunnel_cmdline = ["/etc/init.d/S50stunnel","restart"] |
5 restart_stunnel_cmdline = ["/etc/init.d/S50stunnel","restart"] |
5 |
6 |
|
7 # stunnel takes no encoding for psk, so we try to lose minimum entropy |
|
8 # by using all possible chars except '\0\n\r' (checked stunnel parser to be sure) |
|
9 translator = ''.join([(lambda c: '#' if c in '\0\n\r' else c)(chr(i)) for i in xrange(256)]) |
|
10 |
6 def pskgen(ID, pskpath): |
11 def pskgen(ID, pskpath): |
7 secretstring = hexlify(os.urandom(256)) |
12 secret = os.urandom(256) # 2048 bits is still safe nowadays |
|
13 |
|
14 # following makes 512 length string, rejected by stunnel |
|
15 # using binascii hexlify loses 50% entropy |
|
16 # secretstring = hexlify(secret) |
|
17 |
|
18 secretstring = secret.translate(translator) |
8 pskstring = ID+":"+secretstring |
19 pskstring = ID+":"+secretstring |
9 with open(pskpath, 'w') as f: |
20 with open(pskpath, 'w') as f: |
10 f.write(pskstring) |
21 f.write(pskstring) |
11 call(restart_stunnel_cmdline) |
22 call(restart_stunnel_cmdline) |
12 |
23 |
13 def ensurepsk(ID, pskpath): |
24 def ensurepsk(ID, pskpath): |
14 # check if already there |
25 # check if already there |
15 if not os.path.exists(pskpath): |
26 if not os.path.exists(pskpath): |
16 # create if needed |
27 # create if needed |
17 pskgen(IS, pskpath) |
28 pskgen(ID, pskpath) |
18 |
29 |