-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathVault.php
More file actions
477 lines (419 loc) · 12.4 KB
/
Vault.php
File metadata and controls
477 lines (419 loc) · 12.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
<?php
/**
* module/Vault/src/Service/Vault.php
*/
declare(strict_types=1);
namespace SDNY\Vault\Service;
use Laminas\Http\Client;
use Laminas\Crypt\BlockCipher;
use Laminas\Crypt\Symmetric\Openssl;
use Laminas\EventManager\EventManagerAwareInterface;
use Laminas\EventManager\EventManagerAwareTrait;
use function basename;
use function key_exists;
use function json_encode;
use function json_decode;
use function is_string;
/**
* Extension of Laminas\Http\Client for communciating with Hashicorp Vault
*
* The purpose is enable us to store sensitive data in MySQL using symmetrical
* encryption while avoiding having to store the encryption key in plain text
* anywhere at any time. All the configuration has to be correctly set before
* instantiation. Error-checking is left up to the consumer.
*
* Absent further precautions, it's surely still possible to beat this in a
* worst-case scenario, but it's a good start.
*
*/
class Vault extends Client implements EventManagerAwareInterface
{
use EventManagerAwareTrait;
/**
* event manager
*
* @var EventManagerInterface
*/
protected $events;
/**
* mapping of string keys to CURL integer constants
*
* we need this because if a config array key is an integer
* unfortunate things happen when the framework merges the configs
*
* @var array
*/
private static $curlopt_keys = [
'ssl_key' => \CURLOPT_SSLKEY,
'ssl_cert' => \CURLOPT_SSLCERT,
];
/**
* cipher (key) for symmetrical encryption/decryption
*
* @var string
*/
private $key;
/**
* Blockcipher for encryption/decryption
*
* @var BlockCipher
*/
private $blockCipher;
/**
* vault authentication token
*
* @var string
*/
private $token;
/**
* vault address
*
* @var string
*/
private $vault_address;
/**
* Vault API prefix
*
* @var string
*/
private $prefix = '/v1';
/**
* path to the ultimate secret
*
* @var string
*/
private $path_to_secret;
/**
* path to access token
*
* @var string
*/
private $path_to_access_token;
/**
* constructor
*
* @param array $config
*/
public function __construct(array $config)
{
foreach (['vault_address','path_to_secret','path_to_access_token'] as $setting) {
if (! isset($config[$setting]) or ! is_string($config[$setting])) {
throw new \RuntimeException("missing/invalid configuration value for '$setting'");
} else {
$this->$setting = $config[$setting];
}
}
$this->vault_address .= $this->prefix;
$curloptions = [];
foreach ($config as $key => $value) {
if (key_exists($key, self::$curlopt_keys)) {
$curloptions[self::$curlopt_keys[$key]] = $value;
}
}
$config['curloptions'] = $curloptions;
parent::__construct(null, $config);
$this->getRequest()
->getHeaders()
->addHeaderLine('Accept: application/json');
}
/**
* gets Vault /sys/health response
*
* @return Array
*/
public function health() : Array
{
$this->setMethod('GET')
->setUri($this->vault_address .'/sys/health')
->send();
$response = $this->responseToArray($this->getResponse()->getBody());
return $response;
}
/**
* sets path to secret
*
* @param string
*/
public function setPathToSecret($path) : Vault
{
$this->path_to_secret = $path;
return $this;
}
/**
* gets path to secret
*
* @return string
*/
public function getPathToSecret() : string
{
return $this->path_to_secret;
}
/**
* gets the vault address
*
* @return string
*/
public function getVaultAddress() : string
{
return $this->vault_address;
}
/**
* checks response for errors
*
* @param Array $response
* @return boolean true if error
*/
public function isError(array $response) : bool
{
return key_exists('errors', $response);
}
/**
* resets request, response, etc, and restores
* request header for JSON responses
*
* @return \SDNY\Vault\Service\Vault
*/
public function reset() : Vault
{
parent::reset();
$this->getRequest()
->getHeaders()
->addHeaderLine('Accept: application/json');
return $this;
}
/**
* attempts Vault TLS authentication
*
* this will attempt to authenticate using TLS certificates, which have to
* have been installed and set in our configuration up front.
*
* @link https://www.vaultproject.io/docs/auth/cert.html
*
* @return Vault
* @throws VaultException
*/
public function authenticateTLSCert() : Vault
{
try {
$this->setMethod('POST')
->setUri($this->vault_address .'/auth/cert/login')
->send();
$response = $this->responseToArray($this->getResponse()->getBody());
if ($this->isError($response)) {
$this->getEventManager()->trigger(__FUNCTION__, $this, []);
throw new VaultException($response['errors'][0]);
}
$this->token = $response['auth']['client_token'];
//printf("DEBUG: \$this->token has been set to: $this->token in %s\n",__FUNCTION__);
return $this;
} catch (\Exception $e) {
throw new VaultException(
'could not authenticate via TLS: '.
$e->getMessage(),
$e->getCode(),
$e
);
}
}
/**
* Attempts to acquire access token that is authorized to read the cipher
* we use for symmetrical encryption/decryption of sensitive Interpreter
* data.
*
* @return Vault
* @throws VaultException
*/
public function requestCipherAccessToken() : Vault
{
//printf("DEBUG: \$this->token has been set to: $this->token in %s\n",__FUNCTION__);
$this->getRequest()->getHeaders()
->addHeaderLine("X-Vault-Token: $this->token")
->addHeaderLine("X-Vault-Wrap-TTL: 10s");
$endpoint = $this->vault_address . $this->path_to_access_token; //'/auth/token/create/read-secret';
$this->getRequest()->setContent(json_encode(
[
// maybe reconsider these settings
'ttl' => '5m',
'num_uses' => 3,
]
));
//printf("\n DEBUG: %s\n","endpoint: $endpoint");
$this->setMethod('POST')->setUri($endpoint)->send();
$response = $this->responseToArray($this->getResponse()->getBody());
if ($this->isError($response)) {
$this->getEventManager()->trigger(__FUNCTION__, $this, [
'message' => 'failed to get token for cipher access'
]);
throw new VaultException($response['errors'][0]);
}
$this->token = $response['wrap_info']['token'];
return $this;
}
/**
* unwraps a wrapped response and returns it
*
* @param string $token
* @return array
*/
public function unwrap() : Array
{
$this->reset();
$endpoint = $this->vault_address . '/sys/wrapping/unwrap';
$this->setAuthToken($this->token);
$this->setMethod('POST')->setUri($endpoint)->send();
$response = $this->responseToArray($this->getResponse()->getBody());
if ($this->isError($response)) {
$this->getEventManager()->trigger(__FUNCTION__, $this, [
'message' => 'failed to unwrap response'
]);
throw new VaultException($response['errors'][0]);
}
if (isset($response['auth'])) {
$this->setAuthToken($response['auth']['client_token']);
}
return $response;
}
/**
* requests response-wrapped encryption key
*
* @param string $token authentication token
* @return Vault
* @throws VaultException
*/
public function requestWrappedEncryptionKey() : Vault
{
$endpoint = $this->vault_address . $this->path_to_secret;
$this->getRequest()->getHeaders()->addHeaderLine("X-Vault-Wrap-TTL: 10s");
$this->setMethod('GET')->setUri($endpoint)->send();
$response = $this->responseToArray($this->getResponse()->getBody());
if ($this->isError($response)) {
$this->getEventManager()->trigger(__FUNCTION__, $this, [
'message' => 'failed to get wrapped encryption-key response'
]);
throw new VaultException($response['errors'][0]);
}
$this->setAuthToken($response['wrap_info']['token']);
return $this;
}
/**
* gets encryption key.
*
* convenience method that wraps the several
* steps into one.
*
* @return Vault
* @throws VaultException
*/
public function getEncryptionKey() : string
{
if (! $this->key) {
$this->authenticateTLSCert()
->requestCipherAccessToken()
->unwrap();
$this->requestWrappedEncryptionKey();
$data = $this->unwrap()['data'];
// it looks like the data structure we get may vary
if (!key_exists('cipher',$data)) {
$this->key = $data['data']['cipher'] ?? null;
} else {
$this->key = $data['cipher'] ?? null;
}
if (! is_string($this->key)) {
throw new VaultException(__FUNCTION__ . ' could not get encryption/decryption key');
}
}
return $this->key;
}
/**
* gets BlockCipher
*
* @return BlockCipher
*/
protected function getBlockCipher() : BlockCipher
{
if (! $this->blockCipher) {
$this->blockCipher = new BlockCipher(new Openssl());
}
return $this->blockCipher;
}
/**
* decrypts an encrypted string
*
* @param string $string the encrypted datum
* @throws VaultException
* @return string
*/
public function decrypt(string $string) : string
{
$cipher = $this->getBlockCipher();
$cipher->setKey($this->getEncryptionKey());
return $cipher->decrypt($string);
}
/**
* encrypts a string
*
* @param string $string
* @return string
* @throws VaultException
*/
public function encrypt($string) : string
{
$key = $this->getEncryptionKey();
$cipher = $this->getBlockCipher();
$cipher->setKey($key);
return $cipher->encrypt($string);
}
/**
* sets Vault authentication token header
* and instance variable
*
* @param string $token
* @return \SDNY\Service\Vault
*/
public function setAuthToken(string $token) : Vault
{
$this->getRequest()
->getHeaders()
->addHeaderLine("X-Vault-Token:$token");
$this->token = $token;
return $this;
}
/**
* returns Authentication token
*
* @return string
*/
public function getAuthToken() : string
{
return $this->token;
}
/**
* converts json to array
*
* @param string $json
* @return Array
*/
public function responseToArray(string $json) : Array
{
return json_decode($json, true);
}
/**
* attempts user/password authentication
*
* this will attempt to authenticate user against Vault's
* userpass auth backend. NOTE: looks like we won't be using this auth
* method after all, so this method is not currently used.
* @link https://www.vaultproject.io/docs/auth/userpass.html
*
* @param string $user
* @param string $password
* @return array Vault response as array
*/
public function authenticateUser(string $user, string $password) : Array
{
$uri = $this->vault_address . "/auth/userpass/login/$user";
$this->getRequest()->setContent(json_encode(['password' => $password]));
$this->setUri($uri)->setMethod('POST')->send();
return $this->responseToArray($this->getResponse()->getBody());
}
}