Python secrets.token_hex() Examples

The following are 30 code examples of secrets.token_hex(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module secrets , or try the search function .
Example #1
Source File: test_hub.py    From the-littlest-jupyterhub with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_user_admin_add():
    """
    User is made an admin, logs in and we check if they are in admin group
    """
    # This *must* be localhost, not an IP
    # aiohttp throws away cookies if we are connecting to an IP!
    hub_url = 'http://localhost'
    username = secrets.token_hex(8)

    assert 0 == await (await asyncio.create_subprocess_exec(*TLJH_CONFIG_PATH, 'set', 'auth.type', 'dummyauthenticator.DummyAuthenticator')).wait()
    assert 0 == await (await asyncio.create_subprocess_exec(*TLJH_CONFIG_PATH, 'add-item', 'users.admin', username)).wait()
    assert 0 == await (await asyncio.create_subprocess_exec(*TLJH_CONFIG_PATH, 'reload')).wait()

    async with User(username, hub_url, partial(login_dummy, password='')) as u:
            await u.login()
            await u.ensure_server()

            # Assert that the user exists
            assert pwd.getpwnam(f'jupyter-{username}') is not None

            # Assert that the user has admin rights
            assert f'jupyter-{username}' in grp.getgrnam('jupyterhub-admins').gr_mem


# FIXME: Make this test pass 
Example #2
Source File: test_salt_master.py    From heist with GNU General Public License v3.0 6 votes vote down vote up
def test_detect_os(self,
                             mock_hub):
        '''
        test heist.heist.salt_master.detect_os
        when returncode is 0 and os is linux
        '''
        cmd_ret = asyncssh.process.SSHCompletedProcess(
            command={'uname -a'},
            exit_status=0,
            returncode=0,
            stdout='Linux test-name 5.0',
            stderr='')

        # Setup
        t_name = secrets.token_hex()
        mock_hub.tunnel.asyncssh.cmd.return_value = cmd_ret
        ret = await heist.heist.salt_master.detect_os(mock_hub, t_name, 'asyncssh')
        assert ret == 'linux' 
Example #3
Source File: test_salt_master.py    From heist with GNU General Public License v3.0 6 votes vote down vote up
def test_get_start_cmd(self,
                                 mock_hub: testing.MockHub):
        '''
        test heist.heist.salt_master._get_start_cmd when systemctl exists
        '''
        # Setup
        t_name = secrets.token_hex()
        run_dir = os.path.join(os.sep, 'var', 'tmp', 'test')
        mock_hub.heist.ROSTERS[t_name]['bootstrap'] = True
        cmd_ret = asyncssh.process.SSHCompletedProcess(
            command={'which systemctl'},
            exit_status=0,
            returncode=0,
            stdout='/usr/bin/systemctl',
            stderr='')

        mock_hub.tunnel.asyncssh.cmd.return_value = cmd_ret

        ret = await heist.heist.salt_master._get_start_cmd(mock_hub, 'asyncssh', t_name,
                                                           os.path.join(run_dir, 'salt-2019.2.2'),
                                                           run_dir, os.path.join(run_dir, 'pfile'))
        assert ret == 'systemctl start salt-minion' 
Example #4
Source File: addinteraction.py    From apex-sigma-core with GNU General Public License v3.0 6 votes vote down vote up
def make_interaction_data(message: discord.Message, interaction_name: str, interaction_url: str, url_hash: str):
    """

    :param message:
    :type message:
    :param interaction_name:
    :type interaction_name:
    :param interaction_url:
    :type interaction_url:
    :param url_hash:
    :type url_hash:
    :return:
    :rtype:
    """
    return {
        'name': interaction_name.lower(),
        'user_id': message.author.id,
        'server_id': message.guild.id,
        'url': interaction_url,
        'hash': url_hash,
        'interaction_id': secrets.token_hex(4),
        'message_id': None,
        'reported': False,
        'active': False
    } 
Example #5
Source File: brute.py    From OneForAll with GNU General Public License v3.0 6 votes vote down vote up
def detect_wildcard(domain, authoritative_ns):
    """
    Detect use wildcard dns record or not

    :param  str  domain:  domain
    :param  list authoritative_ns: authoritative name server
    :return bool use wildcard dns record or not
    """
    logger.log('INFOR', f'Detecting {domain} use wildcard dns record or not')
    token = secrets.token_hex(4)
    random_subdomain = f'{token}.{domain}'
    resolver = utils.dns_resolver()
    resolver.nameservers = authoritative_ns
    resolver.rotate = True
    resolver.cache = None
    try:
        wildcard = do_query_a(random_subdomain, resolver)
    except Exception as e:
        logger.log('DEBUG', e.args)
        logger.log('ALERT', f'Multiple detection errors, so temporarily {domain} does not use wildcard dns record')
        return False
    else:
        return wildcard 
Example #6
Source File: smoke_test_scoring_service.py    From MLOpsPython with MIT License 6 votes vote down vote up
def call_web_app(url, headers):

    # Generate an HTTP 'traceparent' distributed tracing header
    # (per the W3C Trace Context proposed specification).
    headers['traceparent'] = "00-{0}-{1}-00".format(
        secrets.token_hex(16), secrets.token_hex(8))

    retries = 600
    for i in range(retries):
        try:
            response = requests.post(
                url, json=input, headers=headers)
            response.raise_for_status()
            return response.json()
        except requests.exceptions.HTTPError as e:
            if i == retries - 1:
                raise e
            print(e)
            print("Retrying...")
            time.sleep(1) 
Example #7
Source File: addstatus.py    From apex-sigma-core with GNU General Public License v3.0 6 votes vote down vote up
def addstatus(cmd, pld):
    """
    :param cmd: The command object referenced in the command.
    :type cmd: sigma.core.mechanics.command.SigmaCommand
    :param pld: The payload with execution data and details.
    :type pld: sigma.core.mechanics.payload.CommandPayload
    """
    if pld.args:
        status_text = ' '.join(pld.args)
        status_exists = await cmd.db[cmd.db.db_nam].StatusFiles.find_one({'text': status_text})
        if not status_exists:
            status_id = secrets.token_hex(5)
            await cmd.db[cmd.db.db_nam].StatusFiles.insert_one({'text': status_text, 'id': status_id})
            response = ok(f'Added status `{status_id}`.')
        else:
            response = error('Status already exists.')
    else:
        response = error('Nothing inputted.')
    await pld.msg.channel.send(embed=response) 
Example #8
Source File: makelist.py    From apex-sigma-core with GNU General Public License v3.0 6 votes vote down vote up
def makelist(cmd, pld):
    """
    :param cmd: The command object referenced in the command.
    :type cmd: sigma.core.mechanics.command.SigmaCommand
    :param pld: The payload with execution data and details.
    :type pld: sigma.core.mechanics.payload.CommandPayload
    """
    mode = None
    if pld.args:
        mode = settings(pld.args[0].lower())
    list_data = {
        'server_id': pld.msg.guild.id,
        'user_id': pld.msg.author.id,
        'list_id': secrets.token_hex(2),
        'mode': mode,
        'name': f'{pld.msg.author.name}\'s List',
        'contents': []
    }
    await cmd.db[cmd.db.db_nam].CustomLists.insert_one(list_data)
    response = ok(f'List `{list_data.get("list_id")}` has been created.')
    response.set_footer(text=f'You can rename it with {cmd.bot.cfg.pref.prefix}renamelist.')
    await pld.msg.channel.send(embed=response) 
Example #9
Source File: botsuggest.py    From apex-sigma-core with GNU General Public License v3.0 6 votes vote down vote up
def botsuggest(cmd, pld):
    """
    :param cmd: The command object referenced in the command.
    :type cmd: sigma.core.mechanics.command.SigmaCommand
    :param pld: The payload with execution data and details.
    :type pld: sigma.core.mechanics.payload.CommandPayload
    """
    coll = cmd.db[cmd.db.db_nam].Suggestions
    if cmd.cfg.channel:
        if pld.args:
            sugg_text = ' '.join(pld.args)
            exmp_text = ' '.join(cmd.usage.split(' ')[1:])
            if sugg_text.lower() != exmp_text.lower():
                sugg_token = secrets.token_hex(4)
                await coll.insert_one(make_sugg_data(pld.msg, pld.args, sugg_token))
                response = ok(f'Suggestion {sugg_token} submitted.')
            else:
                response = error('Please do not use this command to submit the usage example.')
        else:
            response = error('Nothing inputted.')
    else:
        response = error('Missing suggestion channel configuration.')
    await pld.msg.channel.send(embed=response) 
Example #10
Source File: makerolegroup.py    From apex-sigma-core with GNU General Public License v3.0 6 votes vote down vote up
def makerolegroup(cmd, pld):
    """
    :param cmd: The command object referenced in the command.
    :type cmd: sigma.core.mechanics.command.SigmaCommand
    :param pld: The payload with execution data and details.
    :type pld: sigma.core.mechanics.payload.CommandPayload
    """
    if pld.msg.author.guild_permissions.manage_guild:
        role_groups = pld.settings.get('role_groups') or {}
        group_id = secrets.token_hex(3)
        role_groups.update({group_id: []})
        await cmd.db.set_guild_settings(pld.msg.guild.id, 'role_groups', role_groups)
        response = ok(f'Role group {group_id} has been created.')
    else:
        response = denied('Access Denied. Manage Server needed.')
    await pld.msg.channel.send(embed=response) 
Example #11
Source File: serversuggestion.py    From apex-sigma-core with GNU General Public License v3.0 6 votes vote down vote up
def serversuggestion(cmd, pld):
    """
    :param cmd: The command object referenced in the command.
    :type cmd: sigma.core.mechanics.command.SigmaCommand
    :param pld: The payload with execution data and details.
    :type pld: sigma.core.mechanics.payload.CommandPayload
    """
    sugg_channel = await cmd.db.get_guild_settings(pld.msg.guild.id, 'suggestion_channel')
    if pld.args:
        if sugg_channel:
            channel = pld.msg.guild.get_channel(int(sugg_channel))
            if channel:
                sugg_token = secrets.token_hex(4)
                sugg_msg = await channel.send(embed=make_sugg_embed(pld.msg, pld.args, sugg_token))
                [await sugg_msg.add_reaction(r) for r in ['⬆', '⬇']]
                response = ok(f'Suggestion {sugg_token} submitted.')
            else:
                response = error('Cannot find suggestion channel.')
        else:
            response = error('Suggestion channel not set.')
    else:
        response = error('Nothing inputted.')
    await pld.msg.channel.send(embed=response) 
Example #12
Source File: etho_db.py    From ethoscope with GNU General Public License v3.0 6 votes vote down vote up
def createRandomRuns(number):

    edb = ExperimentalDB()
    users = ["ggilestro", "afrench", "hjones", "mjoyce", "ebeckwith", "qgeissmann"]
    ethoscopes = {"ETHOSCOPE_%03d" % num : eid for (num, eid) in zip (range(1,150), [secrets.token_hex(8) for i in range(149)] ) }
    
    for run in [secrets.token_hex(8) for i in range(number)]:
        user = random.choice(users)
        user_id = users.index(user)
        ethoscope_name = random.choice([n for n in ethoscopes.keys()])
        ethoscope_id = ethoscopes[ethoscope_name]
        location = random.choice(["Incubator_%02d" % i for i in range(1,11)])
        date = random_date(datetime.datetime(2020,1,1), datetime.datetime(2020,12,31)).strftime("%Y-%m-%d_%H-%M-%S")
        database = "%s_%s.db" % (date, ethoscope_id)
        filepath = "/ethoscope_data/results/%s/%s/%s/%s" % (ethoscope_id, ethoscope_name, date, database)
        r = edb.addRun(run, "tracking", ethoscope_name, ethoscope_id, user, user_id, location, random.choice([1,0]), "", filepath)
        print (r) 
Example #13
Source File: test_hub.py    From the-littlest-jupyterhub with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_user_code_execute():
    """
    User logs in, starts a server & executes code
    """
    # This *must* be localhost, not an IP
    # aiohttp throws away cookies if we are connecting to an IP!
    hub_url = 'http://localhost'
    username = secrets.token_hex(8)

    assert 0 == await (await asyncio.create_subprocess_exec(*TLJH_CONFIG_PATH, 'set', 'auth.type', 'dummyauthenticator.DummyAuthenticator')).wait()
    assert 0 == await (await asyncio.create_subprocess_exec(*TLJH_CONFIG_PATH, 'reload')).wait()

    async with User(username, hub_url, partial(login_dummy, password='')) as u:
            await u.login()
            await u.ensure_server()
            await u.start_kernel()
            await u.assert_code_output("5 * 4", "20", 5, 5)

            # Assert that the user exists
            assert pwd.getpwnam(f'jupyter-{username}') is not None 
Example #14
Source File: vm_functions.py    From vm-automation with MIT License 6 votes vote down vote up
def vm_set_mac(vm, mac):
    """Change MAC address for VM

    :param vm: Virtual machine name.
    :param mac: New MAC address.
    :return: returncode, stdout, stderr.
    """
    logging.debug(f'Changing MAC address for VM "{vm}".')
    if mac == 'new':
        # Generate new MAC in VirtualBox range (080027xxxxxx)
        mac = f'080027{secrets.token_hex(3)}'
    if mac == 'random':
        # Fully random MAC
        mac = secrets.token_hex(6)
    result = vboxmanage(f'modifyvm {vm} --macaddress1 {mac}')
    if result[0] == 0:
        logging.debug('MAC changed.')
    else:
        logging.error(f'Unable to change MAC address: {result[2]}')
    return result[0], result[1], result[2] 
Example #15
Source File: organization.py    From parsec-cloud with GNU Affero General Public License v3.0 6 votes vote down vote up
def api_organization_create(self, client_ctx, msg):
        msg = apiv1_organization_create_serializer.req_load(msg)

        bootstrap_token = token_hex(self.bootstrap_token_size)
        expiration_date = msg.get("expiration_date", None)
        try:
            await self.create(
                msg["organization_id"],
                bootstrap_token=bootstrap_token,
                expiration_date=expiration_date,
            )

        except OrganizationAlreadyExistsError:
            return {"status": "already_exists"}

        rep = {"bootstrap_token": bootstrap_token, "status": "ok"}
        if expiration_date:
            rep["expiration_date"] = expiration_date

        return apiv1_organization_create_serializer.rep_dump(rep) 
Example #16
Source File: test_salt_artifact.py    From heist with GNU General Public License v3.0 6 votes vote down vote up
def test_get_artifact(self,
                                mock_hub: testing.MockHub,
                                tmp_path):
        '''
        test heist.salt_master.get_artifact
        when artifact does not already exist
        '''
        t_name = secrets.token_hex()
        ver = '2019.2.1'

        art_l = os.path.join(tmp_path, f'salt-{ver}')
        os.mknod(art_l)

        mock_hub.artifact.salt.fetch.return_value = art_l
        mock_hub.heist.salt_master.latest.return_value = False
        ret = await heist.artifact.salt_artifact.get_artifact(mock_hub, t_name,
                                                              'asyncssh', tmp_path,
                                                              'linux', ver)
        assert ret 
Example #17
Source File: test_salt_artifact.py    From heist with GNU General Public License v3.0 6 votes vote down vote up
def test_get_artifact_exists(self,
                                       mock_hub: testing.MockHub,
                                       tmp_path):
        '''
        test heist.salt_master.get_artifact
        when artifact already exists
        '''
        t_name = secrets.token_hex()
        ver = '2019.2.1'

        art_l = os.path.join(tmp_path, f'salt-{ver}')

        mock_hub.artifact.salt.fetch.return_value = art_l
        mock_hub.heist.salt_master.latest.return_value = True
        ret = await heist.artifact.salt_artifact.get_artifact(mock_hub, t_name,
                                                              'asyncssh', tmp_path,
                                                              'linux', ver)
        assert ret
        mock_hub.artifact.salt.fetch.assert_not_called() 
Example #18
Source File: test_salt_master.py    From heist with GNU General Public License v3.0 6 votes vote down vote up
def test_mk_config_bootstrap(self, mock_hub):
        '''
        test heist.salt_master.mk_config when expecting bootstrap to be
        returned
        '''
        t_name = secrets.token_hex()
        root_dir = 'test_dir'
        roster = {'master': '1.1.1.1', 'master_port': '4506'}
        mock_hub.heist.ROSTERS = {t_name: roster}
        mock_hub.heist.init.ip_is_loopback.return_value = False
        minion_config = heist.heist.salt_master.mk_config(mock_hub, root_dir, t_name)
        with open(minion_config, 'r') as min_conf:
            conf = dict(line.strip().split(': ') for line in min_conf.readlines())

        for key, default in [('master', '127.0.0.1'),
                             ('master_port', '44506'),
                             ('publish_port', '44505')]:
            if roster.get(key):
                assert conf[key] == roster[key]
            else:
                assert conf[key] == default

        roster_data = mock_hub.heist.ROSTERS
        assert roster_data[list(roster_data.keys())[0]]['bootstrap']
        assert conf['root_dir'] == root_dir 
Example #19
Source File: 961ab9adc300_.py    From SempoBlockchain with GNU General Public License v3.0 6 votes vote down vote up
def upgrade():
    conn = op.get_bind()
    session = Session(bind=conn)

    op.add_column('organisation', sa.Column('external_auth_username', sa.String(), nullable=True))
    op.add_column('organisation', sa.Column('_external_auth_password', sa.String(), nullable=True))

    tcr = sa.sql.table('organisation',
                       sa.Column('id', sa.Integer, primary_key=True),
                       sa.Column('external_auth_username', sa.String(), nullable=True),
                       sa.Column('_external_auth_password', sa.String(), nullable=True),
                       sa.Column('name', sa.String(), nullable=True))

    for org in session.query(tcr).execution_options(show_all=True).all():
        org.external_auth_username = 'admin_'+(org.name or '').lower().replace(' ', '_')
        org._external_auth_password = encrypt_string(secrets.token_hex(16))
    session.commit() 
Example #20
Source File: crypto.py    From Zilliqa-Mining-Proxy with GNU General Public License v3.0 5 votes vote down vote up
def rand_hex_str(n_len=TOKEN_STR_LENGTH, prefix="") -> str:
    if n_len <= 0:
        raise ValueError("0 and negative argument not allowed")
    return prefix + (secrets.token_hex(n_len // 2 + 1)[:n_len]) 
Example #21
Source File: etho_db.py    From ethoscope with GNU General Public License v3.0 5 votes vote down vote up
def createRandomEthoscopes(number):

    edb = ExperimentalDB()
    ethoscopes = {"ETHOSCOPE_%03d" % num : eid for (num, eid) in zip (range(1,number+1), [secrets.token_hex(8) for i in range(number)] ) }
    
    for etho in [name for name in ethoscopes.keys()]:
        print (edb.updateEthoscopes(ethoscopes[etho], etho)) 
Example #22
Source File: security.py    From permon with MIT License 5 votes vote down vote up
def get_secret_key():
    """
    Get the secret key. This key is created once and stays the same afterwards.
    """
    os.makedirs(data_dir, exist_ok=True)

    if os.path.exists(secret_path):
        return open(secret_path).read()
    else:
        token = secrets.token_hex()
        with open(secret_path, 'w') as f:
            f.write(token)

        return token 
Example #23
Source File: server.py    From gd.py with MIT License 5 votes vote down vote up
def __init__(self, name: str, password: str, account_id: int, id: int) -> None:
        self.name = name
        self.password = password
        self.account_id = account_id
        self.id = id
        # generate 256-bit token (32 bytes -> 256 bits)
        self.token = secrets.token_hex(32) 
Example #24
Source File: machine.py    From apex-sigma-core with GNU General Public License v3.0 5 votes vote down vote up
def new():
        """

        :return:
        :rtype:
        """
        components = {'attribute': None, 'manufacturer': None, 'ammunition': None, 'classification': None}
        for ck in components:
            comp_roll = secrets.randbelow(8)
            components.update({ck: comp_roll})
        return {
            'machine_id': secrets.token_hex(4),
            'components': components
        } 
Example #25
Source File: etho_db.py    From ethoscope with GNU General Public License v3.0 5 votes vote down vote up
def addRun (self, run_id="", experiment_type="tracking", ethoscope_name="", ethoscope_id="n/a", username="n/a", user_id=0, location="", alert=False, comments="", experimental_data=""):
        """
        Add a new row with a new experiment
        :param run_id: A unique run ID
        :param experiment_type: Type of experiment e.g. tracking, video, etc
        :param etho_num: Ethoscope number
        :param etho_id:  Ethoscope id string
        :param username: Username of the user who started the experiment
        :param user_id:  User ID of the user who started the experiment
        :param location: The location where the ethoscope is running
        :param alert:    Send alert via email, sms?
        :param comments: Any comment
        :param experimental_data: link to the metadata (currently unsupported)
        :return: the ID of the experiment assigned by the database
        """

        #if a run_id is not provided, it will be generated on the spot
        if run_id == "": run_id = secrets.token_hex(8)
        
        start_time = datetime.datetime.now()
        end_time = 0
        status = "running"

        problems = ""
        
        sql_enter_new_experiment = "INSERT INTO %s VALUES( NULL, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s')" % ( self._runs_table_name, run_id, experiment_type, ethoscope_name, ethoscope_id, username, user_id, location, start_time, end_time, alert, problems, experimental_data, comments, status)
        return self.executeSQL ( sql_enter_new_experiment ) 
Example #26
Source File: get_random_password.py    From node-launcher with MIT License 5 votes vote down vote up
def get_random_password() -> str:
    return secrets.token_hex() 
Example #27
Source File: generate.py    From fbctf-2019-challenges with MIT License 5 votes vote down vote up
def gen_key():
    # generate a random 256 bit (i.e. 32 byte) secret
    return secrets.token_hex(32) 
Example #28
Source File: config.py    From cronyo with MIT License 5 votes vote down vote up
def _config_template():
    from pkg_resources import resource_filename as resource
    import secrets
    template = open(resource('cronyo', 'config.yml.template'), 'r').read()
    template = template.replace("RANDOM_KEY", secrets.token_hex(40))
    return template 
Example #29
Source File: cron_rules.py    From cronyo with MIT License 5 votes vote down vote up
def update(cron_expression,
        target_arn,
        target_input,
        name=_namespaced(secrets.token_hex(10)),
        description=None):

    rules = _find([name, _namespaced(name)])
    if len(rules) > 0:
        put(name, cron_expression, target_arn, target_input, description) 
Example #30
Source File: cron_rules.py    From cronyo with MIT License 5 votes vote down vote up
def add(cron_expression,
        target_arn,
        target_input,
        name=_namespaced(secrets.token_hex(10)),
        description=None):

    rules = _find([name, _namespaced(name)])
    if len(rules) > 0:
        logger.warn("rule with name {} already exists. "
                    "Use `update` instead?".format(name))
        return

    put(name, cron_expression, target_arn, target_input, description)