-
-
Notifications
You must be signed in to change notification settings - Fork 161
Expand file tree
/
Copy pathKeyService.php
More file actions
280 lines (230 loc) · 10.9 KB
/
Copy pathKeyService.php
File metadata and controls
280 lines (230 loc) · 10.9 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
<?php
namespace Admidio\SSO\Service;
use Admidio\Infrastructure\Database;
use Admidio\Infrastructure\Utils\FileSystemUtils;
use Admidio\Users\Entity\User;
use Admidio\SSO\Entity\Key;
use Admidio\Infrastructure\Exception;
class KeyService {
private Database $db;
private User $currentUser;
public function __construct(Database $db) {
$this->db = $db;
}
/**
* Return an array of all configured cryptographic key data.
* @param bool $activeOnly If true, only active key uuids are returned
* @return array Returns an array with all key data for list view.
*/
public function getKeysData(bool $activeOnly = false) {
global $gCurrentOrgId;
$sql = 'SELECT key_id, key_uuid, key_org_id, key_name, key_algorithm, key_certificate, key_expires_at, key_is_active
FROM ' . TBL_SSO_KEYS . '
WHERE key_org_id = ?
' . ($activeOnly ? ' and key_is_active = 1 ' : '') . '
ORDER BY key_name';
$keysList = $this->db->getArrayFromSql($sql, array($gCurrentOrgId));
return $keysList;
}
public function setupKeyConfig(string $algorithm) : array {
$config = ['digest_alg' => 'sha256'];
switch($algorithm) {
case "RSA":
case "RSA-2048":
$config['private_key_type'] = OPENSSL_KEYTYPE_RSA;
$config['private_key_bits'] = 2048;
break;
case "RSA-3072":
$config['private_key_type'] = OPENSSL_KEYTYPE_RSA;
$config['private_key_bits'] = 3072;
break;
case "RSA-4096":
$config['private_key_type'] = OPENSSL_KEYTYPE_RSA;
$config['private_key_bits'] = 4096;
break;
case "RSA-8192":
$config['private_key_type'] = OPENSSL_KEYTYPE_RSA;
$config['private_key_bits'] = 8192;
break;
case "ECDSA":
case "ECDSA-256":
$config['private_key_type'] = OPENSSL_KEYTYPE_EC;
$config['curve_name'] = 'prime256v1';
break;
case "ECDSA-384":
$config['private_key_type'] = OPENSSL_KEYTYPE_EC;
$config['curve_name'] = 'secp384r1';
break;
case "ECDSA-521":
$config['private_key_type'] = OPENSSL_KEYTYPE_EC;
$config['curve_name'] = 'secp521r1';
break;
}
return $config;
}
public function generateKey(string $algorithm) : array {
$config = $this->setupKeyConfig($algorithm);
$key = openssl_pkey_new($config);
if ($key === false) {
throw new Exception(openssl_error_string(), array(openssl_error_string()));
}
openssl_pkey_export($key, $privateKey);
$keyDetails = openssl_pkey_get_details($key);
$publicKey = $keyDetails['key'];
return ['private_key' => $privateKey, 'public_key' => $publicKey, 'key_details' => $keyDetails];
}
public function generateCertificate(string $keyPem, array $csrData, string $algorithm, string $expiration) : string {
$config = $this->setupKeyConfig($algorithm);
$privateKey = openssl_pkey_get_private($keyPem);
$csr = openssl_csr_new($csrData, $privateKey, $config);
if (!$csr) {
throw new Exception('SYS_SSO_CERTIFICATE_FAILURE', array(openssl_error_string()));
}
$expiration = \DateTime::createFromFormat('Y-m-d', $expiration);
$now = new \DateTime();
$certificate = openssl_csr_sign($csr, null, $privateKey, $now->diff($expiration)->days);
if (!$certificate) {
throw new Exception('SYS_SSO_CERTIFICATE_FAILURE', array(openssl_error_string()));
}
openssl_x509_export($certificate, $certificatePEM);
return $certificatePEM;
}
public function exportToPkcs12(string $keyUUID, string $password = '') {
global $gL10n;
$ssoKey = new Key($this->db);
$ssoKey->readDataByUuid($keyUUID);
if (empty($keyUUID)) {
throw new Exception('SYS_SSO_KEY_EXPORT_FAILURE', array($gL10n->get('SYS_ERROR_UUID_MISSING')));
}
if ($ssoKey->isNewRecord()) {
throw new Exception('SYS_SSO_KEY_EXPORT_FAILURE', array($gL10n->get('SYS_SSO_KEY_NOT_FOUND')));
}
$name = $ssoKey->getValue('key_name');
$privkeyPem = $ssoKey->getValue('key_private');
$certPem = $ssoKey->getValue('key_certificate');
if (empty($privkeyPem) || empty($certPem)) {
throw new Exception('SYS_SSO_KEY_EXPORT_FAILURE', array($gL10n->get('SYS_SSO_KEY_NOT_FOUND')));
}
// Load the private key
$privateKey = openssl_pkey_get_private($privkeyPem);
if (!$privateKey) {
throw new Exception('SYS_SSO_KEY_EXPORT_FAILURE', array(openssl_error_string()));
}
// Load the certificate
$certificate = openssl_x509_read($certPem);
if (!$certificate) {
throw new Exception('SYS_SSO_KEY_EXPORT_FAILURE', array(openssl_error_string()));
}
// Export the PKCS#12
$pkcs12 = "";
openssl_pkcs12_export($certificate, $pkcs12, $privateKey, $password, ["friendly_name" => $name]);
if (!$pkcs12) {
throw new Exception('SYS_SSO_KEY_EXPORT_FAILURE', array(openssl_error_string()));
}
// Send the PKCS#12 file as a download to the browser (All errors were already handled with an exception, which caused a JSON response!)
$filename = FileSystemUtils::getSanitizedPathEntry($name);
header('Content-Type: application/x-pkcs12');
header('Content-Disposition: attachment; filename="' . $filename . '.p12"');
header('Content-Length: ' . strlen($pkcs12));
echo $pkcs12;
exit;
}
public function extractCertificateInfo($certificatePem) {
try {
// Parse the certificate from PEM format
$certificateResource = openssl_x509_read($certificatePem);
if ($certificateResource === false) {
throw new Exception("Failed to parse certificate: " . openssl_error_string());
}
// Extract certificate details
$certificateDetails = openssl_x509_parse($certificateResource);
if ($certificateDetails === false) {
throw new Exception("Failed to extract certificate details: " . openssl_error_string());
}
// Return the certificate details
return $certificateDetails;
} catch (Exception $e) {
// Handle errors appropriately (e.g., log, display a message)
error_log("Certificate processing error: " . $e->getMessage());
return false; // Or throw the exception, depending on your error handling
}
}
/**
* Save data from the SSO key edit form into the database.
* @param string $keyUUID UUID of the cryptographic key
* @throws Exception
*/
public function save(string $keyUUID, string $mode = 'save')
{
global $gCurrentSession, $gCurrentOrgId;
// check form field input and sanitized it from malicious content
$keyEditForm = $gCurrentSession->getFormObject($_POST['adm_csrf_token']);
$formValues = $keyEditForm->validate($_POST);
$ssoKey = new Key($this->db);
if (!empty($keyUUID)) {
$ssoKey->readDataByUuid($keyUUID);
}
// If no key or cert exists yet, make sure it is generated
if ($ssoKey->isNewRecord() || empty($ssoKey->getValue('key_private'))) {
$mode = 'key';
} elseif (empty($ssoKey->getValue('key_certificate')) && ($mode != 'key')) {
$mode = 'cert';
}
switch ($mode) {
case 'key':
// 1. Create a new key for the selected algorithm
$key_algorithm = $formValues['key_algorithm'];
$newKey = $this->generateKey($key_algorithm);
$ssoKey->setValue('key_algorithm', $key_algorithm);
$ssoKey->setValue('key_private', $newKey['private_key']);
$ssoKey->setValue('key_public', $newKey['public_key']);
// fall-through
case 'cert':
unset($formValues['key_algorithm']);
unset($formValues['key_public']);
unset($formValues['key_private']);
// 2. Sign the existing or new key for a certificate
$key_algorithm = $ssoKey->getValue('key_algorithm');
$privateKey = $ssoKey->getValue('key_private');
$privateKey = openssl_pkey_get_private($privateKey);
$csrData = [
"countryName" => $formValues['cert_country'],
"stateOrProvinceName" => $formValues['cert_state'],
"localityName" => $formValues['cert_locality'],
"organizationName" => $formValues['cert_org'],
"organizationalUnitName" => $formValues['cert_orgunit'],
"commonName" => $formValues['cert_common_name'], // Your IdP domain
"emailAddress" => $formValues['cert_admin_email'],
];
$certificatePEM = $this->generateCertificate($ssoKey->getValue('key_private'), $csrData, $key_algorithm, $formValues['key_expires_at']);
$ssoKey->setValue('key_certificate', $certificatePEM);
$ssoKey->setValue('key_expires_at', $formValues['key_expires_at']);
// fall-through
case 'save':
unset($formValues['key_certificate']);
unset($formValues['key_expires_at']);
// 3. Handle all attributes (name, etc.) that do not need the key or cert to be re-generated
// write form values in menu object
foreach ($formValues as $key => $value) {
if (str_starts_with($key, 'key_')) {
$ssoKey->setValue($key, $value);
}
}
$ssoKey->setValue('key_org_id', $gCurrentOrgId);
}
$ssoKey->save();
}
public function exportCertificate(string $keyUUID) {
$ssoKey = new Key($this->db);
$ssoKey->readDataByUuid($keyUUID);
$certificate = $ssoKey->getValue('key_certificate');
$filename = FileSystemUtils::getSanitizedPathEntry($ssoKey->getValue('key_name'));
// Set headers for file download
header('Content-Type: application/x-pem-file');
header('Content-Disposition: attachment; filename="' . $filename . '_Certificate.pem"');
header('Content-Length: ' . strlen($certificate));
// Output the certificate contents
echo $certificate;
exit;
}
}