Passed
Push — master ( dde02d...9b6483 )
by Roeland
08:47 queued 10s
created

Manager::logOpensslError()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 0
dl 0
loc 6
rs 10
c 0
b 0
f 0
1
<?php
2
declare(strict_types=1);
3
/**
4
 * @copyright Copyright (c) 2016 Lukas Reschke <[email protected]>
5
 *
6
 * @author Bjoern Schiessle <[email protected]>
7
 * @author Joas Schilling <[email protected]>
8
 * @author Lukas Reschke <[email protected]>
9
 *
10
 * @license GNU AGPL version 3 or any later version
11
 *
12
 * This program is free software: you can redistribute it and/or modify
13
 * it under the terms of the GNU Affero General Public License as
14
 * published by the Free Software Foundation, either version 3 of the
15
 * License, or (at your option) any later version.
16
 *
17
 * This program is distributed in the hope that it will be useful,
18
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20
 * GNU Affero General Public License for more details.
21
 *
22
 * You should have received a copy of the GNU Affero General Public License
23
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
24
 *
25
 */
26
27
namespace OC\Security\IdentityProof;
28
29
use OC\Files\AppData\Factory;
30
use OCP\Files\IAppData;
31
use OCP\IConfig;
32
use OCP\ILogger;
33
use OCP\IUser;
34
use OCP\Security\ICrypto;
35
36
class Manager {
37
	/** @var IAppData */
38
	private $appData;
39
	/** @var ICrypto */
40
	private $crypto;
41
	/** @var IConfig */
42
	private $config;
43
	/** @var ILogger */
44
	private $logger;
45
46
	public function __construct(Factory $appDataFactory,
47
								ICrypto $crypto,
48
								IConfig $config,
49
								ILogger $logger
50
	) {
51
		$this->appData = $appDataFactory->get('identityproof');
52
		$this->crypto = $crypto;
53
		$this->config = $config;
54
		$this->logger = $logger;
55
	}
56
57
	/**
58
	 * Calls the openssl functions to generate a public and private key.
59
	 * In a separate function for unit testing purposes.
60
	 *
61
	 * @return array [$publicKey, $privateKey]
62
	 * @throws \RuntimeException
63
	 */
64
	protected function generateKeyPair(): array {
65
		$config = [
66
			'digest_alg' => 'sha512',
67
			'private_key_bits' => 2048,
68
		];
69
70
		// Generate new key
71
		$res = openssl_pkey_new($config);
72
73
		if ($res === false) {
74
			$this->logOpensslError();
75
			throw new \RuntimeException('OpenSSL reported a problem');
76
		}
77
78
		if (openssl_pkey_export($res, $privateKey, null, $config) === false) {
79
			$this->logOpensslError();
80
			throw new \RuntimeException('OpenSSL reported a problem');
81
		}
82
83
		// Extract the public key from $res to $pubKey
84
		$publicKey = openssl_pkey_get_details($res);
85
		$publicKey = $publicKey['key'];
86
87
		return [$publicKey, $privateKey];
88
	}
89
90
	/**
91
	 * Generate a key for a given ID
92
	 * Note: If a key already exists it will be overwritten
93
	 *
94
	 * @param string $id key id
95
	 * @return Key
96
	 * @throws \RuntimeException
97
	 */
98
	protected function generateKey(string $id): Key {
99
		list($publicKey, $privateKey) = $this->generateKeyPair();
100
101
		// Write the private and public key to the disk
102
		try {
103
			$this->appData->newFolder($id);
104
		} catch (\Exception $e) {}
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
105
		$folder = $this->appData->getFolder($id);
106
		$folder->newFile('private')
107
			->putContent($this->crypto->encrypt($privateKey));
108
		$folder->newFile('public')
109
			->putContent($publicKey);
110
111
		return new Key($publicKey, $privateKey);
112
	}
113
114
	/**
115
	 * Get key for a specific id
116
	 *
117
	 * @param string $id
118
	 * @return Key
119
	 * @throws \RuntimeException
120
	 */
121
	protected function retrieveKey(string $id): Key {
122
		try {
123
			$folder = $this->appData->getFolder($id);
124
			$privateKey = $this->crypto->decrypt(
125
				$folder->getFile('private')->getContent()
126
			);
127
			$publicKey = $folder->getFile('public')->getContent();
128
			return new Key($publicKey, $privateKey);
129
		} catch (\Exception $e) {
130
			return $this->generateKey($id);
131
		}
132
	}
133
134
	/**
135
	 * Get public and private key for $user
136
	 *
137
	 * @param IUser $user
138
	 * @return Key
139
	 * @throws \RuntimeException
140
	 */
141
	public function getKey(IUser $user): Key {
142
		$uid = $user->getUID();
143
		return $this->retrieveKey('user-' . $uid);
144
	}
145
146
	/**
147
	 * Get instance wide public and private key
148
	 *
149
	 * @return Key
150
	 * @throws \RuntimeException
151
	 */
152
	public function getSystemKey(): Key {
153
		$instanceId = $this->config->getSystemValue('instanceid', null);
154
		if ($instanceId === null) {
155
			throw new \RuntimeException('no instance id!');
156
		}
157
		return $this->retrieveKey('system-' . $instanceId);
158
	}
159
160
	private function logOpensslError(): void {
161
		$errors = [];
162
		while ($error = openssl_error_string()) {
163
			$errors[] = $error;
164
		}
165
		$this->logger->critical('Something is wrong with your openssl setup: ' . implode(', ', $errors));
166
	}
167
168
169
}
170