diff --git a/docs/intro/quickstart.en.md b/docs/intro/quickstart.en.md index 3366fd6c..f41d7828 100644 --- a/docs/intro/quickstart.en.md +++ b/docs/intro/quickstart.en.md @@ -41,12 +41,16 @@ ## Configure monitors On the monitor hosts: -- Put identical etcd_address into `/etc/vitastor/vitastor.conf`. Example: +- Create minimal configuration in `/etc/vitastor/vitastor.conf`: ``` { - "etcd_address": ["10.200.1.10:2379","10.200.1.11:2379","10.200.1.12:2379"] + "etcd_address": ["http://10.200.1.10:2379","http://10.200.1.11:2379","http://10.200.1.12:2379"], + "osd_network": "10.200.1.0/24", + "use_perms": false } ``` +- Note that you can enable encryption by using `https://` and `use_perms` option. + [Details](security.en.md#quick-setup) about encryption setup with make-etcd. - Create systemd units for etcd by running: `/usr/lib/vitastor/mon/make-etcd` Or, if you installed Vitastor in Docker, run `systemctl start vitastor-host; docker exec vitastor make-etcd`. - Start etcd and monitors: `systemctl enable --now vitastor-etcd vitastor-mon` diff --git a/docs/intro/quickstart.ru.md b/docs/intro/quickstart.ru.md index 494d1267..d60d8624 100644 --- a/docs/intro/quickstart.ru.md +++ b/docs/intro/quickstart.ru.md @@ -41,25 +41,23 @@ ## Настройте мониторы На хостах, выделенных под мониторы: -- Пропишите одинаковые etcd_address в `/etc/vitastor/vitastor.conf`. Например: +- Создайте минимальную конфигурацию в `/etc/vitastor/vitastor.conf`: ``` { - "etcd_address": ["10.200.1.10:2379","10.200.1.11:2379","10.200.1.12:2379"] + "etcd_address": ["http://10.200.1.10:2379","http://10.200.1.11:2379","http://10.200.1.12:2379"], + "osd_network": "10.200.1.0/24", + "use_perms": false } ``` +- Обратите внимание, что с помощью схемы `https://` и опции `use_perms` можно включить шифрование. + [Подробно](security.ru.md#быстрая-настройка) о настройке шифрования через make-etcd. - Инициализируйте сервисы etcd, запустив `/usr/lib/vitastor/mon/make-etcd`.\ Либо, если вы установили Vitastor в Docker, запустите `systemctl start vitastor-host; docker exec vitastor make-etcd`. - Запустите etcd и мониторы: `systemctl enable --now vitastor-etcd vitastor-mon` ## Настройте OSD -- Пропишите etcd_address и [osd_network](../config/network.ru.md#osd_network) в `/etc/vitastor/vitastor.conf`. Например: - ``` - { - "etcd_address": ["10.200.1.10:2379","10.200.1.11:2379","10.200.1.12:2379"], - "osd_network": "10.200.1.0/24" - } - ``` +- Создайте/скопируйте с узлов с мониторами файл конфигурации `/etc/vitastor/vitastor.conf`. - Инициализуйте OSD: - Только SSD или только HDD: `vitastor-disk prepare /dev/sdXXX [/dev/sdYYY ...]`. Если вы используете десктопные SSD без конденсаторов, добавьте опцию `--disable_data_fsync off`, diff --git a/docs/intro/security.en.md b/docs/intro/security.en.md new file mode 100644 index 00000000..d34bb07a --- /dev/null +++ b/docs/intro/security.en.md @@ -0,0 +1,657 @@ +[Documentation](../../README.md#documentation) → Introduction → Security in Vitastor + +----- + +[Читать на русском](security.ru.md) + +# Security in Vitastor + +- [Overview](#overview) +- [Quick setup](#quick-setup) +- Principles of operation + - [etcd transport encryption (TLS)](#etcd-transport-encryption-tls) + - [OSD transport encryption (AES-GCM)](#osd-transport-encryption-aes-gcm) + - [End-to-end image data encryption (AES-XTS)](#end-to-end-image-data-encryption-aes-xts) + - [Certificate-based authentication](#certificate-based-authentication) + - [Users and access rights](#users-and-access-rights) + - [etcd privileges](#etcd-privileges) +- Manual setup + - [Configuring OSD transport encryption](#configuring-osd-transport-encryption) + - etcd/Antietcd setup options + - [Mon with embedded Antietcd](#mon-with-embedded-antietcd) + - [Mon as an Etcd proxy](#mon-as-an-etcd-proxy) + - [Mon with a separate Antietcd Proxy](#mon-with-a-separate-antietcd-proxy) + - [Standalone Antietcd without etcd](#standalone-antietcd-without-etcd) + - [Vault/OpenBao setup](#vaultopenbao-setup) + - [Vault setup example](#vault-setup-example) +- Lists of allowed operations + - [etcd data access rights](#etcd-data-access-rights) + - [OSD data access rights](#osd-data-access-rights) + - [API access rights](#api-access-rights) +- [Encryption performance](#encryption-performance) + +## Overview + +Starting from version 3.1.0, Vitastor provides full data protection: +control plane protection (etcd), data plane protection (OSDs), and end-to-end data encryption. + +- Control plane protection: + - etcd transport encryption (TLS) + - Authentication via client TLS (X.509) certificates + - Access control of clients to etcd data +- Data plane protection: + - Full AES-GCM encryption of OSD transport (similar to TLS, but faster) + - Alternatively, AES-GCM encryption of just operation headers with data checksums using a secret "salt" + - Authentication via client TLS (X.509) certificates + - Access control of clients on the OSD side +- End-to-end encryption: + - Data is encrypted using AES-XTS on the client side, the Vitastor cluster has no access to plaintext data + - AES-XTS keys can be stored in etcd or in an external Vault/OpenBao + +All features are optional and disabled in the simplest configuration. By default, only +transport-level data checksums ([proto_checksums](../config/security.en.md#proto_checksums)=payload) +are enabled for clients that support them (>= 3.1.0). For older clients, connections +without data checksums are allowed by default ([force_proto_checksums](../config/security.en.md#force_proto_checksums) is empty). + +For a quick setup, jump to the [Quick setup](#quick-setup) section. + +Descriptions of all security-related parameters can be found [here](../config/security.en.md). + +## Quick setup + +For a quick setup, use the `/usr/lib/vitastor/mon/make-etcd` script: + +1. Log in to the node where the first monitor and etcd will be located. +2. Create `/etc/vitastor/vitastor.conf` with minimal parameters: etcd_address, + osd_network and, if you want to enable privileges, use_perms (note `https://` + in etcd addresses): + ``` + { + "etcd_address": ["https://10.0.0.10:2379","https://10.0.0.11:2379","https://10.0.0.12:2379"], + "osd_network": "10.0.0.0/24", + "use_perms": true + } + ``` +3. Run `/usr/lib/vitastor/mon/make-etcd` without parameters or with the `--antietcd-only` + parameter if you want to initialize the cluster with Antietcd only, without etcd. +4. The script will generate all necessary certificates and offer to copy them to the other + monitor nodes (agree!). +5. Log in to all other monitor nodes and repeat the `/usr/lib/vitastor/mon/make-etcd` call there. +6. If you also have nodes with OSDs only (without monitors), run the following command to + copy only the required configuration to these nodes: + ``` + /usr/lib/vitastor/mon/make-etcd --copy-to-osd osdnode1,osdnode2,... + ``` + +After that, you can proceed with OSD initialization. + +If you want to understand the setup in more detail, read the [Principles of operation](#principles-of-operation) +and [Manual setup](#manual-setup) sections below. + +## Principles of operation + +### etcd transport encryption (TLS) + +Possible setups: +- Without encryption (http) +- With encryption (https) +- With encryption and client certificate authentication. Either the same certificate + used for authentication on the OSD side (`cert`+`pkey` / `osd_cert`+`osd_pkey`) + is used, or a separately specified certificate (`etcd_client_cert`+`etcd_client_key`). + +### OSD transport encryption (AES-GCM) + +Possible setups: +- Unencrypted transport without checksums: `proto_checksums=none`. +- Unencrypted transport with data checksums: `proto_checksums=payload` (may be omitted, + this is the default value). It's allowed to disable checksums on the client side, or + use an older client that does not support checksums. If you want to block connections + from clients without checksums, use the option `force_proto_checksums=payload`. +- Header-only encryption with data checksums: activated when the options + `cert`, `pkey`, `osd_ca` are set on the client side and `osd_cert`, `osd_pkey`, `osd_ca`, `client_ca` + on the OSD side, with `proto_checksums=payload`. In this mode, disabling checksums on the client + side is forbidden by default, i.e. `force_proto_checksums=payload` is used. +- Full transport encryption of all traffic: same as the previous option, but with `proto_checksums=gcm`. + In this case, clients are by default allowed to downgrade to checksums only, but this + can also be forbidden via `force_proto_checksums=gcm`. This is the slowest setup and + it's only recommended for insecure (public) networks. In particular, full traffic + encryption together with end-to-end AES-XTS image encryption encrypts data twice. + +Encryption uses the AES-256-GCM algorithm and a custom simplified key exchange protocol, +fully analogous to TLS 1.3 ECDHE. + +### End-to-end image data encryption (AES-XTS) + +The Vitastor client supports encrypting each image's data with its own key. In this case, +data is encrypted by the client before sending it to OSDs and OSDs can't see it in plain. +The encryption key can be changed when cloning/creating image snapshots. For example, +you can make a base VM image (say, Debian Linux) unencrypted, but have encrypted client VM +images inheriting from it. + +Image encryption keys can be stored in etcd or in an external Vault. In the latter case, +etcd only stores key IDs and Vitastor cluster can't decrypt the data at all. To use +Vault, create an image with the `--enc_key vault:ID` option, specify vault_url and vault_ca +options in the configuration, create accounts for all clients in Vault, and grant them access +to the required v1 secrets. + +Once again, if AES-XTS is used together with full traffic encryption (`proto_checksums=gcm`), +image data is encrypted twice — first with AES-XTS, and then with AES-GCM. Use it only if +you are completely paranoid :-). + +### Certificate-based authentication + +When encryption is enabled, Vitastor clients, OSDs, and monitors authenticate via certificates +for both etcd (Antietcd) and OSD connections. + +Separate certificates must be used for OSDs and monitors — either self-signed, or signed +by separate CAs (`osd_ca` and `mon_ca`). All OSDs can use the same certificate, and all +monitors can also use the same certificate, since the privileges of different OSDs or +different monitors do not differ (theoretically, one could differentiate OSD certificates +by pool, but there has been no need for this so far). + +Also, a monitor certificate may not be needed at all if Antietcd is embedded into the monitor +itself. In this case, the monitor already has access to all etcd data directly in memory. + +### Users and access rights + +When transport encryption is disabled, Vitastor operates without access control, i.e., +any cluster client has full access to both the management layer and the data layer. This +option is suitable for dedicated trusted storage networks. + +When OSD transport encryption is enabled (at least for headers), you can enable access +rights by turning on the `use_perms=true` option. When this option is enabled, each user +can perform only the operations that they are permitted, and even OSDs and monitors are +also forbidden from performing "unnecessary" operations. + +Each user (or administrator) must have their own certificate signed by a common root +certificate for clients (`client_ca`), with a Common Name equal to the user name. +Privilege settings are stored in etcd. OSDs and monitors don't need user accounts; +they authenticate via separate certificates. + +User privileges are stored in etcd data under the keys `/vitastor/config/user/`. +The following is defined per user in this key: +- Type: + - Client (`type=client` or omitted) — can only read and modify explicitly permitted images. + - Administrator (`type=admin`) — can read and modify all images, and also administer the + cluster: view overall statistics and status, create and delete OSDs, etc. +- List of group names the user is a member of. + +Images have the following properties: +- Owner (owner) — the user name that is allowed to both read and modify the image +- Owner group (owner_group) — the owner group name +- Reader group (reader_group) — the name of the group of users allowed to read the image + +And there is also a property on the pool: +- Creator group (creator_group) — the name of the group of users allowed to create images in the pool + +For the list of allowed operations on image data on the OSD side, see the +[OSD data access rights](#osd-data-access-rights) section. + +### etcd privileges + +etcd privileges are implemented through Antietcd in all modes of operation. + +Built-in etcd privileges are not supported due to numerous inconveniences: +- Certificate-based authentication does not work at all in etcd's REST interface, +- Privileges are stored separately from k/v data and cannot participate in transactions, +- Only the administrator (root) can change privileges, +- There is no support for filtering range read responses by privileges. + +If etcd is used, Antietcd acts as a filtering proxy and can be embedded in the Vitastor +monitor or run separately. In this case, etcd must allow incoming connections only from +Antietcd, and all other components must connect to Antietcd. + +If Antietcd runs as a part of the Vitastor monitor, it is sufficient to enable the option +`use_perms=true` and set the required certificates. If Antietcd is run separately, privileges +have to be enabled separately using Antietcd options. For more details on the setup, see +the [etcd/Antietcd setup options](#etcdantietcd-setup-options) section. + +For the list of allowed operations with etcd data, see the +[etcd data access rights](#etcd-data-access-rights) section. + +## Manual setup + +### Configuring OSD transport encryption + +You need 2 certificates: one for OSDs and one for signing all client certificates. +For OSDs, you can use a self-signed certificate (osd_ca.crt) or a separate certificate (osd.crt) +signed by a trusted osd_ca.crt certificate. For clients, you must use separate certificates +signed by a common trusted (client_ca.crt). + +Add to the Vitastor configuration on OSD servers: +- use_perms: true +- osd_ca: osd_ca.crt +- client_ca: client_ca.crt +- osd_cert: osd_ca.crt +- osd_pkey: osd_ca.key + +On the client side: +- use_perms: true +- cert: client.crt +- pkey: client.key + +### etcd/Antietcd setup options + +The following configuration options are available: + +#### Mon with embedded Antietcd + +The simplest option. You need 1 certificate for Antietcd (antietcd.crt), plus root +certificates for OSDs and clients. + +Vitastor settings (`/etc/vitastor/vitastor.conf`): +- etcd_address: [ "http://mon1:2379", ... ] (addresses of your monitors with port 2379) +- use_perms: true +- use_antietcd: true +- antietcd_cert: antietcd.crt +- antietcd_key: antietcd.key +- etcd_ca: antietcd.crt +- osd_ca: osd_ca.crt +- client_ca: client_ca.crt + +#### Mon as an Etcd proxy + +If you want to enable privileges, but stay on etcd, you can use etcd proxy mode. + +You will need 2 separate certificates: one for etcd (etcd.crt) and one for antietcd (antietcd.crt). +The etcd client port must be different from the standard 2379 — for example, you can pick 2381. +OSD and client certificates are also needed. + +Vitastor settings: +- etcd_address: [ "http://mon1:2379", ... ] (addresses of your monitors with port 2379) +- use_perms: true +- use_antietcd: true +- etcd_proxy: + ``` + { + "urls": [ "http://mon1:2381", ... ], // addresses of your etcd with port 2381 + "cert": "antietcd.crt", + "key": "antietcd.key", + "ca": "etcd.crt" + } + ``` +- antietcd_cert: antietcd.crt +- antietcd_key: antietcd.key +- etcd_ca: antietcd.crt +- osd_ca: osd_ca.crt +- client_ca: client_ca.crt + +etcd command-line options: +``` +--advertise-client-urls=https://
:2381 --listen-client-urls=https://
:2381 \ +--client-cert-auth --cert-file=etcd.crt --key-file=etcd.key --trusted-ca-file=antietcd.crt \ +--peer-client-cert-auth --peer-cert-file=etcd.crt --peer-key-file=etcd.key --peer-trusted-ca-file=etcd.crt +``` + +#### Mon with a separate Antietcd Proxy + +If in addition to the previous option you want to offload Antietcd from the Vitastor monitor's +tasks, you can run it separately. + +Similar to the previous option, 2 certificates are needed: one for etcd and one for antietcd, +plus separate certificates for clients, OSDs, and monitors will be needed. + +Vitastor settings: +- etcd_address: [ "http://mon1:2379", ... ] (addresses of your monitors with port 2379) +- use_perms: true +- use_antietcd: false +- etcd_ca: antietcd.crt +- osd_ca: osd_ca.crt +- client_ca: client_ca.crt +- mon_etcd_client_cert: mon_ca.crt +- mon_etcd_client_key: mon_ca.key + +Antietcd command-line options: +``` +--port 2379 \ +--client_cert_auth 1 --auth_filter vitastor_auth_filter.js --etcd_proxy url1,url2,... \ +--cert antietcd.crt --key antietcd.key --ca client_ca.crt --osd_ca osd_ca.crt --mon_ca mon_ca.crt \ +--etcd_cert antietcd.crt --etcd_key antietcd.key --etcd_ca etcd.crt +``` + +etcd command-line options (same as in the previous option): +``` +--advertise-client-urls=https://
:2381 --listen-client-urls=https://
:2381 \ +--client-cert-auth --cert-file=etcd.crt --key-file=etcd.key --trusted-ca-file=antietcd.crt \ +--peer-client-cert-auth --peer-cert-file=etcd.crt --peer-key-file=etcd.key --peer-trusted-ca-file=etcd.crt +``` + +#### Standalone Antietcd without etcd + +Same as the previous option, but etcd and its certificate are not needed: + +Vitastor settings (same as in the previous option): +- etcd_address: [ "http://mon1:2379", ... ] (addresses of your monitors with port 2379) +- use_perms: true +- use_antietcd: false +- etcd_ca: antietcd.crt +- osd_ca: osd_ca.crt +- client_ca: client_ca.crt +- mon_etcd_client_cert: mon_ca.crt +- mon_etcd_client_key: mon_ca.key + +Antietcd command-line options: +``` +--port 2379 \ +--client_cert_auth 1 --auth_filter vitastor_auth_filter.js \ +--persist_filter vitastor_persist_filter.js \ +--cert antietcd.crt --key antietcd.key --ca client_ca.crt --osd_ca osd_ca.crt --mon_ca mon_ca.crt +``` + +### Vault/OpenBao setup + +To use Vault, each client that needs to get image keys from Vault needs a Vault account. +Vitastor only supports client certificate-based authentication, so all client certificates +(`cert`+`pkey`) must be registered in Vault, and they must be granted access to the +corresponding secrets (v1 secrets API is supported). + +The required format of a Vault secret is a single `key` field as a hexadecimal string. +The AES-256-XTS algorithm is used, so the key length is 64 bytes, i.e., the string must +consist of 128 hexadecimal digits. + +To connect to Vault, set the following settings in Vitastor.conf: +- `vault_url` — Vault address (e.g., `https://vault:8200`) +- `vault_ca` — Vault's own certificate + +After that, if you create an image (`vitastor-cli create`) with the option `--enc_key vault:`, +Vitastor clients will first contact Vault to obtain a token at `/v1/auth/cert/login`, +and then request the actual secret from Vault at `/v1/secret/`. + +#### Vault setup example + +Step-by-step instructions for setting up a test Vault using OpenBao as an example: + +1. If TLS is not yet configured, generate a self-signed TLS certificate for Vault: + ``` + openssl req -days 3650 -x509 -addext basicConstraints=critical,CA:TRUE,pathlen:1 --addext subjectAltName=DNS:vault \ + -new -newkey rsa:4096 -nodes -keyout /etc/openbao/vault.key -out /etc/openbao/vault.crt + ``` + Configure it in `/etc/openbao/openbao.hcl`: + ``` + listener "tcp" { + address = "0.0.0.0:8200" + tls_cert_file = "/etc/openbao/vault.crt" + tls_key_file = "/etc/openbao/vault.key" + } + ``` + And restart OpenBao (`systemctl restart openbao`). +2. Copy Vault's TLS certificate for Vitastor: + ``` + cp /etc/openbao/vault.crt /etc/vitastor/vault.crt + ``` + Transfer it to all client nodes and specify it in `/etc/vitastor/vitastor.conf`: + ``` + { + ... + "vault_url": "http://vault:8200", + "vault_ca": "/etc/vitastor/vault.crt" + } + ``` +3. Check Vault status: + ``` + bao status -ca-cert /etc/openbao/vault.crt -address=https://vault:8200 + ``` +4. Initialize Vault in test mode from 1 node (with 1 key share): + ``` + bao operator init -n 1 -t 1 -ca-cert /etc/openbao/vault.crt -address=https://vault:8200 + ``` +5. Unseal Vault: + ``` + bao operator unseal -ca-cert /etc/openbao/vault.crt -address=https://vault:8200 + ``` +6. Enable certificate-based authentication: + ``` + bao auth enable -ca-cert /etc/openbao/vault.crt -address=https://vault:8200 cert + ``` +7. Enable v1 secrets: + ``` + bao secrets enable -ca-cert /etc/openbao/vault.crt -address=https://vault:8200 -path=secret kv-v1 + ``` +8. Create a test secret: + ``` + bao kv put -ca-cert /etc/openbao/vault.crt -address=https://vault:8200 secret/vitastor/testimg3 key=$(openssl rand -hex 64) + ``` +9. Generate a signed certificate for a Vitastor user (on a machine where you have `client_ca.crt` and `client_ca.key`): + ``` + openssl req -subj '/CN=testimg3' -nodes -new -keyout testimg3.key -out testimg3.csr + openssl x509 -req -days 3650 -CA client_ca.crt -CAkey client_ca.key -CAcreateserial -in testimg3.csr -out testimg3.crt + rm testimg3.csr + ``` +10. Create a user in Vault and grant it access to the secret: + ``` + cat >testimg3.policy <' https://vault:8200/v1/secret/vitastor/testimg3 + ``` +12. Create an image in Vitastor with the given secret (as an administrator or someone who + has the right to create images in your pool): + ``` + vitastor-cli create -s 100G --enc_key vault:vitastor/testimg3 --owner testimg3 testimg3 + ``` +13. Test access to the image as user testimg3: + ``` + vitastor-cli --cert testimg3.crt --pkey testimg3.key dd if=/dev/urandom oimg=testimg3 bs=1M count=100 + ``` + +## Lists of allowed operations + +### etcd data access rights + +Below, all key names are given without the common prefix `/vitastor`. + +Allowed operations with keys in Antietcd for clients (`type=client`): +- Read-only: + - Always allowed: + - `/config/global` + - `/config/node_placement` + - `/config/pools` + - `/pg/config` + - `/osd/state/*` + - `/pg/state/*` + - `/index/maxid/*` + - For images [readable by the user](#users-and-access-rights): + - `/config/inode/*` + - `/index/image/*` + - `/inode/stats/*` +- Read and write: + - For pools in which the user can create images: + - `/index/maxid/*` + - For images owned by the user: + - `/config/inode/*` + - `/index/image/*` + +Allowed operations with keys in Antietcd for administrators (`type=admin`): +- Read: + - `/stats` + - `/mon/*` + - `/pg/*` + - `/pgstats/*` + - `/inode/stats/*` + - `/pool/stats/*` +- Read and write: + - `/config/*` + - `/osd/*` + - `/index/*` + - `/pg/history/*` + +Allowed operations with keys in etcd for OSDs: +- Read: + - `/pg/config` + - `/config/*` +- Read and write: + - `/osd/*` + - `/pg/state/*` + - `/pg/history/*` + - `/pgstats/*` + +Allowed operations with keys in etcd for monitors: +- Read: + - `/config/*` + - `/osd/*` + - `/pgstats/*` +- Read and write: + - `/pg/config` + - `/stats` + - `/history/last_clean_pgs` + - `/mon/*` + - `/pg/history/*` + - `/inode/stats/*` + - `/pool/stats/*` + +### OSD data access rights + +When the `use_perms` option and encryption are enabled, OSDs authenticate clients via +certificates and allow each client only what is allowed by the access control model. + +Client operations: +- READ — allowed for images the user has read access to. +- WRITE, DELETE, SCRUB — allowed for images the user has write access to. +- SYNC — the operation is not tied to an image and is always allowed. +- DESCRIBE — the operation is allowed only for administrators (used by the commands + `vitastor-cli describe` and `fix`). +- PING — the operation is always allowed. +- SHOW_CONFIG — the operation is always allowed, however, if the client presents + itself as an OSD in it, then it is verified that it uses a certificate signed by `osd_ca`. +- SEC_LIST (listing) — allowed for other OSDs and administrators with any parameters, + and for regular clients only allowed for requests limited to an image the user has + read access to. + +Cluster operations — allowed only for other OSDs: +- SEC_READ +- SEC_WRITE +- SEC_WRITE_STABLE +- SEC_SYNC +- SEC_STABILIZE +- SEC_ROLLBACK +- SEC_DELETE +- SEC_READ_BMP +- SEC_LOCK + +### API access rights + +[vitastor-cli serve](../usage/cli.en.md#serve) also supports client authentication +via certificates. Only certificates signed by `client_ca` are accepted. A separate +certificate `server_cert` with the key `server_pkey` is used as the server certificate. + +For `vitastor-cli serve` to work correctly, it itself must use a certificate +(`cert`+`pkey`) of a user with administrator rights (`type=admin`) to access Vitastor. + +Regular clients, when accessing the API, are only allowed API operations on images +available to them either for reading (for reads) or for writing (for modification). +All other API calls are allowed only for administrators. + +List of allowed API operations: + +Clients (users with `type=client`) are allowed the following operations: +- image/list — for images the user can read. +- image/create — for pools in which the user is allowed to create images, or for + creating snapshots of images owned by the user. +- image/delete, image/flatten, image/modify — for images owned by the user. + +All other operations are allowed only for administrators (`type=admin`). + +## Encryption performance + +You may wonder — how fast is all this wonderful encryption? + +The answer is — it depends heavily on the CPU. On modern processors (with AVX512 with VAES +support) it is very fast — AES encryption speed can reach 10-20 GB/s and above. This +primarily concerns the CPU of client machines, because end-to-end encryption is performed +entirely on the client, and client uses its signle thread for transport encryption too, +while there are many OSDs on the server side, and it is easier to add resources there. + +On older processors, the speed is noticeably worse — for example, on a Xeon E5 v4 it is +only 3 GB/s. + +You can evaluate the performance of your processors using the `vitastor-cli cpubench` command. + +Example output (💪 AMD EPYC 9575F): + +``` +$ vitastor-cli cpubench +Vitastor transport encryption benchmark (AES-256-GCM, AES-256-XTS and xxhash3) + +Warmup... + +No transport encryption, data checksums enabled, e2e unencrypted image +xxhash3 1 M block... 209000 iterations in 2001 ms = 104447.78 MB/s +xxhash3 4 K block... 37000000 iterations in 2022 ms = 71479.35 MB/s + +Header encryption with payload checksums, e2e unencrypted image +AES-256-GCM encrypt header + xxhash3 1 M block... 210000 iterations in 2015 ms = 104218.36 MB/s +AES-256-GCM encrypt header + xxhash3 4 K block... 26000000 iterations in 2073 ms = 48993.01 MB/s + +Full transport encryption, e2e unencrypted image +AES-256-GCM encrypt header and 1 M block... 54000 iterations in 2000 ms = 27000.00 MB/s +AES-256-GCM encrypt header and 4 K block... 11700000 iterations in 2014 ms = 22692.71 MB/s + +No transport encryption, no checksums, e2e encrypted image +AES-256-XTS encrypt 1 M block... 50000 iterations in 2039 ms = 24521.82 MB/s +AES-256-XTS encrypt 4 K block... 12600000 iterations in 2009 ms = 24499.13 MB/s + +No transport encryption, e2e encrypted image, data checksums enabled +AES-256-XTS encrypt + xxhash3 1 M block... 40000 iterations in 2013 ms = 19870.84 MB/s +AES-256-XTS encrypt + xxhash3 4 K block... 10200000 iterations in 2011 ms = 19812.90 MB/s + +Header encryption with payload checksums, e2e encrypted image +AES-256-GCM encrypt header + AES-256-XTS encrypt + xxhash3 1 M block... 40000 iterations in 2014 ms = 19860.97 MB/s +AES-256-GCM encrypt header + AES-256-XTS encrypt + xxhash3 4 K block... 8700000 iterations in 2011 ms = 16899.24 MB/s + +Full transport encryption, e2e encrypted image +AES-256-XTS + AES-256-GCM encrypt 1 M block... 26000 iterations in 2062 ms = 12609.12 MB/s +AES-256-XTS + AES-256-GCM encrypt 4 K block... 6300000 iterations in 2006 ms = 12267.88 MB/s +``` + +And here is Xeon E5-2680v4: + +``` +$ vitastor-cli cpubench +Vitastor transport encryption benchmark (AES-256-GCM, AES-256-XTS and xxhash3) + +Warmup... + +No transport encryption, data checksums enabled, e2e unencrypted image +xxhash3 1 M block... 62000 iterations in 2021 ms = 30677.88 MB/s +xxhash3 4 K block... 12400000 iterations in 2006 ms = 24146.31 MB/s + +Header encryption with payload checksums, e2e unencrypted image +AES-256-GCM encrypt header + xxhash3 1 M block... 62000 iterations in 2027 ms = 30587.07 MB/s +AES-256-GCM encrypt header + xxhash3 4 K block... 6800000 iterations in 2011 ms = 13208.60 MB/s + +Full transport encryption, e2e unencrypted image +AES-256-GCM encrypt header and 1 M block... 7000 iterations in 2317 ms = 3021.15 MB/s +AES-256-GCM encrypt header and 4 K block... 1500000 iterations in 2102 ms = 2787.52 MB/s + +No transport encryption, no checksums, e2e encrypted image +AES-256-XTS encrypt 1 M block... 7000 iterations in 2317 ms = 3021.15 MB/s +AES-256-XTS encrypt 4 K block... 1600000 iterations in 2088 ms = 2993.30 MB/s + +No transport encryption, e2e encrypted image, data checksums enabled +AES-256-XTS encrypt + xxhash3 1 M block... 6000 iterations in 2188 ms = 2742.23 MB/s +AES-256-XTS encrypt + xxhash3 4 K block... 1400000 iterations in 2053 ms = 2663.78 MB/s + +Header encryption with payload checksums, e2e encrypted image +AES-256-GCM encrypt header + AES-256-XTS encrypt + xxhash3 1 M block... 6000 iterations in 2190 ms = 2739.73 MB/s +AES-256-GCM encrypt header + AES-256-XTS encrypt + xxhash3 4 K block... 1300000 iterations in 2101 ms = 2417.00 MB/s + +Full transport encryption, e2e encrypted image +AES-256-XTS + AES-256-GCM encrypt 1 M block... 4000 iterations in 2666 ms = 1500.38 MB/s +AES-256-XTS + AES-256-GCM encrypt 4 K block... 800000 iterations in 2113 ms = 1478.94 MB/s +``` diff --git a/docs/intro/security.ru.md b/docs/intro/security.ru.md new file mode 100644 index 00000000..1b10d0c6 --- /dev/null +++ b/docs/intro/security.ru.md @@ -0,0 +1,662 @@ +[Документация](../../README-ru.md#документация) → Введение → Безопасность в Vitastor + +----- + +[Read in English](security.en.md) + +# Безопасность в Vitastor + +- [Обзор](#обзор) +- [Быстрая настройка](#быстрая-настройка) +- Принципы работы + - [Шифрование соединений с etcd (TLS)](#шифрование-соединений-с-etcd-tls) + - [Шифрование соединений с OSD (AES-GCM)](#шифрование-соединений-с-osd-aes-gcm) + - [Сквозное шифрование данных образов (AES-XTS)](#сквозное-шифрование-данных-образов-aes-xts) + - [Аутентификация по сертификатам](#аутентификация-по-сертификатам) + - [Пользователи и права доступа](#пользователи-и-права-доступа) + - [Привилегии etcd](#привилегии-etcd) +- Ручная настройка + - [Настройка шифрования соединений OSD](#настройка-шифрования-соединений-osd) + - Варианты настройки etcd/Antietcd + - [Mon со встроенным Antietcd](#mon-со-встроенным-antietcd) + - [Mon в роли Etcd proxy](#mon-в-роли-etcd-proxy) + - [Mon с отдельным Antietcd Proxy](#mon-с-отдельным-antietcd-proxy) + - [Отдельный Antietcd без etcd](#отдельный-antietcd-без-etcd) + - [Настройка Vault/OpenBao](#настройка-vaultopenbao) + - [Пример настройки Vault](#пример-настройки-vault) +- Списки разрешённых операций + - [Права доступа к данным etcd](#права-доступа-к-данным-etcd) + - [Права доступа к данным OSD](#права-доступа-к-данным-osd) + - [Права доступа к API](#права-доступа-к-api) +- [Производительность шифрования](#производительность-шифрования) + +## Обзор + +Начиная с версии 3.1.0, Vitastor предоставляет полную защиту данных: защиту слоя +управления (etcd), защиту слоя данных (OSD) и сквозное шифрование данных. + +- Защита слоя управления: + - Шифрование соединений с etcd (TLS) + - Аутентификация по клиентским TLS (X.509) сертификатам + - Разграничение прав доступа клиентов к данным etcd +- Защита слоя данных: + - Либо полное AES-GCM шифрование соединений с OSD (аналогично TLS, но быстрее) + - Либо шифрование AES-GCM только заголовков команд с контрольными суммами данных с секретной "солью" + - Аутентификация по клиентским TLS (X.509) сертификатам + - Разграничение прав доступа клиентов на стороне OSD +- Сквозное шифрование: + - Данные шифруются AES-XTS на стороне клиента, кластер Vitastor не имеет доступа к открытым данным + - Ключи AES-XTS могут храниться в etcd или во внешнем Vault/OpenBao + +Все функции опциональны и в простейшем варианте настройки выключены. По умолчанию включены +только контрольные суммы данных на транспортном уровне ([proto_checksums](../config/security.ru.md#proto_checksums)=payload) для +поддерживающих их клиентов (>= 3.1.0). Для более старых клиентов по умолчанию разрешены +соединения без контрольных сумм данных ([force_proto_checksums](../config/security.ru.md#force_proto_checksums) пусто). + +Для быстрой настройки перейдите к разделу [Быстрая настройка](#быстрая-настройка). + +Описания всех параметров, связанных с безопасностью, читайте [здесь](../config/security.ru.md). + +## Быстрая настройка + +Для быстрой настройки используйте скрипт `/usr/lib/vitastor/mon/make-etcd`: + +1. Зайдите на узел, на котором будет располагаться первый монитор и etcd. +2. Создайте там минимальный `/etc/vitastor/vitastor.conf` с параметрами etcd_address, + osd_network и, если хотите включить привилегии - use_perms (обратите внимание на `https://` + в адресах etcd): + ``` + { + "etcd_address": ["https://10.0.0.10:2379","https://10.0.0.11:2379","https://10.0.0.12:2379"], + "osd_network": "10.0.0.0/24", + "use_perms": true + } + ``` +3. Запустите `/usr/lib/vitastor/mon/make-etcd` без параметров или с параметром `--antietcd-only`, + если хотите инициализировать кластер только с Antietcd без etcd. +4. Скрипт сгенерирует все необходимые сертификаты и предложит скопировать их на остальные узлы + мониторов (соглашайтесь!). +5. Зайдите на все остальные узлы мониторов и повторите там вызов `/usr/lib/vitastor/mon/make-etcd`. +6. Если у вас будут узлы только с OSD без мониторов, выполните следующую команду, чтобы скопировать + только нужную конфигурацию на эти узлы: + ``` + /usr/lib/vitastor/mon/make-etcd --copy-to-osd osdnode1,osdnode2,... + ``` + +После этого можете переходить к инициализации OSD. + +Если хотите разобраться в настройке подробнее, читайте далее разделы [Принципы работы](#принципы-работы) +и [Ручная настройка](#ручная-настройка). + +## Принципы работы + +### Шифрование соединений с etcd (TLS) + +Варианты настройки: +- Без шифрования (http) +- С шифрованием (https) +- С шифрованием и аутентификацией по клиентским сертификатам. Используется либо тот + же сертификат, что используется для аутентификации на стороне OSD (`cert`+`pkey` / `osd_cert`+`osd_pkey`), + либо отдельно указанный сертификат (`etcd_client_cert`+`etcd_client_key`) + +### Шифрование соединений с OSD (AES-GCM) + +Варианты настройки: +- Без шифрования и без контрольных сумм: `proto_checksums=none`. +- Без шифрования, с контрольными суммами данных: `proto_checksums=payload` (можно не указывать, + т.к. это значение по умолчанию). При этом контрольные суммы можно отключить на стороне + клиента либо использовать более старые версии клиента, не поддерживающие контрольные суммы. + Если нужно запретить подключение клиентов без контрольных сумм, можно использовать опцию + `force_proto_checksums=payload`. +- С шифрованием заголовков и контрольными суммами данных: активируется при установленных опциях + `cert`, `pkey`, `osd_ca` на стороне клиента и `osd_cert`, `osd_pkey`, `osd_ca`, `client_ca` + на стороне OSD, при `proto_checksums=payload`. При этом по умолчанию запрещается + отключение контрольных сумм на уровне клиента, то есть используется `force_proto_checksums=payload`. +- С полным шифрованием всего трафика: аналогично прошлому варианту, но с `proto_checksums=gcm`. + Клиенту при этом по умолчанию разрешается понизить уровень защиты до контрольных сумм, но + это тоже можно запретить через `force_proto_checksums=gcm`. Данный вариант самый медленный и + рекомендуется только для небезопасных (публичных) сетей. В том числе потому, что при использовании + и полного шифрования трафика, и сквозного шифрования образов AES-XTS, данные шифруются дважды. + +Для шифрования используется алгоритм AES-256-GCM и собственный упрощённый протокол согласования +ключей, полностью аналогичный TLS 1.3 ECDHE. + +### Сквозное шифрование данных образов (AES-XTS) + +Клиент Vitastor поддерживает шифрование данных каждого образа своим ключом. В этом случае на OSD +уходят уже зашифрованные данные и сами OSD не видят исходные данные клиента. При этом ключ можно +менять при клонировании/создании снимков образов. Например, можно сделать базовый образ ВМ +(условный Debian Linux) нешифрованным, но наследовать от него шифрованные образы клиентских ВМ. + +Ключи шифрования образов могут храниться либо в etcd, либо во внешнем Vault. Во втором случае +в etcd хранятся только ID ключей, а Vitastor вообще не имеет доступа к данным образов. Для +использования Vault нужно создать образ с опцией `--enc_key vault:ID`, в конфигурации указать +опции vault_url, и vault_ca, создать всем клиентам учётные записи в Vault и дать им доступ +к требуемым секретам v1. + +Ещё раз повторимся, что если AES-XTS используется с полным шифрованием трафика (`proto_checksums=gcm`), +то данные образов шифруются дважды - сначала AES-XTS, а потом AES-GCM. Можете использовать, +только если вы совсем параноик :-). + +### Аутентификация по сертификатам + +При включённом шифровании клиенты, OSD и мониторы Vitastor аутентифицируются по сертификатам +как при соединениях с etcd (Antietcd), так и с OSD. + +Для OSD и мониторов должны использоваться отдельные сертификаты - либо самоподписанные, либо +подписанные отдельными CA (`osd_ca` и `mon_ca`). При этом все OSD могут использовать один и +тот же сертификат и все мониторы тоже могут использовать один и тот же сертификат, так как +привилегии разных OSD или разных мониторов ничем не отличаются (теоретически можно было бы +сделать разграничение сертификатов OSD по пулам, но пока что такой необходимости не было). + +Также сертификат монитора может быть вообще не нужен, если Antietcd встраивается в сам монитор. +В этом случае монитор и так имеет доступ ко всем данным etcd прямо в памяти. + +### Пользователи и права доступа + +При отключённом шифровании трафика Vitastor работает без разграничения прав доступа, то есть, +любой клиент кластера имеет полный доступ как к слою управлению, так и к слою данных. Такой +вариант подходит для выделенных доверенных сетей хранения. + +При включённом шифровании трафика OSD (хотя бы заголовков) есть возможность задействовать +права доступа, включив опцию `use_perms=true`. При включённой опции каждый пользователь может +выполнять только те операции, которые ему разрешены, и даже OSD и мониторам также запрещены +"лишние" операции. + +Каждый пользователь (или администратор) должен иметь свой сертификат, подписанный общим +корневым сертификатом для клиентов (`client_ca`), с Common Name, равным имени пользователя. +Настройки привилегий же хранятся в etcd. Для OSD и мониторов учётные записи не нужны, +они аутентифицируются по отдельным сертификатам. + +Привилегии пользователей хранятся в данных etcd в ключах `/vitastor/config/user/<имя>`. +В этом ключе для каждого пользователя задаётся: +- Тип: + - Клиент (`type=client` или не указано) - может читать и модифицировать только явным образом + разрешённые образы. + - Администратор (`type=admin`) - может читать и модифицировать все образы, а также администрировать + кластер: смотреть общую статистику и состояние, создавать и удалять OSD и так далее. +- Список имён групп, членом которых пользователь является. + +У образов есть следующие свойства: +- Владелец (owner) - имя пользователя, которому разрешено и читать, и менять образ +- Группа владельцев (owner_group) - имя группы владельцев +- Группа читателей (reader_group) - имя группы пользователей, которым разрешено читать образ + +И также есть свойство у пула: +- Группа создателей (creator_group) - имя группы пользователей, которым разрешено создавать образы в пуле + +Перечень разрешённых операций с данными образов на стороне OSD смотрите в разделе +[Права доступа к данным OSD](#права-доступа-к-данным-osd). + +### Привилегии etcd + +Привилегии etcd реализуются через Antietcd во всех режимах работы. + +Встроенные привилегии etcd не поддерживаются по причине их многочисленных неудобств: +- Аутентификация по сертификатам вообще не работает в REST интерфейсе etcd, +- Привилегии хранятся отдельно от k/v данных и не могут участвовать в транзакциях, +- Менять привилегии может только администратор (root), +- Нет поддержки фильтрации диапазонных ответов чтения по привилегиям. + +Если используется etcd, то Antietcd выступает в роли фильтрующего прокси, при этом он +может быть встроен в монитор Vitastor или запущен отдельно. В этом случае etcd должен +разрешать входящие подключения только от Antietcd, а все остальные компоненты должны +соединяться с Antietcd. + +Если Antietcd запускается в составе монитора Vitastor, то достаточно включить опцию +`use_perms=true` и задать нужные сертификаты. Если Antietcd запускается отдельно, то +привилегии нужно включать отдельно опциями Antietcd. Подробнее о настройке смотрите +раздел [Варианты настройки etcd/Antietcd](#варианты-настройки-etcdantietcd). + +Перечень разрешённых операций с данными etcd смотрите в разделе +[Права доступа к данным etcd](#права-доступа-к-данным-etcd). + +## Ручная настройка + +### Настройка шифрования соединений OSD + +Вам нужно 2 сертификата: один для OSD и один для подписи сертификатов всех клиентов. +Для OSD можно использовать самоподписанный сертификат (osd_ca.crt) или отдельный сертификат (osd.crt), +подписанный доверенным сертификатом osd_ca.crt. Для клиентов нужно использовать отдельные +сертификаты, подписанные общим доверенным (client_ca.crt). + +В конфигурацию Vitastor на серверах OSD нужно добавить: +- use_perms: true +- osd_ca: osd_ca.crt +- client_ca: client_ca.crt +- osd_cert: osd_ca.crt +- osd_pkey: osd_ca.key + +На стороне клиентов: +- use_perms: true +- cert: client.crt +- pkey: client.key + +### Варианты настройки etcd/Antietcd + +Доступны следующие варианты настройки: + +#### Mon со встроенным Antietcd + +Самый простой вариант. Вам нужен 1 сертификат для Antietcd (antietcd.crt), плюс +корневые сертификаты для OSD и клиентов. + +Настройки Vitastor (`/etc/vitastor/vitastor.conf`): +- etcd_address: [ "http://mon1:2379", ... ] (адреса ваших мониторов с портом 2379) +- use_perms: true +- use_antietcd: true +- antietcd_cert: antietcd.crt +- antietcd_key: antietcd.key +- etcd_ca: antietcd.crt +- osd_ca: osd_ca.crt +- client_ca: client_ca.crt + +#### Mon в роли Etcd proxy + +Если вы хотите включить привилегии, но остаться на etcd, можно задействовать режим etcd proxy. + +Вам понадобится 2 отдельных сертификата: один для etcd (etcd.crt) и один для antietcd (antietcd.crt). +Клиентский порт etcd должен отличаться от стандартного 2379, например, можно выбрать 2381. +Также нужны сертификаты OSD и клиентов. + +Настройки Vitastor: +- etcd_address: [ "http://mon1:2379", ... ] (адреса ваших мониторов с портом 2379) +- use_perms: true +- use_antietcd: true +- etcd_proxy: + ``` + { + "urls": [ "http://mon1:2381", ... ], // адреса ваших etcd с портом 2381 + "cert": "antietcd.crt", + "key": "antietcd.key", + "ca": "etcd.crt" + } + ``` +- antietcd_cert: antietcd.crt +- antietcd_key: antietcd.key +- etcd_ca: antietcd.crt +- osd_ca: osd_ca.crt +- client_ca: client_ca.crt + +Опции командной строки etcd: +``` +--advertise-client-urls=https://<АДРЕС>:2381 --listen-client-urls=https://<АДРЕС>:2381 \ +--client-cert-auth --cert-file=etcd.crt --key-file=etcd.key --trusted-ca-file=antietcd.crt \ +--peer-client-cert-auth --peer-cert-file=etcd.crt --peer-key-file=etcd.key --peer-trusted-ca-file=etcd.crt +``` + +#### Mon с отдельным Antietcd Proxy + +Если в дополнение к предыдущему варианту вы хотите разгрузить Antietcd от задач монитора Vitastor, +можно запустить его отдельно. + +Аналогично предыдущему варианту нужно 2 сертификата: один для etcd и один для antietcd, плюс понадобятся +отдельные сертификаты для клиентов, OSD и монитора. + +Настройки Vitastor: +- etcd_address: [ "http://mon1:2379", ... ] (адреса ваших мониторов с портом 2379) +- use_perms: true +- use_antietcd: false +- etcd_ca: antietcd.crt +- osd_ca: osd_ca.crt +- client_ca: client_ca.crt +- mon_etcd_client_cert: mon_ca.crt +- mon_etcd_client_key: mon_ca.key + +Опции командной строки Antietcd: +``` +--port 2379 \ +--client_cert_auth 1 --auth_filter vitastor_auth_filter.js --etcd_proxy url1,url2,... \ +--cert antietcd.crt --key antietcd.key --ca client_ca.crt --osd_ca osd_ca.crt --mon_ca mon_ca.crt \ +--etcd_cert antietcd.crt --etcd_key antietcd.key --etcd_ca etcd.crt +``` + +Опции командной строки etcd (не отличаются от предыдущего варианта): +``` +--advertise-client-urls=https://<АДРЕС>:2381 --listen-client-urls=https://<АДРЕС>:2381 \ +--client-cert-auth --cert-file=etcd.crt --key-file=etcd.key --trusted-ca-file=antietcd.crt \ +--peer-client-cert-auth --peer-cert-file=etcd.crt --peer-key-file=etcd.key --peer-trusted-ca-file=etcd.crt +``` + +#### Отдельный Antietcd без etcd + +Аналогично предыдущему варианту, но etcd и его сертификат не нужны: + +Настройки Vitastor (не отличаются от предыдущего варианта): +- etcd_address: [ "http://mon1:2379", ... ] (адреса ваших мониторов с портом 2379) +- use_perms: true +- use_antietcd: false +- etcd_ca: antietcd.crt +- osd_ca: osd_ca.crt +- client_ca: client_ca.crt +- mon_etcd_client_cert: mon_ca.crt +- mon_etcd_client_key: mon_ca.key + +Опции командной строки Antietcd: +``` +--port 2379 \ +--client_cert_auth 1 --auth_filter vitastor_auth_filter.js \ +--persist_filter vitastor_persist_filter.js \ +--cert antietcd.crt --key antietcd.key --ca client_ca.crt --osd_ca osd_ca.crt --mon_ca mon_ca.crt +``` + +### Настройка Vault/OpenBao + +Для использования Vault каждому клиенту, который будет получать из Vault ключи +образов, нужна учётная запись в Vault. Vitastor поддерживает только аутентификацию +по клиентским сертификатам, так что все сертификаты клиентов (`cert`+`pkey`) должны +быть зарегистрированы в Vault и им должен быть дан доступ к соответствующим секретам +(поддерживается API секретов v1). + +Требуемый формат секрета Vault - одно поле `key` в формате шестнадцатеричной строки. +Используется алгоритм AES-256-XTS, так что длина ключа - 64 байта, то есть строка +должна состоять из 128 шестнадцатеричных цифр. + +Для подключения Vault включите следующие настройки в Vitastor.conf: +- `vault_url` - адрес Vault (например, `https://vault:8200`) +- `vault_ca` - сертификат самого Vault + +После этого, если создать образ (`vitastor-cli create`) с опцией `--enc_key vault:`, +то для получения ключа клиенты Vitastor сначала обратятся к Vault для получения токена +по адресу `/v1/auth/cert/login`, а потом запросят из Vault сам секрет по адресу `/v1/secret/`. + +#### Пример настройки Vault + +Пошаговая инструкция для настройки тестового Vault на примере OpenBao: + +1. Если ещё не настроен TLS, генерируем самоподписанный TLS сертификат для Vault: + ``` + openssl req -days 3650 -x509 -addext basicConstraints=critical,CA:TRUE,pathlen:1 --addext subjectAltName=DNS:vault \ + -new -newkey rsa:4096 -nodes -keyout /etc/openbao/vault.key -out /etc/openbao/vault.crt + ``` + Настраиваем его в `/etc/openbao/openbao.hcl`: + ``` + listener "tcp" { + address = "0.0.0.0:8200" + tls_cert_file = "/etc/openbao/vault.crt" + tls_key_file = "/etc/openbao/vault.key" + } + ``` + И перезапускаем OpenBao (`systemctl restart openbao`). +2. Копируем TLS сертификат Vault для Vitastor: + ``` + cp /etc/openbao/vault.crt /etc/vitastor/vault.crt + ``` + Переносим его на все клиентские ноды и прописываем в `/etc/vitastor/vitastor.conf`: + ``` + { + ... + "vault_url": "http://vault:8200", + "vault_ca": "/etc/vitastor/vault.crt" + } + ``` +3. Проверяем статус Vault: + ``` + bao status -ca-cert /etc/openbao/vault.crt -address=https://vault:8200 + ``` +4. Инициализируем Vault в тестовом режиме из 1 ноды (с 1 частью ключа): + ``` + bao operator init -n 1 -t 1 -ca-cert /etc/openbao/vault.crt -address=https://vault:8200 + ``` +5. Разблокируем Vault: + ``` + bao operator unseal -ca-cert /etc/openbao/vault.crt -address=https://vault:8200 + ``` +6. Включаем аутентификацию по сертификатам: + ``` + bao auth enable -ca-cert /etc/openbao/vault.crt -address=https://vault:8200 cert + ``` +7. Включаем секреты v1: + ``` + bao secrets enable -ca-cert /etc/openbao/vault.crt -address=https://vault:8200 -path=secret kv-v1 + ``` +8. Создаём тестовый секрет: + ``` + bao kv put -ca-cert /etc/openbao/vault.crt -address=https://vault:8200 secret/vitastor/testimg3 key=$(openssl rand -hex 64) + ``` +9. Генерируем подписанный сертификат для пользователя Vitastor (там, где у вас есть `client_ca.crt` и `client_ca.key`): + ``` + openssl req -subj '/CN=testimg3' -nodes -new -keyout testimg3.key -out testimg3.csr + openssl x509 -req -days 3650 -CA client_ca.crt -CAkey client_ca.key -CAcreateserial -in testimg3.csr -out testimg3.crt + rm testimg3.csr + ``` +10. Создаём пользователя в Vault и даём ему доступ к секрету: + ``` + cat >testimg3.policy <' https://vault:8200/v1/secret/vitastor/testimg3 + ``` +12. Создаём образ в Vitastor с заданным секретом (от имени администратора или того, кто имеет + право создавать образы в вашем пуле): + ``` + vitastor-cli create -s 100G --enc_key vault:vitastor/testimg3 --owner testimg3 testimg3 + ``` +13. Тестируем доступ к образу от имени пользователя testimg3: + ``` + vitastor-cli --cert testimg3.crt --pkey testimg3.key dd if=/dev/urandom oimg=testimg3 bs=1M count=100 + ``` + +## Списки разрешённых операций + +### Права доступа к данным etcd + +Ниже все названия ключей приведены без общего префикса `/vitastor`. + +Разрешённые операции с ключами в Antietcd для клиентов (`type=client`): +- Только чтение: + - Разрешено всегда: + - `/config/global` + - `/config/node_placement` + - `/config/pools` + - `/pg/config` + - `/osd/state/*` + - `/pg/state/*` + - `/index/maxid/*` + - Для образов, которые [может читать пользователь](#пользователи-и-права-доступа): + - `/config/inode/*` + - `/index/image/*` + - `/inode/stats/*` +- Чтение и запись: + - Для пулов, в которых может создавать образы пользователь: + - `/index/maxid/*` + - Для образов, которыми владеет пользователь: + - `/config/inode/*` + - `/index/image/*` + +Разрешённые операции с ключами в Antietcd для администраторов (`type=admin`): +- Чтение: + - `/stats` + - `/mon/*` + - `/pg/*` + - `/pgstats/*` + - `/inode/stats/*` + - `/pool/stats/*` +- Чтение и запись: + - `/config/*` + - `/osd/*` + - `/index/*` + - `/pg/history/*` + +Разрешённые операции с ключами в etcd для OSD: +- Чтение: + - `/pg/config` + - `/config/*` +- Чтение и запись: + - `/osd/*` + - `/pg/state/*` + - `/pg/history/*` + - `/pgstats/*` + +Разрешённые операции с ключами в etcd для мониторов: +- Чтение: + - `/config/*` + - `/osd/*` + - `/pgstats/*` +- Чтение и запись: + - `/pg/config` + - `/stats` + - `/history/last_clean_pgs` + - `/mon/*` + - `/pg/history/*` + - `/inode/stats/*` + - `/pool/stats/*` + +### Права доступа к данным OSD + +При включённой опции `use_perms` и шифровании OSD аутентифицирует клиентов по сертификатам +и разрешает каждому клиенту только то, что ему разрешено согласно модели прав доступа. + +Клиентские операции: +- READ - разрешено для образов, доступных пользователю на чтение. +- WRITE, DELETE, SCRUB - разрешены для образов, доступных пользователю на запись. +- SYNC - операция не связана с образом и разрешена всегда. +- DESCRIBE - операция разрешена только для администраторов (используются командами + `vitastor-cli describe` и `fix`). +- PING - операция разрешена всегда. +- SHOW_CONFIG - операция разрешена всегда, однако если в ней клиент представляется + как OSD, то проверяется, что он использует сертификат, подписанный `osd_ca`. +- SEC_LIST (листинг) - разрешена другим OSD и администраторам с любыми параметрами, + а обычным клиентам разрешена только для запросов, ограниченных образом, доступным + пользователю на чтение. + +Кластерные операции - разрешаются только другим OSD: +- SEC_READ +- SEC_WRITE +- SEC_WRITE_STABLE +- SEC_SYNC +- SEC_STABILIZE +- SEC_ROLLBACK +- SEC_DELETE +- SEC_READ_BMP +- SEC_LOCK + +### Права доступа к API + +[vitastor-cli serve](../usage/cli.ru.md#serve) также поддерживает клиентскую +аутентификацию по сертификатам. Принимаются только сертификаты, подписанные +`client_ca`. В качестве серверного сертификата используется отдельный сертификат +`server_cert` с ключом `server_pkey`. + +При этом для корректной работы `vitastor-cli serve` он сам должен использовать +для доступа в Vitastor сертификат (`cert`+`pkey`) пользователя с правами +администратора (`type=admin`). + +Обычным клиентам при доступе к API разрешаются только API-операции с образами, +доступными им либо на чтение (для чтения), либо на запись (для модификации). +Все остальные API-вызовы разрешаются только для администраторов. + +Список разрешённых операций API: + +Клиентам (пользователям с `type=client`) разрешаются операции: +- image/list - для образов, которые пользователь может читать. +- image/create - для пулов, в которых пользователю разрешено создавать образы, либо + для создания снимков образов, которыми пользователь владеет. +- image/delete, image/flatten, image/modify - для образов, которыми пользователь владеет. + +Все остальные операции разрешаются только администраторам (`type=admin`). + +## Производительность шифрования + +У вас может возникнуть вопрос - а как быстро всё это прекрасное шифрование работает? + +Ответ - сильно зависит от процессора. На современных процессорах (при наличии AVX512 с VAES) +очень быстро - скорость шифрования AES может составлять 10-20 Гбайт/с и выше. В первую очередь +подразумевается CPU клиентских машин, потому что сквозное шифрование выполняется целиком на +клиенте, а транспортное хоть также и затрагивает OSD, но у клиента поток один, а OSD на стороне +сервера много и добавить там ресурсов легче. + +На более старых процессорах скорость заметно хуже, например, на Xeon E5 v4 она составляет +буквально 3 Гбайт/с. + +Вы можете оценить производительность своих процессоров с помощью команды `vitastor-cli cpubench`. + +Пример вывода (💪 AMD EPYC 9575F): + +``` +$ vitastor-cli cpubench +Vitastor transport encryption benchmark (AES-256-GCM, AES-256-XTS and xxhash3) + +Warmup... + +No transport encryption, data checksums enabled, e2e unencrypted image +xxhash3 1 M block... 209000 iterations in 2001 ms = 104447.78 MB/s +xxhash3 4 K block... 37000000 iterations in 2022 ms = 71479.35 MB/s + +Header encryption with payload checksums, e2e unencrypted image +AES-256-GCM encrypt header + xxhash3 1 M block... 210000 iterations in 2015 ms = 104218.36 MB/s +AES-256-GCM encrypt header + xxhash3 4 K block... 26000000 iterations in 2073 ms = 48993.01 MB/s + +Full transport encryption, e2e unencrypted image +AES-256-GCM encrypt header and 1 M block... 54000 iterations in 2000 ms = 27000.00 MB/s +AES-256-GCM encrypt header and 4 K block... 11700000 iterations in 2014 ms = 22692.71 MB/s + +No transport encryption, no checksums, e2e encrypted image +AES-256-XTS encrypt 1 M block... 50000 iterations in 2039 ms = 24521.82 MB/s +AES-256-XTS encrypt 4 K block... 12600000 iterations in 2009 ms = 24499.13 MB/s + +No transport encryption, e2e encrypted image, data checksums enabled +AES-256-XTS encrypt + xxhash3 1 M block... 40000 iterations in 2013 ms = 19870.84 MB/s +AES-256-XTS encrypt + xxhash3 4 K block... 10200000 iterations in 2011 ms = 19812.90 MB/s + +Header encryption with payload checksums, e2e encrypted image +AES-256-GCM encrypt header + AES-256-XTS encrypt + xxhash3 1 M block... 40000 iterations in 2014 ms = 19860.97 MB/s +AES-256-GCM encrypt header + AES-256-XTS encrypt + xxhash3 4 K block... 8700000 iterations in 2011 ms = 16899.24 MB/s + +Full transport encryption, e2e encrypted image +AES-256-XTS + AES-256-GCM encrypt 1 M block... 26000 iterations in 2062 ms = 12609.12 MB/s +AES-256-XTS + AES-256-GCM encrypt 4 K block... 6300000 iterations in 2006 ms = 12267.88 MB/s +``` + +А вот Xeon E5-2680v4: + +``` +$ vitastor-cli cpubench +Vitastor transport encryption benchmark (AES-256-GCM, AES-256-XTS and xxhash3) + +Warmup... + +No transport encryption, data checksums enabled, e2e unencrypted image +xxhash3 1 M block... 62000 iterations in 2021 ms = 30677.88 MB/s +xxhash3 4 K block... 12400000 iterations in 2006 ms = 24146.31 MB/s + +Header encryption with payload checksums, e2e unencrypted image +AES-256-GCM encrypt header + xxhash3 1 M block... 62000 iterations in 2027 ms = 30587.07 MB/s +AES-256-GCM encrypt header + xxhash3 4 K block... 6800000 iterations in 2011 ms = 13208.60 MB/s + +Full transport encryption, e2e unencrypted image +AES-256-GCM encrypt header and 1 M block... 7000 iterations in 2317 ms = 3021.15 MB/s +AES-256-GCM encrypt header and 4 K block... 1500000 iterations in 2102 ms = 2787.52 MB/s + +No transport encryption, no checksums, e2e encrypted image +AES-256-XTS encrypt 1 M block... 7000 iterations in 2317 ms = 3021.15 MB/s +AES-256-XTS encrypt 4 K block... 1600000 iterations in 2088 ms = 2993.30 MB/s + +No transport encryption, e2e encrypted image, data checksums enabled +AES-256-XTS encrypt + xxhash3 1 M block... 6000 iterations in 2188 ms = 2742.23 MB/s +AES-256-XTS encrypt + xxhash3 4 K block... 1400000 iterations in 2053 ms = 2663.78 MB/s + +Header encryption with payload checksums, e2e encrypted image +AES-256-GCM encrypt header + AES-256-XTS encrypt + xxhash3 1 M block... 6000 iterations in 2190 ms = 2739.73 MB/s +AES-256-GCM encrypt header + AES-256-XTS encrypt + xxhash3 4 K block... 1300000 iterations in 2101 ms = 2417.00 MB/s + +Full transport encryption, e2e encrypted image +AES-256-XTS + AES-256-GCM encrypt 1 M block... 4000 iterations in 2666 ms = 1500.38 MB/s +AES-256-XTS + AES-256-GCM encrypt 4 K block... 800000 iterations in 2113 ms = 1478.94 MB/s +```