Beispiel #1
0
    def authenticate_start(self, username, invalidate=False):
        user = self._get_user(username)
        if user is None or len(user.devices) == 0:
            log.info('User "%s" has no devices registered', username)
            raise NoEligibleDevicesException('No devices registered', [])

        sign_requests = []
        descriptors = []
        challenges = {}
        rand = rand_bytes(32)

        for handle, dev in user.devices.items():
            if not dev.compromised:
                challenge = start_authenticate(dev.bind_data, rand)
                sign_requests.append(challenge)
                descriptors.append(dev.get_descriptor(
                    self._metadata.get_metadata(dev)))
                challenges[handle] = {
                    'keyHandle': challenge.keyHandle,
                    'challenge': challenge
                }

        if not sign_requests:
            raise NoEligibleDevicesException(
                'All devices compromised',
                [d.get_descriptor() for d in user.devices.values()]
            )
        self._memstore.store(self._client.id, username, rand, challenges)
        return sign_requests, descriptors
Beispiel #2
0
    def authenticate_start(self, username, setChallenge=None, invalidate=False):
        user = self._get_user(username)
        if user is None or len(user.devices) == 0:
            log.info('User "%s" has no devices registered', username)
            raise NoEligableDevicesException('No devices registered', [])

        sign_requests = []
        challenges = {}
        if setChallenge:
            rand = setChallenge.decode("hex")
        else:
            rand = rand_bytes(32)

        for handle, dev in user.devices.items():
            if not dev.compromised:
                challenge = start_authenticate(dev.bind_data, rand)
                sign_requests.append(challenge)
                challenges[handle] = {
                    'keyHandle': challenge.keyHandle,
                    'challenge': challenge
                }

        if not sign_requests:
            raise NoEligableDevicesException(
                'All devices compromised',
                [d.get_descriptor() for d in user.devices.values()]
            )
        self._memstore.store(self._client.id, username, rand, challenges)
        return sign_requests
def start_register(app_id, challenge=None):
    if challenge is None:
        challenge = rand_bytes(32)

    return RegisterRequest(version=VERSION,
                           appId=app_id,
                           challenge=websafe_encode(challenge))
    def __init__(self, binding, challenge=None):
        self.binding = binding
        self.app_param = H(binding.app_id.encode('idna'))

        if challenge is None:
            self.challenge = rand_bytes(32)
        else:
            self.challenge = challenge
Beispiel #5
0
    def __init__(self, binding, challenge=None):
        self.binding = binding
        self.app_param = H(binding.app_id.encode('idna'))

        if challenge is None:
            self.challenge = rand_bytes(32)
        else:
            self.challenge = challenge
def start_register(app_id, challenge=None):
    if challenge is None:
        challenge = rand_bytes(32)

    return RegisterRequest(
        version=VERSION,
        appId=app_id,
        challenge=websafe_encode(challenge)
    )
def start_authenticate(device, challenge=None):
    device = DeviceRegistration.wrap(device)

    if challenge is None:
        challenge = rand_bytes(32)

    return SignRequest(version=VERSION,
                       appId=device.appId,
                       keyHandle=device.keyHandle,
                       challenge=websafe_encode(challenge))
def start_authenticate(device, challenge=None):
    device = DeviceRegistration.wrap(device)

    if challenge is None:
        challenge = rand_bytes(32)

    return SignRequest(
        version=VERSION,
        appId=device.appId,
        keyHandle=device.keyHandle,
        challenge=websafe_encode(challenge)
    )
Beispiel #9
0
    def __init__(self, app_id, facets=None, challenge=None):
        self.app_id = app_id
        self.app_param = H(app_id.encode('idna'))

        if facets is None:
            self.facets = []
        else:
            self.facets = facets

        if challenge is None:
            self.challenge = rand_bytes(32)
        else:
            self.challenge = challenge
Beispiel #10
0
    def __init__(self, app_id, facets=None, challenge=None):
        self.app_id = app_id
        self.app_param = H(app_id.encode('idna'))

        if facets is None:
            self.facets = []
        else:
            self.facets = facets

        if challenge is None:
            self.challenge = rand_bytes(32)
        else:
            self.challenge = challenge
    def register(self, request, facet="https://www.example.com"):
        """
        RegisterRequest = {
            "version": "U2F_V2",
            "challenge": string, //b64 encoded challenge
            "appId": string, //app_id
        }
        """

        if not isinstance(request, RegisterRequest):
            request = RegisterRequest(request)

        if request.version != "U2F_V2":
            raise ValueError("Unsupported U2F version: %s" % request.version)

        # Client data
        client_data = ClientData(typ='navigator.id.finishEnrollment',
                                 challenge=request['challenge'],
                                 origin=facet)
        client_data = client_data.json.encode('utf-8')
        client_param = sha_256(client_data)

        # ECC key generation
        priv_key = ec.generate_private_key(CURVE, default_backend())
        pub_key = priv_key.public_key().public_bytes(
            Encoding.DER, PublicFormat.SubjectPublicKeyInfo)
        pub_key = pub_key[-65:]

        # Store
        key_handle = rand_bytes(64)
        app_param = request.appParam
        self.keys[key_handle] = (priv_key, app_param)

        # Attestation signature
        cert_priv = load_pem_private_key(CERT_PRIV,
                                         password=None,
                                         backend=default_backend())
        cert = CERT
        data = b'\x00' + app_param + client_param + key_handle + pub_key
        signer = cert_priv.signer(ec.ECDSA(hashes.SHA256()))
        signer.update(data)
        signature = signer.finalize()

        raw_response = (b'\x05' + pub_key + int2byte(len(key_handle)) +
                        key_handle + cert + signature)

        return RegisterResponse(
            registrationData=websafe_encode(raw_response),
            clientData=websafe_encode(client_data),
        )
    def register(
        self,
        data,
        facet="https://www.example.com",
    ):
        """
        data = {
            "version": "U2F_V2",
            "challenge": string, //b64 encoded challenge
            "appId": string, //app_id
        }
        """
        if isinstance(data, basestring):
            data = json.loads(data)

        if data['version'] != "U2F_V2":
            raise ValueError("Unsupported U2F version: %s" % data['version'])

        # Client data
        client_data = {
            'typ': "navigator.id.finishEnrollment",
            'challenge': data['challenge'],
            'origin': facet
        }
        client_data = json.dumps(client_data)
        client_param = H(client_data)

        # ECC key generation
        privu = EC.gen_params(CURVE)
        privu.gen_key()
        pub_key = str(privu.pub().get_der())[-65:]

        # Store
        key_handle = rand_bytes(64)
        app_param = H(data['appId'])
        self.keys[key_handle] = (privu, app_param)

        # Attestation signature
        cert_priv = EC.load_key_bio(BIO.MemoryBuffer(CERT_PRIV))
        cert = CERT
        digest = H(chr(0x00) + app_param + client_param + key_handle + pub_key)
        signature = cert_priv.sign_dsa_asn1(digest)

        raw_response = chr(0x05) + pub_key + chr(len(key_handle)) + \
            key_handle + cert + signature

        return json.dumps({
            "registrationData": websafe_encode(raw_response),
            "clientData": websafe_encode(client_data),
        })
    def register(self, request, facet="https://www.example.com"):
        """
        RegisterRequest = {
            "version": "U2F_V2",
            "challenge": string, //b64 encoded challenge
            "appId": string, //app_id
        }
        """

        if not isinstance(request, RegisterRequest):
            request = RegisterRequest(request)

        if request.version != "U2F_V2":
            raise ValueError("Unsupported U2F version: %s" % request.version)

        # Client data
        client_data = ClientData(
            typ='navigator.id.finishEnrollment',
            challenge=request['challenge'],
            origin=facet
        )
        client_data = client_data.json.encode('utf-8')
        client_param = sha_256(client_data)

        # ECC key generation
        priv_key = ec.generate_private_key(CURVE, default_backend())
        pub_key = priv_key.public_key().public_bytes(Encoding.DER, PublicFormat.SubjectPublicKeyInfo)
        pub_key = pub_key[-65:]

        # Store
        key_handle = rand_bytes(64)
        app_param = request.appParam
        self.keys[key_handle] = (priv_key, app_param)

        # Attestation signature
        cert_priv = load_pem_private_key(CERT_PRIV, password=None, backend=default_backend())
        cert = CERT
        data = b'\x00' + app_param + client_param + key_handle + pub_key
        signer = cert_priv.signer(ec.ECDSA(hashes.SHA256()))
        signer.update(data)
        signature = signer.finalize()

        raw_response = (b'\x05' + pub_key + int2byte(len(key_handle)) +
                        key_handle + cert + signature)

        return RegisterResponse(
            registrationData=websafe_encode(raw_response),
            clientData=websafe_encode(client_data),
        )
Beispiel #14
0
    def get_context_data(self, **kwargs):
        ctx = super().get_context_data()

        devices = [DeviceRegistration.wrap(device.json_data)
                   for device in U2FDevice.objects.filter(confirmed=True, user=self.user)]
        if devices:
            challenge = u2f.start_authenticate(devices, challenge=rand_bytes(32))
            self.request.session['_u2f_challenge'] = challenge.json
            ctx['jsondata'] = challenge.json
        else:
            if '_u2f_challenge' in self.request.session:
                del self.request.session['_u2f_challenge']
            ctx['jsondata'] = None

        return ctx
    def register(self, request, facet="https://www.example.com"):
        """
        RegisterRequest = {
            "version": "U2F_V2",
            "challenge": string, //b64 encoded challenge
            "appId": string, //app_id
        }
        """
        if not isinstance(request, RegisterRequest):
            request = RegisterRequest(request)

        if request.version != "U2F_V2":
            raise ValueError("Unsupported U2F version: %s" % request.version)

        # Client data
        client_data = ClientData(
            typ='navigator.id.finishEnrollment',
            challenge=request['challenge'],
            origin=facet
        )
        client_data = client_data.json
        client_param = H(client_data)

        # ECC key generation
        privu = EC.gen_params(CURVE)
        privu.gen_key()
        pub_key = str(privu.pub().get_der())[-65:]

        # Store
        key_handle = rand_bytes(64)
        app_param = request.appParam
        self.keys[key_handle] = (privu, app_param)

        # Attestation signature
        cert_priv = EC.load_key_bio(BIO.MemoryBuffer(CERT_PRIV))
        cert = CERT
        digest = H(chr(0x00) + app_param + client_param + key_handle + pub_key)
        signature = cert_priv.sign_dsa_asn1(digest)

        raw_response = chr(0x05) + pub_key + chr(len(key_handle)) + \
            key_handle + cert + signature

        return RegisterResponse(
            registrationData=websafe_encode(raw_response),
            clientData=websafe_encode(client_data),
        )
    def register(self, data, facet="https://www.example.com", ):
        """
        data = {
            "version": "U2F_V2",
            "challenge": string, //b64 encoded challenge
            "appId": string, //app_id
        }
        """
        if isinstance(data, basestring):
            data = json.loads(data)

        if data['version'] != "U2F_V2":
            raise ValueError("Unsupported U2F version: %s" % data['version'])

        # Client data
        client_data = {
            'typ': "navigator.id.finishEnrollment",
            'challenge': data['challenge'],
            'origin': facet
        }
        client_data = json.dumps(client_data)
        client_param = H(client_data)

        # ECC key generation
        privu = EC.gen_params(CURVE)
        privu.gen_key()
        pub_key = str(privu.pub().get_der())[-65:]

        # Store
        key_handle = rand_bytes(64)
        app_param = H(data['appId'])
        self.keys[key_handle] = (privu, app_param)

        # Attestation signature
        cert_priv = EC.load_key_bio(BIO.MemoryBuffer(CERT_PRIV))
        cert = CERT
        digest = H(chr(0x00) + app_param + client_param + key_handle + pub_key)
        signature = cert_priv.sign_dsa_asn1(digest)

        raw_response = chr(0x05) + pub_key + chr(len(key_handle)) + \
            key_handle + cert + signature

        return json.dumps({
            "registrationData": websafe_encode(raw_response),
            "clientData": websafe_encode(client_data),
        })
Beispiel #17
0
    def register(self, request, facet="https://www.example.com"):
        """
        RegisterRequest = {
            "version": "U2F_V2",
            "challenge": string, //b64 encoded challenge
            "appId": string, //app_id
        }
        """

        if not isinstance(request, RegisterRequest):
            request = RegisterRequest(request)

        if request.version != "U2F_V2":
            raise ValueError("Unsupported U2F version: %s" % request.version)

        # Client data
        client_data = ClientData(typ='navigator.id.finishEnrollment',
                                 challenge=request['challenge'],
                                 origin=facet)
        client_data = client_data.json
        client_param = H(client_data)

        # ECC key generation
        privu = EC.gen_params(CURVE)
        privu.gen_key()
        pub_key = str(privu.pub().get_der())[-65:]

        # Store
        key_handle = rand_bytes(64)
        app_param = request.appParam
        self.keys[key_handle] = (privu, app_param)

        # Attestation signature
        cert_priv = EC.load_key_bio(BIO.MemoryBuffer(CERT_PRIV))
        cert = CERT
        digest = H(chr(0x00) + app_param + client_param + key_handle + pub_key)
        signature = cert_priv.sign_dsa_asn1(digest)

        raw_response = chr(0x05) + pub_key + chr(len(key_handle)) + \
            key_handle + cert + signature

        return RegisterResponse(
            registrationData=websafe_encode(raw_response),
            clientData=websafe_encode(client_data),
        )
Beispiel #18
0
    def get_context_data(self, **kwargs):
        ctx = super().get_context_data()

        devices = [
            DeviceRegistration.wrap(device.json_data)
            for device in U2FDevice.objects.filter(confirmed=True,
                                                   user=self.request.user)
        ]
        if devices:
            challenge = u2f.start_authenticate(devices,
                                               challenge=rand_bytes(32))
            self.request.session['_u2f_challenge'] = challenge.json
            ctx['jsondata'] = challenge.json
        else:
            if '_u2f_challenge' in self.request.session:
                del self.request.session['_u2f_challenge']
            ctx['jsondata'] = None

        return ctx
Beispiel #19
0
def start_authenticate(devices, challenge=None):
    sign_requests = [u2f_v2.start_authenticate(d, challenge or rand_bytes(32))
                     for d in devices]

    return AuthenticateRequestData(authenticateRequests=sign_requests)