Verify U2F PIN for YubiKey FIPS.

    Unlock the YubiKey FIPS and allow U2F registration.
429955
def unlock(ctx, pin):
    

    controller = ctx.obj['controller']
    if not controller.is_fips:
        ctx.fail('This is not a YubiKey FIPS, and therefore'
                 ' does not support a U2F PIN.')

    if pin is None:
        pin = _prompt_current_pin('Enter your PIN')

    _fail_if_not_valid_pin(ctx, pin, True)
    try:
        controller.verify_pin(pin)
    except ApduError as e:
        if e.code == SW.VERIFY_FAIL_NO_RETRY:
            ctx.fail('Wrong PIN.')
        if e.code == SW.AUTH_METHOD_BLOCKED:
            ctx.fail('PIN is blocked.')
        if e.code == SW.COMMAND_NOT_ALLOWED:
            ctx.fail('PIN is not set.')

        logger.error('PIN verification failed', exc_info=e)
        ctx.fail('PIN verification failed.')
170359
def auth(username, password):
    '''
    
    '''
    _cred = __get_yubico_users(username)

    client = Yubico(_cred['id'], _cred['key'])

    try:
        return client.verify(password)
    except yubico_exceptions.StatusCodeError as e:
        log.info('Unable to verify YubiKey `%s`', e)
        return False
950302
def _read_capabilities(self):
        

        frame = yubikey_frame.YubiKeyFrame(command=SLOT.YK4_CAPABILITIES)
        self._device._write(frame)
        response = self._device._read_response()
        r_len = yubico_util.ord_byte(response[0])

        # 1 byte length, 2 byte CRC.
        if not yubico_util.validate_crc16(response[:r_len+3]):
            raise YubiKey4_USBHIDError("Read from device failed CRC check")

        return response[1:r_len+1]
1125378
def decrypt_yubikey_otp(self, from_key):
        
        if not re.match(valid_input_from_key, from_key):
            self.log_error("IN: %s, Invalid OTP" % (from_key))
            if self.stats_url:
                stats['invalid'] += 1
            return "ERR Invalid OTP"

        public_id, _otp = pyhsm.yubikey.split_id_otp(from_key)

        try:
            aead = self.aead_backend.load_aead(public_id)
        except Exception as e:
            self.log_error(str(e))
            if self.stats_url:
                stats['no_aead'] += 1
            return "ERR Unknown public_id"

        try:
            res = pyhsm.yubikey.validate_yubikey_with_aead(
                self.hsm, from_key, aead, aead.key_handle)
            # XXX double-check public_id in res, in case BaseHTTPServer suddenly becomes multi-threaded
            # XXX fix use vs session counter confusion
            val_res = "OK counter=%04x low=%04x high=%02x use=%02x" % \
                (res.use_ctr, res.ts_low, res.ts_high, res.session_ctr)
            if self.stats_url:
                stats['ok'] += 1
        except pyhsm.exception.YHSM_Error as e:
            self.log_error ("IN: %s, Validate FAILED: %s" % (from_key, str(e)))
            val_res = "ERR"
            if self.stats_url:
                stats['err'] += 1

        self.log_message("SUCCESS OTP %s PT hsm %s", from_key, val_res)
        return val_res
1256136
def _SignedBinaryURNFromID(binary_id
                          ):
  """"""
  binary_type = binary_id.binary_type
  if binary_type == rdf_objects.SignedBinaryID.BinaryType.PYTHON_HACK:
    return GetAFF4PythonHackRoot().Add(binary_id.path)
  elif binary_type == rdf_objects.SignedBinaryID.BinaryType.EXECUTABLE:
    return GetAFF4ExecutablesRoot().Add(binary_id.path)
  else:
    raise ValueError("Unknown binary type %s." % binary_type)
636380
def verify_enroll(self, response):
        """"""

        seed = session.pop('_u2f_enroll_')
        try:
            new_device, cert = complete_register(seed, response, self.__facets_list)
        except Exception as e:
            if self.__call_fail_enroll:
                self.__call_fail_enroll(e)

            return {
                'status' : 'failed', 
                'error'  : 'Invalid key handle!'
            }

        finally:
            pass

        

        devices = self.__get_u2f_devices()

        # Setting new device counter to 0
        new_device['counter'] = 0
        new_device['index']   = 0

        for device in devices:
            if new_device['index'] <= device['index']:
                new_device['index'] = device['index'] + 1

        devices.append(new_device)

        self.__save_u2f_devices(devices)
        
        self.__call_success_enroll()

        return {'status': 'ok', 'message': 'Successfully enrolled new U2F device!'}
62451
def disable_ipv6():
    
    exit_code = subprocess.call(['sed', '-i', 's/IPV6=.*/IPV6=no/g',
                                 '/etc/default/ufw'])
    if exit_code == 0:
        hookenv.log('IPv6 support in ufw disabled', level='INFO')
    else:
        hookenv.log("Couldn't disable IPv6 support in ufw", level="ERROR")
        raise UFWError("Couldn't disable IPv6 support in ufw")
479786
def Verify(self, public_key):
    
    if self.digest_type != self.HashType.SHA256:
      raise rdfvalue.DecodeError("Unsupported digest.")
    if self.signature_type not in [
        self.SignatureType.RSA_PKCS1v15, self.SignatureType.RSA_PSS
    ]:
      raise rdfvalue.DecodeError("Unsupported signature type.")

    try:
      public_key.Verify(self.data, self.signature)
    except InvalidSignature as e:
      raise rdfvalue.DecodeError("Could not verify blob. Error: %s" % e)

    return True
361200
def enable_mfa_device(self,
                          user_name,
                          serial_number,
                          authentication_code_1,
                          authentication_code_2):
        """"""
        user = self.get_user(user_name)
        if serial_number in user.mfa_devices:
            raise IAMConflictException(
                "EntityAlreadyExists",
                "Device {0} already exists".format(serial_number)
            )

        user.enable_mfa_device(
            serial_number,
            authentication_code_1,
            authentication_code_2
        )
1292315
async def finish_authentication(self, username, password):
        
        # Step 1
        self.srp.step1(username, password)
        data = await self._send_plist(
            'step1', method='pin', user=username)
        resp = plistlib.loads(data)

        # Step 2
        pub_key, key_proof = self.srp.step2(resp['pk'], resp['salt'])
        await self._send_plist(
            'step2',
            pk=binascii.unhexlify(pub_key),
            proof=binascii.unhexlify(key_proof))

        # Step 3
        epk, tag = self.srp.step3()
        await self._send_plist('step3', epk=epk, authTag=tag)
        return True
114402
def challenge_response(self, challenge, mode='HMAC', slot=1, variable=True, may_block=True):
        
        if not self.capabilities.have_challenge_response(mode):
            raise yubikey_base.YubiKeyVersionError("%s challenge-response unsupported in YubiKey %s" % (mode, self.version()) )
        return self._challenge_response(challenge, mode, slot, variable, may_block)
1334033
def _verify(function):
    """"""
    # @functools.wraps
    def wrapped(pin, *args, **kwargs):
        pin = int(pin)
        if pin not in _open:
            ppath = gpiopath(pin)
            if not os.path.exists(ppath):
                log.debug("Creating Pin {0}".format(pin))
                with _export_lock:
                    with open(pjoin(gpio_root, 'export'), 'w') as f:
                        _write(f, pin)
            value = open(pjoin(ppath, 'value'), FMODE)
            direction = open(pjoin(ppath, 'direction'), FMODE)
            _open[pin] = PinState(value=value, direction=direction)
        return function(pin, *args, **kwargs)
    return wrapped
599361
def _register_key(fingerprint, gpg):
    """"""

    for private_key in gpg.list_keys(True):
        try:
            if str(fingerprint) == private_key['fingerprint']:
                config["gpg_key_fingerprint"] = \
                    repr(private_key['fingerprint'])
        except KeyError:
            pass
562366
def valid_configs(self):
        
        if self.ykver() < (2,1,0):
            raise YubiKeyUSBHIDError('Valid configs unsupported in firmware %s' % (self.version()))
        res = []
        if self.touch_level & self.CONFIG1_VALID == self.CONFIG1_VALID:
            res.append(1)
        if self.touch_level & self.CONFIG2_VALID == self.CONFIG2_VALID:
            res.append(2)
        return res
820644
def _u2i(uint32):
    
    v = u2i(uint32)
    if v < 0:
        if exceptions:
            raise ApigpioError(error_text(v))
    return v
1150134
def verify_signature_unicode(self, address, signature, message):
        """"""
        hexdata = binascii.hexlify(message.encode("utf-8"))
        return self.verify_signature(address, signature, hexdata)
78520
private boolean checkOSSCredentials(UnderFileSystemConfiguration conf) {
    return conf.isSet(PropertyKey.OSS_ACCESS_KEY)
        && conf.isSet(PropertyKey.OSS_SECRET_KEY)
        && conf.isSet(PropertyKey.OSS_ENDPOINT_KEY);
  }