def active_cert(key): cert_str = pem_format(key) certificate = load_cert_string(cert_str) try: not_before = to_time(str(certificate.get_not_before())) not_after = to_time(str(certificate.get_not_after())) assert not_before < utc_now() assert not_after > utc_now() return True except AssertionError: return False
def _since_epoch(cdate): """ :param cdate: date format 'Wed, 06-Jun-2012 01:34:34 GMT' :return: UTC time """ if len(cdate) < 29: # somethings broken if len(cdate) < 5: return utc_now() cdate = cdate[5:] # assume short weekday, i.e. do not support obsolete RFC 1036 date format try: t = time.strptime(cdate, "%d-%b-%Y %H:%M:%S %Z") # e.g. 18-Apr-2014 12:30:51 GMT except ValueError: try: t = time.strptime(cdate, "%d-%b-%y %H:%M:%S %Z") # e.g. 18-Apr-14 12:30:51 GMT except ValueError: try: t = time.strptime(cdate, "%d %b %Y %H:%M:%S %Z") # e.g. 18 Apr 2014 12:30:51 GMT except ValueError: raise (Exception, 'ValueError: Date "{0}" does not match any of '.format(cdate) + \ '"%d-%b-%Y %H:%M:%S %Z", ' + \ '"%d-%b-%y %H:%M:%S %Z", ' + \ '"%d %b %Y %H:%M:%S %Z".') #return int(time.mktime(t)) return calendar.timegm(t)
def cookies(self, url): """ Return cookies that are matching the path and are still valid :param url: :return: """ part = urlparse(url) #if part.port: # _domain = "%s:%s" % (part.hostname, part.port) #else: _domain = part.hostname cookie_dict = {} now = utc_now() for _, a in list(self.cookiejar._cookies.items()): for _, b in a.items(): for cookie in list(b.values()): # print(cookie) if cookie.expires and cookie.expires <= now: continue if not re.search("%s$" % cookie.domain, _domain): continue if not re.match(cookie.path, part.path): continue cookie_dict[cookie.name] = cookie.value return cookie_dict
def set_cookie(self, kaka, request): """Returns a cookielib.Cookie based on a set-cookie header line""" if not kaka: return part = urlparse.urlparse(request.url) _domain = part.hostname logger.debug("%s: '%s'" % (_domain, kaka)) for cookie_name, morsel in kaka.items(): std_attr = ATTRS.copy() std_attr["name"] = cookie_name _tmp = morsel.coded_value if _tmp.startswith('"') and _tmp.endswith('"'): std_attr["value"] = _tmp[1:-1] else: std_attr["value"] = _tmp std_attr["version"] = 0 # copy attributes that have values for attr in morsel.keys(): if attr in ATTRS: if morsel[attr]: if attr == "expires": std_attr[attr] = _since_epoch(morsel[attr]) else: std_attr[attr] = morsel[attr] elif attr == "max-age": if morsel["max-age"]: std_attr["expires"] = _since_epoch(morsel["max-age"]) for att, item in PAIRS.items(): if std_attr[att]: std_attr[item] = True if std_attr["domain"]: if std_attr["domain"].startswith("."): std_attr["domain_initial_dot"] = True else: std_attr["domain"] = _domain std_attr["domain_specified"] = True if morsel["max-age"] is 0: try: self.cookiejar.clear(domain=std_attr["domain"], path=std_attr["path"], name=std_attr["name"]) except ValueError: pass elif morsel["expires"] < utc_now(): try: self.cookiejar.clear(domain=std_attr["domain"], path=std_attr["path"], name=std_attr["name"]) except ValueError: pass else: new_cookie = cookielib.Cookie(**std_attr) self.cookiejar.set_cookie(new_cookie)
def _since_epoch(cdate): """ :param cdate: date format 'Wed, 06-Jun-2012 01:34:34 GMT' :return: UTC time """ if len(cdate) < 29: # somethings broken if len(cdate) < 5: return utc_now() cdate = cdate[5:] # assume short weekday, i.e. do not support obsolete RFC 1036 date format t = -1 for time_format in TIME_FORMAT : try: t = time.strptime(cdate, time_format) # e.g. 18-Apr-2014 12:30:51 GMT except ValueError: pass else: break if t == -1: raise (Exception, 'ValueError: Date "{0}" does not match any of: {1}'.format( cdate,TIME_FORMAT)) return calendar.timegm(t)
def validate_before(not_before, slack): if not_before: now = time_util.utc_now() nbefore = calendar.timegm(time_util.str_to_time(not_before)) if nbefore > now + slack: raise ToEarly("Can't use it yet %d <= %d" % (now + slack, nbefore)) return True
def validate_before(not_before, slack): if not_before: now = time_util.utc_now() nbefore = calendar.timegm(time_util.str_to_time(not_before)) if nbefore > now + slack: now_str = time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime(now)) raise ToEarly("Can't use response yet: (now=%s + slack=%d) " "<= notbefore=%s" % (now_str, slack, not_before)) return True
def validate_on_or_after(not_on_or_after, slack): if not_on_or_after: now = time_util.utc_now() nooa = calendar.timegm(time_util.str_to_time(not_on_or_after)) if now > nooa + slack: raise ResponseLifetimeExceed("Can't use it, it's too old %d > %d".format(now - slack, nooa)) return nooa else: return False
def validate_on_or_after(not_on_or_after, slack): if not_on_or_after: now = time_util.utc_now() nooa = calendar.timegm(time_util.str_to_time(not_on_or_after)) if now > nooa + slack: raise Exception("Can't use it, it's too old %d > %d" % (nooa, now)) return nooa else: return False
def active_cert(key): """ Verifies that a key is active that is present time is after not_before and before not_after. :param key: The Key :return: True if the key is active else False """ cert_str = pem_format(key) certificate = load_cert_string(cert_str) try: not_before = to_time(str(certificate.get_not_before())) not_after = to_time(str(certificate.get_not_after())) assert not_before < utc_now() assert not_after > utc_now() return True except AssertionError: return False except AttributeError: return False
def validate_on_or_after(not_on_or_after, slack): if not_on_or_after: now = time_util.utc_now() nooa = calendar.timegm(time_util.str_to_time(not_on_or_after)) if now > nooa + slack: now_str=time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime(now)) raise ResponseLifetimeExceed( "Can't use response, too old (now=%s + slack=%d > " \ "not_on_or_after=%s" % (now_str, slack, not_on_or_after)) return nooa else: return False
def _since_epoch(cdate): """ :param cdate: date format 'Wed, 06-Jun-2012 01:34:34 GMT' :return: UTC time """ if len(cdate) < 29: # somethings broken if len(cdate) < 5: return utc_now() cdate = cdate[5:] try: t = time.strptime(cdate, "%d-%b-%Y %H:%M:%S %Z") except ValueError: t = time.strptime(cdate, "%d-%b-%y %H:%M:%S %Z") #return int(time.mktime(t)) return calendar.timegm(t)
def get_profile_info(self, test_id=None): try: _conv = self.session["conv"] except KeyError: res = {} else: # Should only be one md = list(_conv.entity.metadata.metadata.values())[0] try: iss = list(md.entity.keys())[0] except TypeError: iss = "" except IndexError: if md.entity_descr: iss = md.entity_descr.entity_id elif md.entities_descr: # should only be one iss = md.entities_descr[0].entity_id else: iss = '' profile = self.to_profile("list") if test_id is None: try: test_id = self.session["testid"] except KeyError: return {} res = { "Issuer": iss, "Profile": profile, "Test ID": test_id, "Test description": self.session["flow"]['desc'], "Timestamp": utc_now() } return res
def set_cookie(self, kaka, request): """Returns a cookielib.Cookie based on a set-cookie header line""" if not kaka: return part = urlparse.urlparse(request.url) _domain = part.hostname logger.debug("%s: '%s'" % (_domain, kaka)) for cookie_name, morsel in kaka.items(): std_attr = ATTRS.copy() std_attr["name"] = cookie_name _tmp = morsel.coded_value if _tmp.startswith('"') and _tmp.endswith('"'): std_attr["value"] = _tmp[1:-1] else: std_attr["value"] = _tmp std_attr["version"] = 0 # copy attributes that have values for attr in morsel.keys(): if attr in ATTRS: if morsel[attr]: if attr == "expires": std_attr[attr] = _since_epoch(morsel[attr]) elif attr == "path": if morsel[attr].endswith(","): std_attr[attr] = morsel[attr][:-1] else: std_attr[attr] = morsel[attr] else: std_attr[attr] = morsel[attr] elif attr == "max-age": if morsel["max-age"]: std_attr["expires"] = time.time() + int( morsel["max-age"]) for att, item in PAIRS.items(): if std_attr[att]: std_attr[item] = True if std_attr["domain"]: if std_attr["domain"].startswith("."): std_attr["domain_initial_dot"] = True else: std_attr["domain"] = _domain std_attr["domain_specified"] = True if morsel["max-age"] is 0: try: self.cookiejar.clear(domain=std_attr["domain"], path=std_attr["path"], name=std_attr["name"]) except ValueError: pass elif morsel["expires"] < utc_now(): try: self.cookiejar.clear(domain=std_attr["domain"], path=std_attr["path"], name=std_attr["name"]) except ValueError: pass else: new_cookie = cookielib.Cookie(**std_attr) self.cookiejar.set_cookie(new_cookie)