本文整理汇总了Python中ssl.cert_time_to_seconds函数的典型用法代码示例。如果您正苦于以下问题:Python cert_time_to_seconds函数的具体用法?Python cert_time_to_seconds怎么用?Python cert_time_to_seconds使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了cert_time_to_seconds函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: update
def update(self):
"""Fetch the certificate information."""
try:
ctx = ssl.create_default_context()
sock = ctx.wrap_socket(
socket.socket(), server_hostname=self.server_name)
sock.settimeout(TIMEOUT)
sock.connect((self.server_name, self.server_port))
except socket.gaierror:
_LOGGER.error("Cannot resolve hostname: %s", self.server_name)
return
except socket.timeout:
_LOGGER.error(
"Connection timeout with server: %s", self.server_name)
return
except OSError:
_LOGGER.error("Cannot connect to %s", self.server_name)
return
try:
cert = sock.getpeercert()
except OSError:
_LOGGER.error("Cannot fetch certificate from %s", self.server_name)
return
ts_seconds = ssl.cert_time_to_seconds(cert['notAfter'])
timestamp = datetime.datetime.fromtimestamp(ts_seconds)
expiry = timestamp - datetime.datetime.today()
self._state = expiry.days
示例2: probe
def probe(self):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(self.timeout)
ssl_sock = ssl.wrap_socket(s)
try:
ssl_sock.connect((self.domain, self.port))
addr = ssl_sock.getpeername()
certificate = ssl.get_server_certificate(addr=addr)
except socket.timeout:
raise IOError("timeout connecting to %s" % self.domain)
except:
# provide a nice error message to caller
raise IOError("cannot connect to %s" % self.domain)
finally:
ssl_sock.close()
p1 = subprocess.Popen(["openssl", "x509", "-noout", "-enddate"],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE)
stdout, _ = p1.communicate(certificate)
_, expirydate = stdout.split("=")
expiry_date_in_seconds = ssl.cert_time_to_seconds(expirydate.strip())
expiry_in_seconds = timedelta_to_seconds(datetime.fromtimestamp(expiry_date_in_seconds) - datetime.now())
return nagiosplugin.Metric("expiry",
value=expiry_in_seconds,
uom="s",
context="certificate_expiry")
示例3: check_ssl_valid_date
def check_ssl_valid_date(self, url_data, cert):
"""Check if the certificate is still valid, or if configured check
if it's at least a number of days valid.
"""
import ssl
try:
notAfter = ssl.cert_time_to_seconds(cert['notAfter'])
except ValueError as msg:
msg = _('Invalid SSL certficate "notAfter" value %r') % cert['notAfter']
url_data.add_warning(msg)
return
curTime = time.time()
# Calculate seconds until certifcate expires. Can be negative if
# the certificate is already expired.
secondsValid = notAfter - curTime
args = dict(expire=cert['notAfter'])
if secondsValid < 0:
msg = _('SSL certficate is expired on %(expire)s.')
url_data.add_warning(msg % args)
else:
args['valid'] = strformat.strduration_long(secondsValid)
if secondsValid < self.warn_ssl_cert_secs_valid:
msg = _('SSL certificate expires on %(expire)s and is only %(valid)s valid.')
url_data.add_warning(msg % args)
else:
msg = _('SSL certificate expires on %(expire)s and is %(valid)s valid.')
url_data.add_info(msg % args)
示例4: from_ssl_socket
def from_ssl_socket(cls, ssl_socket):
"""Load certificate data from an SSL socket.
"""
cert = cls()
try:
data = ssl_socket.getpeercert()
except AttributeError:
# PyPy doesn't have .getppercert
return cert
logger.debug("Certificate data from ssl module: {0!r}".format(data))
if not data:
return cert
cert.validated = True
cert.subject_name = data.get("subject")
cert.alt_names = defaultdict(list)
if "subjectAltName" in data:
for name, value in data["subjectAltName"]:
cert.alt_names[name].append(value)
if "notAfter" in data:
tstamp = ssl.cert_time_to_seconds(data["notAfter"])
cert.not_after = datetime.utcfromtimestamp(tstamp)
if sys.version_info.major < 3:
cert._decode_names() # pylint: disable=W0212
cert.common_names = []
if cert.subject_name:
for part in cert.subject_name:
for name, value in part:
if name == "commonName":
cert.common_names.append(value)
return cert
示例5: is_ssl_expiring
def is_ssl_expiring(self, ip_address, port=443, ssl_expiration_days=0):
# Check site's cert
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ssl_sock = ssl.wrap_socket(s, ca_certs=get_certs_file(), cert_reqs=ssl.CERT_REQUIRED)
try:
ssl_sock.connect((ip_address, port))
cert = ssl_sock.getpeercert()
cert_expiration = ssl.cert_time_to_seconds(cert["notAfter"])
exp = cert_expiration - time.time()
if exp <= 0: return 1
elif exp <= (ssl_expiration_days * 24 * 60 * 60): return 2
except:
return 3
finally:
ssl_sock.shutdown(socket.SHUT_RDWR)
ssl_sock.close()
return 0
示例6: gen_gmtime_dates
def gen_gmtime_dates():
""" Generate the dates used for this run.
Creating openssl gmtime dates may be simpler than this.
"""
gmtfmt = "%b %d %H:%M:%S %Y GMT"
ok_stamp = ssl.cert_time_to_seconds(
time.strftime(gmtfmt, time.gmtime())) - (60*60*24)
two_days_ago_stamp = ok_stamp - (60*60*48)
two_days_ago_end_stamp = two_days_ago_stamp + (60*60*24)
future_stamp = ok_stamp + (60*60*24*365*1)
future_end_stamp = future_stamp + (60*60*24*365*1)
return dict(OK_NOW=gmc(ok_stamp),
OLD=gmc(two_days_ago_stamp),
OLD_END=gmc(two_days_ago_end_stamp),
FUTURE=gmc(future_stamp),
FUTURE_END=gmc(future_end_stamp))
示例7: _validate_certificate
def _validate_certificate(self, cert):
now = time.time()
# Refuse to connect if there's no certificate.
if cert is None:
err = "no SSL certificate for %s" % (self.host,)
raise socket.error(err)
# Refuse to connect if the certificate has expired.
if "notAfter" in cert:
if ssl.cert_time_to_seconds(cert["notAfter"]) < now:
err = "expired SSL certificate for %s" % (self.host,)
raise socket.error(err)
# Refuse to connect if the certificate is missing subject data.
if "subject" not in cert:
err = "malformed SSL certificate for %s" % (self.host,)
raise socket.error(err)
# Try to match the certificate to the requested host.
if not self._validate_certificate_hostname(cert):
err = "invalid SSL certificate for %s" % (self.host,)
raise socket.error(err)
示例8: gen_gmtime_dates
def gen_gmtime_dates():
""" Generate the dates used for this run.
Creating openssl gmtime dates may be simpler than this.
"""
gmtfmt = "%b %d %H:%M:%S %Y GMT"
ok_stamp = ssl.cert_time_to_seconds(
time.strftime(gmtfmt, time.gmtime())) - (60*60*24)
two_days_ago_stamp = ok_stamp - (60*60*48)
two_days_ago_end_stamp = two_days_ago_stamp + (60*60*24)
# Make future certs only +300 days, so we have a time overlap
# between currently valid certs (1 year) and these futuristic certs
future_stamp = ok_stamp + (60*60*24*365*1)
future_end_stamp = future_stamp + (60*60*24*365*2)
return dict(OK_NOW=gmc(ok_stamp),
OLD=gmc(two_days_ago_stamp),
OLD_END=gmc(two_days_ago_end_stamp),
FUTURE=gmc(future_stamp),
FUTURE_END=gmc(future_end_stamp))
示例9: expiring_certificate
def expiring_certificate(connection, expiry_days):
'''
Pass in the connection and number of days. Verify that the expiry date isn't
within the specified number of days
'''
# Convert the presented certificate's expiry date into a datetime object.
# This could be done in one line, but for readability, we'll do this over three
expiry_date = connection.getpeercert()['notAfter']
expiry_epoch = ssl.cert_time_to_seconds(expiry_date)
expires = datetime.datetime.fromtimestamp(expiry_epoch)
# Create a datetime object of the specified date
now = datetime.datetime.now()
specified_date = now + datetime.timedelta(days=expiry_days)
# this evalutes to True if the certificate expires before the specified
# expiry date.
return expires < specified_date
示例10: check_ssl_valid_date
def check_ssl_valid_date(self, url_data, ssl_sock, cert):
"""Check if the certificate is still valid, or if configured check
if it's at least a number of days valid.
"""
import ssl
try:
notAfter = ssl.cert_time_to_seconds(cert['notAfter'])
except ValueError as msg:
msg = _('invalid certficate "notAfter" value %r') % cert['notAfter']
self.add_ssl_warning(url_data, ssl_sock, msg)
return
curTime = time.time()
# Calculate seconds until certifcate expires. Can be negative if
# the certificate is already expired.
secondsValid = notAfter - curTime
if secondsValid < 0:
msg = _('certficate is expired on %s') % cert['notAfter']
self.add_ssl_warning(url_data, ssl_sock, msg)
elif secondsValid < self.warn_ssl_cert_secs_valid:
strSecondsValid = strformat.strduration_long(secondsValid)
msg = _('certificate is only %s valid') % strSecondsValid
self.add_ssl_warning(url_data, ssl_sock, msg)
示例11: __verifycert
def __verifycert(self, cert, hostname):
"""Verify that cert (in socket.getpeercert() format) matches hostname.
CRLs are not handled.
Returns error message if any problems are found and None on success."""
errstr = "CA Cert verifying failed: "
if not cert:
return ('%s no certificate received'% errstr)
dnsname = hostname.lower()
certnames = []
# cert expired?
notafter = cert.get('notAfter')
if notafter:
if time.time() >= cert_time_to_seconds(notafter):
return '%s certificate expired %s'% (errstr, notafter)
# First read commonName
for s in cert.get('subject', []):
key, value = s[0]
if key == 'commonName':
certnames.append(value.lower())
if len(certnames) == 0:
return ('%s no commonName found in certificate'% errstr)
# Then read subjectAltName
for key, value in cert.get('subjectAltName', []):
if key == 'DNS':
certnames.append(value.lower())
# And finally try to match hostname with one of these names
for certname in certnames:
if (certname == dnsname or
'.' in dnsname and certname == '*.' + dnsname.split('.', 1)[1]):
return None
return ('%s no matching domain name found in certificate'% errstr)
示例12: check_validation
def check_validation(host):
now = time.time()
context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
context.verify_mode = ssl.CERT_REQUIRED
context.check_hostname = True
context.load_default_certs()
conn = context.wrap_socket(socket.socket(socket.AF_INET),server_hostname=host)
conn.connect((host, 443))
cert = conn.getpeercert()
ttl = ssl.cert_time_to_seconds(cert['notAfter']) - now
print(ttl)
print(ttl/3600/24)
k = host.split('.')[0]
if ttl < 0:
push_metrics("trapper.ssl-certificate.{0}.valid".format(k), 2)
else:
push_metrics("trapper.ssl-certificate.{0}.valid".format(k), 1)
push_metrics("trapper.ssl-certificate.{0}.days".format(k), round(ttl/3600/24, 2))
示例13: _cert_expiration_analysis
def _cert_expiration_analysis(self, url, domain):
cert, cert_der, cipher = self._get_cert(url, domain)
try:
exp_date = gmtime(ssl.cert_time_to_seconds(cert['notAfter']))
except ValueError:
msg = 'Invalid SSL certificate date format.'
om.out.debug(msg)
except KeyError:
msg = 'SSL certificate does not have notAfter field.'
om.out.debug(msg)
else:
expire_days = (date(exp_date.tm_year, exp_date.tm_mon,
exp_date.tm_mday) - date.today()).days
if expire_days < self._min_expire_days:
desc = 'The certificate for "%s" will expire soon.' % domain
i = Info('Soon to expire SSL certificate', desc, 1, self.get_name())
i.set_url(url)
self.kb_append(self, 'ssl_soon_expire', i)
示例14: _verifycert
def _verifycert(self, cert, hostname):
"""Verify that cert (in socket.getpeercert() format) matches hostname.
CRLs are not handled.
Returns error message if any problems are found and None on success.
"""
if not cert:
return "no certificate received"
dnsname = hostname.lower()
certnames = []
# cert expired?
notafter = cert.get("notAfter")
if notafter:
if time.time() >= ssl.cert_time_to_seconds(notafter):
return ("server certificate error: certificate expired %s") % notafter
# First read commonName
for s in cert.get("subject", []):
key, value = s[0]
if key == "commonName":
certnames.append(value.lower())
if len(certnames) == 0:
return "no commonName found in certificate"
# Then read subjectAltName
for key, value in cert.get("subjectAltName", []):
if key == "DNS":
certnames.append(value.lower())
# And finally try to match hostname with one of these names
for certname in certnames:
if certname == dnsname or "." in dnsname and certname == "*." + dnsname.split(".", 1)[1]:
return None
return "no matching domain name found in certificate"
示例15: gmtime
v.set_url(url)
self.kb_append(self, tag, v)
return
except Exception, e:
om.out.debug(str(e))
return
cert = ssl_sock.getpeercert()
cert_der = ssl_sock.getpeercert(binary_form=True)
cipher = ssl_sock.cipher()
ssl_sock.close()
exp_date = gmtime(ssl.cert_time_to_seconds(cert['notAfter']))
expire_days = (date(exp_date.tm_year, exp_date.tm_mon,
exp_date.tm_mday) - date.today()).days
if expire_days < self._min_expire_days:
desc = 'The certificate for "%s" will expire soon.' % domain
i = Info('Soon to expire SSL certificate', desc, 1, self.get_name())
i.set_url(url)
self.kb_append(self, 'ssl_soon_expire', i)
# Print the SSL information to the log
desc = 'This is the information about the SSL certificate used for'\
' %s site:\n%s' % (domain,
self._dump_ssl_info(cert, cert_der, cipher))
om.out.information(desc)