robust_server_socket 0.4.3 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +4 -4
- data/README.en.md +16 -12
- data/README.md +13 -9
- data/lib/robust_server_socket/client_token.rb +1 -1
- data/lib/robust_server_socket/configuration.rb +3 -12
- data/lib/robust_server_socket/secure_token/decrypt.rb +4 -17
- data/lib/robust_server_socket/secure_token.rb +8 -0
- data/lib/robust_server_socket/token_cipher.rb +153 -0
- data/lib/robust_server_socket.rb +2 -0
- data/lib/version.rb +1 -1
- data/robust_server_socket.gemspec +1 -0
- metadata +17 -1
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA256:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: bc349adc4590867bfb7be8600730d77032a124db1c3bc74fbd694b3da71e0600
|
|
4
|
+
data.tar.gz: d8008700912aeb8489757f5349c5acfd43a84614853cf07a4b1a25c81d813ae3
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: 37a467787b410e0b447c7b3acae12d2ea6cb47e0aa10a1bc3fa440897610e5486a89ba2e7f05cbd4ebfedfa751fa2c08ce04c8a214b49d189c11d7b51f42b8fc
|
|
7
|
+
data.tar.gz: 33166d0426563742b4fec7508de14e85dd5afca44852f4d524b2b81b28044c0fed5eaf761c0f84f42aa40a478890746cd513a931132822dfd5f6cbcd1fa1129b
|
data/README.en.md
CHANGED
|
@@ -23,7 +23,7 @@ When building microservice architecture, the server side faces:
|
|
|
23
23
|
|
|
24
24
|
RobustServerSocket provides:
|
|
25
25
|
|
|
26
|
-
- **
|
|
26
|
+
- **Token decryption**: X25519 + AES-256-GCM authenticity check
|
|
27
27
|
- **Client whitelist**: Only authorized services allowed
|
|
28
28
|
- **Replay protection**: Blacklist of used tokens in Redis
|
|
29
29
|
- **Rate limiting**: Sliding window per-client request limits
|
|
@@ -39,7 +39,7 @@ Incoming request with Secure-Token
|
|
|
39
39
|
┌──────────────────────────────┐
|
|
40
40
|
│ RobustServerSocket │
|
|
41
41
|
│ │
|
|
42
|
-
│ 1.
|
|
42
|
+
│ 1. Open token (AES-GCM) │
|
|
43
43
|
│ 2. Validate Format │
|
|
44
44
|
│ 3. Check Client Whitelist │
|
|
45
45
|
│ 4. Check Rate Limit │
|
|
@@ -55,7 +55,7 @@ Incoming request with Secure-Token
|
|
|
55
55
|
|
|
56
56
|
### Validation Flow
|
|
57
57
|
|
|
58
|
-
1. **Decryption**: Base64 decode →
|
|
58
|
+
1. **Decryption**: Base64 decode → X25519 + AES-256-GCM with the service private key
|
|
59
59
|
2. **Parsing**: Extract `{client_name}_{timestamp_ms}` from token
|
|
60
60
|
3. **Whitelist**: Verify client_name is in `allowed_services`
|
|
61
61
|
4. **Rate limit**: Sliding window — check request count within `rate_limit_window_seconds`
|
|
@@ -82,8 +82,10 @@ Checks are enabled via `using_modules`:
|
|
|
82
82
|
RobustServerSocket implements a multi-layered protection system for inter-service communications:
|
|
83
83
|
|
|
84
84
|
### 1. Cryptographic Protection
|
|
85
|
-
- **
|
|
86
|
-
- **
|
|
85
|
+
- **Scheme**: `c.cipher`, default `:x25519`, `:x448` is built in. Client and server must pick the same one
|
|
86
|
+
- **X25519 / X448 + AES-256-GCM**: the token is sealed with an ephemeral key to the service's static key pair
|
|
87
|
+
- **Your own scheme**: `CipherRegistry.register(:name, object)` — an object with `open` and `read_private_key`
|
|
88
|
+
- **Key validation**: only a private key of the selected scheme is accepted; RSA is rejected
|
|
87
89
|
|
|
88
90
|
### 2. Access Control
|
|
89
91
|
- **Client Whitelist**: Only authorized services can connect, when `:client_auth_protection` module is enabled
|
|
@@ -106,7 +108,7 @@ RobustServerSocket implements a multi-layered protection system for inter-servic
|
|
|
106
108
|
|
|
107
109
|
### 6. Injection Protection
|
|
108
110
|
- **Input Validation**: Type, length, and format verification of tokens
|
|
109
|
-
- **Maximum Token Length**:
|
|
111
|
+
- **Maximum Token Length**: 512 character limit
|
|
110
112
|
- **Empty Value Checks**: Rejection of empty or malformed tokens
|
|
111
113
|
|
|
112
114
|
## 📦 Installation
|
|
@@ -132,8 +134,9 @@ RobustServerSocket.configure do |c|
|
|
|
132
134
|
rate_limit_protection
|
|
133
135
|
]
|
|
134
136
|
|
|
135
|
-
# Service private key (
|
|
137
|
+
# Service private key (X25519 PEM, or X448 when cipher is :x448)
|
|
136
138
|
c.private_key = ENV['ROBUST_SERVER_PRIVATE_KEY']
|
|
139
|
+
c.cipher = :x25519
|
|
137
140
|
|
|
138
141
|
# Token lifetime in seconds (must match TTL on client side)
|
|
139
142
|
c.token_expiration_time = 10
|
|
@@ -158,7 +161,8 @@ RobustServerSocket.load!
|
|
|
158
161
|
|
|
159
162
|
| Parameter | Type | Required | Default | Description |
|
|
160
163
|
|-----------------------------|---------|----------|-------------------------------------------------------------------------------------|-------------------------------------------------|
|
|
161
|
-
| `private_key` | String | ✅ | — |
|
|
164
|
+
| `private_key` | String | ✅ | — | Private key of the selected scheme (PEM) |
|
|
165
|
+
| `cipher` | Symbol | ❌ | `:x25519` | Token scheme: `:x25519`, `:x448`, or your own |
|
|
162
166
|
| `token_expiration_time` | Integer | ✅ | 10 | Token lifetime in seconds |
|
|
163
167
|
| `allowed_services` | Array | ✅ | — | Allowed services whitelist |
|
|
164
168
|
| `redis_url` | String | ✅ | — | Redis connection URL |
|
|
@@ -171,7 +175,7 @@ RobustServerSocket.load!
|
|
|
171
175
|
|
|
172
176
|
### Compatibility with RobustClientSocket
|
|
173
177
|
|
|
174
|
-
The token contains a timestamp in **milliseconds**. RobustClientSocket starting from version
|
|
178
|
+
The token contains a timestamp in **milliseconds**. RobustClientSocket starting from version 0.5.3 must generate:
|
|
175
179
|
|
|
176
180
|
```ruby
|
|
177
181
|
Process.clock_gettime(Process::CLOCK_REALTIME, :millisecond)
|
|
@@ -291,7 +295,7 @@ end
|
|
|
291
295
|
|
|
292
296
|
**Without RobustServerSocket (plain HTTP controller):**
|
|
293
297
|
- Real time: ~2.5 seconds
|
|
294
|
-
- No token verification, no
|
|
298
|
+
- No token verification, no AES-GCM open, no Redis checks
|
|
295
299
|
|
|
296
300
|
**With RobustServerSocket (full protection):**
|
|
297
301
|
- Real time: ~2.77 seconds
|
|
@@ -301,7 +305,7 @@ end
|
|
|
301
305
|
|
|
302
306
|
| Operation | Time | % of Request |
|
|
303
307
|
|------------------------|-------------|-------------|
|
|
304
|
-
|
|
|
308
|
+
| AES-256-GCM open | ~0.05ms | 1–3% |
|
|
305
309
|
| Redis Token Check | ~0.05–0.1ms | 2–3% |
|
|
306
310
|
| Rate Limiting | ~0.02–0.05ms| 1% |
|
|
307
311
|
| Whitelist Validation | <0.01ms | <1% |
|
|
@@ -316,7 +320,7 @@ Up to 1000 req/s — excellent performance. Higher loads require Redis Sentinel/
|
|
|
316
320
|
## 📚 Additional Resources
|
|
317
321
|
|
|
318
322
|
- [RobustClientSocket](https://github.com/tee0zed/robust_client_socket)
|
|
319
|
-
- [
|
|
323
|
+
- [X25519](https://www.rfc-editor.org/rfc/rfc7748) and [AES-GCM](https://www.rfc-editor.org/rfc/rfc5116)
|
|
320
324
|
- [Redis security guide](https://redis.io/topics/security)
|
|
321
325
|
|
|
322
326
|
## 📝 License
|
data/README.md
CHANGED
|
@@ -23,7 +23,7 @@ Gem для межсервисной аутентификации, использ
|
|
|
23
23
|
|
|
24
24
|
RobustServerSocket предоставляет:
|
|
25
25
|
|
|
26
|
-
-
|
|
26
|
+
- **Расшифровка токена**: X25519 + AES-256-GCM, проверка подлинности
|
|
27
27
|
- **Whitelist клиентов**: Только разрешённые сервисы
|
|
28
28
|
- **Защиту от replay**: Блэклист использованных токенов в Redis
|
|
29
29
|
- **Rate limiting**: Скользящее окно запросов на клиента
|
|
@@ -39,7 +39,7 @@ RobustServerSocket предоставляет:
|
|
|
39
39
|
┌──────────────────────────────┐
|
|
40
40
|
│ RobustServerSocket │
|
|
41
41
|
│ │
|
|
42
|
-
│ 1.
|
|
42
|
+
│ 1. Open token (AES-GCM) │
|
|
43
43
|
│ 2. Validate Format │
|
|
44
44
|
│ 3. Check Client Whitelist │
|
|
45
45
|
│ 4. Check Rate Limit │
|
|
@@ -55,7 +55,7 @@ RobustServerSocket предоставляет:
|
|
|
55
55
|
|
|
56
56
|
### Поток валидации
|
|
57
57
|
|
|
58
|
-
1. **Расшифровка**: Base64 decode →
|
|
58
|
+
1. **Расшифровка**: Base64 decode → X25519 + AES-256-GCM с приватным ключом сервиса
|
|
59
59
|
2. **Парсинг**: Извлечение `{client_name}_{timestamp_ms}` из токена
|
|
60
60
|
3. **Whitelist**: Проверка client_name в `allowed_services`
|
|
61
61
|
4. **Rate limit**: Скользящее окно — проверка количества запросов за `rate_limit_window_seconds`
|
|
@@ -82,8 +82,10 @@ RobustServerSocket предоставляет:
|
|
|
82
82
|
RobustServerSocket реализует многоуровневую систему защиты для межсервисных коммуникаций:
|
|
83
83
|
|
|
84
84
|
### 1. Криптографическая защита
|
|
85
|
-
-
|
|
86
|
-
-
|
|
85
|
+
- **Схема**: `c.cipher`, по умолчанию `:x25519`, встроен ещё `:x448`. Клиент и сервер должны выбрать одну
|
|
86
|
+
- **X25519 / X448 + AES-256-GCM**: токен запечатан эфемерным ключом на статическую пару сервиса
|
|
87
|
+
- **Своя схема**: `CipherRegistry.register(:name, object)` — объект с `open` и `read_private_key`
|
|
88
|
+
- **Валидация ключей**: принимается только приватный ключ выбранной схемы, RSA отвергается
|
|
87
89
|
|
|
88
90
|
### 2. Контроль доступа
|
|
89
91
|
- **Whitelist клиентов**: Только авторизованные сервисы могут подключаться, при включенном модуле `:client_auth_protection`
|
|
@@ -127,8 +129,9 @@ RobustServerSocket.configure do |c|
|
|
|
127
129
|
rate_limit_protection
|
|
128
130
|
]
|
|
129
131
|
|
|
130
|
-
# Приватный ключ сервиса (
|
|
132
|
+
# Приватный ключ сервиса (X25519, PEM). Для :x448 — ключ X448.
|
|
131
133
|
c.private_key = ENV['ROBUST_SERVER_PRIVATE_KEY']
|
|
134
|
+
c.cipher = :x25519
|
|
132
135
|
|
|
133
136
|
# Время жизни токена в секундах (должно совпадать с TTL на клиенте)
|
|
134
137
|
c.token_expiration_time = 10
|
|
@@ -153,7 +156,8 @@ RobustServerSocket.load!
|
|
|
153
156
|
|
|
154
157
|
| Параметр | Тип | Обязательный | Default | Описание |
|
|
155
158
|
|-----------------------------|---------|-------------|-------------------------------------------------------------------------------------|-------------------------------------------------|
|
|
156
|
-
| `private_key` | String | ✅ | — | Приватный
|
|
159
|
+
| `private_key` | String | ✅ | — | Приватный ключ выбранной схемы (PEM) |
|
|
160
|
+
| `cipher` | Symbol | ❌ | `:x25519` | Схема токена: `:x25519`, `:x448` или своя |
|
|
157
161
|
| `token_expiration_time` | Integer | ✅ | 10 | Время жизни токена в секундах |
|
|
158
162
|
| `allowed_services` | Array | ✅ | — | Список разрешённых сервисов (whitelist) |
|
|
159
163
|
| `redis_url` | String | ✅ | — | URL для подключения к Redis |
|
|
@@ -166,7 +170,7 @@ RobustServerSocket.load!
|
|
|
166
170
|
|
|
167
171
|
### Совместимость с RobustClientSocket
|
|
168
172
|
|
|
169
|
-
Токен содержит таймстамп в **миллисекундах**. RobustClientSocket начиная с версии
|
|
173
|
+
Токен содержит таймстамп в **миллисекундах**. RobustClientSocket начиная с версии 0.5.3 должен генерировать:
|
|
170
174
|
|
|
171
175
|
```ruby
|
|
172
176
|
Process.clock_gettime(Process::CLOCK_REALTIME, :millisecond)
|
|
@@ -287,7 +291,7 @@ end
|
|
|
287
291
|
## 📚 Дополнительные ресурсы
|
|
288
292
|
|
|
289
293
|
- [RobustClientSocket](https://github.com/tee0zed/robust_client_socket)
|
|
290
|
-
- [
|
|
294
|
+
- [X25519](https://www.rfc-editor.org/rfc/rfc7748) и [AES-GCM](https://www.rfc-editor.org/rfc/rfc5116)
|
|
291
295
|
- [Redis security guide](https://redis.io/topics/security)
|
|
292
296
|
|
|
293
297
|
## 📝 Лицензия
|
|
@@ -84,7 +84,7 @@ module RobustServerSocket
|
|
|
84
84
|
# Validate token input to prevent injection
|
|
85
85
|
raise InvalidToken, 'Token must be a string' unless token.is_a?(String)
|
|
86
86
|
raise InvalidToken, 'Token cannot be empty' if token.empty?
|
|
87
|
-
raise InvalidToken, 'Token too long' if token.length >
|
|
87
|
+
raise InvalidToken, 'Token too long' if token.length > 512
|
|
88
88
|
|
|
89
89
|
# Check for null-byte injection
|
|
90
90
|
raise InvalidToken, 'Token contains invalid characters' if token.include?("\x00")
|
|
@@ -2,8 +2,6 @@
|
|
|
2
2
|
|
|
3
3
|
module RobustServerSocket
|
|
4
4
|
module Configuration
|
|
5
|
-
MIN_KEY_SIZE = 2048
|
|
6
|
-
|
|
7
5
|
ConfigurationError = Class.new(StandardError)
|
|
8
6
|
|
|
9
7
|
attr_reader :configuration, :configured
|
|
@@ -55,21 +53,13 @@ module RobustServerSocket
|
|
|
55
53
|
end
|
|
56
54
|
|
|
57
55
|
def validate_key_security!
|
|
58
|
-
|
|
59
|
-
key_bits = key.n.num_bits
|
|
60
|
-
|
|
61
|
-
if key_bits < MIN_KEY_SIZE
|
|
62
|
-
raise SecurityError,
|
|
63
|
-
"RSA key size (#{key_bits} bits) below minimum (#{MIN_KEY_SIZE} bits)"
|
|
64
|
-
end
|
|
65
|
-
rescue ::OpenSSL::PKey::RSAError => e
|
|
66
|
-
raise SecurityError, "Invalid private key: #{e.message}"
|
|
56
|
+
TokenCipher.read_private_key(configuration.private_key, cipher: configuration.cipher)
|
|
67
57
|
end
|
|
68
58
|
end
|
|
69
59
|
|
|
70
60
|
class ConfigStore
|
|
71
61
|
attr_accessor :allowed_services, :private_key, :token_expiration_time,
|
|
72
|
-
:redis_url, :redis_pass,
|
|
62
|
+
:redis_url, :redis_pass, :cipher,
|
|
73
63
|
:rate_limit_max_requests, :rate_limit_window_seconds, :using_modules
|
|
74
64
|
|
|
75
65
|
attr_reader :_modules_check_rows, :_bang_modules_check_rows
|
|
@@ -78,6 +68,7 @@ module RobustServerSocket
|
|
|
78
68
|
@rate_limit_max_requests = 100
|
|
79
69
|
@rate_limit_window_seconds = 60
|
|
80
70
|
@token_expiration_time = 10
|
|
71
|
+
@cipher = :x25519
|
|
81
72
|
@using_modules = %i[client_auth_protection rate_limit_protection replay_attack_protection]
|
|
82
73
|
@_modules_check_rows = []
|
|
83
74
|
@_bang_modules_check_rows = []
|
|
@@ -2,34 +2,21 @@
|
|
|
2
2
|
|
|
3
3
|
module RobustServerSocket
|
|
4
4
|
module SecureToken
|
|
5
|
-
BASE64_REGEXP = %r{\A[A-Za-z0-9+/]+={0,2}\z}.freeze
|
|
6
|
-
InvalidToken = Class.new(StandardError)
|
|
7
|
-
|
|
8
5
|
module Decrypt
|
|
9
6
|
class << self
|
|
10
7
|
def call(token)
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
decoded_token = ::Base64.strict_decode64(token)
|
|
14
|
-
|
|
15
|
-
raise InvalidToken, 'Token too large' if decoded_token.bytesize > 1024
|
|
16
|
-
|
|
17
|
-
private_key.private_decrypt(decoded_token, OpenSSL::PKey::RSA::PKCS1_OAEP_PADDING).force_encoding('UTF-8')
|
|
18
|
-
rescue ::OpenSSL::PKey::RSAError, ArgumentError
|
|
19
|
-
raise InvalidToken, 'Invalid token'
|
|
8
|
+
TokenCipher.open(token, private_key_pem, cipher: RobustServerSocket.configuration.cipher)
|
|
20
9
|
end
|
|
21
10
|
|
|
22
11
|
# Clear cached private key (useful for hot reloading in development)
|
|
23
12
|
def clear_private_key_cache!
|
|
24
|
-
@
|
|
13
|
+
@private_key_pem = nil
|
|
25
14
|
end
|
|
26
15
|
|
|
27
16
|
private
|
|
28
17
|
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
def private_key
|
|
32
|
-
@private_key ||= ::OpenSSL::PKey::RSA.new(RobustServerSocket.configuration.private_key)
|
|
18
|
+
def private_key_pem
|
|
19
|
+
@private_key_pem ||= RobustServerSocket.configuration.private_key
|
|
33
20
|
end
|
|
34
21
|
end
|
|
35
22
|
end
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require 'openssl'
|
|
4
|
+
require 'base64'
|
|
5
|
+
|
|
6
|
+
module RobustServerSocket
|
|
7
|
+
# A named asymmetric token scheme. Built-ins are X25519 and X448.
|
|
8
|
+
# Register your own with CipherRegistry.register(:name, scheme).
|
|
9
|
+
# A scheme answers open(token, private_key_pem) and read_private_key(pem).
|
|
10
|
+
module CipherRegistry
|
|
11
|
+
UnknownCipher = Class.new(SecurityError)
|
|
12
|
+
|
|
13
|
+
@schemes = {}
|
|
14
|
+
|
|
15
|
+
class << self
|
|
16
|
+
def register(name, scheme)
|
|
17
|
+
raise ArgumentError, 'cipher name must be a Symbol' unless name.is_a?(Symbol)
|
|
18
|
+
raise ArgumentError, 'cipher must answer open and read_private_key' unless scheme.respond_to?(:open) && scheme.respond_to?(:read_private_key)
|
|
19
|
+
|
|
20
|
+
@schemes[name] = scheme
|
|
21
|
+
name
|
|
22
|
+
end
|
|
23
|
+
|
|
24
|
+
def fetch(name)
|
|
25
|
+
@schemes.fetch(name.to_sym) { raise UnknownCipher, "Unknown cipher: #{name}" }
|
|
26
|
+
end
|
|
27
|
+
|
|
28
|
+
def registered?(name)
|
|
29
|
+
@schemes.key?(name.to_sym)
|
|
30
|
+
end
|
|
31
|
+
end
|
|
32
|
+
end
|
|
33
|
+
|
|
34
|
+
module EcdhCipher
|
|
35
|
+
IV_LENGTH = 12
|
|
36
|
+
TAG_LENGTH = 16
|
|
37
|
+
KEY_LENGTH = 32
|
|
38
|
+
MAX_BLOB_BYTES = 1024
|
|
39
|
+
|
|
40
|
+
def self.build(algorithm, ephemeral_der_length)
|
|
41
|
+
Module.new do
|
|
42
|
+
extend self
|
|
43
|
+
|
|
44
|
+
const_set(:ALGORITHM, algorithm)
|
|
45
|
+
const_set(:EPHEMERAL_DER_LENGTH, ephemeral_der_length)
|
|
46
|
+
const_set(:HEADER_LENGTH, ephemeral_der_length + IV_LENGTH + TAG_LENGTH)
|
|
47
|
+
const_set(:INFO, "robust-socket-token-v1-#{algorithm.downcase}")
|
|
48
|
+
|
|
49
|
+
def seal(plaintext, public_key_pem)
|
|
50
|
+
recipient = OpenSSL::PKey.read(public_key_pem)
|
|
51
|
+
raise SecurityError, 'Invalid public key' unless recipient.oid == self::ALGORITHM
|
|
52
|
+
|
|
53
|
+
ephemeral = OpenSSL::PKey.generate_key(self::ALGORITHM)
|
|
54
|
+
blob = ephemeral.public_to_der.b + gcm_seal(derive_key(ephemeral.derive(recipient)), plaintext)
|
|
55
|
+
|
|
56
|
+
::Base64.strict_encode64(blob)
|
|
57
|
+
end
|
|
58
|
+
|
|
59
|
+
def open(token, private_key_pem)
|
|
60
|
+
raise SecureToken::InvalidToken, 'Invalid token format' unless token.is_a?(String) && token.match?(SecureToken::BASE64_REGEXP)
|
|
61
|
+
|
|
62
|
+
decoded = ::Base64.strict_decode64(token)
|
|
63
|
+
raise SecureToken::InvalidToken, 'Token too large' if decoded.bytesize > EcdhCipher::MAX_BLOB_BYTES
|
|
64
|
+
raise SecureToken::InvalidToken, 'Invalid token' if decoded.bytesize <= self::HEADER_LENGTH
|
|
65
|
+
|
|
66
|
+
ephemeral_der = decoded.byteslice(0, self::EPHEMERAL_DER_LENGTH)
|
|
67
|
+
iv = decoded.byteslice(self::EPHEMERAL_DER_LENGTH, EcdhCipher::IV_LENGTH)
|
|
68
|
+
tag = decoded.byteslice(self::EPHEMERAL_DER_LENGTH + EcdhCipher::IV_LENGTH, EcdhCipher::TAG_LENGTH)
|
|
69
|
+
ciphertext = decoded.byteslice(self::HEADER_LENGTH..-1)
|
|
70
|
+
key = derive_key(read_private_key(private_key_pem).derive(read_ephemeral(ephemeral_der)))
|
|
71
|
+
|
|
72
|
+
gcm_open(key, iv, tag, ciphertext)
|
|
73
|
+
rescue OpenSSL::PKey::PKeyError, OpenSSL::Cipher::CipherError, ArgumentError
|
|
74
|
+
raise SecureToken::InvalidToken, 'Invalid token'
|
|
75
|
+
end
|
|
76
|
+
|
|
77
|
+
def read_private_key(pem)
|
|
78
|
+
key = OpenSSL::PKey.read(pem)
|
|
79
|
+
raise SecurityError, 'Invalid private key' unless private_key?(key)
|
|
80
|
+
|
|
81
|
+
key
|
|
82
|
+
rescue OpenSSL::PKey::PKeyError => e
|
|
83
|
+
raise SecurityError, "Invalid private key: #{e.message}"
|
|
84
|
+
end
|
|
85
|
+
|
|
86
|
+
def private_key?(key)
|
|
87
|
+
key.oid == self::ALGORITHM && holds_private_key?(key)
|
|
88
|
+
end
|
|
89
|
+
|
|
90
|
+
def holds_private_key?(key)
|
|
91
|
+
!key.raw_private_key.nil?
|
|
92
|
+
rescue OpenSSL::PKey::PKeyError
|
|
93
|
+
false
|
|
94
|
+
end
|
|
95
|
+
|
|
96
|
+
def read_ephemeral(der)
|
|
97
|
+
key = OpenSSL::PKey.read(der)
|
|
98
|
+
raise OpenSSL::PKey::PKeyError, 'invalid ephemeral key' unless key.oid == self::ALGORITHM && !holds_private_key?(key)
|
|
99
|
+
|
|
100
|
+
key
|
|
101
|
+
end
|
|
102
|
+
|
|
103
|
+
def derive_key(shared_secret)
|
|
104
|
+
OpenSSL::KDF.hkdf(shared_secret, salt: '', info: self::INFO, length: EcdhCipher::KEY_LENGTH, hash: 'SHA256')
|
|
105
|
+
end
|
|
106
|
+
|
|
107
|
+
def gcm_seal(key, plaintext)
|
|
108
|
+
cipher = OpenSSL::Cipher.new('aes-256-gcm')
|
|
109
|
+
cipher.encrypt
|
|
110
|
+
cipher.key = key
|
|
111
|
+
iv = cipher.random_iv
|
|
112
|
+
cipher.auth_data = self::INFO
|
|
113
|
+
ciphertext = cipher.update(plaintext) + cipher.final
|
|
114
|
+
|
|
115
|
+
iv + cipher.auth_tag + ciphertext
|
|
116
|
+
end
|
|
117
|
+
|
|
118
|
+
def gcm_open(key, iv, tag, ciphertext)
|
|
119
|
+
cipher = OpenSSL::Cipher.new('aes-256-gcm')
|
|
120
|
+
cipher.decrypt
|
|
121
|
+
cipher.key = key
|
|
122
|
+
cipher.iv = iv
|
|
123
|
+
cipher.auth_tag = tag
|
|
124
|
+
cipher.auth_data = self::INFO
|
|
125
|
+
|
|
126
|
+
(cipher.update(ciphertext) + cipher.final).force_encoding('UTF-8')
|
|
127
|
+
end
|
|
128
|
+
end
|
|
129
|
+
end
|
|
130
|
+
end
|
|
131
|
+
|
|
132
|
+
X25519 = EcdhCipher.build('X25519', 44)
|
|
133
|
+
X448 = EcdhCipher.build('X448', 68)
|
|
134
|
+
|
|
135
|
+
CipherRegistry.register(:x25519, X25519)
|
|
136
|
+
CipherRegistry.register(:x448, X448)
|
|
137
|
+
|
|
138
|
+
module TokenCipher
|
|
139
|
+
module_function
|
|
140
|
+
|
|
141
|
+
def seal(plaintext, public_key_pem, cipher: :x25519)
|
|
142
|
+
CipherRegistry.fetch(cipher).seal(plaintext, public_key_pem)
|
|
143
|
+
end
|
|
144
|
+
|
|
145
|
+
def open(token, private_key_pem, cipher: :x25519)
|
|
146
|
+
CipherRegistry.fetch(cipher).open(token, private_key_pem)
|
|
147
|
+
end
|
|
148
|
+
|
|
149
|
+
def read_private_key(pem, cipher: :x25519)
|
|
150
|
+
CipherRegistry.fetch(cipher).read_private_key(pem)
|
|
151
|
+
end
|
|
152
|
+
end
|
|
153
|
+
end
|
data/lib/robust_server_socket.rb
CHANGED
|
@@ -6,6 +6,8 @@ require 'redis'
|
|
|
6
6
|
require 'connection_pool'
|
|
7
7
|
|
|
8
8
|
require_relative 'robust_server_socket/configuration'
|
|
9
|
+
require_relative 'robust_server_socket/secure_token'
|
|
10
|
+
require_relative 'robust_server_socket/token_cipher'
|
|
9
11
|
require_relative 'robust_server_socket/secure_token/decrypt'
|
|
10
12
|
require_relative 'robust_server_socket/client_token'
|
|
11
13
|
|
data/lib/version.rb
CHANGED
|
@@ -23,6 +23,7 @@ Gem::Specification.new do |spec|
|
|
|
23
23
|
spec.bindir = 'exe'
|
|
24
24
|
spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) }
|
|
25
25
|
spec.require_paths = ['lib']
|
|
26
|
+
spec.add_dependency 'base64'
|
|
26
27
|
spec.add_dependency 'hiredis'
|
|
27
28
|
spec.add_dependency 'rake'
|
|
28
29
|
spec.add_dependency 'redis'
|
metadata
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
--- !ruby/object:Gem::Specification
|
|
2
2
|
name: robust_server_socket
|
|
3
3
|
version: !ruby/object:Gem::Version
|
|
4
|
-
version: 0.
|
|
4
|
+
version: 0.6.0
|
|
5
5
|
platform: ruby
|
|
6
6
|
authors:
|
|
7
7
|
- tee_zed
|
|
@@ -9,6 +9,20 @@ bindir: exe
|
|
|
9
9
|
cert_chain: []
|
|
10
10
|
date: 1980-01-02 00:00:00.000000000 Z
|
|
11
11
|
dependencies:
|
|
12
|
+
- !ruby/object:Gem::Dependency
|
|
13
|
+
name: base64
|
|
14
|
+
requirement: !ruby/object:Gem::Requirement
|
|
15
|
+
requirements:
|
|
16
|
+
- - ">="
|
|
17
|
+
- !ruby/object:Gem::Version
|
|
18
|
+
version: '0'
|
|
19
|
+
type: :runtime
|
|
20
|
+
prerelease: false
|
|
21
|
+
version_requirements: !ruby/object:Gem::Requirement
|
|
22
|
+
requirements:
|
|
23
|
+
- - ">="
|
|
24
|
+
- !ruby/object:Gem::Version
|
|
25
|
+
version: '0'
|
|
12
26
|
- !ruby/object:Gem::Dependency
|
|
13
27
|
name: hiredis
|
|
14
28
|
requirement: !ruby/object:Gem::Requirement
|
|
@@ -88,7 +102,9 @@ files:
|
|
|
88
102
|
- lib/robust_server_socket/modules/rate_limit_protection.rb
|
|
89
103
|
- lib/robust_server_socket/modules/replay_attack_protection.rb
|
|
90
104
|
- lib/robust_server_socket/rate_limiter.rb
|
|
105
|
+
- lib/robust_server_socket/secure_token.rb
|
|
91
106
|
- lib/robust_server_socket/secure_token/decrypt.rb
|
|
107
|
+
- lib/robust_server_socket/token_cipher.rb
|
|
92
108
|
- lib/version.rb
|
|
93
109
|
- robust_server_socket.gemspec
|
|
94
110
|
licenses:
|