From 60bcc7b27aa934a0d62033e7152b87d5af638491 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1s=20Touceda?= Date: Wed, 13 Mar 2013 11:09:38 -0300 Subject: Add valid pemfile check before saving the downloaded client cert --- src/leap/services/eip/eipbootstrapper.py | 5 ++++ src/leap/util/certs.py | 47 ++++++++++++++++++++++++++++++++ 2 files changed, 52 insertions(+) (limited to 'src') diff --git a/src/leap/services/eip/eipbootstrapper.py b/src/leap/services/eip/eipbootstrapper.py index 3e4e2063..ec3dfe7b 100644 --- a/src/leap/services/eip/eipbootstrapper.py +++ b/src/leap/services/eip/eipbootstrapper.py @@ -32,6 +32,7 @@ from leap.util.check import leap_assert, leap_assert_type from leap.util.checkerthread import CheckerThread from leap.util.files import check_and_fix_urw_only, get_mtime, mkdir_p from leap.util.request_helpers import get_content +from leap.util.certs import is_valid_pemfile logger = logging.getLogger(__name__) @@ -183,6 +184,10 @@ class EIPBootstrapper(QtCore.QObject): # TODO: check certificate validity + if not is_valid_pemfile(client_cert): + raise Exception(self.tr("The downloaded certificate is not a " + "valid PEM file")) + mkdir_p(os.path.dirname(client_cert_path)) with open(client_cert_path, "w") as f: diff --git a/src/leap/util/certs.py b/src/leap/util/certs.py index 7cbd7519..d6065474 100644 --- a/src/leap/util/certs.py +++ b/src/leap/util/certs.py @@ -19,8 +19,14 @@ Implements cert checks and helpers """ +import logging + from OpenSSL import crypto +from leap.util.check import leap_assert + +logger = logging.getLogger(__name__) + def get_digest(cert_data, method): """ @@ -37,3 +43,44 @@ def get_digest(cert_data, method): digest = x509.digest(method).replace(":", "").lower() return digest + + +def can_load_cert_and_pkey(string): + """ + Loads certificate and private key from a buffer, returns True if + everything went well, False otherwise + + @param string: buffer containing the cert and private key + @type string: str or any kind of buffer + + @rtype: bool + """ + + can_load = True + + try: + cert = crypto.load_certificate(crypto.FILETYPE_PEM, string) + key = crypto.load_privatekey(crypto.FILETYPE_PEM, string) + + leap_assert(cert, 'The certificate could not be loaded') + leap_assert(key, 'The private key could not be loaded') + except Exception as e: + can_load = False + logger.error("Something went wrong while trying to load " + "the certificate: %r" % (e,)) + + return can_load + + +def is_valid_pemfile(cert): + """ + Checks that the passed string is a valid pem certificate + + @param cert: String containing pem content + @type cert: str + + @rtype: bool + """ + leap_assert(cert, "We need a cert to load") + + return can_load_cert_and_pkey(cert) -- cgit v1.2.3