Switch language: EN|RU

Tuesday, February 9, 2021

Guidelines for services: using convenient multi-factor authentication. Part 2 || Рекомендации сервисам по использованию удобной мультифакторной аутентификации. Часть 2

   


Наконец, финальная заметка с тезисным обзором хороших практик по удобной аутентификации в сервисах, изложенных в рекомендации NIST Special Publication 800-63B. Digital Identity Guidelines. Authentication and Lifecycle ManagementПредыдущая заметка была про пароли, сегодня - про мультифакторную аутентификацию (MFA). Часть 2. В самом начале я рассказал о том, Как сервисам сделать использование паролей удобнымВ Части 1 про MFA мы рассматривали 3 типа рекомендаций для сервисов по удобной и безопасной мультафакторной аутентификации: Отдельный канал связи до выделенного устройства (Out-of-Band Devices), Простой генератор одноразовых паролей (Single-Factor OTP Device) и Мультифакторный генератор одноразовых паролей (Multi-Factor OTP Device). Сегодня приведем рекомендации относительно остальных четырех: Ключ, хранимый в софте/на диске (Single-Factor Cryptographic Software), Ключ, хранимый на подключаемом устройстве (Single-Factor Cryptographic Devices), Ключ, хранимый в софте/на диске + другой фактор Multi-Factor Cryptographic Software, Ключ, хранимый на подключаемом устройстве + другой фактор (Multi-Factor Cryptographic Device).

Ключ, хранимый в софте/на диске (Single-Factor Cryptographic Software)
Предполагает использование для второго фактора аутентификации некоего ключа, который хранится на устройстве пользователя прямо на диске (файл), либо внутри специального софта (суть - та же). Может инкапсулировать в себе один или несколько секретных ключей. Реализует принцип "то, что у меня есть". Фактически, это и есть принцип электронной подписи. По идее, любой, у кого появился доступ на устройство пользователя, может воспользоваться ей для подтверждения аутентификации. Очевидно, что хранить ключ просто файлом на диске - не лучшее решение с точки зрения безопасности, однако, если такое применяется, то следуйте следующим советам:
  1. Ключ должен содержаться в безопасном хранилище (Keychain, TPM, TEE и т.п.)
  2. Ключ должен быть защищен от несанкционированного доступа, а права обращения к нему - назначены только необходимому приложению (-ям)
  3. Нельзя допускать клонирование ключа и возможности его переиспользования на другом устройстве
  4. Поскольку для проверки ключа на стороне сервиса хранится ассиметричный или симметричный ключ, они должны быть защищены от модификации, а симметричный - еще и от раскрытия
  5. Посылаемое со стороны сервиса на устройство (или в приложение) в момент аутентификации "секретное сообщение" должно быть уникальным (не повторяться) и длиной не менее 64 бит   
Ключ, хранимый на подключаемом устройстве (Single-Factor Cryptographic Devices)
В отличие от предыдущего способа, здесь секретный ключ хранится на отчуждаемом носителе. Чтобы использовать его, как второй фактор, необходимо каждый раз при аутентификации на сервисе подключать его к устройству, а после завершения работы с сервисом - отключать. Реализует принцип "то, что у меня есть". Удостоверение (подписание) с помощью ключа происходит путем прямого подключения к интерфейсу клиентского устройства (например, USB-порт или более современные - по bluetooth). Главное отличие от софтового вариант в том, что здесь управление доступом к ключам происходит на подключаемом устройстве. Вот - рекомендации по безопасности:
  1. Главный принцип - ключи должны быть не клонируемыми и не удаляемыми (исключение - "заводское" обнуление)
  2. Хорошо, если подключаемое устройство может иметь собственный криптографический процессор
  3. Алгоритм, секретный ключ должны удовлетворять минимальным требованиям безопасности (быть по крайней мере 112 бит)
  4. Секретный ключ должен быть длиной не менее 64 бит
  5. Хорошей практикой в момент использования ключа является наличие на устройстве "физического активатора" вроде кнопки, чтобы предотвратить его злоумышленное использование
  6. Поскольку для проверки ключа на стороне сервиса хранится ассиметричный или симметричный ключ, они должны быть защищены от модификации, а симметричный - еще и от раскрытия
  7. Посылаемое со стороны сервиса в момент аутентификации "секретное сообщение" должно быть уникальным (не повторяться) и длиной не менее 64 бит
Ключ, хранимый в софте/на диске + другой фактор (Multi-Factor Cryptographic Software)
Основное отличие от простого софтового хранилища - дополнительный второй фактор, требуемый для обращения к секрету (подписи, сертификату). В качестве него может выступать пин-код, пароль или биометрические данные. Для самого сервиса нет при проверке ключа никакой разницы по сравнению с обычным "софтовым" хранением, усиление происходит только на стороне клиента. Реализует сразу два принципа: "то, что у меня есть" совместно с "тем, что я знаю"/"тем, кто я". Все рекомендации из раздела "Ключ, хранимый в софте/на диске" справедливы и для текущего. Однако, вот, на что стоит обратить внимание сервисам и клиентам:
  1. Ключ должен содержаться в безопасном хранилище (Keychain, TPM, TEE и т.п.)
  2. Ключ должен быть защищен от неавторизованного доступа путем создания такой модели, при которой обращение к нему происходит только от определенного списком клиентского софта
  3. Нельзя допускать клонирование ключа и возможности его переиспользования на другом устройстве
  4. Каждая без исключений операция обращения к ключу должна сопровождаться требованием предъявления второго фактора
  5. Если для обращения к ключу используется числовой код, то он должен состоять из не менее чем 6 цифр, количество попыток ввода должно быть ограничено
  6. Если для активации OTP устройства используется биометрия, то должно быть ограничено число попыток и другие меры безопасности (подробнее - ниже в Бонусе 2)
  7. Ключ, образец биометрии, иной секрет в случае успешного обращения к ключу должны быть затерты сразу же после завершения второго шага (использование ключа непосредственно по назначению)
Ключ, хранимый на подключаемом устройстве + другой фактор (Multi-Factor Cryptographic Device)
При таком способе хранение ключа и непосредственно криптографические операции осуществляются на отдельном устройстве, для активация которого требуется  дополнительный второй фактор (пин-код, пароль, биометрия). Для аутентификации на сервисе клиенту необходимо подключить отдельное устройство напрямую к своему основному (компьютер, ноутбук, смартфон). Принцип действия и базовые советы здесь повторяют таковые для "Ключа, хранимого на подключаемом устройстве". По сути, единственное отличие - необходимость предъявить что-то еще. Реализует сразу два принципа: "то, что у меня есть" совместно с "тем, что я знаю"/"тем, кто я"Ниже приведем дополнительные к уже описанным рекомендации по безопасности:
  1. Каждая без исключений операция обращения к ключу должна сопровождаться требованием предъявления второго фактора, что можно сделать либо непосредственно на таком отдельном устройстве (ввести пароль, приложить палец), либо с помощью подключения к нему (смарт-карта, USB) 
  2. Ключ, образец биометрии, иной секрет в случае успешного обращения к ключу должны быть затерты сразу же после завершения второго шага (использование ключа непосредственно по назначению)
Бонус 1. Дополнительные рекомендации по ограничению попыток доступа
Хорошей практикой является внедрение по-умолчанию механизмов ограничения попыток неправильного ввода пароля, предъявления второго фактора (защита от угадывания и брутфорс атак). В качестве базового требования для задач любого сервиса предлагается установить ограничение в 100 попыток (для одного аккаунта). Но не так все просто. Необходимо принимать следующие меры, чтобы минимизировать вероятность блокировки легитимных пользователей злоумышленниками:
  1. Использование сервисом капчи непосредственно перед процедурой аутентификации
  2. Задание временного промежутка (от 30 до 60 мин.) невозможности очередного ввода после нескольких попыток неудачной аутентификации
  3. Отслеживание сервисом IP-адресов, с которых подключаются клиенты, и, как минимум, предупреждать (или блокировать) попытки доступа с незнакомых
  4. Внедрение сервисом продвинутых техник поведенческой аналитики пользователей (и их устройств) и детектирование отклонений (IP-адреса, геолокация, временные промежутки, метаданные браузера и т.п.)
  5. При успешной аутентификации сервис должен игнорировать все предыдущие неуспешные попытки этого пользователя с этого IP-адреса 
Бонус 2. Дополнительные рекомендации по использованию биометрии
Использование биометрии в качестве второго фактора (реализует принцип "тот, кто я") включает как физиологические характеристики (палец, глаз, лицо, ладонь и т.п.), так и поведенческие (например, стиль клавиатурного ввода). В обозреваемом документе NIST приводится некий скепсис (ограничения) по использованию биометрии:
  1. Существует так называемый биометрический Коэффициент ложного совпадения (False Match Rate - FMR), который в общем случае не гарантирует точность процедуры (в отличие от иных методов). Кроме того, FMR не стоек к спуффинг-атакам
  2. Схемы защиты биометрических шаблонов, такие как отзыв биометрических учетных данных вроде бы уже придуманы и схожи с остальными методами (сертификаты PKI, пароль и т.п.), однако на практике они еще сырые, разрабатываются и тестируются
  3. Некоторые виды популярной биометрии относительно легко подвержены копированию (вспомните дипфейки или приемы кражи отпечатков пальцев). Разрабатываются методы противодействия подобного рода атакам такие как  Presentation Attack Detection - PAD (например, интеллектуальное определение живого/не живого человека), но главное "слово" все равно остается за сенсором, в котором нужно будет предусматривать дополнительные механизмы доверия
Если вы все же решились использовать биометрию, то придерживайтесь следующих рекомендаций:
  1. Биометрия должны использоваться исключительно как часть мультифакторной аутентификации с физическим устройством (т.е. "тем, что я имею")
  2. Канал от датчика клиента до сервиса должен быть защищен, а доступ к ключу в самом втором факторе (его активация с помощью биометрии) должен быть открыт только после успешной биометрической аутентификации на нем 
  3. False Match Rate (FMR) должен удовлетворять требованиям "1 из 1000" стандарта ISO/IEC 2382-37
  4. Биометрическая система должна реализовывать Presentation Attack Detection (PAD) на выбор: либо на стороне сервиса, либо на стороне клиента. Тестирование такого механизма должно показывать как минимум 90% стойкость к presentation атакам каждого из типов 
  5. Биометрическая система должна допускать не более 5 неудачных попыток аутентификации или не более 10 (в случае реализации PAD). При превышении порога допускаются следующие сценарии (на выбор сервиса):
    1. принудительная задержка перед следующей попыткой сначала 30 секунд, потом 1 минута, потом 2 минуты
    2. блокировка биометрии, как второго фактора и предложение альтернативного метода (если он предусмотрен)
  6. Сервис должен каким-либо способом установить доверие к биометрическому датчику путем: его (или устройства пользователя) дополнительной аутентификации, сертификации независимым органом, внедрение неких метаданных в качестве подписи прямо на лету
  7. Проверка биометрии может осуществляться локально на устройстве пользователя (предпочтительный и более безопасный вариант) или централизованно сервисом. Во втором случае сервису необходимо внедрить:
    1. использование биометрии должно быть ограничено на конкретных устройствах, которые сервис способен идентифицировать (например, с помощью отдельного ключа, отличного от основного)
    2. механизм отзыва биометрии согласно ISO/IEC 24745
    3.  любая передача биометрии должна осуществляться по защищенному каналу
  8. С согласия пользователя биометрические образцы можно агрегировать с целью обучения (тюнинга) алгоритмов проверки, они должны быть удалены после достижения таких целей
  9. Биометрия также может быть использована сервисами для обеспечения неотказуемости на всех этапах регистрации пользователя и работы в сервисе, подробнее об этом - в публикации NIST SP800-63A 
Как мы видим, внедрение даже самых современных методов многофакторной аутентификации уже можно осуществлять согласно лучшим практикам (спасибо коллегам из NIST), которые довольно подробно описывают базовые требования по безопасности. Когда есть куда "подсмотреть" - это всегда полезно.

Основной целью данного цикла заметок было рассказать, что существуют не только строгие нормативные требования по организации аутентификации в сервисах, но и рекомендации, учитывающие как лучшие практики по безопасности, так и вопросы удобства. Последнее является обязательным, ведь, как мы знаем, пользователи - самый первый и едва ли не самый важный рубеж обороны в противостоянии со злоумышленниками. Удобная безопасность всегда будет наиболее эффективна.

Читайте также: MFA. Часть 1, Удобные пароли

Оставайтесь на светлой стороне. R.Z. 




Finally, I bring to your attention the latest article with a brief review of the best practices of secure and convenient authentication in services according to NIST Special Publication 800-63B. Digital Identity Guidelines. Authentication and Lifecycle Management. Today I'm going to talk about Multi-factoк authentication (MFA). Part 2. At the very beginnig of this series of articles I told you about How services can make using passwords convenientIn the MFA. Part 1 we discussed the recommendations related to three (out of 7) types of secure and convenient MFAs: Out-of-Band Devices, Single-Factor OTP Device and Multi-Factor OTP Device. Now let's move on to the remaining ones: Single-Factor Cryptographic Software, Single-Factor Cryptographic Devices, Multi-Factor Cryptographic Software and Multi-Factor Cryptographic Device.

Single-Factor Cryptographic Software
Means using a cryptographic key stored on a disk (e.g. file) or some other special "soft" media (the essence is the same). Single-factor software cryptographic authenticators encapsulate one or more secret keys unique to the service. Implements the concept "something you have". It is like a digital signature. In fact anyone who has direct access to the user's device can use it to confirm authentication. Obviously, the key stored on disk as a simple file is not the best solution. However, if this works for you, please follow these guidelines:
  1. The key shall be stored in suitably secure storage available to the user's application (e.g., keychain storage, TPM, or TEE if available)
  2. The key shall be strongly protected against unauthorized disclosure by the use of access controls that limit access to the key to only those software components on the device requiring access
  3. Single-factor cryptographic software authenticators should discourage and shall not facilitate the cloning of the secret key onto multiple devices
  4. The service has either symmetric or asymmetric cryptographic keys corresponding to each users. While both types of keys shall be protected against modification, symmetric keys shall additionally be protected against unauthorized disclosure
  5. The challenge nonce shall be at least 64 bits in length, and shall either be unique over the authenticator’s lifetime or statistically unique
Single-Factor Cryptographic Devices
Unlike the previous method, this one means using a hardware device that performs cryptographic operations using protected cryptographic key(s) and provides the user output via direct connection to the user endpoint. The device uses embedded symmetric or asymmetric cryptographic keys, and does not require activation through a second factor of authentication. The authenticator output is provided by direct connection to the user endpoint and operates by signing a challenge nonce presented through a direct computer interface (USB port or something modern like bluetooth). Implements the concept "something you have". The main difference is that the keys are accessed directly on that device. Follow these guidelines:
  1. Single-factor cryptographic device authenticators encapsulate one or more secret keys unique to the device that shall not be exportable (i.e., cannot be removed from the device)
  2. Alternatively, the authenticator could be a suitably secure processor integrated with the user endpoint itself (e.g., a hardware TPM)
  3. The secret key and its algorithm shall provide at least the minimum security length 112 bits
  4. The challenge nonce shall be at least 64 bits in length
  5. It's a good practice to use a physical input (e.g., the pressing of a button) in order to operate. This provides defense against unintended operation of the device, which might occur if the endpoint to which it is connected is compromised
  6. The service has either symmetric or asymmetric cryptographic keys corresponding to each user. While both types of keys shall be protected against modification, symmetric keys shall additionally be protected against unauthorized disclosure
  7. The challenge nonce shall be at least 64 bits in length, and shall either be unique over the authenticator’s lifetime or statistically unique
Multi-Factor Cryptographic Software
The key difference from simple single-factor cryptographic software is a cryptographic key stored on disk or some other "soft" mediathat requires activation through a second factor of authentication. It can be a PIN, password or biometric data. Authentication is accomplished by proving possession and control of the key. Implements two concepts at once: "something you have" with "something you know or something you are". For the service, there is no difference from simple single-factor cryptographic software, hardening is performed on the user's side. In this case, all the previous recommendations are works, however, here are a few more noteworthy ones:
  1. The key should be stored in suitably secure storage available to the user's application (e.g., keychain storage, TPM, TEE)
  2. The key shall be strongly protected against unauthorized disclosure by the use of access controls that limit access to the key to only those software components on the device requiring access
  3. Multi-factor cryptographic software authenticators should discourage and shall not facilitate the cloning of the secret key onto multiple devices
  4. Ключ должен содержаться в безопасном хранилище (Keychain, TPM, TEE и т.п.)
  5. Each authentication operation using the authenticator shall require the input of both factor, whitout exceptions
  6. Any memorized secret used by the user for activation shall be a randomly-chosen numeric value at least 6 decimal digits in length and the number of attempts shall be rate limited
  7. A biometric activation factor (in case of its use) shall includes limits on the number of consecutive authentication failures. For more information about biometric guildelines, see Appendix B
  8. The unencrypted key and activation secret or biometric sample — and any biometric data derived from the biometric sample such as a probe produced through signal processing — shall be zeroized immediately after an authentication transaction has taken place
Multi-Factor Cryptographic Device
In this case, both key storage and cryptographic operations are performed directly inside the device. These operations use one or more protected cryptographic keys and requires activation through a second authentication factor (e.g. PIN, password, biometrics). Authentication is accomplished by proving possession of the device and control of the key, the authenticator output is provided by direct connection to the user endpoint (laptop, phone, PC). Implements two concepts at once: "something you have" with "something you know or something you are". The basic principles and guidelines are the same as for single-factor cryptographic devices. In fact, the only difference is the need to present something else. Below you'll find additional recommendations:
  1. Each authentication operation using the authenticator should require the input of the additional factor. Input of the additional factor may be accomplished via either direct input on the device or via a hardware connection (e.g., USB, smartcard) 
  2. The unencrypted key and activation secret or biometric sample — and any biometric data derived from the biometric sample such as a probe produced through signal processing — shall be zeroized immediately after an authentication transaction has taken place
Appendix A. Guidelines for Rate Limiting (Throttling)
It is a good practice for services to implement mechanisms to limit the unseccessful MFA attempts (against guessing attacks and brute force) by default. The main recommendations are to set limit consecutive failed authentication attempts on a single account to no more than 100. Not everything is as simple as it seems. On the other hand, services should reduce the likelihood that an attacker will lock the legitimate claimant out as a result of rate limiting. Such measures may include:
  1. Requiring the claimant (user) to complete a CAPTCHA before attempting authentication
  2. Requiring the claimant (user) to wait following a failed attempt for a period of time that increases as the account approaches its maximum allowance for consecutive failed attempts (e.g., 30 seconds up to an hour)
  3. Accepting only authentication requests that come from a white list of IP addresses from which the subscriber has been successfully authenticated before
  4. Leveraging other risk-based or adaptive authentication techniques to identify user behavior that falls within, or out of, typical norms. These might, for example, include use of IP address, geolocation, timing of request patterns, or browser metadata
  5. When the subscriber (user) successfully authenticates, the service should disregard any previous failed attempts for that user from the same IP address
Appendex B. Guidelines for Use of Biometrics
Using biometrics as a second factor (concept "something you are"in authentication includes both measurement of physical characteristics (e.g., fingerprint, iris, facial characteristics) and behavioral characteristics (e.g., typing cadence). The NIST's document provides some concern on the use of biometrics:
  1. The biometric False Match Rate (FMR) does not provide confidence in the authentication of the subscriber by itself. Biometric comparison is probabilistic, whereas the other authentication factors are deterministic. In addition, FMR does not account for spoofing attacks
  2. Biometric template protection schemes provide a method for revoking biometric credentials that is comparable to other authentication factors (e.g., PKI certificates and passwords). However, the availability of such solutions is limited, and standards for testing these methods are under development
  3. Biometric characteristics do not constitute secrets. They can be obtained online or by taking a picture of someone with a camera phone (e.g., facial images) with or without their knowledge, lifted from objects someone touches (e.g., latent fingerprints), or captured with high resolution images (e.g., iris patterns). While presentation attack detection (PAD) technologies (e.g., liveness detection) can mitigate the risk of these types of attacks
If you still decide to use biometrics, then follow these recommendations:
  1. Biometrics shall be used only as part of multi-factor authentication with a physical authenticator (something you have)
  2. An authenticated protected channel between sensor (or an endpoint containing a sensor that resists sensor replacement) and verifier shall be established and the sensor or endpoint shall be authenticated prior to capturing the biometric sample from the claimant (user)
  3. The biometric system shall operate with an FMR (ISO/IEC 2382-37) of 1 in 1000 or better
  4. The biometric system should implement presentation attack detection (PAD). Testing of the biometric system to be deployed should demonstrate at least 90% resistance to presentation attacks for each relevant attack type (i.e., species)
  5. The biometric system shall allow no more than 5 consecutive failed authentication attempts or 10 consecutive failed attempts if PAD meeting the above requirements is implemented. Once that limit has been reached, the biometric authenticator shall either (the choice is left to the service):
    1. impose a delay of at least 30 seconds before the next attempt, increasing exponentially with each successive attempt (e.g., 1 minute before the following failed attempt, 2 minutes before the second following attempt) or
    2. disable the biometric user authentication and offer another factor (e.g., a different biometric modality or a PIN/Passcode if it is not already a required factor) if such an alternative method is already available
  6. The service shall make a determination of sensor and endpoint performance, integrity, and authenticity. Acceptable methods for making this determination include, but are not limited to: Authentication of the sensor or endpoin, Certification by an approved accreditation authority and Runtime interrogation of signed metadata
  7. Biometric comparison can be performed locally on claimant’s device or at a central verifier. Since the potential for attacks on a larger scale is greater at central verifiers, local comparison is preferred. Yet if the comparison performs centrally:
    1. use of the biometric as an authentication factor shall be limited to one or more specific devices that are identified using approved cryptography. Since the biometric has not yet unlocked the main authentication key, a separate key shall be used for identifying the device
    2. biometric revocation, referred to as biometric template protection in ISO/IEC 24745, shall be implemented
    3. all transmission of biometrics shall be over the authenticated protected channel
  8. Канал от датчика клиента до сервиса должен быть защищен, а доступ к ключу в самом втором факторе (его активация с помощью биометрии) должен быть открыт только после успешной биометрической аутентификации на нем 
  9. False Match Rate (FMR) должен удовлетворять требованиям "1 из 1000" стандарта ISO/IEC 2382-37
  10. Biometric samples collected in the authentication process may be used to train comparison algorithms or — with user consent — for other research purposes. Biometric samples and any biometric data derived from the biometric sample such as a probe produced through signal processing shall be zeroized immediately after any training or research data has been derived
  11. Biometrics are also used in some cases to prevent repudiation of enrollment and to verify that the same individual participates in all phases of the enrollment process as described in SP 800-63 
To sum up, we can say that the implementation of even modern methods of Multi-Factor authentication has a "right to live" and can be used in the wild to meet the need of both services and users. Following of already issued best practices (thanks to colleagues from NIST), they help to ensure that the basic security controls step-by-step and not to forget essencial features.  It's very useful to have that cheat sheet.

The main purpose of this series of posts was to highlight that there are not only strict regulatory security requirements, but also guidelines and best practices for addressing convenience issues. This is important because, as we know, users are the most valuable fort in the struggle against attackers. Convenient security will always be the most effective.


Stay on the light side. R.Z.

No comments:

Post a Comment