Python os.urandom() Examples

The following are 30 code examples of os.urandom(). 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 os , or try the search function .
Example #1
Source File: mtprotostate.py    From Telethon with MIT License 7 votes vote down vote up
def encrypt_message_data(self, data):
        """
        Encrypts the given message data using the current authorization key
        following MTProto 2.0 guidelines core.telegram.org/mtproto/description.
        """
        data = struct.pack('<qq', self.salt, self.id) + data
        padding = os.urandom(-(len(data) + 12) % 16 + 12)

        # Being substr(what, offset, length); x = 0 for client
        # "msg_key_large = SHA256(substr(auth_key, 88+x, 32) + pt + padding)"
        msg_key_large = sha256(
            self.auth_key.key[88:88 + 32] + data + padding).digest()

        # "msg_key = substr (msg_key_large, 8, 16)"
        msg_key = msg_key_large[8:24]
        aes_key, aes_iv = self._calc_key(self.auth_key.key, msg_key, True)

        key_id = struct.pack('<Q', self.auth_key.key_id)
        return (key_id + msg_key +
                AES.encrypt_ige(data + padding, aes_key, aes_iv)) 
Example #2
Source File: test_put_get_snow_4525.py    From snowflake-connector-python with Apache License 2.0 6 votes vote down vote up
def test_load_bogus_json_file(tmpdir, conn_cnx, db_parameters):
    """SNOW-4525: Loads Bogus JSON file and should fail."""
    with conn_cnx() as cnx:
        json_table = db_parameters['name'] + "_json"
        cnx.cursor().execute(
            "create table {name} (v variant)".format(name=json_table))

        temp_file = str(tmpdir.join('bogus_json_files'))
        with open(temp_file, 'wb') as random_binary_file:
            random_binary_file.write(os.urandom(1024))
        cnx.cursor().execute(
            "put file://{file} @%{name}".format(file=temp_file,
                                                name=json_table))

        with cnx.cursor() as c:
            c.execute(
                "copy into {name} on_error='skip_file' "
                "file_format=(type='json')".format(
                    name=json_table))
            cnt = 0
            for _rec in c:
                cnt += 1
            assert _rec[1] == "LOAD_FAILED"
        cnx.cursor().execute(
            "drop table if exists {name}".format(name=json_table)) 
Example #3
Source File: test_bootaction_asset_render.py    From drydock with Apache License 2.0 6 votes vote down vote up
def test_bootaction_render_key(self, input_files, deckhand_ingester,
                                   setup):
        """Test that a bootaction can render the correct action_id and
           action_key needed by the signalling API."""
        input_file = input_files.join("deckhand_fullsite.yaml")

        design_state = DrydockState()
        design_ref = "file://%s" % str(input_file)

        design_status, design_data = deckhand_ingester.ingest_data(
            design_state=design_state, design_ref=design_ref)

        ba = design_data.get_bootaction('helloworld')
        action_id = ulid2.generate_binary_ulid()
        action_key = os.urandom(32)
        assets = ba.render_assets('compute01', design_data, action_id,
                                  action_key, design_ref)

        assert action_key.hex() in assets[2].rendered_bytes.decode('utf-8')
        assert ulid2.ulid_to_base32(
            action_id) in assets[2].rendered_bytes.decode('utf-8') 
Example #4
Source File: gipc.py    From gipc with MIT License 6 votes vote down vote up
def __init__(self):
        global _all_handles
        # Generate label of text/unicode type from three random bytes.
        self._id = codecs.encode(os.urandom(3), "hex_codec").decode("ascii")
        self._legit_pid = os.getpid()
        self._make_nonblocking()

        # Define lock for synchronizing access to this handle within the current
        # process. Note that a `gevent.lock.Semaphore` instance lives on the
        # heap of the current process and cannot be used to synchronize access
        # across multiple processes. That is, this lock is only meaningful in
        # the current process. This is especially important to consider when the
        # platform supports fork()ing.
        self._lock = gevent.lock.Semaphore(value=1)
        self._closed = False
        _all_handles.append(self) 
Example #5
Source File: efs.py    From aegea with Apache License 2.0 6 votes vote down vote up
def create(args):
    vpc = ensure_vpc()
    if args.security_groups is None:
        args.security_groups = [__name__]
        ensure_security_group(__name__, vpc, tcp_ingress=[dict(port=socket.getservbyname("nfs"),
                                                               source_security_group_name=__name__)])
    creation_token = base64.b64encode(bytearray(os.urandom(24))).decode()
    args.tags.append("Name=" + args.name)
    create_file_system_args = dict(CreationToken=creation_token,
                                   PerformanceMode=args.performance_mode,
                                   ThroughputMode=args.throughput_mode,
                                   Tags=encode_tags(args.tags))
    if args.throughput_mode == "provisioned":
        create_file_system_args.update(ProvisionedThroughputInMibps=args.provisioned_throughput_in_mibps)
    fs = clients.efs.create_file_system(**create_file_system_args)
    waiter = make_waiter(clients.efs.describe_file_systems, "FileSystems[].LifeCycleState", "available", "pathAny")
    waiter.wait(FileSystemId=fs["FileSystemId"])
    security_groups = [resolve_security_group(g, vpc).id for g in args.security_groups]
    for subnet in vpc.subnets.all():
        clients.efs.create_mount_target(FileSystemId=fs["FileSystemId"],
                                        SubnetId=subnet.id,
                                        SecurityGroups=security_groups)
    return fs 
Example #6
Source File: test_bootaction_asset_render.py    From drydock with Apache License 2.0 6 votes vote down vote up
def test_bootaction_render_design_ref(self, input_files, deckhand_ingester,
                                          setup):
        """Test the bootaction render routine provides expected output."""
        input_file = input_files.join("deckhand_fullsite.yaml")

        design_state = DrydockState()
        design_ref = "file://%s" % str(input_file)

        design_status, design_data = deckhand_ingester.ingest_data(
            design_state=design_state, design_ref=design_ref)

        ba = design_data.get_bootaction('helloworld')
        action_id = ulid2.generate_binary_ulid()
        action_key = os.urandom(32)
        assets = ba.render_assets('compute01', design_data, action_id,
                                  action_key, design_ref)

        assert 'deckhand_fullsite.yaml' in assets[2].rendered_bytes.decode(
            'utf-8') 
Example #7
Source File: Mainframe.py    From BiblioPixelAnimations with MIT License 6 votes vote down vote up
def step(self, amt=8):
        if self.scroll:
            new_bytes = [i for i in bytearray(
                os.urandom(self.rand_bytes_rows))]
            for y in range(self.rand_bytes_rows):
                self.bytes[y].pop(0)
                self.bytes[y].append(new_bytes[y])
        else:
            self.__genBytes()

        for y in range(self.height):
            for x in range(self.width):
                b = self.bytes[y // 8][x]
                bit = bool(b & (1 << (y % 8)))
                color = self.palette(int(bit))
                self.layout.set(self.width - x - 1, y, color) 
Example #8
Source File: BinaryFuzz_test.py    From ALF with Apache License 2.0 6 votes vote down vote up
def test_BinaryFuzz_fuzz_data(self):
        f = BinaryFuzz.BinaryFileFuzzer()
        test_size = 1000
        test_data = os.urandom(test_size)
        for fuzz_type in range(BinaryFuzz.BINFUZZ_N+1):
            if fuzz_type >= BinaryFuzz.BINFUZZ_N:
                fuzz_type = None
            with self.assertRaises(TypeError):
                f.fuzz_data(test_data, "1")
            fuzz_count, fuzz_data = f.fuzz_data(test_data, 0, fuzz_type=fuzz_type) # no fuzzing
            self.assertEqual(fuzz_count, 0, "Data was fuzzed")
            fuzz_count, fuzz_data = f.fuzz_data(test_data, -1, fuzz_type=fuzz_type)
            self.assertEqual(fuzz_count, 1)
            self.assertNotEqual(test_data, fuzz_data, "Data was not fuzzed (may happen randomly)")
            fuzz_count, fuzz_data = f.fuzz_data(test_data, test_size/100, fuzz_type=fuzz_type)
            self.assertAlmostEqual(fuzz_count, test_size/10, delta=10)
            self.assertNotEqual(test_data, fuzz_data, "Data was not fuzzed") 
Example #9
Source File: sessions.py    From cherrypy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def generate_id(self):
        """Return a new session id."""
        return binascii.hexlify(os.urandom(20)).decode('ascii') 
Example #10
Source File: test_api_bootaction_status.py    From drydock with Apache License 2.0 6 votes vote down vote up
def seed_bootaction_status(self, blank_state, yaml_orchestrator,
                               input_files):
        """Add a task and boot action to the database for testing."""
        input_file = input_files.join("fullsite.yaml")
        design_ref = "file://%s" % input_file
        test_task = yaml_orchestrator.create_task(
            action=hd_fields.OrchestratorAction.Noop, design_ref=design_ref)

        id_key = os.urandom(32)
        action_id = ulid2.generate_binary_ulid()
        blank_state.post_boot_action('compute01', test_task.get_id(), id_key,
                                     action_id, 'helloworld')

        ba = dict(
            nodename='compute01',
            task_id=test_task.get_id(),
            identity_key=id_key.hex(),
            action_id=ulid2.encode_ulid_base32(action_id))
        return ba 
Example #11
Source File: test_cache_system.py    From zmirror with MIT License 6 votes vote down vote up
def test_io_and_many_files(self):
        import os
        from time import time

        start = time()
        for i in range(10000):  # 顺便测试能不能承受大量文件
            obj = os.urandom(16 * 1024)
            self.cache.put_obj(i, obj, info_dict={"bin": obj})
        for i in range(10000):
            info = self.cache.get_info(i)
            obj = self.cache.get_obj(i)
            self.assertEqual(info['bin'], obj)
        print("test_io_and_many_files IO total time:", time() - start)

        # test clean delete
        all_cache_file_path = [v[0] for v in self.cache.items_dict.values()]
        start = time()
        del self.cache
        print("test_io_and_many_files DELETE ALL total time:", time() - start)
        for path in all_cache_file_path:
            self.assertFalse(os.path.exists(path), msg=path) 
Example #12
Source File: test_unit_arrow_chunk_iterator.py    From snowflake-connector-python with Apache License 2.0 6 votes vote down vote up
def test_iterate_over_binary_chunk():
    random.seed(datetime.datetime.now())
    column_meta = {
        "byteLength": "100",
        "logicalType": "BINARY",
        "precision": "0",
        "scale": "0",
        "charLength": "0"
    }

    def byte_array_generator():
        return bytearray(os.urandom(1000))

    iterate_over_test_chunk([pyarrow.binary(), pyarrow.binary()],
                            [column_meta, column_meta],
                            byte_array_generator) 
Example #13
Source File: test_put_get_snow_4525.py    From snowflake-connector-python with Apache License 2.0 6 votes vote down vote up
def test_load_bogus_json_file(tmpdir, conn_cnx, db_parameters):
    """SNOW-4525: Loads Bogus JSON file and should fail."""
    with conn_cnx() as cnx:
        json_table = db_parameters['name'] + "_json"
        cnx.cursor().execute(
            "create table {name} (v variant)".format(name=json_table))

        temp_file = str(tmpdir.join('bogus_json_files'))
        with open(temp_file, 'wb') as random_binary_file:
            random_binary_file.write(os.urandom(1024))
        cnx.cursor().execute(
            "put file://{file} @%{name}".format(file=temp_file,
                                                name=json_table))

        with cnx.cursor() as c:
            c.execute(
                "copy into {name} on_error='skip_file' "
                "file_format=(type='json')".format(
                    name=json_table))
            cnt = 0
            for _rec in c:
                cnt += 1
            assert _rec[1] == "LOAD_FAILED"
        cnx.cursor().execute(
            "drop table if exists {name}".format(name=json_table)) 
Example #14
Source File: crypt.py    From pgrepup with GNU General Public License v3.0 6 votes vote down vote up
def _get_key():
    if this.key:
        return this.key

    secret = getpass.getpass()
    try:
        salt = config().get('Security', 'salt')
    except NoOptionError:
        salt = base64.urlsafe_b64encode(os.urandom(16))
        config().set('Security', 'salt', salt)

    kdf = PBKDF2HMAC(
        algorithm=hashes.SHA256(),
        length=32,
        salt=salt,
        iterations=100000,
        backend=default_backend()
    )
    this.key = base64.urlsafe_b64encode(kdf.derive(secret))
    return this.key 
Example #15
Source File: test_unit_arrow_chunk_iterator.py    From snowflake-connector-python with Apache License 2.0 6 votes vote down vote up
def test_iterate_over_binary_chunk():
    random.seed(datetime.datetime.now())
    column_meta = {
        "byteLength": "100",
        "logicalType": "BINARY",
        "precision": "0",
        "scale": "0",
        "charLength": "0"
    }

    def byte_array_generator():
        return bytearray(os.urandom(1000))

    iterate_over_test_chunk([pyarrow.binary(), pyarrow.binary()],
                            [column_meta, column_meta],
                            byte_array_generator) 
Example #16
Source File: connection.py    From smbprotocol with MIT License 6 votes vote down vote up
def _encrypt(self, b_data, session):
        header = SMB2TransformHeader()
        header['original_message_size'] = len(b_data)
        header['session_id'] = session.session_id

        encryption_key = session.encryption_key
        if self.dialect >= Dialects.SMB_3_1_1:
            cipher = self.cipher_id
        else:
            cipher = Ciphers.get_cipher(Ciphers.AES_128_CCM)
        if cipher == aead.AESGCM:
            nonce = os.urandom(12)
            header['nonce'] = nonce + (b"\x00" * 4)
        else:
            nonce = os.urandom(11)
            header['nonce'] = nonce + (b"\x00" * 5)

        cipher_text = cipher(encryption_key).encrypt(nonce, b_data, header.pack()[20:])
        signature = cipher_text[-16:]
        enc_message = cipher_text[:-16]

        header['signature'] = signature
        header['data'] = enc_message

        return header 
Example #17
Source File: account.py    From eth-account with MIT License 6 votes vote down vote up
def create(self, extra_entropy=''):
        r"""
        Creates a new private key, and returns it as a :class:`~eth_account.local.LocalAccount`.

        :param extra_entropy: Add extra randomness to whatever randomness your OS can provide
        :type extra_entropy: str or bytes or int
        :returns: an object with private key and convenience methods

        .. code-block:: python

            >>> from eth_account import Account
            >>> acct = Account.create('KEYSMASH FJAFJKLDSKF7JKFDJ 1530')
            >>> acct.address
            '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E'
            >>> acct.key
            HexBytes('0x8676e9a8c86c8921e922e61e0bb6e9e9689aad4c99082620610b00140e5f21b8')

            # These methods are also available: sign_message(), sign_transaction(), encrypt()
            # They correspond to the same-named methods in Account.*
            # but without the private key argument
        """
        extra_key_bytes = text_if_str(to_bytes, extra_entropy)
        key_bytes = keccak(os.urandom(32) + extra_key_bytes)
        return self.from_key(key_bytes) 
Example #18
Source File: qutescheme.py    From qutebrowser with GNU General Public License v3.0 6 votes vote down vote up
def qute_settings(url: QUrl) -> _HandlerRet:
    """Handler for qute://settings. View/change qute configuration."""
    global csrf_token

    if url.path() == '/set':
        if url.password() != csrf_token:
            message.error("Invalid CSRF token for qute://settings!")
            raise RequestDeniedError("Invalid CSRF token!")
        return _qute_settings_set(url)

    # Requests to qute://settings/set should only be allowed from
    # qute://settings. As an additional security precaution, we generate a CSRF
    # token to use here.
    if secrets:
        csrf_token = secrets.token_urlsafe()
    else:
        # On Python < 3.6, from secrets.py
        token = base64.urlsafe_b64encode(os.urandom(32))
        csrf_token = token.rstrip(b'=').decode('ascii')

    src = jinja.render('settings.html', title='settings',
                       configdata=configdata,
                       confget=config.instance.get_str,
                       csrf_token=csrf_token)
    return 'text/html', src 
Example #19
Source File: test_leveldb.py    From leveldb-py with MIT License 6 votes vote down vote up
def testApproximateSizes(self):
        db = self.db_class(self.db_path, create_if_missing=True)
        self.assertEqual([0, 0, 0],
            db.approximateDiskSizes(("a", "z"), ("0", "9"), ("A", "Z")))
        batch = leveldb.WriteBatch()
        for i in xrange(100):
            batch.put("c%d" % i, os.urandom(4096))
        db.write(batch, sync=True)
        db.close()
        db = self.db_class(self.db_path)
        sizes = db.approximateDiskSizes(("0", "9"), ("A", "Z"), ("a", "z"))
        self.assertEqual(sizes[0], 0)
        self.assertEqual(sizes[1], 0)
        self.assertTrue(sizes[2] >= 4096 * 100)
        for i in xrange(10):
            db.put("3%d" % i, os.urandom(10))
        db.close()
        db = self.db_class(self.db_path)
        sizes = db.approximateDiskSizes(("A", "Z"), ("a", "z"), ("0", "9"))
        self.assertEqual(sizes[0], 0)
        self.assertTrue(sizes[1] >= 4096 * 100)
        self.assertTrue(sizes[2] < 4096 * 100)
        self.assertTrue(sizes[2] >= 10 * 10)
        db.close() 
Example #20
Source File: core.py    From brutemap with GNU General Public License v3.0 6 votes vote down vote up
def makeFile():
    """
    Membuat file hasil brute force
    """

    dirname = os.path.dirname(SETTING.OUTPUT)
    if not dirname:
        dirname = DEFAULT.OUTPUT_DIRECTORY
    elif not os.path.isdir(os.path.realpath(dirname)):
        warnMsg = "No such directory %s (using default %s)"
        warnMsg %= (repr(dirname), repr(DEFAULT.OUTPUT_DIRECTORY))
        logger.warn(warnMsg)
        dirname = DEFAULT.OUTPUT_DIRECTORY

    dirname = os.path.realpath(dirname)
    filename = os.path.basename(SETTING.OUTPUT)
    if not filename:
        filename = DEFAULT.FILENAME
    else:
        filename = filename.split(".", 1)[0]

    filename = filename + "-" + os.urandom(4).encode("hex") + "." + DEFAULT.FILE_EXTENSION
    filepath = os.path.join(dirname, filename)
    fp = open(filepath, "w")
    return fp 
Example #21
Source File: tcpobfuscated.py    From Telethon with MIT License 6 votes vote down vote up
def init_header(packet_codec):
        # Obfuscated messages secrets cannot start with any of these
        keywords = (b'PVrG', b'GET ', b'POST', b'\xee\xee\xee\xee')
        while True:
            random = os.urandom(64)
            if (random[0] != 0xef and
                    random[:4] not in keywords and
                    random[4:8] != b'\0\0\0\0'):
                break

        random = bytearray(random)
        random_reversed = random[55:7:-1]  # Reversed (8, len=48)

        # Encryption has "continuous buffer" enabled
        encrypt_key = bytes(random[8:40])
        encrypt_iv = bytes(random[40:56])
        decrypt_key = bytes(random_reversed[:32])
        decrypt_iv = bytes(random_reversed[32:48])

        encryptor = AESModeCTR(encrypt_key, encrypt_iv)
        decryptor = AESModeCTR(decrypt_key, decrypt_iv)

        random[56:60] = packet_codec.obfuscate_tag
        random[56:64] = encryptor.encrypt(bytes(random))[56:64]
        return (random, encryptor, decryptor) 
Example #22
Source File: aes.py    From Telethon with MIT License 5 votes vote down vote up
def encrypt_ige(plain_text, key, iv):
        """
        Encrypts the given text in 16-bytes blocks by using the
        given key and 32-bytes initialization vector.
        """
        padding = len(plain_text) % 16
        if padding:
            plain_text += os.urandom(16 - padding)

        if cryptg:
            return cryptg.encrypt_ige(plain_text, key, iv)
        if libssl.encrypt_ige:
            return libssl.encrypt_ige(plain_text, key, iv)

        iv1 = iv[:len(iv) // 2]
        iv2 = iv[len(iv) // 2:]

        aes = pyaes.AES(key)

        cipher_text = []
        blocks_count = len(plain_text) // 16

        for block_index in range(blocks_count):
            plain_text_block = list(
                plain_text[block_index * 16:block_index * 16 + 16]
            )
            for i in range(16):
                plain_text_block[i] ^= iv1[i]

            cipher_text_block = aes.encrypt(plain_text_block)

            for i in range(16):
                cipher_text_block[i] ^= iv2[i]

            iv1 = cipher_text_block
            iv2 = plain_text[block_index * 16:block_index * 16 + 16]

            cipher_text.extend(cipher_text_block)

        return bytes(cipher_text) 
Example #23
Source File: seed.py    From monero-python with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def generate_hex(n_bytes=32):
    """Generate a secure and random hexadecimal string. 32 bytes by default, but arguments can override.

    :rtype: str
    """
    h = hexlify(urandom(n_bytes))
    return "".join(h.decode("utf-8")) 
Example #24
Source File: low_level.py    From ServerlessCrawler-VancouverRealState with MIT License 5 votes vote down vote up
def _temporary_keychain():
    """
    This function creates a temporary Mac keychain that we can use to work with
    credentials. This keychain uses a one-time password and a temporary file to
    store the data. We expect to have one keychain per socket. The returned
    SecKeychainRef must be freed by the caller, including calling
    SecKeychainDelete.

    Returns a tuple of the SecKeychainRef and the path to the temporary
    directory that contains it.
    """
    # Unfortunately, SecKeychainCreate requires a path to a keychain. This
    # means we cannot use mkstemp to use a generic temporary file. Instead,
    # we're going to create a temporary directory and a filename to use there.
    # This filename will be 8 random bytes expanded into base64. We also need
    # some random bytes to password-protect the keychain we're creating, so we
    # ask for 40 random bytes.
    random_bytes = os.urandom(40)
    filename = base64.b64encode(random_bytes[:8]).decode('utf-8')
    password = base64.b64encode(random_bytes[8:])  # Must be valid UTF-8
    tempdirectory = tempfile.mkdtemp()

    keychain_path = os.path.join(tempdirectory, filename).encode('utf-8')

    # We now want to create the keychain itself.
    keychain = Security.SecKeychainRef()
    status = Security.SecKeychainCreate(
        keychain_path,
        len(password),
        password,
        False,
        None,
        ctypes.byref(keychain)
    )
    _assert_no_error(status)

    # Having created the keychain, we want to pass it off to the caller.
    return keychain, tempdirectory 
Example #25
Source File: extract_payload.py    From stoq with Apache License 2.0 5 votes vote down vote up
def scan(
        self, payload: Payload, request: Request
    ) -> Optional[WorkerResponse]:
        if self.EXTRACTED_PAYLOAD:
            return WorkerResponse(
                extracted=[ExtractedPayload(self.EXTRACTED_PAYLOAD)]  # type: ignore
            )
        else:
            return WorkerResponse(extracted=[ExtractedPayload(os.urandom(50))]) 
Example #26
Source File: low_level.py    From misp42splunk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def _temporary_keychain():
    """
    This function creates a temporary Mac keychain that we can use to work with
    credentials. This keychain uses a one-time password and a temporary file to
    store the data. We expect to have one keychain per socket. The returned
    SecKeychainRef must be freed by the caller, including calling
    SecKeychainDelete.

    Returns a tuple of the SecKeychainRef and the path to the temporary
    directory that contains it.
    """
    # Unfortunately, SecKeychainCreate requires a path to a keychain. This
    # means we cannot use mkstemp to use a generic temporary file. Instead,
    # we're going to create a temporary directory and a filename to use there.
    # This filename will be 8 random bytes expanded into base64. We also need
    # some random bytes to password-protect the keychain we're creating, so we
    # ask for 40 random bytes.
    random_bytes = os.urandom(40)
    filename = base64.b16encode(random_bytes[:8]).decode("utf-8")
    password = base64.b16encode(random_bytes[8:])  # Must be valid UTF-8
    tempdirectory = tempfile.mkdtemp()

    keychain_path = os.path.join(tempdirectory, filename).encode("utf-8")

    # We now want to create the keychain itself.
    keychain = Security.SecKeychainRef()
    status = Security.SecKeychainCreate(
        keychain_path, len(password), password, False, None, ctypes.byref(keychain)
    )
    _assert_no_error(status)

    # Having created the keychain, we want to pass it off to the caller.
    return keychain, tempdirectory 
Example #27
Source File: websocket.py    From tornado-zh with MIT License 5 votes vote down vote up
def _write_frame(self, fin, opcode, data, flags=0):
        if fin:
            finbit = self.FIN
        else:
            finbit = 0
        frame = struct.pack("B", finbit | opcode | flags)
        l = len(data)
        if self.mask_outgoing:
            mask_bit = 0x80
        else:
            mask_bit = 0
        if l < 126:
            frame += struct.pack("B", l | mask_bit)
        elif l <= 0xFFFF:
            frame += struct.pack("!BH", 126 | mask_bit, l)
        else:
            frame += struct.pack("!BQ", 127 | mask_bit, l)
        if self.mask_outgoing:
            mask = os.urandom(4)
            data = mask + _websocket_mask(mask, data)
        frame += data
        self._wire_bytes_out += len(frame)
        try:
            return self.stream.write(frame)
        except StreamClosedError:
            self._abort() 
Example #28
Source File: websocket.py    From tornado-zh with MIT License 5 votes vote down vote up
def __init__(self, io_loop, request, on_message_callback=None,
                 compression_options=None):
        self.compression_options = compression_options
        self.connect_future = TracebackFuture()
        self.protocol = None
        self.read_future = None
        self.read_queue = collections.deque()
        self.key = base64.b64encode(os.urandom(16))
        self._on_message_callback = on_message_callback
        self.close_code = self.close_reason = None

        scheme, sep, rest = request.url.partition(':')
        scheme = {'ws': 'http', 'wss': 'https'}[scheme]
        request.url = scheme + sep + rest
        request.headers.update({
            'Upgrade': 'websocket',
            'Connection': 'Upgrade',
            'Sec-WebSocket-Key': self.key,
            'Sec-WebSocket-Version': '13',
        })
        if self.compression_options is not None:
            # Always offer to let the server set our max_wbits (and even though
            # we don't offer it, we will accept a client_no_context_takeover
            # from the server).
            # TODO: set server parameters for deflate extension
            # if requested in self.compression_options.
            request.headers['Sec-WebSocket-Extensions'] = (
                'permessage-deflate; client_max_window_bits')

        self.tcp_client = TCPClient(io_loop=io_loop)
        super(WebSocketClientConnection, self).__init__(
            io_loop, None, request, lambda: None, self._on_http_response,
            104857600, self.tcp_client, 65536, 104857600) 
Example #29
Source File: process.py    From tornado-zh with MIT License 5 votes vote down vote up
def _reseed_random():
    if 'random' not in sys.modules:
        return
    import random
    # If os.urandom is available, this method does the same thing as
    # random.seed (at least as of python 2.6).  If os.urandom is not
    # available, we mix in the pid in addition to a timestamp.
    try:
        seed = long(hexlify(os.urandom(16)), 16)
    except NotImplementedError:
        seed = int(time.time() * 1000) ^ os.getpid()
    random.seed(seed) 
Example #30
Source File: low_level.py    From misp42splunk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def _temporary_keychain():
    """
    This function creates a temporary Mac keychain that we can use to work with
    credentials. This keychain uses a one-time password and a temporary file to
    store the data. We expect to have one keychain per socket. The returned
    SecKeychainRef must be freed by the caller, including calling
    SecKeychainDelete.

    Returns a tuple of the SecKeychainRef and the path to the temporary
    directory that contains it.
    """
    # Unfortunately, SecKeychainCreate requires a path to a keychain. This
    # means we cannot use mkstemp to use a generic temporary file. Instead,
    # we're going to create a temporary directory and a filename to use there.
    # This filename will be 8 random bytes expanded into base64. We also need
    # some random bytes to password-protect the keychain we're creating, so we
    # ask for 40 random bytes.
    random_bytes = os.urandom(40)
    filename = base64.b16encode(random_bytes[:8]).decode("utf-8")
    password = base64.b16encode(random_bytes[8:])  # Must be valid UTF-8
    tempdirectory = tempfile.mkdtemp()

    keychain_path = os.path.join(tempdirectory, filename).encode("utf-8")

    # We now want to create the keychain itself.
    keychain = Security.SecKeychainRef()
    status = Security.SecKeychainCreate(
        keychain_path, len(password), password, False, None, ctypes.byref(keychain)
    )
    _assert_no_error(status)

    # Having created the keychain, we want to pass it off to the caller.
    return keychain, tempdirectory