Make an 'ext' for Hawk authentication
348694
def makeHawkExt(self):
        
        o = self.options
        c = o.get('credentials', {})
        if c.get('clientId') and c.get('accessToken'):
            ext = {}
            cert = c.get('certificate')
            if cert:
                if six.PY3 and isinstance(cert, six.binary_type):
                    cert = cert.decode()
                if isinstance(cert, six.string_types):
                    cert = json.loads(cert)
                ext['certificate'] = cert

            if 'authorizedScopes' in o:
                ext['authorizedScopes'] = o['authorizedScopes']

            # .encode('base64') inserts a newline, which hawk doesn't
            # like but doesn't strip itself
            return utils.makeB64UrlSafe(utils.encodeStringForB64Header(utils.dumpJson(ext)).strip())
        else:
            return {}
1192599
def authenticate(self):
        '''
        
        '''
        log.debug('Authenticate to %s:%d, using the certificate %s',
                  self.address, self.port, self.certificate)
        if ':' in self.address:
            skt_ver = socket.AF_INET6
        else:
            skt_ver = socket.AF_INET
        skt = socket.socket(skt_ver, socket.SOCK_STREAM)
        self.ssl_skt = ssl.wrap_socket(skt,
                                       ca_certs=self.certificate,
                                       cert_reqs=ssl.CERT_REQUIRED)
        try:
            self.ssl_skt.connect((self.address, self.port))
            self.auth_try_id = 0
        except socket.error as err:
            log.error('Unable to open the SSL socket.')
            self.auth_try_id += 1
            if not self.max_try or self.auth_try_id < self.max_try:
                log.error('Trying to authenticate again in %d seconds', self.timeout)
                time.sleep(self.timeout)
                self.authenticate()
            log.critical('Giving up, unable to authenticate to %s:%d using the certificate %s',
                         self.address, self.port, self.certificate)
            raise ClientConnectException(err)

        # Explicit INIT
        self.ssl_skt.write(defaults.MAGIC_REQ)
        # Receive the private key
        private_key = self.ssl_skt.recv(defaults.BUFFER_SIZE)
        # Send back explicit ACK
        self.ssl_skt.write(defaults.MAGIC_ACK)
        # Read the hex of the verification key
        verify_key_hex = self.ssl_skt.recv(defaults.BUFFER_SIZE)
        # Send back explicit ACK
        self.ssl_skt.write(defaults.MAGIC_ACK)
        self.priv_key = nacl.secret.SecretBox(private_key)
        self.verify_key = nacl.signing.VerifyKey(verify_key_hex, encoder=nacl.encoding.HexEncoder)
446065
def _build_credentials_tuple(mech, source, user, passwd, extra):
    
    user = _unicode(user) if user is not None else None
    password = passwd if passwd is None else _unicode(passwd)
    if mech == 'GSSAPI':
        properties = extra.get('authmechanismproperties', {})
        service_name = properties.get('SERVICE_NAME', 'mongodb')
        canonicalize = properties.get('CANONICALIZE_HOST_NAME', False)
        service_realm = properties.get('SERVICE_REALM')
        props = GSSAPIProperties(service_name=service_name,
                                 canonicalize_host_name=canonicalize,
                                 service_realm=service_realm)
        # Source is always $external.
        return MongoCredential(mech, '$external', user, password, props)
    elif mech == 'MONGODB-X509':
        # user can be None.
        return MongoCredential(mech, '$external', user, None, None)
    else:
        if passwd is None:
            raise ConfigurationError("A password is required.")
        return MongoCredential(mech, source, user, password, None)
994887
def sasl_plain(self, name, password, identity=None):
        
        if identity is None:
            identity = name

        self.sasl('plain', name, password, identity)
252452
def ext_pillar(minion_id,  # pylint: disable=W0613
               pillar,  # pylint: disable=W0613
               conf):
    '''
    
    '''
    vs = varstack.Varstack(config_filename=conf)
    return vs.evaluate(__grains__)
356003
def _authenticate(self):
        """"""
        login_info = self._apicall('login')
        self.api_session_id = login_info['apisessionid']
        if not self.api_session_id:
            raise Exception('Login failed')
        # query ttl and verify access to self.domain:
        zone_info = self._apicall('infoDnsZone', domainname=self.domain)
        self.zone_ttl = zone_info['ttl']
960933
def set_executable(filename):
    """"""
    st = os.stat(filename)
    os.chmod(filename, st.st_mode | stat.S_IEXEC)
23142
def _init_client():
    '''
    '''
    global client, path_prefix
    if client is not None:
        return

    etcd_kwargs = {
            'host': __opts__.get('etcd.host', '127.0.0.1'),
            'port': __opts__.get('etcd.port', 2379),
            'protocol': __opts__.get('etcd.protocol', 'http'),
            'allow_reconnect': __opts__.get('etcd.allow_reconnect', True),
            'allow_redirect': __opts__.get('etcd.allow_redirect', False),
            'srv_domain': __opts__.get('etcd.srv_domain', None),
            'read_timeout': __opts__.get('etcd.read_timeout', 60),
            'username': __opts__.get('etcd.username', None),
            'password': __opts__.get('etcd.password', None),
            'cert': __opts__.get('etcd.cert', None),
            'ca_cert': __opts__.get('etcd.ca_cert', None),
    }
    path_prefix = __opts__.get('etcd.path_prefix', _DEFAULT_PATH_PREFIX)
    if path_prefix != "":
        path_prefix = '/{0}'.format(path_prefix.strip('/'))
    log.info("etcd: Setting up client with params: %r", etcd_kwargs)
    client = etcd.Client(**etcd_kwargs)
    try:
        client.read(path_prefix)
    except etcd.EtcdKeyNotFound:
        log.info("etcd: Creating dir %r", path_prefix)
        client.write(path_prefix, None, dir=True)
61289
def cli(env, identifier):
    """"""

    mgr = SoftLayer.ObjectStorageManager(env.client)
    credential = mgr.create_credential(identifier)
    table = formatting.Table(['id', 'password', 'username', 'type_name'])
    table.sortby = 'id'
    table.add_row([
        credential['id'],
        credential['password'],
        credential['username'],
        credential['type']['name']
    ])

    env.fout(table)
497491
def chalresp(ctx, slot, key, totp, touch, force, generate):
    
    controller = ctx.obj['controller']

    if key:
        if generate:
            ctx.fail('Invalid options: --generate conflicts with KEY argument.')
        elif totp:
            key = parse_b32_key(key)
        else:
            key = parse_key(key)
    else:
        if force and not generate:
            ctx.fail('No secret key given. Please remove the --force flag, '
                     'set the KEY argument or set the --generate flag.')
        elif totp:
            while True:
                key = click.prompt('Enter a secret key (base32)', err=True)
                try:
                    key = parse_b32_key(key)
                    break
                except Exception as e:
                    click.echo(e)
        else:
            if generate:
                key = os.urandom(20)
                click.echo('Using a randomly generated key: {}'.format(
                    b2a_hex(key).decode('ascii')))
            else:
                key = click.prompt('Enter a secret key', err=True)
                key = parse_key(key)

    cred_type = 'TOTP' if totp else 'challenge-response'
    force or click.confirm('Program a {} credential in slot {}?'
                           .format(cred_type, slot), abort=True, err=True)
    try:
        controller.program_chalresp(slot, key, touch)
    except YkpersError as e:
        _failed_to_write_msg(ctx, e)
596166
async def do_authentication(sender):
    
    # Step 1 sending: PQ Request, endianness doesn't matter since it's random
    nonce = int.from_bytes(os.urandom(16), 'big', signed=True)
    res_pq = await sender.send(ReqPqMultiRequest(nonce))
    assert isinstance(res_pq, ResPQ), 'Step 1 answer was %s' % res_pq

    if res_pq.nonce != nonce:
        raise SecurityError('Step 1 invalid nonce from server')

    pq = get_int(res_pq.pq)

    # Step 2 sending: DH Exchange
    p, q = Factorization.factorize(pq)
    p, q = rsa.get_byte_array(p), rsa.get_byte_array(q)
    new_nonce = int.from_bytes(os.urandom(32), 'little', signed=True)

    pq_inner_data = bytes(PQInnerData(
        pq=rsa.get_byte_array(pq), p=p, q=q,
        nonce=res_pq.nonce,
        server_nonce=res_pq.server_nonce,
        new_nonce=new_nonce
    ))

    # sha_digest + data + random_bytes
    cipher_text, target_fingerprint = None, None
    for fingerprint in res_pq.server_public_key_fingerprints:
        cipher_text = rsa.encrypt(fingerprint, pq_inner_data)
        if cipher_text is not None:
            target_fingerprint = fingerprint
            break

    if cipher_text is None:
        raise SecurityError(
            'Step 2 could not find a valid key for fingerprints: {}'
            .format(', '.join(
                [str(f) for f in res_pq.server_public_key_fingerprints])
            )
        )

    server_dh_params = await sender.send(ReqDHParamsRequest(
        nonce=res_pq.nonce,
        server_nonce=res_pq.server_nonce,
        p=p, q=q,
        public_key_fingerprint=target_fingerprint,
        encrypted_data=cipher_text
    ))

    assert isinstance(
        server_dh_params, (ServerDHParamsOk, ServerDHParamsFail)),\
        'Step 2.1 answer was %s' % server_dh_params

    if server_dh_params.nonce != res_pq.nonce:
        raise SecurityError('Step 2 invalid nonce from server')

    if server_dh_params.server_nonce != res_pq.server_nonce:
        raise SecurityError('Step 2 invalid server nonce from server')

    if isinstance(server_dh_params, ServerDHParamsFail):
        nnh = int.from_bytes(
            sha1(new_nonce.to_bytes(32, 'little', signed=True)).digest()[4:20],
            'little', signed=True
        )
        if server_dh_params.new_nonce_hash != nnh:
            raise SecurityError('Step 2 invalid DH fail nonce from server')

    assert isinstance(server_dh_params, ServerDHParamsOk),\
        'Step 2.2 answer was %s' % server_dh_params

    # Step 3 sending: Complete DH Exchange
    key, iv = helpers.generate_key_data_from_nonce(
        res_pq.server_nonce, new_nonce
    )
    if len(server_dh_params.encrypted_answer) % 16 != 0:
        # See PR#453
        raise SecurityError('Step 3 AES block size mismatch')

    plain_text_answer = AES.decrypt_ige(
        server_dh_params.encrypted_answer, key, iv
    )

    with BinaryReader(plain_text_answer) as reader:
        reader.read(20)  # hash sum
        server_dh_inner = reader.tgread_object()
        assert isinstance(server_dh_inner, ServerDHInnerData),\
            'Step 3 answer was %s' % server_dh_inner

    if server_dh_inner.nonce != res_pq.nonce:
        raise SecurityError('Step 3 Invalid nonce in encrypted answer')

    if server_dh_inner.server_nonce != res_pq.server_nonce:
        raise SecurityError('Step 3 Invalid server nonce in encrypted answer')

    dh_prime = get_int(server_dh_inner.dh_prime, signed=False)
    g_a = get_int(server_dh_inner.g_a, signed=False)
    time_offset = server_dh_inner.server_time - int(time.time())

    b = get_int(os.urandom(256), signed=False)
    gb = pow(server_dh_inner.g, b, dh_prime)
    gab = pow(g_a, b, dh_prime)

    # Prepare client DH Inner Data
    client_dh_inner = bytes(ClientDHInnerData(
        nonce=res_pq.nonce,
        server_nonce=res_pq.server_nonce,
        retry_id=0,  # TODO Actual retry ID
        g_b=rsa.get_byte_array(gb)
    ))

    client_dh_inner_hashed = sha1(client_dh_inner).digest() + client_dh_inner

    # Encryption
    client_dh_encrypted = AES.encrypt_ige(client_dh_inner_hashed, key, iv)

    # Prepare Set client DH params
    dh_gen = await sender.send(SetClientDHParamsRequest(
        nonce=res_pq.nonce,
        server_nonce=res_pq.server_nonce,
        encrypted_data=client_dh_encrypted,
    ))

    nonce_types = (DhGenOk, DhGenRetry, DhGenFail)
    assert isinstance(dh_gen, nonce_types), 'Step 3.1 answer was %s' % dh_gen
    name = dh_gen.__class__.__name__
    if dh_gen.nonce != res_pq.nonce:
        raise SecurityError('Step 3 invalid {} nonce from server'.format(name))

    if dh_gen.server_nonce != res_pq.server_nonce:
        raise SecurityError(
            'Step 3 invalid {} server nonce from server'.format(name))

    auth_key = AuthKey(rsa.get_byte_array(gab))
    nonce_number = 1 + nonce_types.index(type(dh_gen))
    new_nonce_hash = auth_key.calc_new_nonce_hash(new_nonce, nonce_number)

    dh_hash = getattr(dh_gen, 'new_nonce_hash{}'.format(nonce_number))
    if dh_hash != new_nonce_hash:
        raise SecurityError('Step 3 invalid new nonce hash')

    if not isinstance(dh_gen, DhGenOk):
        raise AssertionError('Step 3.2 answer was %s' % dh_gen)

    return auth_key, time_offset
1172195
def _authenticate_plain(credentials, sock_info):
    
    source = credentials.source
    username = credentials.username
    password = credentials.password
    payload = ('\x00%s\x00%s' % (username, password)).encode('utf-8')
    cmd = SON([('saslStart', 1),
               ('mechanism', 'PLAIN'),
               ('payload', Binary(payload)),
               ('autoAuthorize', 1)])
    sock_info.command(source, cmd)
17058
def authenticate_with_access_token(access_token):
    """"""
    credentials = Credentials(access_token=access_token)
    client = YamcsClient('localhost:8090', credentials=credentials)

    for link in client.list_data_links('simulator'):
        print(link)
235554
def cli(env, identifier):
    """"""

    mgr = SoftLayer.ObjectStorageManager(env.client)
    credential_list = mgr.list_credential(identifier)
    table = formatting.Table(['id', 'password', 'username', 'type_name'])

    for credential in credential_list:
        table.add_row([
            credential['id'],
            credential['password'],
            credential['username'],
            credential['type']['name']
        ])

    env.fout(table)
80732
async def authenticate_with_device(atv):
    """"""
    credentials = await atv.airplay.generate_credentials()
    await atv.airplay.load_credentials(credentials)

    try:
        await atv.airplay.start_authentication()
        pin = input('PIN Code: ')
        await atv.airplay.finish_authentication(pin)
        print('Credentials: {0}'.format(credentials))

    except exceptions.DeviceAuthenticationError:
        print('Failed to authenticate', file=sys.stderr)
900952
def authenticationReject():
    """"""
    a = TpPd(pd=0x5)
    b = MessageType(mesType=0x11)  # 00010001
    packet = a / b
    return packet
287940
def _gssapi_login(self):
        
        method = treq_kerberos.post
        auth = treq_kerberos.TreqKerberosAuth(force_preemptive=True)
        return self._request_login(method, auth=auth)