Example #1
0
 def test_randbits(self):
     # Test randbits.
     errmsg = "randbits(%d) returned %d"
     for numbits in (3, 12, 30):
         for i in range(6):
             n = secrets.randbits(numbits)
             self.assertTrue(0 <= n < 2**numbits, errmsg % (numbits, n))
Example #2
0
def challenge8():
    # MT19937 stream cipher -----------------------
    seed = secrets.randbits(16)
    mersenne_stream_cipher(seed, b"AAAAA")
    seed = recover_16_bit_seed()
    print(f"Seed: {seed}")

    # Password Reset Token ------------------------
    token = generate_password_reset_token()
    is_seeded_with_time, seed = break_password_reset_token(token)
    print(f"Is seeded with time? {is_seeded_with_time}")
    print(f"Seed: {seed}")
Example #3
0
def randomNum():
    # 聽到參加者夠發的event gov就發隨機數到合約裡
    r = secrets.randbits(64)
    contract_interface = contract_instance("whitelist")
    print(
        "> Calculate the difference of user's secrets with a random number. \n"
    )
    contract_interface.functions.calc_random(r).transact({'from': gov_acct})
    # print(contract_interface.functions.get_data().call())
    contract_interface.functions.sort().transact({'from': gov_acct})
    pprint.pprint(contract_interface.functions.get_difference().call())
    print("\n")
Example #4
0
    def test_conversions(self):
        binstr_entropy = "10101011" * 32
        entropy = binstr_from_entropy(binstr_entropy)
        self.assertEqual(entropy, binstr_entropy)

        int_entropy = int(binstr_entropy, 2)
        entropy = binstr_from_entropy(int_entropy)
        self.assertEqual(entropy, binstr_entropy)

        entropy = binstr_from_entropy(bin(int_entropy))
        self.assertEqual(entropy, binstr_entropy)

        bytes_entropy = int_entropy.to_bytes(32, byteorder="big")
        entropy = binstr_from_entropy(bytes_entropy)
        self.assertEqual(entropy, binstr_entropy)

        binstr_entropy = "00101011" * 32
        entropy = binstr_from_entropy(binstr_entropy)
        self.assertEqual(entropy, binstr_entropy)

        int_entropy = int(binstr_entropy, 2)
        entropy = binstr_from_entropy(int_entropy)
        self.assertEqual(entropy, binstr_entropy)

        bytes_entropy = int_entropy.to_bytes(32, byteorder="big")
        entropy = binstr_from_entropy(bytes_entropy)
        self.assertEqual(entropy, binstr_entropy)

        binstr_entropy = "00000000" + "10101011" * 31
        entropy = binstr_from_entropy(binstr_entropy)
        self.assertEqual(entropy, binstr_entropy)

        int_entropy = int(binstr_entropy, 2)
        entropy = binstr_from_entropy(int_entropy)
        self.assertEqual(entropy, binstr_entropy)

        bytes_entropy = int_entropy.to_bytes(32, byteorder="big")
        entropy = binstr_from_entropy(bytes_entropy)
        self.assertEqual(entropy, binstr_entropy)

        # the 32 bytes integer has its leftmost bit set to 0
        int_entropy = secrets.randbits(255)
        binstr_entropy = binstr_from_entropy(int_entropy)
        self.assertEqual(len(binstr_entropy), 256)

        # 257 bits
        int_entropy = 1 << 256
        binstr_entropy = binstr_from_entropy(int_entropy)
        self.assertEqual(len(binstr_entropy), 256)

        exp_int_entropy = int_entropy >> 1
        int_entropy = int(binstr_entropy, 2)
        self.assertEqual(int_entropy, exp_int_entropy)
Example #5
0
File: ice.py Project: bsdpunk/pyal
    def __init__(
        self,
        ice_controlling: bool,
        components: int = 1,
        stun_server: Optional[Tuple[str, int]] = None,
        turn_server: Optional[Tuple[str, int]] = None,
        turn_username: Optional[str] = None,
        turn_password: Optional[str] = None,
        turn_ssl: bool = False,
        turn_transport: str = "udp",
        use_ipv4: bool = True,
        use_ipv6: bool = True,
    ) -> None:
        self.ice_controlling = ice_controlling
        #: Local username, automatically set to a random value.
        self.local_username = random_string(4)
        #: Local password, automatically set to a random value.
        self.local_password = random_string(22)
        #: Whether the remote party is an ICE Lite implementation.
        self.remote_is_lite = False
        #: Remote username, which you need to set.
        self.remote_username: Optional[str] = None
        #: Remote password, which you need to set.
        self.remote_password: Optional[str] = None

        self.stun_server = stun_server
        self.turn_server = turn_server
        self.turn_username = turn_username
        self.turn_password = turn_password
        self.turn_ssl = turn_ssl
        self.turn_transport = turn_transport

        # private
        self._components = set(range(1, components + 1))
        self._check_list: List[CandidatePair] = []
        self._check_list_done = False
        self._check_list_state: asyncio.Queue = asyncio.Queue()
        self._early_checks: List[Tuple[stun.Message, Tuple[str, int],
                                       StunProtocol]] = []
        self._id = next(connection_id)
        self._local_candidates: List[Candidate] = []
        self._local_candidates_end = False
        self._local_candidates_start = False
        self._nominated: Dict[int, CandidatePair] = {}
        self._nominating: Set[int] = set()
        self._protocols: List[StunProtocol] = []
        self._remote_candidates: List[Candidate] = []
        self._remote_candidates_end = False
        self._query_consent_handle: Optional[asyncio.Future[None]] = None
        self._queue: asyncio.Queue = asyncio.Queue()
        self._tie_breaker = secrets.randbits(64)
        self._use_ipv4 = use_ipv4
        self._use_ipv6 = use_ipv6
Example #6
0
def pow(
    digits=2
):  # proof of work algorithm using random numbers. the number is how many digits
    out = 3
    while black_iverson(out)[:digits] != "0" * digits:
        data = randbits(
            64
        )  # we only need 64 bits; we're not bitcoin so we can do this without filling the space completely
        print(data)
        out = prng(data)
        print(out)
    return data
Example #7
0
def challenge7():
    rng = MersenneTwister()
    seed = secrets.randbits(32)
    rng.seed_mt(seed)
    cloned_rng = clone_rng(rng)
    for i in range(10000):
        original = rng.extract_number()
        cloned = cloned_rng.extract_number()
        correct = original == cloned
        assert correct
        print(f"\r{i + 1} numbers are correct", end="")
    print()
    def __init__(self, length):
        """
    Args:
      length: Length in bits of the nonce. """
        self.__length = length
        self.__hex_length = (self.__length + 3) // 4

        # Pick a random initial value.
        self.__nonce = secrets.randbits(self.__length)

        # Maximum nonce value.
        self.__max_nonce = pow(2, self.__length + 1) - 1
Example #9
0
def generate_zksnarks_vote_polynomial(num_challenges):
    coefficients = []

    for i in range(num_challenges):
        s = int(secrets.randbits(255).to_bytes(32, byteorder='big').hex(), 16)
        coefficients += [s]

    coefficients_encrypted = []
    for coeff in coefficients:
        coefficients_encrypted += [coeff * secp256k1.G]

    return (coefficients, coefficients_encrypted)
Example #10
0
def get_randbits(n: int) -> int:
    """

    get n bits random number

    Args:
        n (int): bits size

    Returns:
        int: n bits random number
    """
    return secrets.randbits(n)
Example #11
0
def otpgenerator(length):
    f = open("otp_secret", "w")
    otp = ""
    # Since secrets.randbits function sometimes returns value whose binary value length is less than the required length.
    # If we use that, part of plaintext will directly be present in cipher text as it would be xored with zero.
    while (len(otp) != length):
        otp = secrets.randbits(length)
        otp = BitVector(intVal=otp)
    otp = str(otp)
    f.write(otp)
    f.close()
    return "otp_secret"
Example #12
0
def generate_prime_candidate(length):
    """ Generate an odd integer randomly
        Args:
            length -- int -- the length of the number to generate, in bits
        return a integer
    """
    # generate random bits
    p = randbits(length)
    # apply a mask to set MSB and LSB to 1
    p |= (1 << length - 1) | 1

    return p
Example #13
0
 def register_cookie(self, cookie=None):
     with self.registered_lock:
         if cookie is None:
             while True:
                 cookie = b'%08X' % secrets.randbits(32)
                 if cookie not in self.registered:
                     break
         else:
             assert len(cookie) == 8
         if cookie not in self.registered:
             self.registered[cookie] = threading.Event()
     return ReverseConnectionHost.FutureConnection(self, cookie)
Example #14
0
def _resampled_data_results_1(sample, grouped_statistics):
    """Yields values for all the statistics in `grouped_statistics` after
    shuffling values from `sample.a_class` and `sample.b_class`.
    """

    # Reseed to avoid exploring the same random sequence multiple
    # times when multiprocessing.
    EXACT.exact_test_prng_seed(secrets.randbits(64))

    a = sample.a_class
    b = sample.b_class

    def _make_buf():
        buf = FFI.new("uint64_t[]", len(a) + len(b))
        for i, x in enumerate(a + b):
            buf[i] = x
        return buf

    m = len(a)
    n = len(b)
    buf = _make_buf()
    total = m + n
    shuffled_buf = FFI.new("uint64_t[]", total)
    sorted_buf = FFI.new("uint64_t[]", total)
    error_ptr = FFI.new("char**")
    xoshiro = EXACT.exact_test_prng_create()

    def compute_results():
        results = dict()
        for p_a_lt, stats_for_p in grouped_statistics.items():
            FFI.memmove(shuffled_buf, buf, total * FFI.sizeof("uint64_t"))
            if not EXACT.exact_test_shuffle(xoshiro, shuffled_buf, m, n,
                                            p_a_lt, error_ptr):
                raise Exception("Shuffle failed: %s" %
                                str(FFI.string(error_ptr[0]), "utf-8"))

            for (a_offset, b_offset), stats_for_offset in stats_for_p.items():
                FFI.memmove(sorted_buf, shuffled_buf,
                            total * FFI.sizeof("uint64_t"))
                EXACT.exact_test_offset_sort(xoshiro, sorted_buf, m, n,
                                             a_offset, b_offset)
                for stat in stats_for_offset:
                    results[stat.name] = getattr(EXACT,
                                                 stat.fn_name)(sorted_buf, m,
                                                               n,
                                                               *stat.fn_args)
        return results

    try:
        while True:
            yield compute_results()
    finally:
        EXACT.exact_test_prng_destroy(xoshiro)
Example #15
0
def gen_secret_num(p, q, g):
    acceptable_values = [(1024, 160), (2048, 224), (2048, 256), (3072, 256)]
    L = (p.bit_length() + 1, p.bit_length())[p.bit_length() % 2 == 0]
    N = (q.bit_length() + 1, q.bit_length())[q.bit_length() % 2 == 0]

    if (L, N) not in acceptable_values:
        return "ERROR", (0, 0)

    c = secrets.randbits(N + 64)
    k = (c % (q - 1)) + 1
    inv_k = pow(k, q - 2, q)
    return "SUCCESS", (k, inv_k)
Example #16
0
def approve(token):
    applicant = Applicant.query.filter_by(secure_token=token).first()
    if applicant is None: abort(404)

    if applicant.email_confirmed:
        applicant.registration_id = randbits(32)
        applicant.set_accepted()
        db.session.commit()
        return redirect(
            url_for('administrator.applicant', token=applicant.secure_token))
    flash("Email not confirmed cant approve this use")
    return redirect(url_for('administrator.applications'))
Example #17
0
def _encryption(p):
    password = "******"
    passwordSalt = os.urandom(16)
    key = pbkdf2.PBKDF2(password, passwordSalt).read(16)

    m = []
    m.clear()
    iv = secrets.randbits(128)
    aes = pyaes.AESModeOfOperationCTR(key, pyaes.Counter(iv))
    ciphertext = aes.encrypt(p)
    m.append(ciphertext), m.append(key), m.append(iv)
    return m
Example #18
0
 def __gen_valid_priv_keys(self, p, e=None):
     if e is not None:
         good = False
         while not good:
             q = secrets.randbits(self.k)
             while not miller_rabin(q, self.l):
                 q = secrets.randbits(self.k)
             phi = (p - 1) * (q - 1)
             n = p * q
             d = self.__validate_e(e, phi)
             if d is not None:
                 good = True
         return q, phi, d
     else:
         q = secrets.randbits(self.k)
         while not miller_rabin(q, self.l):
             q = secrets.randbits(self.k)
         phi = (p - 1) * (q - 1)
         n = p * q
         e, d = self.__gen_e_d(phi)
         return q, phi, d, e
Example #19
0
 def __init__(self,
              key: bytes,
              nonce: int = secrets.randbits(64),
              counter: int = 0):
     assert len(key) == 16, "key must be 16 bytes long."
     assert 0 <= self.__bit_length(
         nonce) <= 64, "nonce must be a valid 64 bit integer."
     assert 0 <= self.__bit_length(
         counter) <= 64, "counter must be a valid 64 bit integer."
     self.__KEY = key
     self.__NONCE = nonce
     self.__block_counter = counter
Example #20
0
    def __DLEQ_prove(cls, x, X, Y, Z):
        Q = cls.Q

        a = secrets.randbits(256) % Q
        A_G = a * cls.__G()
        A_Y = a * Y
        b_bytes = cls.__derive_b(X, Y, Z, A_G, A_Y)
        b = int.from_bytes(b_bytes, 'big')
        c = (a + b * x) % Q
        c_bytes = (c).to_bytes(32, 'big')

        return (b + c_bytes).hex()
Example #21
0
def encrypt():
    key = randbits(16 * 8)
    r = randbits(15 * 8 + 7)
    b = randbits(1)
    input_bytes = r << 1 | b
    aes = AES.new(key.to_bytes(16, "big"))

    ciphertext = aes.encrypt(input_bytes.to_bytes(16, "big"))
    print(f'Alice sent E(k,rb),r to Bob: {ciphertext}, {r}')

    b2 = randbits(1)
    print(f'Bob sent his bit to Alice: {b2}')
    print(f'Alice sent her key to Bob: {key}')

    plaintext = aes.decrypt(ciphertext)
    b3 = int.from_bytes(plaintext, "big") & 1
    print(f'Bob decrypted data and got: {str(b3)}')
    if b2 == b3:
        print("bits are the same")
    else:
        print("bits are different")
Example #22
0
    def cbc(self, m, encrypt=True):
        _in, blocks = self.initialize(m, encrypt)
        self.aes.inverse = False if encrypt else True
        print('AES INVERSE %s' % self.aes.inverse)
        #Junk First block implying no IV
        if encrypt:
            _in = [c_ubyte(secrets.randbits(8)) for i in range(16)] + _in
            blocks += 1
        iv = [c_ubyte(secrets.randbits(8)) for i in range(16)]

        _out = []
        prev = iv
        for i in range(blocks):
            temp = _in[16 * i:16 * (i + 1)]
            if encrypt:
                xor_block = [
                    c_ubyte(a.value ^ b.value) for a, b in zip(prev, temp)
                ]
                prev = self.aes.Cipher(xor_block)
                _out.extend(prev)
            else:
                c_out = self.aes.Cipher(temp)
                _out.extend(
                    [c_ubyte(a.value ^ b.value) for a, b in zip(prev, c_out)])
                prev = temp
        if encrypt == False:
            _out = _out[16:]
            digest = self.array_to_string(_out[len(_out) - 32:])
            _out = _out[:len(_out) - 32]
            _str = self.array_to_string(_out)
            digest2 = self.hash_string(_str)
            print('DIGEST 1: %s' % digest)
            print('DIGEST 2: %s' % digest2)
            print(digest == digest2)
            if digest != digest2:
                print(self.array_to_string(_out))
                return None
        else:
            _str = self.array_to_string(_out)
        return _str
Example #23
0
def generate_nonce():
    """Generate pseudorandom nonce that is unlikely to repeat.

    Per `section 3.3`_ of the OAuth 1 RFC 5849 spec.
    Per `section 3.2.1`_ of the MAC Access Authentication spec.

    A random 64-bit number is appended to the epoch timestamp for both
    randomness and to decrease the likelihood of collisions.

    .. _`section 3.2.1`: https://tools.ietf.org/html/draft-ietf-oauth-v2-http-mac-01#section-3.2.1
    .. _`section 3.3`: https://tools.ietf.org/html/rfc5849#section-3.3
    """
    return unicode_type(unicode_type(randbits(64)) + generate_timestamp())
Example #24
0
 def login(self) -> str:
     """
     Redirects the user to the authorization endpoint for Authorization
     """
     url = self.authorization_endpoint + (
         f"?client_id={self.client_id}&redirect_uri={self.redirect_uri}&"
         f"scope={self.scope}&response_type={self.response_type}&"
         f"response_mode={self.response_mode}")
     if self.cache_nonces:
         nonce = secrets.randbits(16)
         cache.set(nonce, self.auth_server)
         url += f"&nonce={nonce}"
     return HttpResponseRedirect(url)
Example #25
0
    async def start_recovery(self):
        self.current_state = State.RECOVERING
        self.n_recovery_messages = 0

        self.timer.cancel()
        #Send broadcast to all replicas with random nonce and its address
        self.recovery_nonce = secrets.randbits(32)
        message = json.dumps({
            "Type": "Recover",
            "N_replica": self.local_ip,
            "Nonce": self.recovery_nonce
        })
        self.replica_broadcast("post", "Recover", message)
Example #26
0
def listShuffler(initialList: list):
    workingList = copy.deepcopy(initialList)  # deepcopy that random sample
    randomNumber = secrets.randbits(
        8192)  # generate random number for random.seed()
    random.seed(
        randomNumber)  # improve the randomizer by calling random.seed()
    random.shuffle(
        workingList
    )  # shuffle the copy of the random sample again just to be sure :)
    # shuffledList = random.sample(workingList, len(workingList))  # take a random sample of list [which returns a shuffled version]

    # return the now shuffled list
    return workingList
Example #27
0
def bin_str_entropy_from_random(bits: int,
                                entropy: Optional[BinStr] = None,
                                to_be_hashed: bool = True) -> BinStr:
    """Return CSPRNG raw entropy XOR-ed with input raw entropy.

    The input raw entropy is used as initialization value;
    if not provided, then entropy is generated with the system
    cryptographically strong pseudo-random number generator (CSPRNG).

    Then, this entropy is:

    - XOR-ed with CSPRNG system entropy
    - possibly hashed (if requested)
    """

    if entropy is None or entropy == "":
        i = secrets.randbits(bits)
    else:
        if len(entropy) > bits:
            # only the leftmost bits are retained
            entropy = entropy[:bits]
        i = int(entropy, 2)

    # XOR the current entropy with CSPRNG system entropy
    i ^= secrets.randbits(bits)

    # hash the current entropy
    if to_be_hashed:
        hf = sha512()
        max_bits = hf.digest_size * 8
        if bits > max_bits:
            err_msg = f"Too many bits required: {bits}, max is {max_bits}"
            raise BTClibValueError(err_msg)
        n_bytes = math.ceil(i.bit_length() / 8)
        h512 = sha512(i.to_bytes(n_bytes, byteorder="big",
                                 signed=False)).digest()
        i = int.from_bytes(h512, byteorder="big", signed=False)

    return bin_str_entropy_from_int(i, bits)
Example #28
0
def create_keys():
    """Create the keys used by the RSA model. Public key is given first, and
    the private key is given in second.
    
    Note that :
     - the private key is the tuple (U, N)
     - public key is the tuple (N, C)
    
    """
    P = prime_numbers.found_prime(2)
    P, Q = P[0], P[1]

    N = P * Q
    M = (P - 1) * (Q - 1)

    C = randbits(8)
    while gcd(M, C) != 1:
        C = randbits(8)

    R, U, V = extended_euclidean(C, M, rsa=True)

    return ((N, C), (U, N))
Example #29
0
def generate_nonce():
    """Generate pseudorandom nonce that is unlikely to repeat.

    Per `section 3.3`_ of the OAuth 1 RFC 5849 spec.
    Per `section 3.2.1`_ of the MAC Access Authentication spec.

    A random 64-bit number is appended to the epoch timestamp for both
    randomness and to decrease the likelihood of collisions.

    .. _`section 3.2.1`: https://tools.ietf.org/html/draft-ietf-oauth-v2-http-mac-01#section-3.2.1
    .. _`section 3.3`: https://tools.ietf.org/html/rfc5849#section-3.3
    """
    return str(str(randbits(64)) + generate_timestamp())
Example #30
0
def Vernam(bits, key=-1):
    """Permet de crypter des bits grâce à une clef et un XOR appliqué aux bits.

    key est un paramètre optionnel, si une clef est donnée en paramètre alors le programme va décrypter les données
    sinon il crypte les données et renvois les données cryptées ainsi que la clef

    """
    if key == -1:
        key = randbits(len(bits))
        key = to_binary(key, len(bits))
        return XOR(bits, key), key
    else:
        return XOR(bits, key)
Example #31
0
File: user.py Project: KaiFish/DES
def sanitize(key):  #make sure user is not stupid
    b = ''
    if str.isdecimal(key) == False:
        for c in key:
            b = b + charToBits(c)
    else:
        b = b + key
    if len(b) < 64:               # pad given key if too short
        x = 64 - len(b)
        b = b + format(secrets.randbits(x), 'b')
    elif len(b) > 64:             # cut given key if too long
        b = b[0:63]
    return b
Example #32
0
def registerpassword(connection,username,password):
    """ Registers a new password hash in the database """
    duplicateuser = connection.execute("""SELECT * FROM "users" WHERE name = :username;""",dict(username=username)).fetchall()
    if duplicateuser:
        raise KeyError("User already exists")
    mysalt = secrets.randbits(1000)
    mypass = password.encode()
    myhash = gethash(mysalt,mypass)
    connection.execute("""INSERT INTO "users" (name, salt, hash) VALUES (:name, :salt, :hash);""",dict(name = username,
                                                                                  salt = binascii.hexlify(mysalt),
                                                                                  hash = binascii.hexlify(myhash))
                       )
    return True
Example #33
0
	def get_TGS(self, spn_user, override_etype = None):
		"""
		Requests a TGS ticket for the specified user.
		Retruns the TGS ticket, end the decrpyted encTGSRepPart.

		spn_user: KerberosTarget: the service user you want to get TGS for.
		override_etype: None or list of etype values (int) Used mostly for kerberoasting, will override the AP_REQ supported etype values (which is derived from the TGT) to be able to recieve whatever tgs tiecket 
		"""
		#construct tgs_req
		logging.debug('Constructing TGS request for user %s' % spn_user.get_formatted_pname())
		now = datetime.datetime.utcnow() 
		kdc_req_body = {}
		kdc_req_body['kdc-options'] = KDCOptions(set(['forwardable','renewable','renewable_ok', 'canonicalize']))
		kdc_req_body['realm'] = spn_user.domain.upper()
		kdc_req_body['sname'] = PrincipalName({'name-type': NAME_TYPE.SRV_INST.value, 'name-string': spn_user.get_principalname()})
		kdc_req_body['till'] = now + datetime.timedelta(days=1)
		kdc_req_body['nonce'] = secrets.randbits(31)
		if override_etype:
			kdc_req_body['etype'] = override_etype
		else:
			kdc_req_body['etype'] = [self.kerberos_cipher_type]

		authenticator_data = {}
		authenticator_data['authenticator-vno'] = krb5_pvno
		authenticator_data['crealm'] = Realm(self.kerberos_TGT['crealm'])
		authenticator_data['cname'] = self.kerberos_TGT['cname']
		authenticator_data['cusec'] = now.microsecond
		authenticator_data['ctime'] = now
		
		authenticator_data_enc = self.kerberos_cipher.encrypt(self.kerberos_session_key, 7, Authenticator(authenticator_data).dump(), None)
		
		ap_req = {}
		ap_req['pvno'] = krb5_pvno
		ap_req['msg-type'] = MESSAGE_TYPE.KRB_AP_REQ.value
		ap_req['ap-options'] = APOptions(set())
		ap_req['ticket'] = Ticket(self.kerberos_TGT['ticket'])
		ap_req['authenticator'] = EncryptedData({'etype': self.kerberos_cipher_type, 'cipher': authenticator_data_enc})
		
		pa_data_1 = {}
		pa_data_1['padata-type'] = PaDataType.TGS_REQ.value
		pa_data_1['padata-value'] = AP_REQ(ap_req).dump()
		
		
		kdc_req = {}
		kdc_req['pvno'] = krb5_pvno
		kdc_req['msg-type'] = MESSAGE_TYPE.KRB_TGS_REQ.value
		kdc_req['padata'] = [pa_data_1]
		kdc_req['req-body'] = KDC_REQ_BODY(kdc_req_body)
		
		req = TGS_REQ(kdc_req)
		logging.debug('Constructing TGS request to server')
		rep = self.ksoc.sendrecv(req.dump())
		logging.debug('Got TGS reply, decrypting...')
		tgs = rep.native
		
		encTGSRepPart = EncTGSRepPart.load(self.kerberos_cipher.decrypt(self.kerberos_session_key, 8, tgs['enc-part']['cipher'])).native
		key = Key(encTGSRepPart['key']['keytype'], encTGSRepPart['key']['keyvalue'])
		
		self.ccache.add_tgs(tgs, encTGSRepPart)
		logging.debug('Got valid TGS reply')
		return tgs, encTGSRepPart, key
Example #34
0
	def get_TGT(self):
		"""
		Steps performed:
			1. Send and empty (no encrypted timestamp) AS_REQ with all the encryption types we support
			2. Depending on the response (either error or AS_REP with TGT) we either send another AS_REQ with the encrypted data or return the TGT (or fail miserably)
			3. PROFIT
		"""
		logging.debug('Generating initial TGT without authentication data')
		now = datetime.datetime.utcnow()
		kdc_req_body = {}
		kdc_req_body['kdc-options'] = KDCOptions(set(['forwardable','renewable','proxiable']))
		kdc_req_body['cname'] = PrincipalName({'name-type': NAME_TYPE.PRINCIPAL.value, 'name-string': [self.usercreds.username]})
		kdc_req_body['realm'] = self.usercreds.domain.upper()
		kdc_req_body['sname'] = PrincipalName({'name-type': NAME_TYPE.PRINCIPAL.value, 'name-string': ['krbtgt', self.usercreds.domain.upper()]})
		kdc_req_body['till'] = now + datetime.timedelta(days=1)
		kdc_req_body['rtime'] = now + datetime.timedelta(days=1)
		kdc_req_body['nonce'] = secrets.randbits(31)
		kdc_req_body['etype'] = self.usercreds.get_supported_enctypes()
		
		pa_data_1 = {}
		pa_data_1['padata-type'] = int(PADATA_TYPE('PA-PAC-REQUEST'))
		pa_data_1['padata-value'] = PA_PAC_REQUEST({'include-pac': True}).dump()
		
		kdc_req = {}
		kdc_req['pvno'] = krb5_pvno
		kdc_req['msg-type'] = MESSAGE_TYPE.KRB_AS_REQ.value
		kdc_req['padata'] = [pa_data_1]
		kdc_req['req-body'] = KDC_REQ_BODY(kdc_req_body)
		
		req = AS_REQ(kdc_req)	
		
		logging.debug('Sending initial TGT to %s' % self.ksoc.get_addr_s())
		rep = self.ksoc.sendrecv(req.dump(), throw = False)
				
		if rep.name != 'KRB_ERROR':
			#this user doesn't need to provide auth data
			raise Exception('IMPLEMENT!!!')
			return
		
		if rep.native['error-code'] != KerberosErrorCode.KDC_ERR_PREAUTH_REQUIRED.value:
			raise KerberosError(rep)
		rep = rep.native
		logging.debug('Got reply from server, asikg to provide auth data')
		
		#now getting server's supported encryption methods
		
		supp_enc_methods = collections.OrderedDict()
		for enc_method in METHOD_DATA.load(rep['e-data']).native:					
			data_type = PaDataType(enc_method['padata-type'])
			
			if data_type == PaDataType.ETYPE_INFO or data_type == PaDataType.ETYPE_INFO2:
				if data_type == PaDataType.ETYPE_INFO:
					enc_info_list = ETYPE_INFO.load(enc_method['padata-value'])
					
				elif data_type == PaDataType.ETYPE_INFO2:
					enc_info_list = ETYPE_INFO2.load(enc_method['padata-value'])
		
				for enc_info in enc_info_list.native:
					supp_enc_methods[EncryptionType(enc_info['etype'])] = enc_info['salt']
					logging.debug('Server supports encryption type %s with salt %s' % (EncryptionType(enc_info['etype']).name, enc_info['salt']))
		
		logging.debug('Constructing TGT request with auth data')
		#now to create an AS_REQ with encrypted timestamp for authentication
		now = datetime.datetime.utcnow()
		pa_data_1 = {}
		pa_data_1['padata-type'] = int(PADATA_TYPE('PA-PAC-REQUEST'))
		pa_data_1['padata-value'] = PA_PAC_REQUEST({'include-pac': True}).dump()
		
		
		#creating timestamp asn1
		timestamp = PA_ENC_TS_ENC({'patimestamp': now, 'pausec': now.microsecond}).dump()
		
		supp_enc = self.usercreds.get_preferred_enctype(supp_enc_methods)
		logging.debug('Selecting common encryption type: %s' % supp_enc.name)
		cipher = _enctype_table[supp_enc.value]
		key = Key(cipher.enctype, self.usercreds.get_key_for_enctype(supp_enc))
		enc_timestamp = cipher.encrypt(key, 1, timestamp, None)
		self.kerberos_cipher = cipher
		self.kerberos_cipher_type = supp_enc.value
		
		pa_data_2 = {}
		pa_data_2['padata-type'] = int(PADATA_TYPE('ENC-TIMESTAMP'))
		pa_data_2['padata-value'] = EncryptedData({'etype': supp_enc.value, 'cipher': enc_timestamp}).dump()
		
		
		
		kdc_req_body = {}
		kdc_req_body['kdc-options'] = KDCOptions(set(['forwardable','renewable','proxiable']))
		kdc_req_body['cname'] = PrincipalName({'name-type': NAME_TYPE.PRINCIPAL.value, 'name-string': [self.usercreds.username]})
		kdc_req_body['realm'] = self.usercreds.domain.upper()
		kdc_req_body['sname'] = PrincipalName({'name-type': NAME_TYPE.PRINCIPAL.value, 'name-string': ['krbtgt', self.usercreds.domain.upper()]})
		kdc_req_body['till'] = now + datetime.timedelta(days=1)
		kdc_req_body['rtime'] = now + datetime.timedelta(days=1)
		kdc_req_body['nonce'] = secrets.randbits(31)
		kdc_req_body['etype'] = [supp_enc.value] #selecting according to server's preferences
		
		
		kdc_req = {}
		kdc_req['pvno'] = krb5_pvno
		kdc_req['msg-type'] = MESSAGE_TYPE.KRB_AS_REQ.value
		kdc_req['padata'] = [pa_data_2,pa_data_1]
		kdc_req['req-body'] = KDC_REQ_BODY(kdc_req_body)
		
		req = AS_REQ(kdc_req)
		
		logging.debug('Sending TGT request to server')
		rep = self.ksoc.sendrecv(req.dump())
		logging.debug('Got valid TGT response from server')
		rep = rep.native
		self.kerberos_TGT = rep
		
		
		cipherText = rep['enc-part']['cipher']
		temp = cipher.decrypt(key, 3, cipherText)
		enc_as_rep_part = EncASRepPart.load(temp).native
		self.kerberos_session_key = Key(cipher.enctype, enc_as_rep_part['key']['keyvalue'])
		self.ccache.add_tgt(self.kerberos_TGT, enc_as_rep_part)
		logging.debug('Got valid TGT')
		
		return 
    def doRollover(self):
        """
        Do a rollover, as described in __init__().
        """
        self._close()
        if self.backupCount <= 0:
            # Don't keep any backups, just overwrite the existing backup file
            # Locking doesn't much matter here; since we are overwriting it anyway
            self.stream = self._open("w")
            return
        try:
            # Determine if we can rename the log file or not. Windows refuses to
            # rename an open file, Unix is inode base so it doesn't care.

            # Attempt to rename logfile to tempname:
            # There is a slight race-condition here, but it seems unavoidable
            tmpname = None
            while not tmpname or os.path.exists(tmpname):
                tmpname = "%s.rotate.%08d" % (self.baseFilename, randbits(64))
            try:
                # Do a rename test to determine if we can successfully rename the log file
                os.rename(self.baseFilename, tmpname)

                if self.use_gzip:
                    self.do_gzip(tmpname)
            except (IOError, OSError):
                exc_value = sys.exc_info()[1]
                self._console_log(
                    "rename failed.  File in use? exception=%s" % (exc_value,))
                self._degrade(
                    True, "rename failed.  File in use? exception=%s", exc_value)
                return

            gzip_ext = ''
            if self.use_gzip:
                gzip_ext = '.gz'

            def do_rename(source_fn, dest_fn):
                self._console_log("Rename %s -> %s" % (source_fn, dest_fn + gzip_ext))
                if os.path.exists(dest_fn):
                    os.remove(dest_fn)
                if os.path.exists(dest_fn + gzip_ext):
                    os.remove(dest_fn + gzip_ext)
                source_gzip = source_fn + gzip_ext
                if os.path.exists(source_gzip):
                    os.rename(source_gzip, dest_fn + gzip_ext)
                elif os.path.exists(source_fn):
                    os.rename(source_fn, dest_fn)

            # Q: Is there some way to protect this code from a KeyboardInterrupt?
            # This isn't necessarily a data loss issue, but it certainly does 
            # break the rotation process during stress testing.

            # There is currently no mechanism in place to handle the situation
            # where one of these log files cannot be renamed. (Example, user
            # opens "logfile.3" in notepad); we could test rename each file, but
            # nobody's complained about this being an issue; so the additional
            # code complexity isn't warranted.
            for i in range(self.backupCount - 1, 0, -1):
                sfn = "%s.%d" % (self.baseFilename, i)
                dfn = "%s.%d" % (self.baseFilename, i + 1)
                if os.path.exists(sfn + gzip_ext):
                    do_rename(sfn, dfn)
            dfn = self.baseFilename + ".1"
            do_rename(tmpname, dfn)

            if self.use_gzip:
                logFilename = self.baseFilename + ".1.gz"
                self._do_chown_and_chmod(logFilename)

            self._console_log("Rotation completed")
            self._degrade(False, "Rotation completed")
        finally:
            # Re-open the output stream, but if "delay" is enabled then wait
            # until the next emit() call. This could reduce rename contention in
            # some usage patterns.
            if not self.delay:
                self.stream = self._open()
Example #36
0
from starlette.middleware.authentication import AuthenticationMiddleware
from sentry_asgi import SentryMiddleware
import sentry_sdk

from . import toggles, features, environments, auditing, health
from .permissions import InsufficientPermissionsError
from .security import GoogleAuthBackend


DEBUG = os.getenv('DEBUG', 'false').lower() == 'true'
LOCAL_DEV = os.getenv('IS_LOCAL', 'false').lower() == 'true'
GOOGLE_ID = os.getenv('GOOGLE_ID')
GOOGLE_SECRET = os.getenv('GOOGLE_SECRET')
GOOGLE_ORG = os.getenv('GOOGLE_ORG')
COOKIE_NAME = os.getenv('COOKIE_NAME', 'tmeister-auth')
COOKIE_KEY = os.getenv('COOKIE_KEY') or secrets.randbits(60)
POSTGRES_URL = os.getenv('DATABASE_URL', 'localhost')
POSTGRES_USERNAME = os.getenv('DATABASE_USER', 'postgres')
POSTGRES_PASSWORD = os.getenv('DATABASE_PASS', 'password')
POSTGRES_DB_NAME = os.getenv('DATABASE_DB_NAME', 'postgres')
POSTGRES_MIN_POOL_SIZE = int(os.getenv('DATABASE_MIN_POOL_SIZE', '2'))
POSTGRES_MAX_POOL_SIZE = int(os.getenv('DATABASE_MAX_POOL_SIZE', '4'))
SENTRY_URL = os.getenv('SENTRY_URL')
ENV_NAME = os.getenv('ENV_LOCATION', 'Local')


if (not LOCAL_DEV) and None in (GOOGLE_ID, GOOGLE_SECRET, GOOGLE_ORG):
    raise ValueError('GITHUB_ID, GITHUB_SECRET or GITHUB_ORG'
                     ' environment variables are missing')