1 /* Icinga 2 | (c) 2012 Icinga GmbH | GPLv2+ */
2 
3 #include "remote/pkiutility.hpp"
4 #include "remote/apilistener.hpp"
5 #include "base/defer.hpp"
6 #include "base/io-engine.hpp"
7 #include "base/logger.hpp"
8 #include "base/application.hpp"
9 #include "base/tcpsocket.hpp"
10 #include "base/tlsutility.hpp"
11 #include "base/console.hpp"
12 #include "base/tlsstream.hpp"
13 #include "base/tcpsocket.hpp"
14 #include "base/json.hpp"
15 #include "base/utility.hpp"
16 #include "base/convert.hpp"
17 #include "base/exception.hpp"
18 #include "remote/jsonrpc.hpp"
19 #include <fstream>
20 #include <iostream>
21 #include <boost/asio/ssl/context.hpp>
22 #include <boost/filesystem/path.hpp>
23 
24 using namespace icinga;
25 
NewCa()26 int PkiUtility::NewCa()
27 {
28 	String caDir = ApiListener::GetCaDir();
29 	String caCertFile = caDir + "/ca.crt";
30 	String caKeyFile = caDir + "/ca.key";
31 
32 	if (Utility::PathExists(caCertFile) && Utility::PathExists(caKeyFile)) {
33 		Log(LogWarning, "cli")
34 			<< "CA files '" << caCertFile << "' and '" << caKeyFile << "' already exist.";
35 		return 1;
36 	}
37 
38 	Utility::MkDirP(caDir, 0700);
39 
40 	MakeX509CSR("Icinga CA", caKeyFile, String(), caCertFile, true);
41 
42 	return 0;
43 }
44 
NewCert(const String & cn,const String & keyfile,const String & csrfile,const String & certfile)45 int PkiUtility::NewCert(const String& cn, const String& keyfile, const String& csrfile, const String& certfile)
46 {
47 	try {
48 		MakeX509CSR(cn, keyfile, csrfile, certfile);
49 	} catch(std::exception&) {
50 		return 1;
51 	}
52 
53 	return 0;
54 }
55 
SignCsr(const String & csrfile,const String & certfile)56 int PkiUtility::SignCsr(const String& csrfile, const String& certfile)
57 {
58 	char errbuf[256];
59 
60 	InitializeOpenSSL();
61 
62 	BIO *csrbio = BIO_new_file(csrfile.CStr(), "r");
63 	X509_REQ *req = PEM_read_bio_X509_REQ(csrbio, nullptr, nullptr, nullptr);
64 
65 	if (!req) {
66 		ERR_error_string_n(ERR_peek_error(), errbuf, sizeof errbuf);
67 		Log(LogCritical, "SSL")
68 			<< "Could not read X509 certificate request from '" << csrfile << "': " << ERR_peek_error() << ", \"" << errbuf << "\"";
69 		return 1;
70 	}
71 
72 	BIO_free(csrbio);
73 
74 	std::shared_ptr<EVP_PKEY> pubkey = std::shared_ptr<EVP_PKEY>(X509_REQ_get_pubkey(req), EVP_PKEY_free);
75 	std::shared_ptr<X509> cert = CreateCertIcingaCA(pubkey.get(), X509_REQ_get_subject_name(req));
76 
77 	X509_REQ_free(req);
78 
79 	WriteCert(cert, certfile);
80 
81 	return 0;
82 }
83 
FetchCert(const String & host,const String & port)84 std::shared_ptr<X509> PkiUtility::FetchCert(const String& host, const String& port)
85 {
86 	Shared<boost::asio::ssl::context>::Ptr sslContext;
87 
88 	try {
89 		sslContext = MakeAsioSslContext();
90 	} catch (const std::exception& ex) {
91 		Log(LogCritical, "pki")
92 			<< "Cannot make SSL context.";
93 		Log(LogDebug, "pki")
94 			<< "Cannot make SSL context:\n"  << DiagnosticInformation(ex);
95 		return std::shared_ptr<X509>();
96 	}
97 
98 	auto stream (Shared<AsioTlsStream>::Make(IoEngine::Get().GetIoContext(), *sslContext, host));
99 
100 	try {
101 		Connect(stream->lowest_layer(), host, port);
102 	} catch (const std::exception& ex) {
103 		Log(LogCritical, "pki")
104 			<< "Cannot connect to host '" << host << "' on port '" << port << "'";
105 		Log(LogDebug, "pki")
106 			<< "Cannot connect to host '" << host << "' on port '" << port << "':\n" << DiagnosticInformation(ex);
107 		return std::shared_ptr<X509>();
108 	}
109 
110 	auto& sslConn (stream->next_layer());
111 
112 	try {
113 		sslConn.handshake(sslConn.client);
114 	} catch (const std::exception& ex) {
115 		Log(LogCritical, "pki")
116 			<< "Client TLS handshake failed. (" << ex.what() << ")";
117 		return std::shared_ptr<X509>();
118 	}
119 
120 	Defer shutdown ([&sslConn]() { sslConn.shutdown(); });
121 
122 	return sslConn.GetPeerCertificate();
123 }
124 
WriteCert(const std::shared_ptr<X509> & cert,const String & trustedfile)125 int PkiUtility::WriteCert(const std::shared_ptr<X509>& cert, const String& trustedfile)
126 {
127 	std::ofstream fpcert;
128 	fpcert.open(trustedfile.CStr());
129 	fpcert << CertificateToString(cert);
130 	fpcert.close();
131 
132 	if (fpcert.fail()) {
133 		Log(LogCritical, "pki")
134 			<< "Could not write certificate to file '" << trustedfile << "'.";
135 		return 1;
136 	}
137 
138 	Log(LogInformation, "pki")
139 		<< "Writing certificate to file '" << trustedfile << "'.";
140 
141 	return 0;
142 }
143 
GenTicket(const String & cn,const String & salt,std::ostream & ticketfp)144 int PkiUtility::GenTicket(const String& cn, const String& salt, std::ostream& ticketfp)
145 {
146 	ticketfp << PBKDF2_SHA1(cn, salt, 50000) << "\n";
147 
148 	return 0;
149 }
150 
RequestCertificate(const String & host,const String & port,const String & keyfile,const String & certfile,const String & cafile,const std::shared_ptr<X509> & trustedCert,const String & ticket)151 int PkiUtility::RequestCertificate(const String& host, const String& port, const String& keyfile,
152 	const String& certfile, const String& cafile, const std::shared_ptr<X509>& trustedCert, const String& ticket)
153 {
154 	Shared<boost::asio::ssl::context>::Ptr sslContext;
155 
156 	try {
157 		sslContext = MakeAsioSslContext(certfile, keyfile);
158 	} catch (const std::exception& ex) {
159 		Log(LogCritical, "cli")
160 			<< "Cannot make SSL context for cert path: '" << certfile << "' key path: '" << keyfile << "' ca path: '" << cafile << "'.";
161 		Log(LogDebug, "cli")
162 			<< "Cannot make SSL context for cert path: '" << certfile << "' key path: '" << keyfile << "' ca path: '" << cafile << "':\n"  << DiagnosticInformation(ex);
163 		return 1;
164 	}
165 
166 	auto stream (Shared<AsioTlsStream>::Make(IoEngine::Get().GetIoContext(), *sslContext, host));
167 
168 	try {
169 		Connect(stream->lowest_layer(), host, port);
170 	} catch (const std::exception& ex) {
171 		Log(LogCritical, "cli")
172 			<< "Cannot connect to host '" << host << "' on port '" << port << "'";
173 		Log(LogDebug, "cli")
174 			<< "Cannot connect to host '" << host << "' on port '" << port << "':\n" << DiagnosticInformation(ex);
175 		return 1;
176 	}
177 
178 	auto& sslConn (stream->next_layer());
179 
180 	try {
181 		sslConn.handshake(sslConn.client);
182 	} catch (const std::exception& ex) {
183 		Log(LogCritical, "cli")
184 			<< "Client TLS handshake failed: " << DiagnosticInformation(ex, false);
185 		return 1;
186 	}
187 
188 	Defer shutdown ([&sslConn]() { sslConn.shutdown(); });
189 
190 	auto peerCert (sslConn.GetPeerCertificate());
191 
192 	if (X509_cmp(peerCert.get(), trustedCert.get())) {
193 		Log(LogCritical, "cli", "Peer certificate does not match trusted certificate.");
194 		return 1;
195 	}
196 
197 	Dictionary::Ptr params = new Dictionary({
198 		{ "ticket", String(ticket) }
199 	});
200 
201 	String msgid = Utility::NewUniqueID();
202 
203 	Dictionary::Ptr request = new Dictionary({
204 		{ "jsonrpc", "2.0" },
205 		{ "id", msgid },
206 		{ "method", "pki::RequestCertificate" },
207 		{ "params", params }
208 	});
209 
210 	Dictionary::Ptr response;
211 
212 	try {
213 		JsonRpc::SendMessage(stream, request);
214 		stream->flush();
215 
216 		for (;;) {
217 			response = JsonRpc::DecodeMessage(JsonRpc::ReadMessage(stream));
218 
219 			if (response && response->Contains("error")) {
220 				Log(LogCritical, "cli", "Could not fetch valid response. Please check the master log (notice or debug).");
221 #ifdef I2_DEBUG
222 				/* we shouldn't expose master errors to the user in production environments */
223 				Log(LogCritical, "cli", response->Get("error"));
224 #endif /* I2_DEBUG */
225 				return 1;
226 			}
227 
228 			if (response && (response->Get("id") != msgid))
229 				continue;
230 
231 			break;
232 		}
233 	} catch (...) {
234 		Log(LogCritical, "cli", "Could not fetch valid response. Please check the master log.");
235 		return 1;
236 	}
237 
238 	if (!response) {
239 		Log(LogCritical, "cli", "Could not fetch valid response. Please check the master log.");
240 		return 1;
241 	}
242 
243 	Dictionary::Ptr result = response->Get("result");
244 
245 	if (result->Contains("ca")) {
246 		try {
247 			StringToCertificate(result->Get("ca"));
248 		} catch (const std::exception& ex) {
249 			Log(LogCritical, "cli")
250 				<< "Could not write CA file: " << DiagnosticInformation(ex, false);
251 			return 1;
252 		}
253 
254 		Log(LogInformation, "cli")
255 			<< "Writing CA certificate to file '" << cafile << "'.";
256 
257 		std::ofstream fpca;
258 		fpca.open(cafile.CStr());
259 		fpca << result->Get("ca");
260 		fpca.close();
261 
262 		if (fpca.fail()) {
263 			Log(LogCritical, "cli")
264 				<< "Could not open CA certificate file '" << cafile << "' for writing.";
265 			return 1;
266 		}
267 	}
268 
269 	if (result->Contains("error")) {
270 		LogSeverity severity;
271 
272 		Value vstatus;
273 
274 		if (!result->Get("status_code", &vstatus))
275 			vstatus = 1;
276 
277 		int status = vstatus;
278 
279 		if (status == 1)
280 			severity = LogCritical;
281 		else {
282 			severity = LogInformation;
283 			Log(severity, "cli", "!!!!!!");
284 		}
285 
286 		Log(severity, "cli")
287 			<< "!!! " << result->Get("error");
288 
289 		if (status == 1)
290 			return 1;
291 		else {
292 			Log(severity, "cli", "!!!!!!");
293 			return 0;
294 		}
295 	}
296 
297 	try {
298 		StringToCertificate(result->Get("cert"));
299 	} catch (const std::exception& ex) {
300 		Log(LogCritical, "cli")
301 			<< "Could not write certificate file: " << DiagnosticInformation(ex, false);
302 		return 1;
303 	}
304 
305 	Log(LogInformation, "cli")
306 		<< "Writing signed certificate to file '" << certfile << "'.";
307 
308 	std::ofstream fpcert;
309 	fpcert.open(certfile.CStr());
310 	fpcert << result->Get("cert");
311 	fpcert.close();
312 
313 	if (fpcert.fail()) {
314 		Log(LogCritical, "cli")
315 			<< "Could not write certificate to file '" << certfile << "'.";
316 		return 1;
317 	}
318 
319 	return 0;
320 }
321 
GetCertificateInformation(const std::shared_ptr<X509> & cert)322 String PkiUtility::GetCertificateInformation(const std::shared_ptr<X509>& cert) {
323 	BIO *out = BIO_new(BIO_s_mem());
324 	String pre;
325 
326 	pre = "\n Version:             " + Convert::ToString(GetCertificateVersion(cert));
327 	BIO_write(out, pre.CStr(), pre.GetLength());
328 
329 	pre = "\n Subject:             ";
330 	BIO_write(out, pre.CStr(), pre.GetLength());
331 	X509_NAME_print_ex(out, X509_get_subject_name(cert.get()), 0, XN_FLAG_ONELINE & ~ASN1_STRFLGS_ESC_MSB);
332 
333 	pre = "\n Issuer:              ";
334 	BIO_write(out, pre.CStr(), pre.GetLength());
335 	X509_NAME_print_ex(out, X509_get_issuer_name(cert.get()), 0, XN_FLAG_ONELINE & ~ASN1_STRFLGS_ESC_MSB);
336 
337 	pre = "\n Valid From:          ";
338 	BIO_write(out, pre.CStr(), pre.GetLength());
339 	ASN1_TIME_print(out, X509_get_notBefore(cert.get()));
340 
341 	pre = "\n Valid Until:         ";
342 	BIO_write(out, pre.CStr(), pre.GetLength());
343 	ASN1_TIME_print(out, X509_get_notAfter(cert.get()));
344 
345 	pre = "\n Serial:              ";
346 	BIO_write(out, pre.CStr(), pre.GetLength());
347 	ASN1_INTEGER *asn1_serial = X509_get_serialNumber(cert.get());
348 	for (int i = 0; i < asn1_serial->length; i++) {
349 		BIO_printf(out, "%02x%c", asn1_serial->data[i], ((i + 1 == asn1_serial->length) ? '\n' : ':'));
350 	}
351 
352 	pre = "\n Signature Algorithm: " + GetSignatureAlgorithm(cert);
353 	BIO_write(out, pre.CStr(), pre.GetLength());
354 
355 	pre = "\n Subject Alt Names:   " + GetSubjectAltNames(cert)->Join(" ");
356 	BIO_write(out, pre.CStr(), pre.GetLength());
357 
358 	pre = "\n Fingerprint:         ";
359 	BIO_write(out, pre.CStr(), pre.GetLength());
360 	unsigned char md[EVP_MAX_MD_SIZE];
361 	unsigned int diglen;
362 	X509_digest(cert.get(), EVP_sha256(), md, &diglen);
363 
364 	char *data;
365 	long length = BIO_get_mem_data(out, &data);
366 
367 	std::stringstream info;
368 	info << String(data, data + length);
369 
370 	BIO_free(out);
371 
372 	for (unsigned int i = 0; i < diglen; i++) {
373 		info << std::setfill('0') << std::setw(2) << std::uppercase
374 			<< std::hex << static_cast<int>(md[i]) << ' ';
375 	}
376 	info << '\n';
377 
378 	return info.str();
379 }
380 
CollectRequestHandler(const Dictionary::Ptr & requests,const String & requestFile)381 static void CollectRequestHandler(const Dictionary::Ptr& requests, const String& requestFile)
382 {
383 	Dictionary::Ptr request = Utility::LoadJsonFile(requestFile);
384 
385 	if (!request)
386 		return;
387 
388 	Dictionary::Ptr result = new Dictionary();
389 
390 	namespace fs = boost::filesystem;
391 	fs::path file(requestFile.Begin(), requestFile.End());
392 	String fingerprint = file.stem().string();
393 
394 	String certRequestText = request->Get("cert_request");
395 	result->Set("cert_request", certRequestText);
396 
397 	Value vcertResponseText;
398 
399 	if (request->Get("cert_response", &vcertResponseText)) {
400 		String certResponseText = vcertResponseText;
401 		result->Set("cert_response", certResponseText);
402 	}
403 
404 	std::shared_ptr<X509> certRequest = StringToCertificate(certRequestText);
405 
406 /* XXX (requires OpenSSL >= 1.0.0)
407 	time_t now;
408 	time(&now);
409 	ASN1_TIME *tm = ASN1_TIME_adj(nullptr, now, 0, 0);
410 
411 	int day, sec;
412 	ASN1_TIME_diff(&day, &sec, tm, X509_get_notBefore(certRequest.get()));
413 
414 	result->Set("timestamp",  static_cast<double>(now) + day * 24 * 60 * 60 + sec); */
415 
416 	BIO *out = BIO_new(BIO_s_mem());
417 	ASN1_TIME_print(out, X509_get_notBefore(certRequest.get()));
418 
419 	char *data;
420 	long length;
421 	length = BIO_get_mem_data(out, &data);
422 
423 	result->Set("timestamp", String(data, data + length));
424 	BIO_free(out);
425 
426 	out = BIO_new(BIO_s_mem());
427 	X509_NAME_print_ex(out, X509_get_subject_name(certRequest.get()), 0, XN_FLAG_ONELINE & ~ASN1_STRFLGS_ESC_MSB);
428 
429 	length = BIO_get_mem_data(out, &data);
430 
431 	result->Set("subject", String(data, data + length));
432 	BIO_free(out);
433 
434 	requests->Set(fingerprint, result);
435 }
436 
GetCertificateRequests(bool removed)437 Dictionary::Ptr PkiUtility::GetCertificateRequests(bool removed)
438 {
439 	Dictionary::Ptr requests = new Dictionary();
440 
441 	String requestDir = ApiListener::GetCertificateRequestsDir();
442 	String ext = "json";
443 
444 	if (removed)
445 		ext = "removed";
446 
447 	if (Utility::PathExists(requestDir))
448 		Utility::Glob(requestDir + "/*." + ext, [requests](const String& requestFile) { CollectRequestHandler(requests, requestFile); }, GlobFile);
449 
450 	return requests;
451 }
452 
453