bug 1239: fixed typo for title
[cacert-devel.git] / includes / lib / check_weak_key.php
1 <?php /*
2 LibreSSL - CAcert web application
3 Copyright (C) 2004-2011 CAcert Inc.
4
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; version 2 of the License.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
13
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software
16 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17 */
18
19 // failWithId()
20 require_once 'general.php';
21
22
23 /**
24 * Checks whether the given CSR contains a vulnerable key
25 *
26 * @param $csr string
27 * The CSR to be checked
28 * @param $encoding string [optional]
29 * The encoding the CSR is in (for the "-inform" parameter of OpenSSL,
30 * currently only "PEM" (default) or "DER" allowed)
31 * @return string containing the reason if the key is considered weak,
32 * empty string otherwise
33 */
34 function checkWeakKeyCSR($csr, $encoding = "PEM")
35 {
36 $encoding = escapeshellarg($encoding);
37 $status = runCommand("openssl req -inform $encoding -text -noout",
38 $csr, $csrText);
39 if ($status === true) {
40 return failWithId("checkWeakKeyCSR(): Failed to start OpenSSL");
41 }
42
43 if ($status !== 0 || $csrText === "") {
44 return _("I didn't receive a valid Certificate Request. Hit ".
45 "the back button and try again.");
46 }
47
48 return checkWeakKeyText($csrText);
49 }
50
51 /**
52 * Checks whether the given X509 certificate contains a vulnerable key
53 *
54 * @param $cert string
55 * The X509 certificate to be checked
56 * @param $encoding string [optional]
57 * The encoding the certificate is in (for the "-inform" parameter of
58 * OpenSSL, currently only "PEM" (default), "DER" or "NET" allowed)
59 * @return string containing the reason if the key is considered weak,
60 * empty string otherwise
61 */
62 function checkWeakKeyX509($cert, $encoding = "PEM")
63 {
64 $encoding = escapeshellarg($encoding);
65 $status = runCommand("openssl x509 -inform $encoding -text -noout",
66 $cert, $certText);
67 if ($status === true) {
68 return failWithId("checkWeakKeyX509(): Failed to start OpenSSL");
69 }
70
71 if ($status !== 0 || $certText === "") {
72 return _("I didn't receive a valid Certificate Request. Hit ".
73 "the back button and try again.");
74 }
75
76 return checkWeakKeyText($certText);
77 }
78
79 /**
80 * Checks whether the given SPKAC contains a vulnerable key
81 *
82 * @param $spkac string
83 * The SPKAC to be checked
84 * @param $spkacname string [optional]
85 * The name of the variable that contains the SPKAC. The default is
86 * "SPKAC"
87 * @return string containing the reason if the key is considered weak,
88 * empty string otherwise
89 */
90 function checkWeakKeySPKAC($spkac, $spkacname = "SPKAC")
91 {
92 $spkacname = escapeshellarg($spkacname);
93 $status = runCommand("openssl spkac -spkac $spkacname", $spkac, $spkacText);
94 if ($status === true) {
95 return failWithId("checkWeakKeySPKAC(): Failed to start OpenSSL");
96 }
97
98 if ($status !== 0 || $spkacText === "") {
99 return _("I didn't receive a valid Certificate Request. Hit the ".
100 "back button and try again.");
101 }
102
103 return checkWeakKeyText($spkacText);
104 }
105
106 /**
107 * Checks whether the given text representation of a CSR or a SPKAC contains
108 * a weak key
109 *
110 * @param $text string
111 * The text representation of a key as output by the
112 * "openssl <foo> -text -noout" commands
113 * @return string containing the reason if the key is considered weak,
114 * empty string otherwise
115 */
116 function checkWeakKeyText($text)
117 {
118 /* Which public key algorithm? */
119 if (!preg_match('/^\s*Public Key Algorithm: ([^\s]+)$/m', $text,
120 $algorithm))
121 {
122 return failWithId("checkWeakKeyText(): Couldn't extract the ".
123 "public key algorithm used.\nData:\n$text");
124 } else {
125 $algorithm = $algorithm[1];
126 }
127
128
129 if ($algorithm === "rsaEncryption")
130 {
131 if (!preg_match('/^\s*RSA Public Key: \((\d+) bit\)$/m', $text,
132 $keysize))
133 {
134 return failWithId("checkWeakKeyText(): Couldn't parse the RSA ".
135 "key size.\nData:\n$text");
136 } else {
137 $keysize = intval($keysize[1]);
138 }
139
140 if ($keysize < 2048)
141 {
142 return sprintf(_("The keys that you use are very small ".
143 "and therefore insecure. Please generate stronger ".
144 "keys. More information about this issue can be ".
145 "found in %sthe wiki%s"),
146 "<a href='//wiki.cacert.org/WeakKeys#SmallKey'>",
147 "</a>");
148 }
149
150
151 $debianVuln = checkDebianVulnerability($text, $keysize);
152 if ($debianVuln === true)
153 {
154 return sprintf(_("The keys you use have very likely been ".
155 "generated with a vulnerable version of OpenSSL which ".
156 "was distributed by debian. Please generate new keys. ".
157 "More information about this issue can be found in ".
158 "%sthe wiki%s"),
159 "<a href='//wiki.cacert.org/WeakKeys#DebianVulnerability'>",
160 "</a>");
161 } elseif ($debianVuln === false) {
162 // not vulnerable => do nothing
163 } else {
164 return failWithId("checkWeakKeyText(): Something went wrong in".
165 "checkDebianVulnerability().\nKeysize: $keysize\n".
166 "Data:\n$text");
167 }
168
169 if (!preg_match('/^\s*Exponent: (\d+) \(0x[0-9a-fA-F]+\)$/m', $text,
170 $exponent))
171 {
172 return failWithId("checkWeakKeyText(): Couldn't parse the RSA ".
173 "exponent.\nData:\n$text");
174 } else {
175 $exponent = $exponent[1]; // exponent might be very big =>
176 //handle as string using bc*()
177
178 if (bccomp($exponent, "3") === 0)
179 {
180 return sprintf(_("The keys you use might be insecure. ".
181 "Although there is currently no known attack for ".
182 "reasonable encryption schemes, we're being ".
183 "cautious and don't allow certificates for such ".
184 "keys. Please generate stronger keys. More ".
185 "information about this issue can be found in ".
186 "%sthe wiki%s"),
187 "<a href='//wiki.cacert.org/WeakKeys#SmallExponent'>",
188 "</a>");
189 } elseif (!(bccomp($exponent, "65537") >= 0 &&
190 (bccomp($exponent, "100000") === -1 ||
191 // speed things up if way smaller than 2^256
192 bccomp($exponent, bcpow("2", "256")) === -1) )) {
193 // 65537 <= exponent < 2^256 recommended by NIST
194 // not critical but log so we have some statistics about
195 // affected users
196 trigger_error("checkWeakKeyText(): Certificate for ".
197 "unsuitable exponent '$exponent' requested",
198 E_USER_NOTICE);
199 }
200 }
201 }
202
203 /* No weakness found */
204 return "";
205 }
206
207 /**
208 * Reimplement the functionality of the openssl-vulnkey tool
209 *
210 * @param $text string
211 * The text representation of a key as output by the
212 * "openssl <foo> -text -noout" commands
213 * @param $keysize int [optional]
214 * If the key size is already known it can be provided so it doesn't
215 * have to be parsed again. This also skips the check whether the key
216 * is an RSA key => use wisely
217 * @return TRUE if key is vulnerable, FALSE otherwise, NULL in case of error
218 */
219 function checkDebianVulnerability($text, $keysize = 0)
220 {
221 $keysize = intval($keysize);
222
223 if ($keysize === 0)
224 {
225 /* Which public key algorithm? */
226 if (!preg_match('/^\s*Public Key Algorithm: ([^\s]+)$/m', $text,
227 $algorithm))
228 {
229 trigger_error("checkDebianVulnerability(): Couldn't extract ".
230 "the public key algorithm used.\nData:\n$text",
231 E_USER_WARNING);
232 return null;
233 } else {
234 $algorithm = $algorithm[1];
235 }
236
237 if ($algorithm !== "rsaEncryption") return false;
238
239 /* Extract public key size */
240 if (!preg_match('/^\s*RSA Public Key: \((\d+) bit\)$/m', $text,
241 $keysize))
242 {
243 trigger_error("checkDebianVulnerability(): Couldn't parse the ".
244 "RSA key size.\nData:\n$text", E_USER_WARNING);
245 return null;
246 } else {
247 $keysize = intval($keysize[1]);
248 }
249 }
250
251 // $keysize has been made sure to contain an int
252 $blacklist = "/usr/share/openssl-blacklist/blacklist.RSA-$keysize";
253 if (!(is_file($blacklist) && is_readable($blacklist)))
254 {
255 if (in_array($keysize, array(512, 1024, 2048, 4096)))
256 {
257 trigger_error("checkDebianVulnerability(): Blacklist for ".
258 "$keysize bit keys not accessible. Expected at ".
259 "$blacklist", E_USER_ERROR);
260 return null;
261 }
262
263 trigger_error("checkDebianVulnerability(): $blacklist is not ".
264 "readable. Unsupported key size?", E_USER_WARNING);
265 return false;
266 }
267
268
269 /* Extract RSA modulus */
270 if (!preg_match('/^\s*Modulus \(\d+ bit\):\n'.
271 '((?:\s*[0-9a-f][0-9a-f]:(?:\n)?)+[0-9a-f][0-9a-f])$/m',
272 $text, $modulus))
273 {
274 trigger_error("checkDebianVulnerability(): Couldn't extract the ".
275 "RSA modulus.\nData:\n$text", E_USER_WARNING);
276 return null;
277 } else {
278 $modulus = $modulus[1];
279 // strip whitespace and colon leftovers
280 $modulus = str_replace(array(" ", "\t", "\n", ":"), "", $modulus);
281
282 // when using "openssl xxx -text" first byte was 00 in all my test
283 // cases but 00 not present in the "openssl xxx -modulus" output
284 if ($modulus[0] === "0" && $modulus[1] === "0")
285 {
286 $modulus = substr($modulus, 2);
287 } else {
288 trigger_error("checkDebianVulnerability(): First byte is not ".
289 "zero", E_USER_NOTICE);
290 }
291
292 $modulus = strtoupper($modulus);
293 }
294
295
296 /* calculate checksum and look it up in the blacklist */
297 $checksum = substr(sha1("Modulus=$modulus\n"), 20);
298
299 // $checksum and $blacklist should be safe, but just to make sure
300 $checksum = escapeshellarg($checksum);
301 $blacklist = escapeshellarg($blacklist);
302 $debianVuln = runCommand("grep $checksum $blacklist");
303 if ($debianVuln === 0) // grep returned something => it is on the list
304 {
305 return true;
306 } elseif ($debianVuln === 1) {
307 // grep returned nothing
308 return false;
309 } else {
310 trigger_error("checkDebianVulnerability(): Something went wrong ".
311 "when looking up the key with checksum $checksum in the ".
312 "blacklist $blacklist", E_USER_ERROR);
313 return null;
314 }
315
316 // Should not get here
317 return null;
318 }