[英]Get the Hashed Tor Password automated in python
我在python中制作了一個腳本,它允許我使用stem更改公共IP。 該腳本沒有問題,但問題是該腳本需要 /etc/tor/torrc 中的散列密碼進行身份驗證。 我希望所有其他人都使用我的腳本,但他們需要手動將散列密碼放入腳本中。 那么,有沒有可以自動獲取散列密碼的python腳本?
(請不要 tor --hash-password my_password,因為密碼也必須存儲在 torrc 中。)
幫助將不勝感激,謝謝。
關於Python 2 os.random 返回一個str,而Python 3 os.random 返回一個字節這一事實,代碼需要稍作改動
import os, hashlib, binascii, codecs
def getTorPassHashv03(sectretPassword='passw0rd'):
#python v3 working
# static 'count' value later referenced as "c"
indicator = chr(96)
# generate salt and append indicator value so that it
salt = "%s%s" % (os.urandom(8), indicator) #this will be working
c = ord(indicator)
#salt = "%s%s" % (codecs.encode(os.urandom(4), 'hex').decode(), indicator) #this will be working
#c = ord(salt[8])
#salt = "%s%s" % (codecs.encode(os.urandom(8), 'hex').decode(), indicator) #this will be working
#c = ord(salt[16])
# generate an even number that can be divided in subsequent sections. (Thanks Roman)
EXPBIAS = 6
count = (16+(c&15)) << ((c>>4) + EXPBIAS)
d = hashlib.sha1()
# take the salt and append the password
tmp = salt[:8] + sectretPassword
# hash the salty password
slen = len(tmp)
while count:
if count > slen:
d.update(tmp.encode('utf-8'))
count -= slen
else:
d.update(tmp[:count].encode('utf-8'))
count = 0
hashed = d.digest()
saltRes = binascii.b2a_hex(salt[:8].encode('utf-8')).upper().decode()
indicatorRes = binascii.b2a_hex(indicator.encode('utf-8')).upper().decode()
torhashRes = binascii.b2a_hex(hashed).upper().decode()
hashedControlPassword = '16:' + str(saltRes) + str(indicatorRes) + str(torhashRes)
return hashedControlPassword
此外,通過生成 Tor 二進制文件的方法(在 Windows 上)獲取哈希,代碼需要像這樣更改它
import subprocess, re
def genTorPassHashV00(sectretPassword='passw0rd'):
""" Launches a subprocess of tor to generate a hashed <password>"""
print('Generating a hashed password')
torP = subprocess.Popen(['tor.exe', '--hash-password', sectretPassword], stdout=subprocess.PIPE)
out, err = torP.communicate()
resultString = str(out)
match = re.search(r'(\\r\\n16:.{58})', resultString)
hashedControlPassword = re.sub(r'(\\r\\n)', "", match.group(0))
return hashedControlPassword
我制作了這個腳本,它使用tor --hash-password
和stem.process.launch_tor_with_config
來使用散列密碼。
from stem.process import launch_tor_with_config
from stem.control import Controller
from subprocess import Popen, PIPE
import logging
def genTorPassHash(password):
""" Launches a subprocess of tor to generate a hashed <password> """
logging.info("Generating a hashed password")
torP = Popen(
['tor', '--hush', '--hash-password', str(password)],
stdout=PIPE,
bufsize=1
)
try:
with torP.stdout:
for line in iter(torP.stdout.readline, b''):
line = line.strip('\n')
if "16:" not in line:
logging.debug(line)
else:
passhash = line
torP.wait()
logging.info("Got hashed password")
return passhash
except Exception:
raise
def startTor(controlPass, config):
"""
Starts tor subprocess using a custom <config>,
returns Popen and connected controller.
"""
try:
# start tor
logging.info("Starting tor subprocess")
process = launch_tor_with_config(
config=config,
tor_cmd='tor',
completion_percent=50,
timeout=60,
take_ownership=True
)
logging.info("Connecting controller")
# create controller
control = Controller.from_port(
address="127.0.0.1",
port=int(config['ControlPort'])
)
# auth controller
control.authenticate(password=controlPass)
logging.info("Connected to tor process")
return process, control
except Exception as e:
logging.exception(e)
raise e
if __name__ == "__main__":
logging.basicConfig(format='[%(asctime)s] %(message)s', datefmt="%H:%M:%S", level=logging.DEBUG)
password = raw_input('password: ')
password_hash = genTorPassHash(password)
config = {
'ClientOnly': '1',
'ControlPort': '9051',
'DataDirectory': '~/.tor/temp',
'Log': ['DEBUG stdout', 'ERR stderr' ],
'HashedControlPassword' : password_hash }
torProcess, torControl = startTor(password, config)
這是不使用 tor 的方法( 原文在這里找到):
from os import urandom
from binascii import b2a_hex
from hashlib import sha1
def getTorPassHash(secret='password'):
'''
https://gist.github.com/jamesacampbell/2f170fc17a328a638322078f42e04cbc
'''
# static 'count' value later referenced as "c"
indicator = chr(96)
# generate salt and append indicator value so that it
salt = "%s%s" % (urandom(8), indicator)
c = ord(salt[8])
# generate an even number that can be divided in subsequent sections. (Thanks Roman)
EXPBIAS = 6
count = (16+(c&15)) << ((c>>4) + EXPBIAS)
d = sha1()
# take the salt and append the password
tmp = salt[:8]+secret
# hash the salty password
slen = len(tmp)
while count:
if count > slen:
d.update(tmp)
count -= slen
else:
d.update(tmp[:count])
count = 0
hashed = d.digest()
# Put it all together into the proprietary Tor format.
return '16:%s%s%s' % (b2a_hex(salt[:8]).upper(),
b2a_hex(indicator),
b2a_hex(hashed).upper())
if __name__ == '__main__':
password = raw_input("password: ")
password_hash = getTorPassHash(password)
config = {
'ClientOnly': '1',
'ControlPort': '9051',
'DataDirectory': '~/.tor/temp',
'Log': ['DEBUG stdout', 'ERR stderr' ],
'HashedControlPassword' : password_hash }
torProcess, torControl = startTor(password, config)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.