Edouard@2321: import os Edouard@2323: #from binascii import hexlify Edouard@2323: from runtime.spawn_subprocess import call Edouard@2321: Edouard@2321: restart_stunnel_cmdline = ["/etc/init.d/S50stunnel","restart"] Edouard@2321: Edouard@2323: # stunnel takes no encoding for psk, so we try to lose minimum entropy Edouard@2323: # by using all possible chars except '\0\n\r' (checked stunnel parser to be sure) Edouard@2323: translator = ''.join([(lambda c: '#' if c in '\0\n\r' else c)(chr(i)) for i in xrange(256)]) Edouard@2323: Edouard@2321: def pskgen(ID, pskpath): Edouard@2323: secret = os.urandom(256) # 2048 bits is still safe nowadays Edouard@2323: Edouard@2323: # following makes 512 length string, rejected by stunnel Edouard@2323: # using binascii hexlify loses 50% entropy Edouard@2323: # secretstring = hexlify(secret) Edouard@2323: Edouard@2323: secretstring = secret.translate(translator) Edouard@2321: pskstring = ID+":"+secretstring Edouard@2321: with open(pskpath, 'w') as f: Edouard@2321: f.write(pskstring) Edouard@2321: call(restart_stunnel_cmdline) Edouard@2321: Edouard@2321: def ensurepsk(ID, pskpath): Edouard@2321: # check if already there Edouard@2321: if not os.path.exists(pskpath): Edouard@2321: # create if needed Edouard@2323: pskgen(ID, pskpath) Edouard@2321: