Math.random()만 할 수 있는데 왜 OTP 라이브러리를 사용합니까?

王林
풀어 주다: 2024-08-17 20:30:32
원래의
262명이 탐색했습니다.

Why do we use OTP libraries when we can just do Math.random()

일회용 비밀번호(OTP)는 다양한 애플리케이션과 서비스에서 인증 및 확인 목적으로 널리 사용됩니다. 서버는 일반적으로 이를 생성하여 SMS, 이메일 또는 기타 채널을 통해 사용자에게 보냅니다. 그런 다음 사용자는 자신의 신원을 확인하거나 작업을 수행하기 위해 OTP를 입력합니다.

Node JS에서 OTP 기반 검증을 구현해야 하는 작업이 생겼습니다. 이와 같은 것을 통합하기 전에 대부분의 개발자/엔지니어는 인터넷에서 모범 사례, 튜토리얼, 최신 기술 동향 및 기타 주요 소프트웨어 시스템이 구현 중에 직면하는 문제를 찾아볼 것이라고 확신합니다. 그래서 해봤는데, 가장 관심을 끌었던 것은 otp-lib, otp-generator와 같은 라이브러리였는데, 이들의 유일한 기능은 OTP를 생성하는 것이었습니다. SMS나 이메일을 통한 전송과 같은 나머지 작업은 여전히 다른 방법으로 수행해야 합니다. 그러한 라이브러리가 존재한다는 것을 알고 나서 떠오르는 첫 번째 질문은 한 줄만 작성하면 되는데 왜 OTP를 생성하기 위해 라이브러리를 사용하기 위해 그렇게 많은 노력을 기울여야 하는가입니다.

으아악

이 블로그 게시물에서는 OTP 생성기에 대한 소규모 연구 중에 배운 내용, Math.random()을 사용하여 OTP를 생성하는 것이 왜 나쁜 생각인지, OTP를 생성하는 다른 방법은 무엇인지, 라이브러리가 있어야 하는 이유에 대해 설명하겠습니다. 그런 작업에 쓰인다고?

난수의 유형

난수에는 주로 두 가지 유형이 있습니다:

  • 의사 난수(PRN)
  • 암호화 난수(CRN).

의사 난수

의사 난수는 시드라고 하는 초기 값을 사용하여 무작위로 보이는 일련의 숫자를 생성하는 알고리즘에 의해 생성됩니다. 그러나 알고리즘은 결정적입니다. 즉, 시드와 알고리즘을 알면 시퀀스의 다음 숫자를 예측할 수 있습니다. Javascript의 Math.random() 및 Python의 random.randInt()는 의사 난수 생성기의 예입니다.

암호화 난수

암호 난수는 예측할 수 없고 재현하거나 추측할 수 없는 프로세스에 의해 생성됩니다. 이는 일반적으로 대기 소음, 열 소음 또는 양자 효과와 같은 일부 물리적 현상을 기반으로 합니다.

Math.random()은 어떻게 작동하나요?

다른 Javascript 엔진은 난수를 생성할 때 약간 다르게 작동하지만, 이는 모두 기본적으로 단일 알고리즘 XorShift128+로 귀결됩니다.

XorShift는 더 빠른 비선형 변환 솔루션으로 추가를 사용하는 결정적 알고리즘입니다. 곱셈을 사용하는 동료에 비해 이 알고리즘은 더 빠릅니다. 또한 Mersenne Twister(Python의 무작위 모듈에서 사용됨)보다 실패 가능성이 적습니다

알고리즘은 두 개의 상태 변수를 가져와 XOR 및 Shift를 적용하고 업데이트된 상태 변수의 합계인 정수를 반환합니다. 상태는 일반적으로 고유 번호에 대한 좋은 소스이기 때문에 시스템 시계를 사용하여 시드됩니다.

자바스크립트에서 XOR 시프트 플러스를 구현하는 방법은 다음과 같습니다.

으아악

반환된 정수는 상수와 OR 연산을 사용하여 double로 변환됩니다. 자세한 구현은 크롬 소스코드에서 확인하실 수 있습니다

Math.random()에 의해 생성된 난수를 예측하는 방법

Math.random()의 결과를 예측하는 것은 어렵지만 완전히 불가능한 것은 아닙니다. 알고리즘을 알면 state0과 state1의 값을 알면 동일한 난수를 쉽게 다시 생성할 수 있습니다.

역엔지니어링 XorShift128+ Z3 정리 증명자를 사용하면 서버에서 생성된 3개의 연속 난수를 제공하여 state0과 state1의 값을 찾을 수 있습니다.

Z3 솔버 구현은 여기에서 확인할 수 있습니다.

이제 질문은 서버에서 3개의 난수를 얻는 방법에 관한 것입니다. 이는 어려운 부분이며 다음과 같은 경우에 얻을 수 있습니다.

  1. If an API returns a randomly generated number in its response or headers, it can easily be obtained by sending requests at set intervals.
  2. API documentation like OpenAPI/Swagger in modern applications is generated on the server. Sometimes their responses can contain an example value that uses a random number.
  3. With frameworks like NextJS that use server-side rendering while also being capable of handling backend API integrations, there are high chances of getting randomly generated numbers from the content served by them.

Another approach to exploit a random number is using the fact that Math.random() only returns numbers between 0 and 1 with 16 decimal places. This means that there are only 10^16 possible values that Math.random() can return. This is a very small space compared to the space of possible OTPs. if your OTP has 6 digits, there are 10^6 possible values. This visualizer shows that there is a pattern to the numbers generated. Using it, the possibilities can be reduced by 30%. Therefore, if you can guess or brute-force some of the digits of the OTP, you can reduce the space of possible values and increase your chances of finding the correct OTP.

Generating a Cryptographic Random Number in NodeJS

As mentioned previously, cryptographic random numbers are non-deterministic because they depend on the physical factors of a system. Every programming language can access those factors using low-level OS kernel calls.

NodeJS provides its inbuilt crypto module, which we can use to generate randomBytes and then convert them to a number. These random bytes are cryptographic and purely random in nature. The generated number can easily be truncated to the exact number of digits we want in OTP.

import * as crypto from 'crypto'; const num = parseInt(crypto.randomBytes(3).toString('hex'), 16) // num.toString().slice(0,4) // truncate to 4 digits
로그인 후 복사

NodeJS 14.10+ provides another function from crypto to generate a random number in a given min-max range.

crypto.randomInt(1001, 9999)
로그인 후 복사

Even after knowing the vulnerability of Math.random() and finding a more secure way to generate a random number cryptographically, we still remain with the same question from the beginning. Why do we have to go to such lengths to use a library to generate OTP when all we have to do is write a one-liner?

Before answering this questions, let's take a look at what is the inconvenience faced while handling and storing an OTP. The problem with using the above method to generate OTPs is that you have to store them in the database in order to verify them later. Storing the OTP in the database is not a good practice for the following reasons:

  1. Storing OTPs in the database creates a lot of garbage data that has to be cleaned up periodically. OTP means a one-time password that can expire after a single use. It can also expire if not used for a specific duration or a new OTP is requested without using the previous one. This mainly adds unnecessary overhead to the database operations for maintaining valid OTPs while also consuming storage space.
  2. Storing OTPs in the database poses a security risk if the database is compromised. An attacker who gains access to the database can read the OTPs and use them to bypass the authentication or verification process. This can lead to account takeover, identity theft, or fraud.
  3. Storing OTPs in the database makes them vulnerable to replay attacks. A replay attack is when an attacker intercepts an incoming valid OTP and uses it again before it expires. This can allow the attacker to perform unauthorised actions or access sensitive information.

What do the OTP libraries do differently?

The OTP libraries use different algorithms and techniques to generate and verify OTPs that behave similarly to a Cryptographic random OTP, while also removing the overhead to store the OTP in a database.

There are mainly two types of OTP implementation techniques.

HOTP

HOTP stands for HMAC-based One-Time Password. It is an algorithm that generates an OTP based on a secret key and a counter. The secret key is a random string that is shared between the server and the user. The counter is an integer that increments every time an OTP is generated or verified.

The algorithm works as follows:

• The server and the user generate the same OTP by applying a cryptographic hash function, such as SHA-1, to the concatenation of the secret key and the counter.
• The server and the user truncate the hash value to obtain a fixed-length OTP, usually 6 or 8 digits.
• The user sends the OTP to the server for verification.
• The server compares the OTP with its own generated OTP and verifies it if they match.
• The server and the user increment their counters by one.

HOTP는 Yubikey와 같은 하드웨어 토큰 기반 인증에 주로 사용됩니다. Yubikey는 기본적으로 컴퓨터나 휴대폰에 물리적으로 연결할 수 있는 프로그래밍된 하드웨어 키입니다. SMS나 이메일로 코드를 받는 대신 Yubikey의 버튼만 누르면 본인을 확인하고 인증할 수 있습니다.

HOTP의 장점은 다음과 같습니다.

• OTP는 즉시 생성되고 검증될 수 있으므로 데이터베이스에 저장할 필요가 없습니다.
• 예측할 수 없고 되돌릴 수 없는 암호화 해시 함수를 사용하므로 의사 난수에 의존하지 않습니다.
• 각 OTP는 한 번만 유효하므로 재생 공격에 강합니다.

HOTP의 단점은 다음과 같습니다.

• 서버와 사용자 카운터 간의 동기화가 필요합니다. 네트워크 지연, 전송 오류 또는 장치 손실로 인해 동기화되지 않은 경우 확인이 실패합니다.
• 새로 생성된 HOTP를 사용하지 않는 한 유효하며 이는 취약점이 될 수 있습니다.
• 비밀 키를 배포하고 저장하는 안전한 방법이 필요합니다. 비밀키가 유출되거나 도난당할 경우 OTP가 침해될 수 있습니다.

TOTP

TOTP는 시간 기반 일회용 비밀번호를 나타냅니다. 비밀키, 타임스탬프, 에포크를 기반으로 OTP를 생성하는 알고리즘입니다.

  • 비밀 키는 서버와 사용자 간에 공유되는 임의의 문자열입니다. SHA1( "secretvalue" + user_id )을 생성하여 각 사용자마다 고유하게 생성할 수 있습니다.
  • 타임스탬프는 현재 시간을 초 단위로 나타내는 정수입니다
  • 에포크는 알고리즘이 동일한 결과를 생성하는 기간입니다. 일반적으로 30초~1분 사이로 유지됩니다

알고리즘은 다음과 같이 작동합니다:
• 서버는 사용자의 비밀 키를 결정하고 이를 인증 앱과 같은 매체를 통해 공유합니다.
• 서버에서 직접 OTP를 생성하여 사용자에게 메일이나 SMS로 보내거나, 인증기를 사용하여 공유키를 사용하여 OTP를 생성하도록 사용자에게 요청할 수 있습니다.
• 메일이나 SMS로 받은 OTP를 사용자가 직접 보내거나, 2FA의 경우 정해진 시간 내에 인증기 앱에서 생성할 수 있습니다.
• 서버는 OTP를 자체 생성된 OTP와 비교하여 에포크 시간 범위에서 충분히 근접한지 확인합니다.

TOTP의 장점은 다음과 같습니다.

• OTP는 즉시 생성되고 검증될 수 있으므로 데이터베이스에 저장할 필요가 없습니다.
• 예측할 수 없고 되돌릴 수 없는 암호화 해시 함수를 사용하므로 의사 난수에 의존하지 않습니다.
• 각 OTP는 짧은 시간 동안만 유효하므로 재생 공격에 강합니다.
• 서버와 사용자의 타임스탬프 간의 동기화가 필요하지 않습니다. 합리적으로 정확한 시계를 보유하고 있는 한 독립적으로 OTP를 생성하고 확인할 수 있습니다.

TOTP의 단점은 다음과 같습니다.

• 비밀 키를 배포하고 저장하는 안전한 방법이 필요합니다. 비밀키가 유출되거나 도난당할 경우 OTP가 침해될 수 있습니다.
• 서버와 사용자 모두에게 신뢰할 수 있는 시간 소스가 필요합니다. 시계가 왜곡되거나 변조된 경우 인증이 실패합니다.
• 서버는 요청 처리 시 시간 변동이나 지연을 고려해야 하므로 클라이언트보다 약간 더 큰 epoch를 유지해야 합니다.

결론

OTP에 대한 작은 연구 여행을 통해 우리는 Math.random()이 예측, 활용 및 재생이 가능하다는 것을 알게 되었습니다. 또한 OTP를 데이터베이스에 저장하는 것은 좋은 습관이 아니라는 것도 알게 되었습니다.

TOTP는 안전하고 효율적인 OTP를 생성하고 검증할 수도 있습니다. 온라인은 물론 오프라인에서도 OTP를 생성할 수 있고 동기화나 저장이 필요하지 않으며 재생 공격에 강합니다. 따라서 모범 사례, 보안 및 안정성과 관련된 대부분의 우려 사항을 해결합니다.

위 내용은 Math.random()만 할 수 있는데 왜 OTP 라이브러리를 사용합니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!