Beispiel #1
0
 def test_wrong_challenge(self):
     device = SoftU2FDevice()
     request = begin_registration(APP_ID)
     data = request.data_for_client
     response = device.register(FACET, data['appId'],
                                data['registerRequests'][0])
     request2 = begin_registration(APP_ID)
     self.assertRaisesRegex(ValueError, 'challenge', complete_registration,
                            request2.json, response)
 def test_wrong_challenge(self):
     device = SoftU2FDevice()
     request = begin_registration(APP_ID)
     data = request.data_for_client
     response = device.register(FACET, data['appId'],
                                data['registerRequests'][0])
     request2 = begin_registration(APP_ID)
     self.assertRaisesRegex(ValueError, 'challenge', complete_registration,
                            request2.json, response)
def register_token(devices=[]):
    token = SoftU2FDevice()
    request = begin_registration(APP_ID, devices)
    data = request.data_for_client
    response = token.register(FACET, data['appId'], data['registerRequests'][0])
    device, cert = complete_registration(request.json, response)
    return device, token
Beispiel #4
0
def start(request):
    enroll = begin_registration(settings.U2F_APPID, [])
    request.session['_u2f_enroll_'] = enroll.json
    context = csrf(request)
    context["token"] = simplejson.dumps(enroll.data_for_client)
    context.update(get_redirect_url())
    return render(request, "U2F/Add.html", context)
Beispiel #5
0
def register_token(devices=[]):
    token = SoftU2FDevice()
    request = begin_registration(APP_ID, devices)
    data = request.data_for_client
    response = token.register(FACET, data['appId'],
                              data['registerRequests'][0])
    device, cert = complete_registration(request.json, response)
    return device, token
Beispiel #6
0
 def __init__(self, *args, **kwargs):
     self.user = kwargs.pop('user')
     super(U2FTokenCreateForm, self).__init__(*args, **kwargs)
     self.helper.form_class = 'u2f-enroll'
     enroll = begin_registration(APP_ID, get_user_devices(self.user))
     self.fields['u2f_enroll'].initial = json.dumps(enroll)
     self.fields['u2f_enroll_signed'].initial = signing.dumps(
         enroll, salt=self._get_sign_salt())
    def enroll(self, username):
        if username not in self.users:
            self.users[username] = {}

        user = self.users[username]
        enroll = begin_registration(self.app_id, user.get('_u2f_devices_', []))
        user['_u2f_enroll_'] = enroll.json
        return json.dumps(enroll.data_for_client)
Beispiel #8
0
 def get_context_data(self, **kwargs):
     kwargs = super(AddKeyView, self).get_context_data(**kwargs)
     request = u2f.begin_registration(self.get_origin(), [
         key.to_json() for key in self.request.user.u2f_keys.all()
     ])
     self.request.session['u2f_registration_request'] = request
     kwargs['registration_request'] = request
     return kwargs
    def enroll(self, username):
        if username not in self.users:
            self.users[username] = {}

        user = self.users[username]
        enroll = begin_registration(self.app_id, user.get('_u2f_devices_', []))
        user['_u2f_enroll_'] = enroll.json
        return json.dumps(enroll.data_for_client)
Beispiel #10
0
def start(request):
    enroll = begin_registration(settings.U2F_APPID, [])
    request.session['_u2f_enroll_'] = enroll.json

    return render(request, "mfa/U2F/add.html", {
        **csrf(request),
        'token': json.dumps(enroll.data_for_client),
        'mode': 'auth',
    })
Beispiel #11
0
    def get_context_data(self, **kwargs):
        kwargs = super(AddKeyView, self).get_context_data(**kwargs)
        request = u2f.begin_registration(self.get_origin(), [
            key.to_json() for key in self.request.user.u2f_keys.all()
        ])
        self.request.session['u2f_registration_request'] = request
        kwargs['registration_request'] = request

        return kwargs
def enroll():
    app_id = get_origin(request.environ)
    username = request.args.get('username', 'user')
    data = request.data.decode()
    if username not in users:
        users[username] = {}
    user = users[username]
    enroll = begin_registration(app_id, user.get('_u2f_devices_', []))
    user['_u2f_enroll_'] = enroll.json
    return json.dumps(enroll.data_for_client)
Beispiel #13
0
    def u2f_get_registration_challenge(self):
        user = self.env.user
        print(user.login)
        baseurl = user.env['ir.config_parameter'].sudo().get_param(
            'web.base.url')
        already_registered_u2f_devices = user.u2f_device_ids.mapped('json')
        challenge = begin_registration(baseurl, already_registered_u2f_devices)
        request.session.u2f_last_registration_challenge = challenge.json

        return challenge
Beispiel #14
0
    def begin_registration():
        """
        Start registering a U2F security key.

        Keep enroll_challenge safe server-side, and give data_for_client to the client. When you get the data back from
        the client, call U2FDevice.create_key with it.

        :return: enroll_challenge, data_for_client
        """
        enroll = begin_registration(settings.OTP_U2F_APP_ID, [])
        return enroll.json, enroll.data_for_client
Beispiel #15
0
def enroll(user):
    user_u2f_tokens = user.credentials.filter(U2F)
    if user_u2f_tokens.count >= current_app.config['U2F_MAX_ALLOWED_TOKENS']:
        current_app.logger.error('User tried to register more than {} tokens.'.format(
            current_app.config['U2F_MAX_ALLOWED_TOKENS']))
        return {'_error': True, 'message': 'security.u2f.max_allowed_tokens'}
    registered_keys = credentials_to_registered_keys(user_u2f_tokens)
    enrollment = begin_registration(current_app.config['U2F_APP_ID'], registered_keys)
    session['_u2f_enroll_'] = enrollment.json
    current_app.stats.count(name='u2f_token_enroll')
    return U2FEnrollResponseSchema().load(enrollment.data_for_client).data
Beispiel #16
0
    def __enable_u2f(self, user):
        if user.uuid not in self.__settings:
            self.__settings[user.uuid] = {}

        user_settings = self.__settings[user.uuid]
        devices = [DeviceRegistration.wrap(device)
                   for device in user_settings.get('_u2f_devices_', [])]
        enroll = begin_registration(self.app_id, devices)
        user_settings['_u2f_enroll_'] = enroll.json
        self.__save_settings()
        return enroll.json
Beispiel #17
0
def enroll(user):
    user_u2f_tokens = user.credentials.filter(U2F)
    if user_u2f_tokens.count >= current_app.config.u2f_max_allowed_tokens:
        current_app.logger.error(
            'User tried to register more than {} tokens.'.format(
                current_app.config.u2f_max_allowed_tokens))
        return error_response(message=SecurityMsg.max_tokens)
    registered_keys = credentials_to_registered_keys(user_u2f_tokens)
    enrollment = begin_registration(current_app.config.u2f_app_id,
                                    registered_keys)
    session['_u2f_enroll_'] = enrollment.json
    current_app.stats.count(name='u2f_token_enroll')
    return U2FEnrollResponseSchema().load(enrollment.data_for_client)
Beispiel #18
0
    def __enable_u2f(self, user):
        if user.uuid not in self.__settings:
            self.__settings[user.uuid] = {}

        user_settings = self.__settings[user.uuid]
        devices = [
            DeviceRegistration.wrap(device)
            for device in user_settings.get('_u2f_devices_', [])
        ]
        enroll = begin_registration(self.app_id, devices)
        user_settings['_u2f_enroll_'] = enroll.json
        self.__save_settings()
        return enroll.json
Beispiel #19
0
def u2f_register():
    # TODO(tsileo): ensure no duplicates
    if request.method == "GET":
        payload = u2f.begin_registration(ID)
        session["challenge"] = payload
        return htmlify(render_template("u2f.html", payload=payload))
    else:
        resp = json.loads(request.form.get("resp"))
        device, device_cert = u2f.complete_registration(
            session["challenge"], resp)
        session["challenge"] = None
        DB.u2f.insert_one({"device": device, "cert": device_cert})
        session["logged_in"] = False
        return redirect("/login")
Beispiel #20
0
    def test_invalid_signature(self):
        device = SoftU2FDevice()
        request = begin_registration(APP_ID)
        data = request.data_for_client
        response = device.register(FACET, data['appId'],
                                   data['registerRequests'][0])
        response = RegisterResponse.wrap(response)
        raw_data = response.registrationData.bytes
        raw_data = raw_data[:-4] + b'\0\0\0\0'
        response['registrationData'] = websafe_encode(raw_data)
        response = response.json

        self.assertRaisesRegex(ValueError, 'signature', complete_registration,
                               request.json, response)
Beispiel #21
0
    def test_invalid_signature(self):
        device = SoftU2FDevice()
        request = begin_registration(APP_ID)
        data = request.data_for_client
        response = device.register(FACET, data['appId'],
                                   data['registerRequests'][0])
        response = RegisterResponse.wrap(response)
        raw_data = response.registrationData.bytes
        raw_data = raw_data[:-4] + b'\0\0\0\0'
        response['registrationData'] = websafe_encode(raw_data)
        response = response.json

        self.assertRaisesRegex(ValueError, 'signature', complete_registration,
                               request.json, response)
    def get(self, request, format=None):
        user = request.user
        # request = u2f.begin_registration(self.get_origin(), [
        #     key for key in user.u2f_key.all()
        # ])
        if user.u2f_key.exists():
            return Response({"error": "conflict with already registered key"},
                            status=HTTP_409_CONFLICT)
        if user.u2f_registration_request.exists():
            user.u2f_registration_request.first().delete()

        reg_request = u2f.begin_registration(settings.APP_ID, [])
        U2FRegistrationRequest.objects.create(user=user,
                                              body=json.dumps(reg_request))
        return Response(reg_request.data_for_client)
Beispiel #23
0
def u2f_register():
    # TODO(tsileo): ensure no duplicates
    if request.method == 'GET':
        payload = u2f.begin_registration(ID)
        session['challenge'] = payload
        return render_template(
            'u2f.html',
            payload=payload,
        )
    else:
        resp = json.loads(request.form.get('resp'))
        device, device_cert = u2f.complete_registration(
            session['challenge'], resp)
        session['challenge'] = None
        DB.u2f.insert_one({'device': device, 'cert': device_cert})
        return ''
Beispiel #24
0
    def __init__(self, user, device, request, **kwargs):
        super(U2FDeviceForm, self).__init__(device, **kwargs)
        self.request = request
        self.user = user
        self.u2f_device = None
        self.appId = '{scheme}://{host}'.format(
            scheme='https' if self.request.is_secure() else 'http',
            host=self.request.get_host())

        if self.data:
            self.registration_request = self.request.session[
                'u2f_registration_request']
        else:
            self.registration_request = u2f.begin_registration(
                self.appId,
                [key.to_json() for key in self.request.user.u2f_keys.all()])
            self.request.session[
                'u2f_registration_request'] = self.registration_request
 def __init__(self, user, device, request, **kwargs):
     super(U2FDeviceForm, self).__init__(device, **kwargs)
     self.request = request
     self.user = user
     self.u2f_device = None
     if request.META['HTTP_X_FORWARDED_HOST']:
         self.appId = '{scheme}://{host}'.format(scheme='https' if self.request.is_secure() else 'http',
                                                 host=request.META['HTTP_X_FORWARDED_HOST']).rstrip('/')
     else:
         self.appId = '{scheme}://{host}'.format(
             scheme='https' if self.request.is_secure() else 'http', host=self.request.get_host()).rstrip('/')
     if self.data:
         self.registration_request = self.request.session['u2f_registration_request']
     else:
         try:
             self.registration_request = u2f.begin_registration(
                 self.appId, [key.to_json() for key in self.request.user.u2f_keys.all()])
             self.request.session['u2f_registration_request'] = self.registration_request
         except JSONDecodeError:
             raise forms.ValidationError("U2F code is wrong")
Beispiel #26
0
def _register_request(user_id, challenge, properties):
    client = get_client()
    user = get_user(user_id)
    registered_keys = []
    descriptors = []
    if user is not None:
        for dev in user.devices.values():
            descriptor = dev.get_descriptor(get_metadata(dev))
            descriptors.append(descriptor)
            key = _get_registered_key(dev, descriptor)
            registered_keys.append(key)
    request_data = begin_registration(
        client.app_id,
        registered_keys,
        challenge
    )
    request_data['properties'] = properties
    store.store(client.id, user_id, challenge, request_data.json)

    data = RegisterRequestData.wrap(request_data.data_for_client)
    data['descriptors'] = descriptors
    return data
Beispiel #27
0
def enroll(**kwargs):
    """
    Begin registration of a new U2F Security Token

    Variables:
    None

    Arguments:
    None

    Data Block:
    None

    Result example:
    <U2F_ENROLL_CHALLENGE_BLOCK>
    """
    uname = kwargs['user']['uname']
    user = STORAGE.get_user(uname)
    u2f_devices = user.get('u2f_devices', [])
    current_enroll = begin_registration(APP_ID, u2f_devices)
    session['_u2f_enroll_'] = current_enroll.json

    return make_api_response(current_enroll.data_for_client)
def add_2fa():
    form = forms.AddTokenForm()
    if form.validate_on_submit():
        # Complete 2FA registration
        registered_device = complete_registration(session['u2f_enroll'],
                                                  form.response.data)[0].json
        user = models.User.query.filter_by(id=session['user']).first()
        u2f_cred = models.U2FCredentials(name=form.name.data,
                                         owner=user.id,
                                         device=registered_device)
        db.session.add(u2f_cred)
        db.session.commit()
        flash("Authentication token added", "success")
        return redirect(url_for('login'))
    # Start 2FA registration
    enroll = begin_registration(app_id, [])
    session['u2f_enroll'] = enroll.json
    challenge = enroll.data_for_client['registerRequests'][0]['challenge']
    return render_template('add_2fa.html',
                           challenge=challenge,
                           appId=app_id,
                           version="U2F_V2",
                           form=form)
Beispiel #29
0
    def start_enrollment(self, user, has_webauthn_register):
        if has_webauthn_register:
            credentials = []
            for registeredKey in self.get_u2f_devices():
                if type(registeredKey) == AuthenticatorData:
                    credentials.append(registeredKey.credential_data)
                else:
                    c = create_credential_object(registeredKey)
                    credentials.append(c)

            registration_data, state = self.webauthn_registration_server.register_begin(
                user={
                    "id": user.id.to_bytes(64, byteorder="big"),
                    "name": user.username,
                    "displayName": user.username,
                },
                credentials=credentials,
                # user_verification is where the authenticator verifies that the user is authorized
                # to use the authenticator, this isn't needed for our usecase so set a discouraged
                user_verification="discouraged",
            )
            return cbor.encode(registration_data), state

        return u2f.begin_registration(self.u2f_app_id, self.get_u2f_devices()).data_for_client
Beispiel #30
0
def add_key(request):
  if request.method == 'GET':
    origin = get_origin(request)
    u2f_request = u2f.begin_registration(origin)
    request.session['u2f_request'] = u2f_request
    context = {'u2f_request': json.dumps(request.session['u2f_request'])}
    return render(request, 'registration/add_key.html', context)

  u2f_response = request.POST['response']
  origin = get_origin(request)
  device, attestation_cert = u2f.complete_registration(
    request.session['u2f_request'], u2f_response)
  models.U2FKey.objects.update_or_create(
    user=request.user,
    defaults={
      'public_key': device['publicKey'],
      'key_handle': device['keyHandle'],
      'app_id': device['appId'],
      },
  )
  messages.success(request, 'Yubikey configured.')
  del request.session['u2f_request']
  request.session['yubikey_authenticated'] = True
  return redirect('home')
Beispiel #31
0
 def start_enrollment(self):
     return u2f.begin_registration(self.u2f_app_id,
                                   self.get_u2f_devices()).data_for_client
Beispiel #32
0
 def get(self, request, *args, **kwargs):
     user_devices = [ud.device for ud in request.user.useru2f_set.all()]
     register_request = begin_registration(
         zentral_settings["api"]["tls_hostname"], user_devices)
     self.request.session["u2f_challenge"] = dict(register_request)
     return super().get(request, *args, **kwargs)
Beispiel #33
0
 def start_enrollment(self):
     return u2f.begin_registration(self.u2f_app_id, self.get_u2f_devices()).data_for_client
 def get_context_data(self, **kwargs):
     enroll = u2f.begin_registration(mf_settings['U2F_APPID'], [])
     self.request.session['multifactor_u2f_enroll_'] = enroll.json
     return {
         'token': json.dumps(enroll.data_for_client),
     }
Beispiel #35
0
def start(request):
    enroll = begin_registration(settings.U2F_APPID, [])
    request.session['_u2f_enroll_'] = enroll.json
    context=csrf(request)
    context["token"]=simplejson.dumps(enroll.data_for_client)
    return render_to_response("U2F/Add.html",context,RequestContext(request))