better usability, add doc

This commit is contained in:
vdimir 2024-10-31 11:44:04 +00:00
parent 4c0e620b92
commit 2b1c21afa9
No known key found for this signature in database
GPG Key ID: 6EE4CE2BEDC51862
4 changed files with 108 additions and 68 deletions

View File

@ -1,7 +1,61 @@
---
slug: /en/operations/external-authenticators/
title: "HTTP"
slug: /en/operations/external-authenticators/totp
title: "TOTP"
---
import SelfManaged from '@site/docs/en/_snippets/_self_managed_only_no_roadmap.md';
<SelfManaged />
Time-Based One-Time Password (TOTP) can be used to authenticate ClickHouse users by generating temporary access codes that are valid for a limited time.
In current implementation it is a standalone authentication method, rather than a second factor for password-based authentication.
This TOTP authentication method aligns with [RFC 6238](https://datatracker.ietf.org/doc/html/rfc6238) standards, making it compatible with popular TOTP applications like Google Authenticator, 1Password and similar tools.
## TOTP Authentication Configuration {#totp-auth-configuration}
To enable TOTP authentication for a user, configure the `time_based_one_time_password` section in `users.xml`. This section defines the TOTP settings, such as secret, validity period, number of digits, and hash algorithm.
**Example**
```xml
<clickhouse>
<!-- ... -->
<users>
<my_user>
<!-- TOTP authentication configuration -->
<time_based_one_time_password>
<secret>JBSWY3DPEHPK3PXP</secret> <!-- Base32-encoded TOTP secret -->
<period>30</period> <!-- Optional: OTP validity period in seconds -->
<digits>6</digits> <!-- Optional: Number of digits in the OTP -->
<algorithm>SHA1</algorithm> <!-- Optional: Hash algorithm: SHA1, SHA256, SHA512 -->
</time_based_one_time_password>
</my_user>
</users>
</clickhouse>
Parameters:
- secret - (Required) The base32-encoded secret key used to generate TOTP codes.
- period - Optional. Sets the validity period of each OTP in seconds. Must be a positive number not exceeding 120. Default is 30.
- digits - Optional. Specifies the number of digits in each OTP. Must be between 4 and 10. Default is 6.
- algorithm - Optional. Defines the hash algorithm for generating OTPs. Supported values are SHA1, SHA256, and SHA512. Default is SHA1.
Generating a TOTP Secret
To generate a TOTP-compatible secret for use with ClickHouse, run the following command in the terminal:
```bash
$ base32 -w32 < /dev/urandom | head -1
```
This command will produce a base32-encoded secret that can be added to the secret field in users.xml.
To enable TOTP for a specific user, replace any existing password-based fields (like `password` or `password_sha256_hex`) with the `time_based_one_time_password` section. Only one authentication method is allowed per user, so TOTP cannot be combined with other methods such as password or LDAP.
## Enabling TOTP Authentication using SQL {#enabling-totp-auth-using-sql}
When SQL-driven Access Control and Account Management is enabled, TOTP authentication can be set for users via SQL:
```SQL
CREATE USER my_user IDENTIFIED WITH one_time_password BY 'JBSWY3DPEHPK3PXP';
```
Values for `period`, `digits`, and `algorithm` will be set to their default values.

View File

@ -7,6 +7,18 @@
#include "config.h"
#if USE_SSL
#include <cotp.h>
constexpr int TOTP_SHA512 = SHA512;
constexpr int TOTP_SHA256 = SHA256;
constexpr int TOTP_SHA1 = SHA1;
#undef SHA512
#undef SHA256
#undef SHA1
#endif
namespace DB
{
@ -15,6 +27,7 @@ namespace ErrorCodes
{
extern const int BAD_ARGUMENTS;
extern const int LOGICAL_ERROR;
extern const int SUPPORT_IS_DISABLED;
}
static const UInt8 b32_alphabet[] = u8"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
@ -109,7 +122,7 @@ OneTimePasswordConfig::OneTimePasswordConfig(Int32 num_digits_, Int32 period_, c
std::string_view OneTimePasswordConfig::getAlgorithmName() const { return toString(algorithm); }
String getOneTimePasswordLink(const String & secret, const OneTimePasswordConfig & config)
String getOneTimePasswordSecretLink(const String & secret, const OneTimePasswordConfig & config)
{
validateBase32Secret(secret);
@ -120,60 +133,41 @@ String getOneTimePasswordLink(const String & secret, const OneTimePasswordConfig
secret, config.num_digits, config.period, toString(config.algorithm));
}
bool checkOneTimePassword(const String & password, const String & secret, const OneTimePasswordConfig & config)
String getOneTimePassword(const String & secret [[ maybe_unused ]], const OneTimePasswordConfig & config [[ maybe_unused ]], UInt64 current_time [[ maybe_unused ]])
{
return password == getOneTimePassword(secret, config);
}
}
#if USE_SSL
#include <cotp.h>
constexpr int TOTP_SHA512 = SHA512;
constexpr int TOTP_SHA256 = SHA256;
constexpr int TOTP_SHA1 = SHA1;
#undef SHA512
#undef SHA256
#undef SHA1
namespace DB
{
String getOneTimePassword(const String & secret, const OneTimePasswordConfig & config)
{
validateBase32Secret(secret);
cotp_error_t error;
int sha_algo = config.algorithm == OneTimePasswordConfig::Algorithm::SHA512 ? TOTP_SHA512
: config.algorithm == OneTimePasswordConfig::Algorithm::SHA256 ? TOTP_SHA256
: TOTP_SHA1;
auto result = std::unique_ptr<char>(get_totp(secret.c_str(), config.num_digits, config.period, sha_algo, &error));
cotp_error_t error;
auto result = std::unique_ptr<char>(get_totp_at(secret.c_str(), current_time, config.num_digits, config.period, sha_algo, &error));
if (result == nullptr || (error != NO_ERROR && error != VALID))
throw Exception(ErrorCodes::BAD_ARGUMENTS, "Error while retrieving one-time password, code: {}",
static_cast<std::underlying_type_t<cotp_error_t>>(error));
return String(result.get(), strlen(result.get()));
}
}
#else
namespace DB
{
namespace ErrorCodes
{
extern const int SUPPORT_IS_DISABLED;
}
String getOneTimePassword(const String & secret)
{
throw Exception(ErrorCodes::SUPPORT_IS_DISABLED, "One-time password support is disabled, because ClickHouse was built without openssl library");
}
}
#endif
}
bool checkOneTimePassword(const String & password, const String & secret, const OneTimePasswordConfig & config)
{
if (password.size() != static_cast<size_t>(config.num_digits)
|| !std::all_of(password.begin(), password.end(), isdigit))
return false;
validateBase32Secret(secret);
auto current_time = static_cast<UInt64>(std::time(nullptr));
for (int delta : {0, -1, 1})
{
if (password == getOneTimePassword(secret, config, current_time + delta * config.period))
return true;
}
return false;
}
}

View File

@ -24,10 +24,7 @@ struct OneTimePasswordConfig
std::string_view getAlgorithmName() const;
};
String getOneTimePasswordLink(const String & secret, const OneTimePasswordConfig & config);
String getOneTimePassword(const String & secret, const OneTimePasswordConfig & config);
String getOneTimePasswordSecretLink(const String & secret, const OneTimePasswordConfig & config);
bool checkOneTimePassword(const String & password, const String & secret, const OneTimePasswordConfig & config);
/// Checks if the secret contains only valid base32 characters.

View File

@ -27,9 +27,9 @@ def started_cluster():
cluster.shutdown()
def generate_totp(secret, interval=30, digits=6):
def generate_totp(secret, interval=30, digits=6, timepoint=None):
key = base64.b32decode(secret, casefold=True)
time_step = int(time.time() / interval)
time_step = int(timepoint or time.time() / interval)
msg = struct.pack(">Q", time_step)
hmac_hash = hmac.new(key, msg, hashlib.sha1).digest()
offset = hmac_hash[-1] & 0x0F
@ -40,11 +40,12 @@ def generate_totp(secret, interval=30, digits=6):
def test_one_time_password(started_cluster):
query_text = "SELECT currentUser() || toString(42)"
totuser_secret = {"secret": "INWGSY3LJBXXK43FBIAA====", "interval": 10, "digits": 9}
old_password = generate_totp(**totuser_secret)
old_password_created = time.time()
assert "totuser42\n" == node.query(
old_password = generate_totp(
**totuser_secret, timepoint=time.time() - 3 * totuser_secret["interval"]
)
assert "AUTHENTICATION_FAILED" in node.query_and_get_error(
query_text, user="totuser", password=old_password
)
@ -52,6 +53,10 @@ def test_one_time_password(started_cluster):
query_text, user="totuser", password=generate_totp(**totuser_secret)
)
assert "totuser42\n" == node.query(
query_text, user="totuser", password=generate_totp(**totuser_secret)
)
assert "CREATE USER totuser IDENTIFIED WITH one_time_password" in node.query(
"SHOW CREATE USER totuser",
user="totuser",
@ -60,6 +65,7 @@ def test_one_time_password(started_cluster):
for bad_secret, error_message in [
("i11egalbase32", "Invalid character in*secret"),
("abc$d", "Invalid character in*secret"),
(" ", "Empty secret"),
(" =", "Empty secret"),
("", "Empty secret"),
@ -99,14 +105,3 @@ def test_one_time_password(started_cluster):
).splitlines()
assert resp[0].startswith("totuser\tone_time_password\tSHA1\t9\t10"), resp
assert resp[1].startswith("user2\tone_time_password"), resp
# check that old password invalidated
elapsed = int(time.time() - old_password_created)
for _ in range(20 - elapsed):
time.sleep(1)
print(".", end="", flush=True)
print()
assert "AUTHENTICATION_FAILED" in node.query_and_get_error(
query_text, user="totuser", password=old_password
)