0

我用 python 编写了一个脚本,它允许我使用 stem 更改公共 IP。该脚本没有问题,但问题是该脚本需要 /etc/tor/torrc 中的哈希密码进行身份验证。我希望所有其他人都使用我的脚本,但他们需要手动将哈希密码放入脚本中。那么,有没有可以自动获取哈希密码的python脚本呢?

(请不要使用 tor --hash-password my_password,因为密码也必须存储在 torrc 中。)

帮助将不胜感激,谢谢。

4

2 回答 2

1

结合 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
于 2021-04-21T15:07:28.737 回答
0

使用 Stem 使用 Tor 子进程对控制器进行身份验证

我制作了这个使用tor --hash-passwordstem.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)
于 2019-05-18T15:55:01.123 回答