id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
232,600 | IdentityPython/pysaml2 | src/saml2/__init__.py | SamlBase.child_class | def child_class(self, child):
""" Return the class a child element should be an instance of
:param child: The name of the child element
:return: The class
"""
for prop, klassdef in self.c_children.values():
if child == prop:
if isinstance(klassdef, list):
return klassdef[0]
else:
return klassdef
return None | python | def child_class(self, child):
for prop, klassdef in self.c_children.values():
if child == prop:
if isinstance(klassdef, list):
return klassdef[0]
else:
return klassdef
return None | [
"def",
"child_class",
"(",
"self",
",",
"child",
")",
":",
"for",
"prop",
",",
"klassdef",
"in",
"self",
".",
"c_children",
".",
"values",
"(",
")",
":",
"if",
"child",
"==",
"prop",
":",
"if",
"isinstance",
"(",
"klassdef",
",",
"list",
")",
":",
... | Return the class a child element should be an instance of
:param child: The name of the child element
:return: The class | [
"Return",
"the",
"class",
"a",
"child",
"element",
"should",
"be",
"an",
"instance",
"of"
] | d3aa78eeb7d37c12688f783cb4db1c7263a14ad6 | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/__init__.py#L865-L877 |
232,601 | IdentityPython/pysaml2 | src/saml2/__init__.py | SamlBase.child_cardinality | def child_cardinality(self, child):
""" Return the cardinality of a child element
:param child: The name of the child element
:return: The cardinality as a 2-tuple (min, max).
The max value is either a number or the string "unbounded".
The min value is always a number.
"""
for prop, klassdef in self.c_children.values():
if child == prop:
if isinstance(klassdef, list):
try:
_min = self.c_cardinality["min"]
except KeyError:
_min = 1
try:
_max = self.c_cardinality["max"]
except KeyError:
_max = "unbounded"
return _min, _max
else:
return 1, 1
return None | python | def child_cardinality(self, child):
for prop, klassdef in self.c_children.values():
if child == prop:
if isinstance(klassdef, list):
try:
_min = self.c_cardinality["min"]
except KeyError:
_min = 1
try:
_max = self.c_cardinality["max"]
except KeyError:
_max = "unbounded"
return _min, _max
else:
return 1, 1
return None | [
"def",
"child_cardinality",
"(",
"self",
",",
"child",
")",
":",
"for",
"prop",
",",
"klassdef",
"in",
"self",
".",
"c_children",
".",
"values",
"(",
")",
":",
"if",
"child",
"==",
"prop",
":",
"if",
"isinstance",
"(",
"klassdef",
",",
"list",
")",
"... | Return the cardinality of a child element
:param child: The name of the child element
:return: The cardinality as a 2-tuple (min, max).
The max value is either a number or the string "unbounded".
The min value is always a number. | [
"Return",
"the",
"cardinality",
"of",
"a",
"child",
"element"
] | d3aa78eeb7d37c12688f783cb4db1c7263a14ad6 | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/__init__.py#L879-L902 |
232,602 | IdentityPython/pysaml2 | src/saml2/mcache.py | Cache.reset | def reset(self, subject_id, entity_id):
""" Scrap the assertions received from a IdP or an AA about a special
subject.
:param subject_id: The subjects identifier
:param entity_id: The identifier of the entity_id of the assertion
:return:
"""
if not self._cache.set(_key(subject_id, entity_id), {}, 0):
raise CacheError("reset failed") | python | def reset(self, subject_id, entity_id):
if not self._cache.set(_key(subject_id, entity_id), {}, 0):
raise CacheError("reset failed") | [
"def",
"reset",
"(",
"self",
",",
"subject_id",
",",
"entity_id",
")",
":",
"if",
"not",
"self",
".",
"_cache",
".",
"set",
"(",
"_key",
"(",
"subject_id",
",",
"entity_id",
")",
",",
"{",
"}",
",",
"0",
")",
":",
"raise",
"CacheError",
"(",
"\"res... | Scrap the assertions received from a IdP or an AA about a special
subject.
:param subject_id: The subjects identifier
:param entity_id: The identifier of the entity_id of the assertion
:return: | [
"Scrap",
"the",
"assertions",
"received",
"from",
"a",
"IdP",
"or",
"an",
"AA",
"about",
"a",
"special",
"subject",
"."
] | d3aa78eeb7d37c12688f783cb4db1c7263a14ad6 | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/mcache.py#L124-L133 |
232,603 | IdentityPython/pysaml2 | src/saml2/population.py | Population.add_information_about_person | def add_information_about_person(self, session_info):
"""If there already are information from this source in the cache
this function will overwrite that information"""
session_info = dict(session_info)
name_id = session_info["name_id"]
issuer = session_info.pop("issuer")
self.cache.set(name_id, issuer, session_info,
session_info["not_on_or_after"])
return name_id | python | def add_information_about_person(self, session_info):
session_info = dict(session_info)
name_id = session_info["name_id"]
issuer = session_info.pop("issuer")
self.cache.set(name_id, issuer, session_info,
session_info["not_on_or_after"])
return name_id | [
"def",
"add_information_about_person",
"(",
"self",
",",
"session_info",
")",
":",
"session_info",
"=",
"dict",
"(",
"session_info",
")",
"name_id",
"=",
"session_info",
"[",
"\"name_id\"",
"]",
"issuer",
"=",
"session_info",
".",
"pop",
"(",
"\"issuer\"",
")",
... | If there already are information from this source in the cache
this function will overwrite that information | [
"If",
"there",
"already",
"are",
"information",
"from",
"this",
"source",
"in",
"the",
"cache",
"this",
"function",
"will",
"overwrite",
"that",
"information"
] | d3aa78eeb7d37c12688f783cb4db1c7263a14ad6 | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/population.py#L20-L29 |
232,604 | IdentityPython/pysaml2 | src/saml2/authn_context/__init__.py | AuthnBroker.add | def add(self, spec, method, level=0, authn_authority="", reference=None):
"""
Adds a new authentication method.
Assumes not more than one authentication method per AuthnContext
specification.
:param spec: What the authentication endpoint offers in the form
of an AuthnContext
:param method: A identifier of the authentication method.
:param level: security level, positive integers, 0 is lowest
:param reference: Desired unique reference to this `spec'
:return:
"""
if spec.authn_context_class_ref:
key = spec.authn_context_class_ref.text
_info = {
"class_ref": key,
"method": method,
"level": level,
"authn_auth": authn_authority
}
elif spec.authn_context_decl:
key = spec.authn_context_decl.c_namespace
_info = {
"method": method,
"decl": spec.authn_context_decl,
"level": level,
"authn_auth": authn_authority
}
else:
raise NotImplementedError()
self.next += 1
_ref = reference
if _ref is None:
_ref = str(self.next)
assert _ref not in self.db["info"]
self.db["info"][_ref] = _info
try:
self.db["key"][key].append(_ref)
except KeyError:
self.db["key"][key] = [_ref] | python | def add(self, spec, method, level=0, authn_authority="", reference=None):
if spec.authn_context_class_ref:
key = spec.authn_context_class_ref.text
_info = {
"class_ref": key,
"method": method,
"level": level,
"authn_auth": authn_authority
}
elif spec.authn_context_decl:
key = spec.authn_context_decl.c_namespace
_info = {
"method": method,
"decl": spec.authn_context_decl,
"level": level,
"authn_auth": authn_authority
}
else:
raise NotImplementedError()
self.next += 1
_ref = reference
if _ref is None:
_ref = str(self.next)
assert _ref not in self.db["info"]
self.db["info"][_ref] = _info
try:
self.db["key"][key].append(_ref)
except KeyError:
self.db["key"][key] = [_ref] | [
"def",
"add",
"(",
"self",
",",
"spec",
",",
"method",
",",
"level",
"=",
"0",
",",
"authn_authority",
"=",
"\"\"",
",",
"reference",
"=",
"None",
")",
":",
"if",
"spec",
".",
"authn_context_class_ref",
":",
"key",
"=",
"spec",
".",
"authn_context_class_... | Adds a new authentication method.
Assumes not more than one authentication method per AuthnContext
specification.
:param spec: What the authentication endpoint offers in the form
of an AuthnContext
:param method: A identifier of the authentication method.
:param level: security level, positive integers, 0 is lowest
:param reference: Desired unique reference to this `spec'
:return: | [
"Adds",
"a",
"new",
"authentication",
"method",
".",
"Assumes",
"not",
"more",
"than",
"one",
"authentication",
"method",
"per",
"AuthnContext",
"specification",
"."
] | d3aa78eeb7d37c12688f783cb4db1c7263a14ad6 | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/authn_context/__init__.py#L55-L98 |
232,605 | IdentityPython/pysaml2 | src/saml2/authn_context/__init__.py | AuthnBroker.pick | def pick(self, req_authn_context=None):
"""
Given the authentication context find zero or more places where
the user could be sent next. Ordered according to security level.
:param req_authn_context: The requested context as an
RequestedAuthnContext instance
:return: An URL
"""
if req_authn_context is None:
return self._pick_by_class_ref(UNSPECIFIED, "minimum")
if req_authn_context.authn_context_class_ref:
if req_authn_context.comparison:
_cmp = req_authn_context.comparison
else:
_cmp = "exact"
if _cmp == 'exact':
res = []
for cls_ref in req_authn_context.authn_context_class_ref:
res += (self._pick_by_class_ref(cls_ref.text, _cmp))
return res
else:
return self._pick_by_class_ref(
req_authn_context.authn_context_class_ref[0].text, _cmp)
elif req_authn_context.authn_context_decl_ref:
if req_authn_context.comparison:
_cmp = req_authn_context.comparison
else:
_cmp = "exact"
return self._pick_by_class_ref(
req_authn_context.authn_context_decl_ref, _cmp) | python | def pick(self, req_authn_context=None):
if req_authn_context is None:
return self._pick_by_class_ref(UNSPECIFIED, "minimum")
if req_authn_context.authn_context_class_ref:
if req_authn_context.comparison:
_cmp = req_authn_context.comparison
else:
_cmp = "exact"
if _cmp == 'exact':
res = []
for cls_ref in req_authn_context.authn_context_class_ref:
res += (self._pick_by_class_ref(cls_ref.text, _cmp))
return res
else:
return self._pick_by_class_ref(
req_authn_context.authn_context_class_ref[0].text, _cmp)
elif req_authn_context.authn_context_decl_ref:
if req_authn_context.comparison:
_cmp = req_authn_context.comparison
else:
_cmp = "exact"
return self._pick_by_class_ref(
req_authn_context.authn_context_decl_ref, _cmp) | [
"def",
"pick",
"(",
"self",
",",
"req_authn_context",
"=",
"None",
")",
":",
"if",
"req_authn_context",
"is",
"None",
":",
"return",
"self",
".",
"_pick_by_class_ref",
"(",
"UNSPECIFIED",
",",
"\"minimum\"",
")",
"if",
"req_authn_context",
".",
"authn_context_cl... | Given the authentication context find zero or more places where
the user could be sent next. Ordered according to security level.
:param req_authn_context: The requested context as an
RequestedAuthnContext instance
:return: An URL | [
"Given",
"the",
"authentication",
"context",
"find",
"zero",
"or",
"more",
"places",
"where",
"the",
"user",
"could",
"be",
"sent",
"next",
".",
"Ordered",
"according",
"to",
"security",
"level",
"."
] | d3aa78eeb7d37c12688f783cb4db1c7263a14ad6 | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/authn_context/__init__.py#L153-L184 |
232,606 | IdentityPython/pysaml2 | src/saml2/cryptography/asymmetric.py | load_pem_private_key | def load_pem_private_key(data, password):
"""Load RSA PEM certificate."""
key = _serialization.load_pem_private_key(
data, password, _backends.default_backend())
return key | python | def load_pem_private_key(data, password):
key = _serialization.load_pem_private_key(
data, password, _backends.default_backend())
return key | [
"def",
"load_pem_private_key",
"(",
"data",
",",
"password",
")",
":",
"key",
"=",
"_serialization",
".",
"load_pem_private_key",
"(",
"data",
",",
"password",
",",
"_backends",
".",
"default_backend",
"(",
")",
")",
"return",
"key"
] | Load RSA PEM certificate. | [
"Load",
"RSA",
"PEM",
"certificate",
"."
] | d3aa78eeb7d37c12688f783cb4db1c7263a14ad6 | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/cryptography/asymmetric.py#L9-L13 |
232,607 | IdentityPython/pysaml2 | src/saml2/cryptography/asymmetric.py | key_sign | def key_sign(rsakey, message, digest):
"""Sign the given message with the RSA key."""
padding = _asymmetric.padding.PKCS1v15()
signature = rsakey.sign(message, padding, digest)
return signature | python | def key_sign(rsakey, message, digest):
padding = _asymmetric.padding.PKCS1v15()
signature = rsakey.sign(message, padding, digest)
return signature | [
"def",
"key_sign",
"(",
"rsakey",
",",
"message",
",",
"digest",
")",
":",
"padding",
"=",
"_asymmetric",
".",
"padding",
".",
"PKCS1v15",
"(",
")",
"signature",
"=",
"rsakey",
".",
"sign",
"(",
"message",
",",
"padding",
",",
"digest",
")",
"return",
... | Sign the given message with the RSA key. | [
"Sign",
"the",
"given",
"message",
"with",
"the",
"RSA",
"key",
"."
] | d3aa78eeb7d37c12688f783cb4db1c7263a14ad6 | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/cryptography/asymmetric.py#L16-L20 |
232,608 | IdentityPython/pysaml2 | src/saml2/cryptography/asymmetric.py | key_verify | def key_verify(rsakey, signature, message, digest):
"""Verify the given signature with the RSA key."""
padding = _asymmetric.padding.PKCS1v15()
if isinstance(rsakey, _asymmetric.rsa.RSAPrivateKey):
rsakey = rsakey.public_key()
try:
rsakey.verify(signature, message, padding, digest)
except Exception as e:
return False
else:
return True | python | def key_verify(rsakey, signature, message, digest):
padding = _asymmetric.padding.PKCS1v15()
if isinstance(rsakey, _asymmetric.rsa.RSAPrivateKey):
rsakey = rsakey.public_key()
try:
rsakey.verify(signature, message, padding, digest)
except Exception as e:
return False
else:
return True | [
"def",
"key_verify",
"(",
"rsakey",
",",
"signature",
",",
"message",
",",
"digest",
")",
":",
"padding",
"=",
"_asymmetric",
".",
"padding",
".",
"PKCS1v15",
"(",
")",
"if",
"isinstance",
"(",
"rsakey",
",",
"_asymmetric",
".",
"rsa",
".",
"RSAPrivateKey"... | Verify the given signature with the RSA key. | [
"Verify",
"the",
"given",
"signature",
"with",
"the",
"RSA",
"key",
"."
] | d3aa78eeb7d37c12688f783cb4db1c7263a14ad6 | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/cryptography/asymmetric.py#L23-L34 |
232,609 | IdentityPython/pysaml2 | src/saml2/request.py | Request.subject_id | def subject_id(self):
""" The name of the subject can be in either of
BaseID, NameID or EncryptedID
:return: The identifier if there is one
"""
if "subject" in self.message.keys():
_subj = self.message.subject
if "base_id" in _subj.keys() and _subj.base_id:
return _subj.base_id
elif _subj.name_id:
return _subj.name_id
else:
if "base_id" in self.message.keys() and self.message.base_id:
return self.message.base_id
elif self.message.name_id:
return self.message.name_id
else: # EncryptedID
pass | python | def subject_id(self):
if "subject" in self.message.keys():
_subj = self.message.subject
if "base_id" in _subj.keys() and _subj.base_id:
return _subj.base_id
elif _subj.name_id:
return _subj.name_id
else:
if "base_id" in self.message.keys() and self.message.base_id:
return self.message.base_id
elif self.message.name_id:
return self.message.name_id
else: # EncryptedID
pass | [
"def",
"subject_id",
"(",
"self",
")",
":",
"if",
"\"subject\"",
"in",
"self",
".",
"message",
".",
"keys",
"(",
")",
":",
"_subj",
"=",
"self",
".",
"message",
".",
"subject",
"if",
"\"base_id\"",
"in",
"_subj",
".",
"keys",
"(",
")",
"and",
"_subj"... | The name of the subject can be in either of
BaseID, NameID or EncryptedID
:return: The identifier if there is one | [
"The",
"name",
"of",
"the",
"subject",
"can",
"be",
"in",
"either",
"of",
"BaseID",
"NameID",
"or",
"EncryptedID"
] | d3aa78eeb7d37c12688f783cb4db1c7263a14ad6 | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/request.py#L104-L123 |
232,610 | IdentityPython/pysaml2 | src/saml2/mdie.py | to_dict | def to_dict(_dict, onts, mdb_safe=False):
"""
Convert a pysaml2 SAML2 message class instance into a basic dictionary
format.
The export interface.
:param _dict: The pysaml2 metadata instance
:param onts: List of schemas to use for the conversion
:return: The converted information
"""
res = {}
if isinstance(_dict, SamlBase):
res["__class__"] = "%s&%s" % (_dict.c_namespace, _dict.c_tag)
for key in _dict.keyswv():
if key in IMP_SKIP:
continue
val = getattr(_dict, key)
if key == "extension_elements":
_eel = extension_elements_to_elements(val, onts)
_val = [_eval(_v, onts, mdb_safe) for _v in _eel]
elif key == "extension_attributes":
if mdb_safe:
_val = dict([(k.replace(".", "__"), v) for k, v in
val.items()])
#_val = {k.replace(".", "__"): v for k, v in val.items()}
else:
_val = val
else:
_val = _eval(val, onts, mdb_safe)
if _val:
if mdb_safe:
key = key.replace(".", "__")
res[key] = _val
else:
for key, val in _dict.items():
_val = _eval(val, onts, mdb_safe)
if _val:
if mdb_safe and "." in key:
key = key.replace(".", "__")
res[key] = _val
return res | python | def to_dict(_dict, onts, mdb_safe=False):
res = {}
if isinstance(_dict, SamlBase):
res["__class__"] = "%s&%s" % (_dict.c_namespace, _dict.c_tag)
for key in _dict.keyswv():
if key in IMP_SKIP:
continue
val = getattr(_dict, key)
if key == "extension_elements":
_eel = extension_elements_to_elements(val, onts)
_val = [_eval(_v, onts, mdb_safe) for _v in _eel]
elif key == "extension_attributes":
if mdb_safe:
_val = dict([(k.replace(".", "__"), v) for k, v in
val.items()])
#_val = {k.replace(".", "__"): v for k, v in val.items()}
else:
_val = val
else:
_val = _eval(val, onts, mdb_safe)
if _val:
if mdb_safe:
key = key.replace(".", "__")
res[key] = _val
else:
for key, val in _dict.items():
_val = _eval(val, onts, mdb_safe)
if _val:
if mdb_safe and "." in key:
key = key.replace(".", "__")
res[key] = _val
return res | [
"def",
"to_dict",
"(",
"_dict",
",",
"onts",
",",
"mdb_safe",
"=",
"False",
")",
":",
"res",
"=",
"{",
"}",
"if",
"isinstance",
"(",
"_dict",
",",
"SamlBase",
")",
":",
"res",
"[",
"\"__class__\"",
"]",
"=",
"\"%s&%s\"",
"%",
"(",
"_dict",
".",
"c_... | Convert a pysaml2 SAML2 message class instance into a basic dictionary
format.
The export interface.
:param _dict: The pysaml2 metadata instance
:param onts: List of schemas to use for the conversion
:return: The converted information | [
"Convert",
"a",
"pysaml2",
"SAML2",
"message",
"class",
"instance",
"into",
"a",
"basic",
"dictionary",
"format",
".",
"The",
"export",
"interface",
"."
] | d3aa78eeb7d37c12688f783cb4db1c7263a14ad6 | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/mdie.py#L46-L87 |
232,611 | IdentityPython/pysaml2 | src/saml2/mdie.py | _kwa | def _kwa(val, onts, mdb_safe=False):
"""
Key word argument conversion
:param val: A dictionary
:param onts: dictionary with schemas to use in the conversion
schema namespase is the key in the dictionary
:return: A converted dictionary
"""
if not mdb_safe:
return dict([(k, from_dict(v, onts)) for k, v in val.items()
if k not in EXP_SKIP])
else:
_skip = ["_id"]
_skip.extend(EXP_SKIP)
return dict([(k.replace("__", "."), from_dict(v, onts)) for k, v in
val.items() if k not in _skip]) | python | def _kwa(val, onts, mdb_safe=False):
if not mdb_safe:
return dict([(k, from_dict(v, onts)) for k, v in val.items()
if k not in EXP_SKIP])
else:
_skip = ["_id"]
_skip.extend(EXP_SKIP)
return dict([(k.replace("__", "."), from_dict(v, onts)) for k, v in
val.items() if k not in _skip]) | [
"def",
"_kwa",
"(",
"val",
",",
"onts",
",",
"mdb_safe",
"=",
"False",
")",
":",
"if",
"not",
"mdb_safe",
":",
"return",
"dict",
"(",
"[",
"(",
"k",
",",
"from_dict",
"(",
"v",
",",
"onts",
")",
")",
"for",
"k",
",",
"v",
"in",
"val",
".",
"i... | Key word argument conversion
:param val: A dictionary
:param onts: dictionary with schemas to use in the conversion
schema namespase is the key in the dictionary
:return: A converted dictionary | [
"Key",
"word",
"argument",
"conversion"
] | d3aa78eeb7d37c12688f783cb4db1c7263a14ad6 | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/mdie.py#L92-L108 |
232,612 | IdentityPython/pysaml2 | example/idp2/idp_uwsgi.py | SSO.redirect | def redirect(self):
""" This is the HTTP-redirect endpoint """
logger.info("--- In SSO Redirect ---")
saml_msg = self.unpack_redirect()
try:
_key = saml_msg["key"]
saml_msg = IDP.ticket[_key]
self.req_info = saml_msg["req_info"]
del IDP.ticket[_key]
except KeyError:
try:
self.req_info = IDP.parse_authn_request(saml_msg["SAMLRequest"],
BINDING_HTTP_REDIRECT)
except KeyError:
resp = BadRequest("Message signature verification failure")
return resp(self.environ, self.start_response)
_req = self.req_info.message
if "SigAlg" in saml_msg and "Signature" in saml_msg: # Signed
# request
issuer = _req.issuer.text
_certs = IDP.metadata.certs(issuer, "any", "signing")
verified_ok = False
for cert in _certs:
if verify_redirect_signature(saml_msg, IDP.sec.sec_backend,
cert):
verified_ok = True
break
if not verified_ok:
resp = BadRequest("Message signature verification failure")
return resp(self.environ, self.start_response)
if self.user:
if _req.force_authn:
saml_msg["req_info"] = self.req_info
key = self._store_request(saml_msg)
return self.not_authn(key, _req.requested_authn_context)
else:
return self.operation(saml_msg, BINDING_HTTP_REDIRECT)
else:
saml_msg["req_info"] = self.req_info
key = self._store_request(saml_msg)
return self.not_authn(key, _req.requested_authn_context)
else:
return self.operation(saml_msg, BINDING_HTTP_REDIRECT) | python | def redirect(self):
logger.info("--- In SSO Redirect ---")
saml_msg = self.unpack_redirect()
try:
_key = saml_msg["key"]
saml_msg = IDP.ticket[_key]
self.req_info = saml_msg["req_info"]
del IDP.ticket[_key]
except KeyError:
try:
self.req_info = IDP.parse_authn_request(saml_msg["SAMLRequest"],
BINDING_HTTP_REDIRECT)
except KeyError:
resp = BadRequest("Message signature verification failure")
return resp(self.environ, self.start_response)
_req = self.req_info.message
if "SigAlg" in saml_msg and "Signature" in saml_msg: # Signed
# request
issuer = _req.issuer.text
_certs = IDP.metadata.certs(issuer, "any", "signing")
verified_ok = False
for cert in _certs:
if verify_redirect_signature(saml_msg, IDP.sec.sec_backend,
cert):
verified_ok = True
break
if not verified_ok:
resp = BadRequest("Message signature verification failure")
return resp(self.environ, self.start_response)
if self.user:
if _req.force_authn:
saml_msg["req_info"] = self.req_info
key = self._store_request(saml_msg)
return self.not_authn(key, _req.requested_authn_context)
else:
return self.operation(saml_msg, BINDING_HTTP_REDIRECT)
else:
saml_msg["req_info"] = self.req_info
key = self._store_request(saml_msg)
return self.not_authn(key, _req.requested_authn_context)
else:
return self.operation(saml_msg, BINDING_HTTP_REDIRECT) | [
"def",
"redirect",
"(",
"self",
")",
":",
"logger",
".",
"info",
"(",
"\"--- In SSO Redirect ---\"",
")",
"saml_msg",
"=",
"self",
".",
"unpack_redirect",
"(",
")",
"try",
":",
"_key",
"=",
"saml_msg",
"[",
"\"key\"",
"]",
"saml_msg",
"=",
"IDP",
".",
"t... | This is the HTTP-redirect endpoint | [
"This",
"is",
"the",
"HTTP",
"-",
"redirect",
"endpoint"
] | d3aa78eeb7d37c12688f783cb4db1c7263a14ad6 | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/example/idp2/idp_uwsgi.py#L342-L389 |
232,613 | IdentityPython/pysaml2 | example/idp2/idp_uwsgi.py | SSO.post | def post(self):
"""
The HTTP-Post endpoint
"""
logger.info("--- In SSO POST ---")
saml_msg = self.unpack_either()
self.req_info = IDP.parse_authn_request(
saml_msg["SAMLRequest"], BINDING_HTTP_POST)
_req = self.req_info.message
if self.user:
if _req.force_authn:
saml_msg["req_info"] = self.req_info
key = self._store_request(saml_msg)
return self.not_authn(key, _req.requested_authn_context)
else:
return self.operation(saml_msg, BINDING_HTTP_POST)
else:
saml_msg["req_info"] = self.req_info
key = self._store_request(saml_msg)
return self.not_authn(key, _req.requested_authn_context) | python | def post(self):
logger.info("--- In SSO POST ---")
saml_msg = self.unpack_either()
self.req_info = IDP.parse_authn_request(
saml_msg["SAMLRequest"], BINDING_HTTP_POST)
_req = self.req_info.message
if self.user:
if _req.force_authn:
saml_msg["req_info"] = self.req_info
key = self._store_request(saml_msg)
return self.not_authn(key, _req.requested_authn_context)
else:
return self.operation(saml_msg, BINDING_HTTP_POST)
else:
saml_msg["req_info"] = self.req_info
key = self._store_request(saml_msg)
return self.not_authn(key, _req.requested_authn_context) | [
"def",
"post",
"(",
"self",
")",
":",
"logger",
".",
"info",
"(",
"\"--- In SSO POST ---\"",
")",
"saml_msg",
"=",
"self",
".",
"unpack_either",
"(",
")",
"self",
".",
"req_info",
"=",
"IDP",
".",
"parse_authn_request",
"(",
"saml_msg",
"[",
"\"SAMLRequest\"... | The HTTP-Post endpoint | [
"The",
"HTTP",
"-",
"Post",
"endpoint"
] | d3aa78eeb7d37c12688f783cb4db1c7263a14ad6 | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/example/idp2/idp_uwsgi.py#L391-L410 |
232,614 | IdentityPython/pysaml2 | src/saml2/ident.py | code | def code(item):
"""
Turn a NameID class instance into a quoted string of comma separated
attribute,value pairs. The attribute names are replaced with digits.
Depends on knowledge on the specific order of the attributes for the
class that is used.
:param item: The class instance
:return: A quoted string
"""
_res = []
i = 0
for attr in ATTR:
val = getattr(item, attr)
if val:
_res.append("%d=%s" % (i, quote(val)))
i += 1
return ",".join(_res) | python | def code(item):
_res = []
i = 0
for attr in ATTR:
val = getattr(item, attr)
if val:
_res.append("%d=%s" % (i, quote(val)))
i += 1
return ",".join(_res) | [
"def",
"code",
"(",
"item",
")",
":",
"_res",
"=",
"[",
"]",
"i",
"=",
"0",
"for",
"attr",
"in",
"ATTR",
":",
"val",
"=",
"getattr",
"(",
"item",
",",
"attr",
")",
"if",
"val",
":",
"_res",
".",
"append",
"(",
"\"%d=%s\"",
"%",
"(",
"i",
",",... | Turn a NameID class instance into a quoted string of comma separated
attribute,value pairs. The attribute names are replaced with digits.
Depends on knowledge on the specific order of the attributes for the
class that is used.
:param item: The class instance
:return: A quoted string | [
"Turn",
"a",
"NameID",
"class",
"instance",
"into",
"a",
"quoted",
"string",
"of",
"comma",
"separated",
"attribute",
"value",
"pairs",
".",
"The",
"attribute",
"names",
"are",
"replaced",
"with",
"digits",
".",
"Depends",
"on",
"knowledge",
"on",
"the",
"sp... | d3aa78eeb7d37c12688f783cb4db1c7263a14ad6 | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/ident.py#L29-L46 |
232,615 | IdentityPython/pysaml2 | src/saml2/ident.py | code_binary | def code_binary(item):
"""
Return a binary 'code' suitable for hashing.
"""
code_str = code(item)
if isinstance(code_str, six.string_types):
return code_str.encode('utf-8')
return code_str | python | def code_binary(item):
code_str = code(item)
if isinstance(code_str, six.string_types):
return code_str.encode('utf-8')
return code_str | [
"def",
"code_binary",
"(",
"item",
")",
":",
"code_str",
"=",
"code",
"(",
"item",
")",
"if",
"isinstance",
"(",
"code_str",
",",
"six",
".",
"string_types",
")",
":",
"return",
"code_str",
".",
"encode",
"(",
"'utf-8'",
")",
"return",
"code_str"
] | Return a binary 'code' suitable for hashing. | [
"Return",
"a",
"binary",
"code",
"suitable",
"for",
"hashing",
"."
] | d3aa78eeb7d37c12688f783cb4db1c7263a14ad6 | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/ident.py#L49-L56 |
232,616 | IdentityPython/pysaml2 | src/saml2/ident.py | IdentDB.remove_remote | def remove_remote(self, name_id):
"""
Remove a NameID to userID mapping
:param name_id: NameID instance
"""
_cn = code(name_id)
_id = self.db[name_id.text]
try:
vals = self.db[_id].split(" ")
vals.remove(_cn)
self.db[_id] = " ".join(vals)
except KeyError:
pass
del self.db[name_id.text] | python | def remove_remote(self, name_id):
_cn = code(name_id)
_id = self.db[name_id.text]
try:
vals = self.db[_id].split(" ")
vals.remove(_cn)
self.db[_id] = " ".join(vals)
except KeyError:
pass
del self.db[name_id.text] | [
"def",
"remove_remote",
"(",
"self",
",",
"name_id",
")",
":",
"_cn",
"=",
"code",
"(",
"name_id",
")",
"_id",
"=",
"self",
".",
"db",
"[",
"name_id",
".",
"text",
"]",
"try",
":",
"vals",
"=",
"self",
".",
"db",
"[",
"_id",
"]",
".",
"split",
... | Remove a NameID to userID mapping
:param name_id: NameID instance | [
"Remove",
"a",
"NameID",
"to",
"userID",
"mapping"
] | d3aa78eeb7d37c12688f783cb4db1c7263a14ad6 | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/ident.py#L125-L140 |
232,617 | IdentityPython/pysaml2 | src/saml2/ident.py | IdentDB.find_nameid | def find_nameid(self, userid, **kwargs):
"""
Find a set of NameID's that matches the search criteria.
:param userid: User id
:param kwargs: The search filter a set of attribute/value pairs
:return: a list of NameID instances
"""
res = []
try:
_vals = self.db[userid]
except KeyError:
logger.debug("failed to find userid %s in IdentDB", userid)
return res
for val in _vals.split(" "):
nid = decode(val)
if kwargs:
for key, _val in kwargs.items():
if getattr(nid, key, None) != _val:
break
else:
res.append(nid)
else:
res.append(nid)
return res | python | def find_nameid(self, userid, **kwargs):
res = []
try:
_vals = self.db[userid]
except KeyError:
logger.debug("failed to find userid %s in IdentDB", userid)
return res
for val in _vals.split(" "):
nid = decode(val)
if kwargs:
for key, _val in kwargs.items():
if getattr(nid, key, None) != _val:
break
else:
res.append(nid)
else:
res.append(nid)
return res | [
"def",
"find_nameid",
"(",
"self",
",",
"userid",
",",
"*",
"*",
"kwargs",
")",
":",
"res",
"=",
"[",
"]",
"try",
":",
"_vals",
"=",
"self",
".",
"db",
"[",
"userid",
"]",
"except",
"KeyError",
":",
"logger",
".",
"debug",
"(",
"\"failed to find user... | Find a set of NameID's that matches the search criteria.
:param userid: User id
:param kwargs: The search filter a set of attribute/value pairs
:return: a list of NameID instances | [
"Find",
"a",
"set",
"of",
"NameID",
"s",
"that",
"matches",
"the",
"search",
"criteria",
"."
] | d3aa78eeb7d37c12688f783cb4db1c7263a14ad6 | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/ident.py#L175-L201 |
232,618 | IdentityPython/pysaml2 | src/saml2/ident.py | IdentDB.construct_nameid | def construct_nameid(self, userid, local_policy=None,
sp_name_qualifier=None, name_id_policy=None,
name_qualifier=""):
""" Returns a name_id for the object. How the name_id is
constructed depends on the context.
:param local_policy: The policy the server is configured to follow
:param userid: The local permanent identifier of the object
:param sp_name_qualifier: The 'user'/-s of the name_id
:param name_id_policy: The policy the server on the other side wants
us to follow.
:param name_qualifier: A domain qualifier
:return: NameID instance precursor
"""
args = self.nim_args(local_policy, sp_name_qualifier, name_id_policy)
if name_qualifier:
args["name_qualifier"] = name_qualifier
else:
args["name_qualifier"] = self.name_qualifier
return self.get_nameid(userid, **args) | python | def construct_nameid(self, userid, local_policy=None,
sp_name_qualifier=None, name_id_policy=None,
name_qualifier=""):
args = self.nim_args(local_policy, sp_name_qualifier, name_id_policy)
if name_qualifier:
args["name_qualifier"] = name_qualifier
else:
args["name_qualifier"] = self.name_qualifier
return self.get_nameid(userid, **args) | [
"def",
"construct_nameid",
"(",
"self",
",",
"userid",
",",
"local_policy",
"=",
"None",
",",
"sp_name_qualifier",
"=",
"None",
",",
"name_id_policy",
"=",
"None",
",",
"name_qualifier",
"=",
"\"\"",
")",
":",
"args",
"=",
"self",
".",
"nim_args",
"(",
"lo... | Returns a name_id for the object. How the name_id is
constructed depends on the context.
:param local_policy: The policy the server is configured to follow
:param userid: The local permanent identifier of the object
:param sp_name_qualifier: The 'user'/-s of the name_id
:param name_id_policy: The policy the server on the other side wants
us to follow.
:param name_qualifier: A domain qualifier
:return: NameID instance precursor | [
"Returns",
"a",
"name_id",
"for",
"the",
"object",
".",
"How",
"the",
"name_id",
"is",
"constructed",
"depends",
"on",
"the",
"context",
"."
] | d3aa78eeb7d37c12688f783cb4db1c7263a14ad6 | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/ident.py#L236-L257 |
232,619 | IdentityPython/pysaml2 | src/saml2/ident.py | IdentDB.find_local_id | def find_local_id(self, name_id):
"""
Only find persistent IDs
:param name_id:
:return:
"""
try:
return self.db[name_id.text]
except KeyError:
logger.debug("name: %s", name_id.text)
#logger.debug("id sub keys: %s", self.subkeys())
return None | python | def find_local_id(self, name_id):
try:
return self.db[name_id.text]
except KeyError:
logger.debug("name: %s", name_id.text)
#logger.debug("id sub keys: %s", self.subkeys())
return None | [
"def",
"find_local_id",
"(",
"self",
",",
"name_id",
")",
":",
"try",
":",
"return",
"self",
".",
"db",
"[",
"name_id",
".",
"text",
"]",
"except",
"KeyError",
":",
"logger",
".",
"debug",
"(",
"\"name: %s\"",
",",
"name_id",
".",
"text",
")",
"#logger... | Only find persistent IDs
:param name_id:
:return: | [
"Only",
"find",
"persistent",
"IDs"
] | d3aa78eeb7d37c12688f783cb4db1c7263a14ad6 | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/ident.py#L272-L285 |
232,620 | IdentityPython/pysaml2 | src/saml2/ident.py | IdentDB.handle_manage_name_id_request | def handle_manage_name_id_request(self, name_id, new_id=None,
new_encrypted_id="", terminate=""):
"""
Requests from the SP is about the SPProvidedID attribute.
So this is about adding,replacing and removing said attribute.
:param name_id: NameID instance
:param new_id: NewID instance
:param new_encrypted_id: NewEncryptedID instance
:param terminate: Terminate instance
:return: The modified name_id
"""
_id = self.find_local_id(name_id)
orig_name_id = copy.copy(name_id)
if new_id:
name_id.sp_provided_id = new_id.text
elif new_encrypted_id:
# TODO
pass
elif terminate:
name_id.sp_provided_id = None
else:
#NOOP
return name_id
self.remove_remote(orig_name_id)
self.store(_id, name_id)
return name_id | python | def handle_manage_name_id_request(self, name_id, new_id=None,
new_encrypted_id="", terminate=""):
_id = self.find_local_id(name_id)
orig_name_id = copy.copy(name_id)
if new_id:
name_id.sp_provided_id = new_id.text
elif new_encrypted_id:
# TODO
pass
elif terminate:
name_id.sp_provided_id = None
else:
#NOOP
return name_id
self.remove_remote(orig_name_id)
self.store(_id, name_id)
return name_id | [
"def",
"handle_manage_name_id_request",
"(",
"self",
",",
"name_id",
",",
"new_id",
"=",
"None",
",",
"new_encrypted_id",
"=",
"\"\"",
",",
"terminate",
"=",
"\"\"",
")",
":",
"_id",
"=",
"self",
".",
"find_local_id",
"(",
"name_id",
")",
"orig_name_id",
"="... | Requests from the SP is about the SPProvidedID attribute.
So this is about adding,replacing and removing said attribute.
:param name_id: NameID instance
:param new_id: NewID instance
:param new_encrypted_id: NewEncryptedID instance
:param terminate: Terminate instance
:return: The modified name_id | [
"Requests",
"from",
"the",
"SP",
"is",
"about",
"the",
"SPProvidedID",
"attribute",
".",
"So",
"this",
"is",
"about",
"adding",
"replacing",
"and",
"removing",
"said",
"attribute",
"."
] | d3aa78eeb7d37c12688f783cb4db1c7263a14ad6 | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/ident.py#L338-L367 |
232,621 | IdentityPython/pysaml2 | src/saml2/server.py | Server.init_config | def init_config(self, stype="idp"):
""" Remaining init of the server configuration
:param stype: The type of Server ("idp"/"aa")
"""
if stype == "aa":
return
# subject information is stored in a database
# default database is in memory which is OK in some setups
dbspec = self.config.getattr("subject_data", "idp")
idb = None
typ = ""
if not dbspec:
idb = {}
elif isinstance(dbspec, six.string_types):
idb = _shelve_compat(dbspec, writeback=True, protocol=2)
else: # database spec is a a 2-tuple (type, address)
# print(>> sys.stderr, "DBSPEC: %s" % (dbspec,))
(typ, addr) = dbspec
if typ == "shelve":
idb = _shelve_compat(addr, writeback=True, protocol=2)
elif typ == "memcached":
import memcache
idb = memcache.Client(addr)
elif typ == "dict": # in-memory dictionary
idb = {}
elif typ == "mongodb":
from saml2.mongo_store import IdentMDB
self.ident = IdentMDB(database=addr, collection="ident")
elif typ == "identdb":
mod, clas = addr.rsplit('.', 1)
mod = importlib.import_module(mod)
self.ident = getattr(mod, clas)()
if typ == "mongodb" or typ == "identdb":
pass
elif idb is not None:
self.ident = IdentDB(idb)
elif dbspec:
raise Exception("Couldn't open identity database: %s" %
(dbspec,))
try:
_domain = self.config.getattr("domain", "idp")
if _domain:
self.ident.domain = _domain
self.ident.name_qualifier = self.config.entityid
dbspec = self.config.getattr("edu_person_targeted_id", "idp")
if not dbspec:
pass
else:
typ = dbspec[0]
addr = dbspec[1]
secret = dbspec[2]
if typ == "shelve":
self.eptid = EptidShelve(secret, addr)
elif typ == "mongodb":
from saml2.mongo_store import EptidMDB
self.eptid = EptidMDB(secret, database=addr,
collection="eptid")
else:
self.eptid = Eptid(secret)
except Exception:
self.ident.close()
raise | python | def init_config(self, stype="idp"):
if stype == "aa":
return
# subject information is stored in a database
# default database is in memory which is OK in some setups
dbspec = self.config.getattr("subject_data", "idp")
idb = None
typ = ""
if not dbspec:
idb = {}
elif isinstance(dbspec, six.string_types):
idb = _shelve_compat(dbspec, writeback=True, protocol=2)
else: # database spec is a a 2-tuple (type, address)
# print(>> sys.stderr, "DBSPEC: %s" % (dbspec,))
(typ, addr) = dbspec
if typ == "shelve":
idb = _shelve_compat(addr, writeback=True, protocol=2)
elif typ == "memcached":
import memcache
idb = memcache.Client(addr)
elif typ == "dict": # in-memory dictionary
idb = {}
elif typ == "mongodb":
from saml2.mongo_store import IdentMDB
self.ident = IdentMDB(database=addr, collection="ident")
elif typ == "identdb":
mod, clas = addr.rsplit('.', 1)
mod = importlib.import_module(mod)
self.ident = getattr(mod, clas)()
if typ == "mongodb" or typ == "identdb":
pass
elif idb is not None:
self.ident = IdentDB(idb)
elif dbspec:
raise Exception("Couldn't open identity database: %s" %
(dbspec,))
try:
_domain = self.config.getattr("domain", "idp")
if _domain:
self.ident.domain = _domain
self.ident.name_qualifier = self.config.entityid
dbspec = self.config.getattr("edu_person_targeted_id", "idp")
if not dbspec:
pass
else:
typ = dbspec[0]
addr = dbspec[1]
secret = dbspec[2]
if typ == "shelve":
self.eptid = EptidShelve(secret, addr)
elif typ == "mongodb":
from saml2.mongo_store import EptidMDB
self.eptid = EptidMDB(secret, database=addr,
collection="eptid")
else:
self.eptid = Eptid(secret)
except Exception:
self.ident.close()
raise | [
"def",
"init_config",
"(",
"self",
",",
"stype",
"=",
"\"idp\"",
")",
":",
"if",
"stype",
"==",
"\"aa\"",
":",
"return",
"# subject information is stored in a database",
"# default database is in memory which is OK in some setups",
"dbspec",
"=",
"self",
".",
"config",
... | Remaining init of the server configuration
:param stype: The type of Server ("idp"/"aa") | [
"Remaining",
"init",
"of",
"the",
"server",
"configuration"
] | d3aa78eeb7d37c12688f783cb4db1c7263a14ad6 | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/server.py#L121-L188 |
232,622 | IdentityPython/pysaml2 | src/saml2/server.py | Server.parse_authn_request | def parse_authn_request(self, enc_request, binding=BINDING_HTTP_REDIRECT):
"""Parse a Authentication Request
:param enc_request: The request in its transport format
:param binding: Which binding that was used to transport the message
to this entity.
:return: A request instance
"""
return self._parse_request(enc_request, AuthnRequest,
"single_sign_on_service", binding) | python | def parse_authn_request(self, enc_request, binding=BINDING_HTTP_REDIRECT):
return self._parse_request(enc_request, AuthnRequest,
"single_sign_on_service", binding) | [
"def",
"parse_authn_request",
"(",
"self",
",",
"enc_request",
",",
"binding",
"=",
"BINDING_HTTP_REDIRECT",
")",
":",
"return",
"self",
".",
"_parse_request",
"(",
"enc_request",
",",
"AuthnRequest",
",",
"\"single_sign_on_service\"",
",",
"binding",
")"
] | Parse a Authentication Request
:param enc_request: The request in its transport format
:param binding: Which binding that was used to transport the message
to this entity.
:return: A request instance | [
"Parse",
"a",
"Authentication",
"Request"
] | d3aa78eeb7d37c12688f783cb4db1c7263a14ad6 | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/server.py#L221-L231 |
232,623 | IdentityPython/pysaml2 | src/saml2/server.py | Server.setup_assertion | def setup_assertion(self, authn, sp_entity_id, in_response_to, consumer_url,
name_id, policy, _issuer, authn_statement, identity,
best_effort, sign_response, farg=None,
session_not_on_or_after=None, **kwargs):
"""
Construct and return the Assertion
:param authn: Authentication information
:param sp_entity_id:
:param in_response_to: The ID of the request this is an answer to
:param consumer_url: The recipient of the assertion
:param name_id: The NameID of the subject
:param policy: Assertion policies
:param _issuer: Issuer of the statement
:param authn_statement: An AuthnStatement instance
:param identity: Identity information about the Subject
:param best_effort: Even if not the SPs demands can be met send a
response.
:param sign_response: Sign the response, only applicable if
ErrorResponse
:param kwargs: Extra keyword arguments
:return: An Assertion instance
"""
ast = Assertion(identity)
ast.acs = self.config.getattr("attribute_converters", "idp")
if policy is None:
policy = Policy()
try:
ast.apply_policy(sp_entity_id, policy, self.metadata)
except MissingValue as exc:
if not best_effort:
return self.create_error_response(in_response_to, consumer_url,
exc, sign_response)
farg = self.update_farg(in_response_to, consumer_url, farg)
if authn: # expected to be a dictionary
# Would like to use dict comprehension but ...
authn_args = dict(
[(AUTHN_DICT_MAP[k], v) for k, v in authn.items() if
k in AUTHN_DICT_MAP])
authn_args.update(kwargs)
assertion = ast.construct(
sp_entity_id, self.config.attribute_converters, policy,
issuer=_issuer, farg=farg['assertion'], name_id=name_id,
session_not_on_or_after=session_not_on_or_after,
**authn_args)
elif authn_statement: # Got a complete AuthnStatement
assertion = ast.construct(
sp_entity_id, self.config.attribute_converters, policy,
issuer=_issuer, authn_statem=authn_statement,
farg=farg['assertion'], name_id=name_id,
**kwargs)
else:
assertion = ast.construct(
sp_entity_id, self.config.attribute_converters, policy,
issuer=_issuer, farg=farg['assertion'], name_id=name_id,
session_not_on_or_after=session_not_on_or_after,
**kwargs)
return assertion | python | def setup_assertion(self, authn, sp_entity_id, in_response_to, consumer_url,
name_id, policy, _issuer, authn_statement, identity,
best_effort, sign_response, farg=None,
session_not_on_or_after=None, **kwargs):
ast = Assertion(identity)
ast.acs = self.config.getattr("attribute_converters", "idp")
if policy is None:
policy = Policy()
try:
ast.apply_policy(sp_entity_id, policy, self.metadata)
except MissingValue as exc:
if not best_effort:
return self.create_error_response(in_response_to, consumer_url,
exc, sign_response)
farg = self.update_farg(in_response_to, consumer_url, farg)
if authn: # expected to be a dictionary
# Would like to use dict comprehension but ...
authn_args = dict(
[(AUTHN_DICT_MAP[k], v) for k, v in authn.items() if
k in AUTHN_DICT_MAP])
authn_args.update(kwargs)
assertion = ast.construct(
sp_entity_id, self.config.attribute_converters, policy,
issuer=_issuer, farg=farg['assertion'], name_id=name_id,
session_not_on_or_after=session_not_on_or_after,
**authn_args)
elif authn_statement: # Got a complete AuthnStatement
assertion = ast.construct(
sp_entity_id, self.config.attribute_converters, policy,
issuer=_issuer, authn_statem=authn_statement,
farg=farg['assertion'], name_id=name_id,
**kwargs)
else:
assertion = ast.construct(
sp_entity_id, self.config.attribute_converters, policy,
issuer=_issuer, farg=farg['assertion'], name_id=name_id,
session_not_on_or_after=session_not_on_or_after,
**kwargs)
return assertion | [
"def",
"setup_assertion",
"(",
"self",
",",
"authn",
",",
"sp_entity_id",
",",
"in_response_to",
",",
"consumer_url",
",",
"name_id",
",",
"policy",
",",
"_issuer",
",",
"authn_statement",
",",
"identity",
",",
"best_effort",
",",
"sign_response",
",",
"farg",
... | Construct and return the Assertion
:param authn: Authentication information
:param sp_entity_id:
:param in_response_to: The ID of the request this is an answer to
:param consumer_url: The recipient of the assertion
:param name_id: The NameID of the subject
:param policy: Assertion policies
:param _issuer: Issuer of the statement
:param authn_statement: An AuthnStatement instance
:param identity: Identity information about the Subject
:param best_effort: Even if not the SPs demands can be met send a
response.
:param sign_response: Sign the response, only applicable if
ErrorResponse
:param kwargs: Extra keyword arguments
:return: An Assertion instance | [
"Construct",
"and",
"return",
"the",
"Assertion"
] | d3aa78eeb7d37c12688f783cb4db1c7263a14ad6 | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/server.py#L323-L385 |
232,624 | IdentityPython/pysaml2 | src/saml2/server.py | Server._authn_response | def _authn_response(self, in_response_to, consumer_url,
sp_entity_id, identity=None, name_id=None,
status=None, authn=None, issuer=None, policy=None,
sign_assertion=False, sign_response=False,
best_effort=False, encrypt_assertion=False,
encrypt_cert_advice=None, encrypt_cert_assertion=None,
authn_statement=None,
encrypt_assertion_self_contained=False,
encrypted_advice_attributes=False,
pefim=False, sign_alg=None, digest_alg=None,
farg=None, session_not_on_or_after=None):
""" Create a response. A layer of indirection.
:param in_response_to: The session identifier of the request
:param consumer_url: The URL which should receive the response
:param sp_entity_id: The entity identifier of the SP
:param identity: A dictionary with attributes and values that are
expected to be the bases for the assertion in the response.
:param name_id: The identifier of the subject
:param status: The status of the response
:param authn: A dictionary containing information about the
authn context.
:param issuer: The issuer of the response
:param policy:
:param sign_assertion: Whether the assertion should be signed or not
:param sign_response: Whether the response should be signed or not
:param best_effort: Even if not the SPs demands can be met send a
response.
:param encrypt_assertion: True if assertions should be encrypted.
:param encrypt_assertion_self_contained: True if all encrypted
assertions should have alla namespaces
selfcontained.
:param encrypted_advice_attributes: True if assertions in the advice
element should be encrypted.
:param encrypt_cert_advice: Certificate to be used for encryption of
assertions in the advice element.
:param encrypt_cert_assertion: Certificate to be used for encryption
of assertions.
:param authn_statement: Authentication statement.
:param sign_assertion: True if assertions should be signed.
:param pefim: True if a response according to the PEFIM profile
should be created.
:param farg: Argument to pass on to the assertion constructor
:return: A response instance
"""
if farg is None:
assertion_args = {}
args = {}
# if identity:
_issuer = self._issuer(issuer)
# if encrypt_assertion and show_nameid:
# tmp_name_id = name_id
# name_id = None
# name_id = None
# tmp_authn = authn
# authn = None
# tmp_authn_statement = authn_statement
# authn_statement = None
if pefim:
encrypted_advice_attributes = True
encrypt_assertion_self_contained = True
assertion_attributes = self.setup_assertion(
None, sp_entity_id, None, None, None, policy, None, None,
identity, best_effort, sign_response, farg=farg)
assertion = self.setup_assertion(
authn, sp_entity_id, in_response_to, consumer_url, name_id,
policy, _issuer, authn_statement, [], True, sign_response,
farg=farg, session_not_on_or_after=session_not_on_or_after)
assertion.advice = saml.Advice()
# assertion.advice.assertion_id_ref.append(saml.AssertionIDRef())
# assertion.advice.assertion_uri_ref.append(saml.AssertionURIRef())
assertion.advice.assertion.append(assertion_attributes)
else:
assertion = self.setup_assertion(
authn, sp_entity_id, in_response_to, consumer_url, name_id,
policy, _issuer, authn_statement, identity, True,
sign_response, farg=farg,
session_not_on_or_after=session_not_on_or_after)
to_sign = []
if not encrypt_assertion:
if sign_assertion:
assertion.signature = pre_signature_part(assertion.id,
self.sec.my_cert, 2,
sign_alg=sign_alg,
digest_alg=digest_alg)
to_sign.append((class_name(assertion), assertion.id))
args["assertion"] = assertion
if (self.support_AssertionIDRequest() or self.support_AuthnQuery()):
self.session_db.store_assertion(assertion, to_sign)
return self._response(
in_response_to, consumer_url, status, issuer, sign_response,
to_sign, sp_entity_id=sp_entity_id,
encrypt_assertion=encrypt_assertion,
encrypt_cert_advice=encrypt_cert_advice,
encrypt_cert_assertion=encrypt_cert_assertion,
encrypt_assertion_self_contained=encrypt_assertion_self_contained,
encrypted_advice_attributes=encrypted_advice_attributes,
sign_assertion=sign_assertion,
pefim=pefim, sign_alg=sign_alg, digest_alg=digest_alg, **args) | python | def _authn_response(self, in_response_to, consumer_url,
sp_entity_id, identity=None, name_id=None,
status=None, authn=None, issuer=None, policy=None,
sign_assertion=False, sign_response=False,
best_effort=False, encrypt_assertion=False,
encrypt_cert_advice=None, encrypt_cert_assertion=None,
authn_statement=None,
encrypt_assertion_self_contained=False,
encrypted_advice_attributes=False,
pefim=False, sign_alg=None, digest_alg=None,
farg=None, session_not_on_or_after=None):
if farg is None:
assertion_args = {}
args = {}
# if identity:
_issuer = self._issuer(issuer)
# if encrypt_assertion and show_nameid:
# tmp_name_id = name_id
# name_id = None
# name_id = None
# tmp_authn = authn
# authn = None
# tmp_authn_statement = authn_statement
# authn_statement = None
if pefim:
encrypted_advice_attributes = True
encrypt_assertion_self_contained = True
assertion_attributes = self.setup_assertion(
None, sp_entity_id, None, None, None, policy, None, None,
identity, best_effort, sign_response, farg=farg)
assertion = self.setup_assertion(
authn, sp_entity_id, in_response_to, consumer_url, name_id,
policy, _issuer, authn_statement, [], True, sign_response,
farg=farg, session_not_on_or_after=session_not_on_or_after)
assertion.advice = saml.Advice()
# assertion.advice.assertion_id_ref.append(saml.AssertionIDRef())
# assertion.advice.assertion_uri_ref.append(saml.AssertionURIRef())
assertion.advice.assertion.append(assertion_attributes)
else:
assertion = self.setup_assertion(
authn, sp_entity_id, in_response_to, consumer_url, name_id,
policy, _issuer, authn_statement, identity, True,
sign_response, farg=farg,
session_not_on_or_after=session_not_on_or_after)
to_sign = []
if not encrypt_assertion:
if sign_assertion:
assertion.signature = pre_signature_part(assertion.id,
self.sec.my_cert, 2,
sign_alg=sign_alg,
digest_alg=digest_alg)
to_sign.append((class_name(assertion), assertion.id))
args["assertion"] = assertion
if (self.support_AssertionIDRequest() or self.support_AuthnQuery()):
self.session_db.store_assertion(assertion, to_sign)
return self._response(
in_response_to, consumer_url, status, issuer, sign_response,
to_sign, sp_entity_id=sp_entity_id,
encrypt_assertion=encrypt_assertion,
encrypt_cert_advice=encrypt_cert_advice,
encrypt_cert_assertion=encrypt_cert_assertion,
encrypt_assertion_self_contained=encrypt_assertion_self_contained,
encrypted_advice_attributes=encrypted_advice_attributes,
sign_assertion=sign_assertion,
pefim=pefim, sign_alg=sign_alg, digest_alg=digest_alg, **args) | [
"def",
"_authn_response",
"(",
"self",
",",
"in_response_to",
",",
"consumer_url",
",",
"sp_entity_id",
",",
"identity",
"=",
"None",
",",
"name_id",
"=",
"None",
",",
"status",
"=",
"None",
",",
"authn",
"=",
"None",
",",
"issuer",
"=",
"None",
",",
"po... | Create a response. A layer of indirection.
:param in_response_to: The session identifier of the request
:param consumer_url: The URL which should receive the response
:param sp_entity_id: The entity identifier of the SP
:param identity: A dictionary with attributes and values that are
expected to be the bases for the assertion in the response.
:param name_id: The identifier of the subject
:param status: The status of the response
:param authn: A dictionary containing information about the
authn context.
:param issuer: The issuer of the response
:param policy:
:param sign_assertion: Whether the assertion should be signed or not
:param sign_response: Whether the response should be signed or not
:param best_effort: Even if not the SPs demands can be met send a
response.
:param encrypt_assertion: True if assertions should be encrypted.
:param encrypt_assertion_self_contained: True if all encrypted
assertions should have alla namespaces
selfcontained.
:param encrypted_advice_attributes: True if assertions in the advice
element should be encrypted.
:param encrypt_cert_advice: Certificate to be used for encryption of
assertions in the advice element.
:param encrypt_cert_assertion: Certificate to be used for encryption
of assertions.
:param authn_statement: Authentication statement.
:param sign_assertion: True if assertions should be signed.
:param pefim: True if a response according to the PEFIM profile
should be created.
:param farg: Argument to pass on to the assertion constructor
:return: A response instance | [
"Create",
"a",
"response",
".",
"A",
"layer",
"of",
"indirection",
"."
] | d3aa78eeb7d37c12688f783cb4db1c7263a14ad6 | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/server.py#L387-L494 |
232,625 | IdentityPython/pysaml2 | src/saml2/server.py | Server.create_attribute_response | def create_attribute_response(self, identity, in_response_to, destination,
sp_entity_id, userid="", name_id=None,
status=None, issuer=None,
sign_assertion=False, sign_response=False,
attributes=None, sign_alg=None,
digest_alg=None, farg=None, **kwargs):
""" Create an attribute assertion response.
:param identity: A dictionary with attributes and values that are
expected to be the bases for the assertion in the response.
:param in_response_to: The session identifier of the request
:param destination: The URL which should receive the response
:param sp_entity_id: The entity identifier of the SP
:param userid: A identifier of the user
:param name_id: The identifier of the subject
:param status: The status of the response
:param issuer: The issuer of the response
:param sign_assertion: Whether the assertion should be signed or not
:param sign_response: Whether the whole response should be signed
:param attributes:
:param kwargs: To catch extra keyword arguments
:return: A response instance
"""
policy = self.config.getattr("policy", "aa")
if not name_id and userid:
try:
name_id = self.ident.construct_nameid(userid, policy,
sp_entity_id)
logger.warning("Unspecified NameID format")
except Exception:
pass
to_sign = []
if identity:
farg = self.update_farg(in_response_to, sp_entity_id, farg=farg)
_issuer = self._issuer(issuer)
ast = Assertion(identity)
if policy:
ast.apply_policy(sp_entity_id, policy, self.metadata)
else:
policy = Policy()
if attributes:
restr = restriction_from_attribute_spec(attributes)
ast = filter_attribute_value_assertions(ast)
assertion = ast.construct(
sp_entity_id, self.config.attribute_converters, policy,
issuer=_issuer, name_id=name_id,
farg=farg['assertion'])
if sign_assertion:
assertion.signature = pre_signature_part(assertion.id,
self.sec.my_cert, 1,
sign_alg=sign_alg,
digest_alg=digest_alg)
# Just the assertion or the response and the assertion ?
to_sign = [(class_name(assertion), assertion.id)]
kwargs['sign_assertion'] = True
kwargs["assertion"] = assertion
if sp_entity_id:
kwargs['sp_entity_id'] = sp_entity_id
return self._response(in_response_to, destination, status, issuer,
sign_response, to_sign, sign_alg=sign_alg,
digest_alg=digest_alg, **kwargs) | python | def create_attribute_response(self, identity, in_response_to, destination,
sp_entity_id, userid="", name_id=None,
status=None, issuer=None,
sign_assertion=False, sign_response=False,
attributes=None, sign_alg=None,
digest_alg=None, farg=None, **kwargs):
policy = self.config.getattr("policy", "aa")
if not name_id and userid:
try:
name_id = self.ident.construct_nameid(userid, policy,
sp_entity_id)
logger.warning("Unspecified NameID format")
except Exception:
pass
to_sign = []
if identity:
farg = self.update_farg(in_response_to, sp_entity_id, farg=farg)
_issuer = self._issuer(issuer)
ast = Assertion(identity)
if policy:
ast.apply_policy(sp_entity_id, policy, self.metadata)
else:
policy = Policy()
if attributes:
restr = restriction_from_attribute_spec(attributes)
ast = filter_attribute_value_assertions(ast)
assertion = ast.construct(
sp_entity_id, self.config.attribute_converters, policy,
issuer=_issuer, name_id=name_id,
farg=farg['assertion'])
if sign_assertion:
assertion.signature = pre_signature_part(assertion.id,
self.sec.my_cert, 1,
sign_alg=sign_alg,
digest_alg=digest_alg)
# Just the assertion or the response and the assertion ?
to_sign = [(class_name(assertion), assertion.id)]
kwargs['sign_assertion'] = True
kwargs["assertion"] = assertion
if sp_entity_id:
kwargs['sp_entity_id'] = sp_entity_id
return self._response(in_response_to, destination, status, issuer,
sign_response, to_sign, sign_alg=sign_alg,
digest_alg=digest_alg, **kwargs) | [
"def",
"create_attribute_response",
"(",
"self",
",",
"identity",
",",
"in_response_to",
",",
"destination",
",",
"sp_entity_id",
",",
"userid",
"=",
"\"\"",
",",
"name_id",
"=",
"None",
",",
"status",
"=",
"None",
",",
"issuer",
"=",
"None",
",",
"sign_asse... | Create an attribute assertion response.
:param identity: A dictionary with attributes and values that are
expected to be the bases for the assertion in the response.
:param in_response_to: The session identifier of the request
:param destination: The URL which should receive the response
:param sp_entity_id: The entity identifier of the SP
:param userid: A identifier of the user
:param name_id: The identifier of the subject
:param status: The status of the response
:param issuer: The issuer of the response
:param sign_assertion: Whether the assertion should be signed or not
:param sign_response: Whether the whole response should be signed
:param attributes:
:param kwargs: To catch extra keyword arguments
:return: A response instance | [
"Create",
"an",
"attribute",
"assertion",
"response",
"."
] | d3aa78eeb7d37c12688f783cb4db1c7263a14ad6 | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/server.py#L499-L570 |
232,626 | IdentityPython/pysaml2 | src/saml2/server.py | Server.create_authn_response | def create_authn_response(self, identity, in_response_to, destination,
sp_entity_id, name_id_policy=None, userid=None,
name_id=None, authn=None, issuer=None,
sign_response=None, sign_assertion=None,
encrypt_cert_advice=None,
encrypt_cert_assertion=None,
encrypt_assertion=None,
encrypt_assertion_self_contained=True,
encrypted_advice_attributes=False, pefim=False,
sign_alg=None, digest_alg=None,
session_not_on_or_after=None,
**kwargs):
""" Constructs an AuthenticationResponse
:param identity: Information about an user
:param in_response_to: The identifier of the authentication request
this response is an answer to.
:param destination: Where the response should be sent
:param sp_entity_id: The entity identifier of the Service Provider
:param name_id_policy: How the NameID should be constructed
:param userid: The subject identifier
:param name_id: The identifier of the subject. A saml.NameID instance.
:param authn: Dictionary with information about the authentication
context
:param issuer: Issuer of the response
:param sign_assertion: Whether the assertion should be signed or not.
:param sign_response: Whether the response should be signed or not.
:param encrypt_assertion: True if assertions should be encrypted.
:param encrypt_assertion_self_contained: True if all encrypted
assertions should have alla namespaces
selfcontained.
:param encrypted_advice_attributes: True if assertions in the advice
element should be encrypted.
:param encrypt_cert_advice: Certificate to be used for encryption of
assertions in the advice element.
:param encrypt_cert_assertion: Certificate to be used for encryption
of assertions.
:param sign_assertion: True if assertions should be signed.
:param pefim: True if a response according to the PEFIM profile
should be created.
:return: A response instance
"""
try:
args = self.gather_authn_response_args(
sp_entity_id, name_id_policy=name_id_policy, userid=userid,
name_id=name_id, sign_response=sign_response,
sign_assertion=sign_assertion,
encrypt_cert_advice=encrypt_cert_advice,
encrypt_cert_assertion=encrypt_cert_assertion,
encrypt_assertion=encrypt_assertion,
encrypt_assertion_self_contained
=encrypt_assertion_self_contained,
encrypted_advice_attributes=encrypted_advice_attributes,
pefim=pefim, **kwargs)
except IOError as exc:
response = self.create_error_response(in_response_to,
destination,
sp_entity_id,
exc, name_id)
return ("%s" % response).split("\n")
try:
_authn = authn
if (sign_assertion or sign_response) and \
self.sec.cert_handler.generate_cert():
with self.lock:
self.sec.cert_handler.update_cert(True)
return self._authn_response(
in_response_to, destination, sp_entity_id, identity,
authn=_authn, issuer=issuer, pefim=pefim,
sign_alg=sign_alg, digest_alg=digest_alg,
session_not_on_or_after=session_not_on_or_after, **args)
return self._authn_response(
in_response_to, destination, sp_entity_id, identity,
authn=_authn, issuer=issuer, pefim=pefim, sign_alg=sign_alg,
digest_alg=digest_alg,
session_not_on_or_after=session_not_on_or_after, **args)
except MissingValue as exc:
return self.create_error_response(in_response_to, destination,
sp_entity_id, exc, name_id) | python | def create_authn_response(self, identity, in_response_to, destination,
sp_entity_id, name_id_policy=None, userid=None,
name_id=None, authn=None, issuer=None,
sign_response=None, sign_assertion=None,
encrypt_cert_advice=None,
encrypt_cert_assertion=None,
encrypt_assertion=None,
encrypt_assertion_self_contained=True,
encrypted_advice_attributes=False, pefim=False,
sign_alg=None, digest_alg=None,
session_not_on_or_after=None,
**kwargs):
try:
args = self.gather_authn_response_args(
sp_entity_id, name_id_policy=name_id_policy, userid=userid,
name_id=name_id, sign_response=sign_response,
sign_assertion=sign_assertion,
encrypt_cert_advice=encrypt_cert_advice,
encrypt_cert_assertion=encrypt_cert_assertion,
encrypt_assertion=encrypt_assertion,
encrypt_assertion_self_contained
=encrypt_assertion_self_contained,
encrypted_advice_attributes=encrypted_advice_attributes,
pefim=pefim, **kwargs)
except IOError as exc:
response = self.create_error_response(in_response_to,
destination,
sp_entity_id,
exc, name_id)
return ("%s" % response).split("\n")
try:
_authn = authn
if (sign_assertion or sign_response) and \
self.sec.cert_handler.generate_cert():
with self.lock:
self.sec.cert_handler.update_cert(True)
return self._authn_response(
in_response_to, destination, sp_entity_id, identity,
authn=_authn, issuer=issuer, pefim=pefim,
sign_alg=sign_alg, digest_alg=digest_alg,
session_not_on_or_after=session_not_on_or_after, **args)
return self._authn_response(
in_response_to, destination, sp_entity_id, identity,
authn=_authn, issuer=issuer, pefim=pefim, sign_alg=sign_alg,
digest_alg=digest_alg,
session_not_on_or_after=session_not_on_or_after, **args)
except MissingValue as exc:
return self.create_error_response(in_response_to, destination,
sp_entity_id, exc, name_id) | [
"def",
"create_authn_response",
"(",
"self",
",",
"identity",
",",
"in_response_to",
",",
"destination",
",",
"sp_entity_id",
",",
"name_id_policy",
"=",
"None",
",",
"userid",
"=",
"None",
",",
"name_id",
"=",
"None",
",",
"authn",
"=",
"None",
",",
"issuer... | Constructs an AuthenticationResponse
:param identity: Information about an user
:param in_response_to: The identifier of the authentication request
this response is an answer to.
:param destination: Where the response should be sent
:param sp_entity_id: The entity identifier of the Service Provider
:param name_id_policy: How the NameID should be constructed
:param userid: The subject identifier
:param name_id: The identifier of the subject. A saml.NameID instance.
:param authn: Dictionary with information about the authentication
context
:param issuer: Issuer of the response
:param sign_assertion: Whether the assertion should be signed or not.
:param sign_response: Whether the response should be signed or not.
:param encrypt_assertion: True if assertions should be encrypted.
:param encrypt_assertion_self_contained: True if all encrypted
assertions should have alla namespaces
selfcontained.
:param encrypted_advice_attributes: True if assertions in the advice
element should be encrypted.
:param encrypt_cert_advice: Certificate to be used for encryption of
assertions in the advice element.
:param encrypt_cert_assertion: Certificate to be used for encryption
of assertions.
:param sign_assertion: True if assertions should be signed.
:param pefim: True if a response according to the PEFIM profile
should be created.
:return: A response instance | [
"Constructs",
"an",
"AuthenticationResponse"
] | d3aa78eeb7d37c12688f783cb4db1c7263a14ad6 | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/server.py#L675-L756 |
232,627 | IdentityPython/pysaml2 | src/saml2/server.py | Server.create_name_id_mapping_response | def create_name_id_mapping_response(self, name_id=None, encrypted_id=None,
in_response_to=None,
issuer=None, sign_response=False,
status=None, sign_alg=None,
digest_alg=None, **kwargs):
"""
protocol for mapping a principal's name identifier into a
different name identifier for the same principal.
Done over soap.
:param name_id:
:param encrypted_id:
:param in_response_to:
:param issuer:
:param sign_response:
:param status:
:return:
"""
# Done over SOAP
ms_args = self.message_args()
_resp = NameIDMappingResponse(name_id, encrypted_id,
in_response_to=in_response_to, **ms_args)
if sign_response:
return self.sign(_resp, sign_alg=sign_alg, digest_alg=digest_alg)
else:
logger.info("Message: %s", _resp)
return _resp | python | def create_name_id_mapping_response(self, name_id=None, encrypted_id=None,
in_response_to=None,
issuer=None, sign_response=False,
status=None, sign_alg=None,
digest_alg=None, **kwargs):
# Done over SOAP
ms_args = self.message_args()
_resp = NameIDMappingResponse(name_id, encrypted_id,
in_response_to=in_response_to, **ms_args)
if sign_response:
return self.sign(_resp, sign_alg=sign_alg, digest_alg=digest_alg)
else:
logger.info("Message: %s", _resp)
return _resp | [
"def",
"create_name_id_mapping_response",
"(",
"self",
",",
"name_id",
"=",
"None",
",",
"encrypted_id",
"=",
"None",
",",
"in_response_to",
"=",
"None",
",",
"issuer",
"=",
"None",
",",
"sign_response",
"=",
"False",
",",
"status",
"=",
"None",
",",
"sign_a... | protocol for mapping a principal's name identifier into a
different name identifier for the same principal.
Done over soap.
:param name_id:
:param encrypted_id:
:param in_response_to:
:param issuer:
:param sign_response:
:param status:
:return: | [
"protocol",
"for",
"mapping",
"a",
"principal",
"s",
"name",
"identifier",
"into",
"a",
"different",
"name",
"identifier",
"for",
"the",
"same",
"principal",
".",
"Done",
"over",
"soap",
"."
] | d3aa78eeb7d37c12688f783cb4db1c7263a14ad6 | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/server.py#L801-L830 |
232,628 | IdentityPython/pysaml2 | src/saml2/server.py | Server.clean_out_user | def clean_out_user(self, name_id):
"""
Remove all authentication statements that belongs to a user identified
by a NameID instance
:param name_id: NameID instance
:return: The local identifier for the user
"""
lid = self.ident.find_local_id(name_id)
logger.info("Clean out %s", lid)
# remove the authentications
try:
for _nid in [decode(x) for x in self.ident.db[lid].split(" ")]:
try:
self.session_db.remove_authn_statements(_nid)
except KeyError:
pass
except KeyError:
pass
return lid | python | def clean_out_user(self, name_id):
lid = self.ident.find_local_id(name_id)
logger.info("Clean out %s", lid)
# remove the authentications
try:
for _nid in [decode(x) for x in self.ident.db[lid].split(" ")]:
try:
self.session_db.remove_authn_statements(_nid)
except KeyError:
pass
except KeyError:
pass
return lid | [
"def",
"clean_out_user",
"(",
"self",
",",
"name_id",
")",
":",
"lid",
"=",
"self",
".",
"ident",
".",
"find_local_id",
"(",
"name_id",
")",
"logger",
".",
"info",
"(",
"\"Clean out %s\"",
",",
"lid",
")",
"# remove the authentications",
"try",
":",
"for",
... | Remove all authentication statements that belongs to a user identified
by a NameID instance
:param name_id: NameID instance
:return: The local identifier for the user | [
"Remove",
"all",
"authentication",
"statements",
"that",
"belongs",
"to",
"a",
"user",
"identified",
"by",
"a",
"NameID",
"instance"
] | d3aa78eeb7d37c12688f783cb4db1c7263a14ad6 | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/server.py#L899-L921 |
232,629 | IdentityPython/pysaml2 | src/saml2/mongo_store.py | _mdb_get_database | def _mdb_get_database(uri, **kwargs):
"""
Helper-function to connect to MongoDB and return a database object.
The `uri' argument should be either a full MongoDB connection URI string,
or just a database name in which case a connection to the default mongo
instance at mongodb://localhost:27017 will be made.
Performs explicit authentication if a username is provided in a connection
string URI, since PyMongo does not always seem to do that as promised.
:params database: name as string or (uri, name)
:returns: pymongo database object
"""
if not "tz_aware" in kwargs:
# default, but not forced
kwargs["tz_aware"] = True
connection_factory = MongoClient
_parsed_uri = {}
try:
_parsed_uri = pymongo.uri_parser.parse_uri(uri)
except pymongo.errors.InvalidURI:
# assume URI to be just the database name
db_name = uri
_conn = MongoClient()
pass
else:
if "replicaset" in _parsed_uri["options"]:
connection_factory = MongoReplicaSetClient
db_name = _parsed_uri.get("database", "pysaml2")
_conn = connection_factory(uri, **kwargs)
_db = _conn[db_name]
if "username" in _parsed_uri:
_db.authenticate(
_parsed_uri.get("username", None),
_parsed_uri.get("password", None)
)
return _db | python | def _mdb_get_database(uri, **kwargs):
if not "tz_aware" in kwargs:
# default, but not forced
kwargs["tz_aware"] = True
connection_factory = MongoClient
_parsed_uri = {}
try:
_parsed_uri = pymongo.uri_parser.parse_uri(uri)
except pymongo.errors.InvalidURI:
# assume URI to be just the database name
db_name = uri
_conn = MongoClient()
pass
else:
if "replicaset" in _parsed_uri["options"]:
connection_factory = MongoReplicaSetClient
db_name = _parsed_uri.get("database", "pysaml2")
_conn = connection_factory(uri, **kwargs)
_db = _conn[db_name]
if "username" in _parsed_uri:
_db.authenticate(
_parsed_uri.get("username", None),
_parsed_uri.get("password", None)
)
return _db | [
"def",
"_mdb_get_database",
"(",
"uri",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"\"tz_aware\"",
"in",
"kwargs",
":",
"# default, but not forced",
"kwargs",
"[",
"\"tz_aware\"",
"]",
"=",
"True",
"connection_factory",
"=",
"MongoClient",
"_parsed_uri",
"=... | Helper-function to connect to MongoDB and return a database object.
The `uri' argument should be either a full MongoDB connection URI string,
or just a database name in which case a connection to the default mongo
instance at mongodb://localhost:27017 will be made.
Performs explicit authentication if a username is provided in a connection
string URI, since PyMongo does not always seem to do that as promised.
:params database: name as string or (uri, name)
:returns: pymongo database object | [
"Helper",
"-",
"function",
"to",
"connect",
"to",
"MongoDB",
"and",
"return",
"a",
"database",
"object",
"."
] | d3aa78eeb7d37c12688f783cb4db1c7263a14ad6 | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/mongo_store.py#L239-L281 |
232,630 | IdentityPython/pysaml2 | src/saml2/argtree.py | add_path | def add_path(tdict, path):
"""
Create or extend an argument tree `tdict` from `path`.
:param tdict: a dictionary representing a argument tree
:param path: a path list
:return: a dictionary
Convert a list of items in a 'path' into a nested dict, where the
second to last item becomes the key for the final item. The remaining
items in the path become keys in the nested dict around that final pair
of items.
For example, for input values of:
tdict={}
path = ['assertion', 'subject', 'subject_confirmation',
'method', 'urn:oasis:names:tc:SAML:2.0:cm:bearer']
Returns an output value of:
{'assertion': {'subject': {'subject_confirmation':
{'method': 'urn:oasis:names:tc:SAML:2.0:cm:bearer'}}}}
Another example, this time with a non-empty tdict input:
tdict={'method': 'urn:oasis:names:tc:SAML:2.0:cm:bearer'},
path=['subject_confirmation_data', 'in_response_to', '_012345']
Returns an output value of:
{'subject_confirmation_data': {'in_response_to': '_012345'},
'method': 'urn:oasis:names:tc:SAML:2.0:cm:bearer'}
"""
t = tdict
for step in path[:-2]:
try:
t = t[step]
except KeyError:
t[step] = {}
t = t[step]
t[path[-2]] = path[-1]
return tdict | python | def add_path(tdict, path):
t = tdict
for step in path[:-2]:
try:
t = t[step]
except KeyError:
t[step] = {}
t = t[step]
t[path[-2]] = path[-1]
return tdict | [
"def",
"add_path",
"(",
"tdict",
",",
"path",
")",
":",
"t",
"=",
"tdict",
"for",
"step",
"in",
"path",
"[",
":",
"-",
"2",
"]",
":",
"try",
":",
"t",
"=",
"t",
"[",
"step",
"]",
"except",
"KeyError",
":",
"t",
"[",
"step",
"]",
"=",
"{",
"... | Create or extend an argument tree `tdict` from `path`.
:param tdict: a dictionary representing a argument tree
:param path: a path list
:return: a dictionary
Convert a list of items in a 'path' into a nested dict, where the
second to last item becomes the key for the final item. The remaining
items in the path become keys in the nested dict around that final pair
of items.
For example, for input values of:
tdict={}
path = ['assertion', 'subject', 'subject_confirmation',
'method', 'urn:oasis:names:tc:SAML:2.0:cm:bearer']
Returns an output value of:
{'assertion': {'subject': {'subject_confirmation':
{'method': 'urn:oasis:names:tc:SAML:2.0:cm:bearer'}}}}
Another example, this time with a non-empty tdict input:
tdict={'method': 'urn:oasis:names:tc:SAML:2.0:cm:bearer'},
path=['subject_confirmation_data', 'in_response_to', '_012345']
Returns an output value of:
{'subject_confirmation_data': {'in_response_to': '_012345'},
'method': 'urn:oasis:names:tc:SAML:2.0:cm:bearer'} | [
"Create",
"or",
"extend",
"an",
"argument",
"tree",
"tdict",
"from",
"path",
"."
] | d3aa78eeb7d37c12688f783cb4db1c7263a14ad6 | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/argtree.py#L54-L94 |
232,631 | IdentityPython/pysaml2 | src/saml2/s_utils.py | valid_email | def valid_email(emailaddress, domains=GENERIC_DOMAINS):
"""Checks for a syntactically valid email address."""
# Email address must be at least 6 characters in total.
# Assuming noone may have addresses of the type a@com
if len(emailaddress) < 6:
return False # Address too short.
# Split up email address into parts.
try:
localpart, domainname = emailaddress.rsplit('@', 1)
host, toplevel = domainname.rsplit('.', 1)
except ValueError:
return False # Address does not have enough parts.
# Check for Country code or Generic Domain.
if len(toplevel) != 2 and toplevel not in domains:
return False # Not a domain name.
for i in '-_.%+.':
localpart = localpart.replace(i, "")
for i in '-_.':
host = host.replace(i, "")
if localpart.isalnum() and host.isalnum():
return True # Email address is fine.
else:
return False | python | def valid_email(emailaddress, domains=GENERIC_DOMAINS):
# Email address must be at least 6 characters in total.
# Assuming noone may have addresses of the type a@com
if len(emailaddress) < 6:
return False # Address too short.
# Split up email address into parts.
try:
localpart, domainname = emailaddress.rsplit('@', 1)
host, toplevel = domainname.rsplit('.', 1)
except ValueError:
return False # Address does not have enough parts.
# Check for Country code or Generic Domain.
if len(toplevel) != 2 and toplevel not in domains:
return False # Not a domain name.
for i in '-_.%+.':
localpart = localpart.replace(i, "")
for i in '-_.':
host = host.replace(i, "")
if localpart.isalnum() and host.isalnum():
return True # Email address is fine.
else:
return False | [
"def",
"valid_email",
"(",
"emailaddress",
",",
"domains",
"=",
"GENERIC_DOMAINS",
")",
":",
"# Email address must be at least 6 characters in total.",
"# Assuming noone may have addresses of the type a@com",
"if",
"len",
"(",
"emailaddress",
")",
"<",
"6",
":",
"return",
"... | Checks for a syntactically valid email address. | [
"Checks",
"for",
"a",
"syntactically",
"valid",
"email",
"address",
"."
] | d3aa78eeb7d37c12688f783cb4db1c7263a14ad6 | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/s_utils.py#L98-L125 |
232,632 | IdentityPython/pysaml2 | src/saml2/s_utils.py | deflate_and_base64_encode | def deflate_and_base64_encode(string_val):
"""
Deflates and the base64 encodes a string
:param string_val: The string to deflate and encode
:return: The deflated and encoded string
"""
if not isinstance(string_val, six.binary_type):
string_val = string_val.encode('utf-8')
return base64.b64encode(zlib.compress(string_val)[2:-4]) | python | def deflate_and_base64_encode(string_val):
if not isinstance(string_val, six.binary_type):
string_val = string_val.encode('utf-8')
return base64.b64encode(zlib.compress(string_val)[2:-4]) | [
"def",
"deflate_and_base64_encode",
"(",
"string_val",
")",
":",
"if",
"not",
"isinstance",
"(",
"string_val",
",",
"six",
".",
"binary_type",
")",
":",
"string_val",
"=",
"string_val",
".",
"encode",
"(",
"'utf-8'",
")",
"return",
"base64",
".",
"b64encode",
... | Deflates and the base64 encodes a string
:param string_val: The string to deflate and encode
:return: The deflated and encoded string | [
"Deflates",
"and",
"the",
"base64",
"encodes",
"a",
"string"
] | d3aa78eeb7d37c12688f783cb4db1c7263a14ad6 | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/s_utils.py#L138-L147 |
232,633 | IdentityPython/pysaml2 | src/saml2/s_utils.py | rndbytes | def rndbytes(size=16, alphabet=""):
"""
Returns rndstr always as a binary type
"""
x = rndstr(size, alphabet)
if isinstance(x, six.string_types):
return x.encode('utf-8')
return x | python | def rndbytes(size=16, alphabet=""):
x = rndstr(size, alphabet)
if isinstance(x, six.string_types):
return x.encode('utf-8')
return x | [
"def",
"rndbytes",
"(",
"size",
"=",
"16",
",",
"alphabet",
"=",
"\"\"",
")",
":",
"x",
"=",
"rndstr",
"(",
"size",
",",
"alphabet",
")",
"if",
"isinstance",
"(",
"x",
",",
"six",
".",
"string_types",
")",
":",
"return",
"x",
".",
"encode",
"(",
... | Returns rndstr always as a binary type | [
"Returns",
"rndstr",
"always",
"as",
"a",
"binary",
"type"
] | d3aa78eeb7d37c12688f783cb4db1c7263a14ad6 | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/s_utils.py#L163-L170 |
232,634 | IdentityPython/pysaml2 | src/saml2/s_utils.py | parse_attribute_map | def parse_attribute_map(filenames):
"""
Expects a file with each line being composed of the oid for the attribute
exactly one space, a user friendly name of the attribute and then
the type specification of the name.
:param filenames: List of filenames on mapfiles.
:return: A 2-tuple, one dictionary with the oid as keys and the friendly
names as values, the other one the other way around.
"""
forward = {}
backward = {}
for filename in filenames:
with open(filename) as fp:
for line in fp:
(name, friendly_name, name_format) = line.strip().split()
forward[(name, name_format)] = friendly_name
backward[friendly_name] = (name, name_format)
return forward, backward | python | def parse_attribute_map(filenames):
forward = {}
backward = {}
for filename in filenames:
with open(filename) as fp:
for line in fp:
(name, friendly_name, name_format) = line.strip().split()
forward[(name, name_format)] = friendly_name
backward[friendly_name] = (name, name_format)
return forward, backward | [
"def",
"parse_attribute_map",
"(",
"filenames",
")",
":",
"forward",
"=",
"{",
"}",
"backward",
"=",
"{",
"}",
"for",
"filename",
"in",
"filenames",
":",
"with",
"open",
"(",
"filename",
")",
"as",
"fp",
":",
"for",
"line",
"in",
"fp",
":",
"(",
"nam... | Expects a file with each line being composed of the oid for the attribute
exactly one space, a user friendly name of the attribute and then
the type specification of the name.
:param filenames: List of filenames on mapfiles.
:return: A 2-tuple, one dictionary with the oid as keys and the friendly
names as values, the other one the other way around. | [
"Expects",
"a",
"file",
"with",
"each",
"line",
"being",
"composed",
"of",
"the",
"oid",
"for",
"the",
"attribute",
"exactly",
"one",
"space",
"a",
"user",
"friendly",
"name",
"of",
"the",
"attribute",
"and",
"then",
"the",
"type",
"specification",
"of",
"... | d3aa78eeb7d37c12688f783cb4db1c7263a14ad6 | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/s_utils.py#L184-L203 |
232,635 | IdentityPython/pysaml2 | src/saml2/s_utils.py | signature | def signature(secret, parts):
"""Generates a signature. All strings are assumed to be utf-8
"""
if not isinstance(secret, six.binary_type):
secret = secret.encode('utf-8')
newparts = []
for part in parts:
if not isinstance(part, six.binary_type):
part = part.encode('utf-8')
newparts.append(part)
parts = newparts
if sys.version_info >= (2, 5):
csum = hmac.new(secret, digestmod=hashlib.sha1)
else:
csum = hmac.new(secret, digestmod=sha)
for part in parts:
csum.update(part)
return csum.hexdigest() | python | def signature(secret, parts):
if not isinstance(secret, six.binary_type):
secret = secret.encode('utf-8')
newparts = []
for part in parts:
if not isinstance(part, six.binary_type):
part = part.encode('utf-8')
newparts.append(part)
parts = newparts
if sys.version_info >= (2, 5):
csum = hmac.new(secret, digestmod=hashlib.sha1)
else:
csum = hmac.new(secret, digestmod=sha)
for part in parts:
csum.update(part)
return csum.hexdigest() | [
"def",
"signature",
"(",
"secret",
",",
"parts",
")",
":",
"if",
"not",
"isinstance",
"(",
"secret",
",",
"six",
".",
"binary_type",
")",
":",
"secret",
"=",
"secret",
".",
"encode",
"(",
"'utf-8'",
")",
"newparts",
"=",
"[",
"]",
"for",
"part",
"in"... | Generates a signature. All strings are assumed to be utf-8 | [
"Generates",
"a",
"signature",
".",
"All",
"strings",
"are",
"assumed",
"to",
"be",
"utf",
"-",
"8"
] | d3aa78eeb7d37c12688f783cb4db1c7263a14ad6 | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/s_utils.py#L371-L390 |
232,636 | IdentityPython/pysaml2 | src/saml2/mdstore.py | MetaData.any | def any(self, typ, service, binding=None):
"""
Return any entity that matches the specification
:param typ: Type of entity
:param service:
:param binding:
:return:
"""
res = {}
for ent in self.keys():
bind = self.service(ent, typ, service, binding)
if bind:
res[ent] = bind
return res | python | def any(self, typ, service, binding=None):
res = {}
for ent in self.keys():
bind = self.service(ent, typ, service, binding)
if bind:
res[ent] = bind
return res | [
"def",
"any",
"(",
"self",
",",
"typ",
",",
"service",
",",
"binding",
"=",
"None",
")",
":",
"res",
"=",
"{",
"}",
"for",
"ent",
"in",
"self",
".",
"keys",
"(",
")",
":",
"bind",
"=",
"self",
".",
"service",
"(",
"ent",
",",
"typ",
",",
"ser... | Return any entity that matches the specification
:param typ: Type of entity
:param service:
:param binding:
:return: | [
"Return",
"any",
"entity",
"that",
"matches",
"the",
"specification"
] | d3aa78eeb7d37c12688f783cb4db1c7263a14ad6 | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/mdstore.py#L268-L283 |
232,637 | IdentityPython/pysaml2 | src/saml2/mdstore.py | MetaData.bindings | def bindings(self, entity_id, typ, service):
"""
Get me all the bindings that are registered for a service entity
:param entity_id:
:param service:
:return:
"""
return self.service(entity_id, typ, service) | python | def bindings(self, entity_id, typ, service):
return self.service(entity_id, typ, service) | [
"def",
"bindings",
"(",
"self",
",",
"entity_id",
",",
"typ",
",",
"service",
")",
":",
"return",
"self",
".",
"service",
"(",
"entity_id",
",",
"typ",
",",
"service",
")"
] | Get me all the bindings that are registered for a service entity
:param entity_id:
:param service:
:return: | [
"Get",
"me",
"all",
"the",
"bindings",
"that",
"are",
"registered",
"for",
"a",
"service",
"entity"
] | d3aa78eeb7d37c12688f783cb4db1c7263a14ad6 | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/mdstore.py#L316-L324 |
232,638 | IdentityPython/pysaml2 | src/saml2/mdstore.py | MetaData.with_descriptor | def with_descriptor(self, descriptor):
'''
Returns any entities with the specified descriptor
'''
res = {}
desc = "%s_descriptor" % descriptor
for eid, ent in self.items():
if desc in ent:
res[eid] = ent
return res | python | def with_descriptor(self, descriptor):
'''
Returns any entities with the specified descriptor
'''
res = {}
desc = "%s_descriptor" % descriptor
for eid, ent in self.items():
if desc in ent:
res[eid] = ent
return res | [
"def",
"with_descriptor",
"(",
"self",
",",
"descriptor",
")",
":",
"res",
"=",
"{",
"}",
"desc",
"=",
"\"%s_descriptor\"",
"%",
"descriptor",
"for",
"eid",
",",
"ent",
"in",
"self",
".",
"items",
"(",
")",
":",
"if",
"desc",
"in",
"ent",
":",
"res",... | Returns any entities with the specified descriptor | [
"Returns",
"any",
"entities",
"with",
"the",
"specified",
"descriptor"
] | d3aa78eeb7d37c12688f783cb4db1c7263a14ad6 | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/mdstore.py#L341-L350 |
232,639 | IdentityPython/pysaml2 | src/saml2/mdstore.py | MetaData.certs | def certs(self, entity_id, descriptor, use="signing"):
'''
Returns certificates for the given Entity
'''
ent = self[entity_id]
def extract_certs(srvs):
res = []
for srv in srvs:
if "key_descriptor" in srv:
for key in srv["key_descriptor"]:
if "use" in key and key["use"] == use:
for dat in key["key_info"]["x509_data"]:
cert = repack_cert(
dat["x509_certificate"]["text"])
if cert not in res:
res.append(cert)
elif not "use" in key:
for dat in key["key_info"]["x509_data"]:
cert = repack_cert(
dat["x509_certificate"]["text"])
if cert not in res:
res.append(cert)
return res
if descriptor == "any":
res = []
for descr in ["spsso", "idpsso", "role", "authn_authority",
"attribute_authority", "pdp"]:
try:
srvs = ent["%s_descriptor" % descr]
except KeyError:
continue
res.extend(extract_certs(srvs))
else:
srvs = ent["%s_descriptor" % descriptor]
res = extract_certs(srvs)
return res | python | def certs(self, entity_id, descriptor, use="signing"):
'''
Returns certificates for the given Entity
'''
ent = self[entity_id]
def extract_certs(srvs):
res = []
for srv in srvs:
if "key_descriptor" in srv:
for key in srv["key_descriptor"]:
if "use" in key and key["use"] == use:
for dat in key["key_info"]["x509_data"]:
cert = repack_cert(
dat["x509_certificate"]["text"])
if cert not in res:
res.append(cert)
elif not "use" in key:
for dat in key["key_info"]["x509_data"]:
cert = repack_cert(
dat["x509_certificate"]["text"])
if cert not in res:
res.append(cert)
return res
if descriptor == "any":
res = []
for descr in ["spsso", "idpsso", "role", "authn_authority",
"attribute_authority", "pdp"]:
try:
srvs = ent["%s_descriptor" % descr]
except KeyError:
continue
res.extend(extract_certs(srvs))
else:
srvs = ent["%s_descriptor" % descriptor]
res = extract_certs(srvs)
return res | [
"def",
"certs",
"(",
"self",
",",
"entity_id",
",",
"descriptor",
",",
"use",
"=",
"\"signing\"",
")",
":",
"ent",
"=",
"self",
"[",
"entity_id",
"]",
"def",
"extract_certs",
"(",
"srvs",
")",
":",
"res",
"=",
"[",
"]",
"for",
"srv",
"in",
"srvs",
... | Returns certificates for the given Entity | [
"Returns",
"certificates",
"for",
"the",
"given",
"Entity"
] | d3aa78eeb7d37c12688f783cb4db1c7263a14ad6 | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/mdstore.py#L388-L428 |
232,640 | IdentityPython/pysaml2 | src/saml2/mdstore.py | InMemoryMetaData.service | def service(self, entity_id, typ, service, binding=None):
""" Get me all services with a specified
entity ID and type, that supports the specified version of binding.
:param entity_id: The EntityId
:param typ: Type of service (idp, attribute_authority, ...)
:param service: which service that is sought for
:param binding: A binding identifier
:return: list of service descriptions.
Or if no binding was specified a list of 2-tuples (binding, srv)
"""
try:
srvs = []
for t in self[entity_id][typ]:
try:
srvs.extend(t[service])
except KeyError:
pass
except KeyError:
return None
if not srvs:
return srvs
if binding:
res = []
for srv in srvs:
if srv["binding"] == binding:
res.append(srv)
else:
res = {}
for srv in srvs:
try:
res[srv["binding"]].append(srv)
except KeyError:
res[srv["binding"]] = [srv]
logger.debug("service => %s", res)
return res | python | def service(self, entity_id, typ, service, binding=None):
try:
srvs = []
for t in self[entity_id][typ]:
try:
srvs.extend(t[service])
except KeyError:
pass
except KeyError:
return None
if not srvs:
return srvs
if binding:
res = []
for srv in srvs:
if srv["binding"] == binding:
res.append(srv)
else:
res = {}
for srv in srvs:
try:
res[srv["binding"]].append(srv)
except KeyError:
res[srv["binding"]] = [srv]
logger.debug("service => %s", res)
return res | [
"def",
"service",
"(",
"self",
",",
"entity_id",
",",
"typ",
",",
"service",
",",
"binding",
"=",
"None",
")",
":",
"try",
":",
"srvs",
"=",
"[",
"]",
"for",
"t",
"in",
"self",
"[",
"entity_id",
"]",
"[",
"typ",
"]",
":",
"try",
":",
"srvs",
".... | Get me all services with a specified
entity ID and type, that supports the specified version of binding.
:param entity_id: The EntityId
:param typ: Type of service (idp, attribute_authority, ...)
:param service: which service that is sought for
:param binding: A binding identifier
:return: list of service descriptions.
Or if no binding was specified a list of 2-tuples (binding, srv) | [
"Get",
"me",
"all",
"services",
"with",
"a",
"specified",
"entity",
"ID",
"and",
"type",
"that",
"supports",
"the",
"specified",
"version",
"of",
"binding",
"."
] | d3aa78eeb7d37c12688f783cb4db1c7263a14ad6 | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/mdstore.py#L548-L585 |
232,641 | IdentityPython/pysaml2 | src/saml2/mdstore.py | InMemoryMetaData.attribute_requirement | def attribute_requirement(self, entity_id, index=None):
""" Returns what attributes the SP requires and which are optional
if any such demands are registered in the Metadata.
:param entity_id: The entity id of the SP
:param index: which of the attribute consumer services its all about
if index=None then return all attributes expected by all
attribute_consuming_services.
:return: 2-tuple, list of required and list of optional attributes
"""
res = {"required": [], "optional": []}
try:
for sp in self[entity_id]["spsso_descriptor"]:
_res = attribute_requirement(sp, index)
res["required"].extend(_res["required"])
res["optional"].extend(_res["optional"])
except KeyError:
return None
return res | python | def attribute_requirement(self, entity_id, index=None):
res = {"required": [], "optional": []}
try:
for sp in self[entity_id]["spsso_descriptor"]:
_res = attribute_requirement(sp, index)
res["required"].extend(_res["required"])
res["optional"].extend(_res["optional"])
except KeyError:
return None
return res | [
"def",
"attribute_requirement",
"(",
"self",
",",
"entity_id",
",",
"index",
"=",
"None",
")",
":",
"res",
"=",
"{",
"\"required\"",
":",
"[",
"]",
",",
"\"optional\"",
":",
"[",
"]",
"}",
"try",
":",
"for",
"sp",
"in",
"self",
"[",
"entity_id",
"]",... | Returns what attributes the SP requires and which are optional
if any such demands are registered in the Metadata.
:param entity_id: The entity id of the SP
:param index: which of the attribute consumer services its all about
if index=None then return all attributes expected by all
attribute_consuming_services.
:return: 2-tuple, list of required and list of optional attributes | [
"Returns",
"what",
"attributes",
"the",
"SP",
"requires",
"and",
"which",
"are",
"optional",
"if",
"any",
"such",
"demands",
"are",
"registered",
"in",
"the",
"Metadata",
"."
] | d3aa78eeb7d37c12688f783cb4db1c7263a14ad6 | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/mdstore.py#L587-L607 |
232,642 | IdentityPython/pysaml2 | src/saml2/mdstore.py | MetaDataExtern.load | def load(self, *args, **kwargs):
""" Imports metadata by the use of HTTP GET.
If the fingerprint is known the file will be checked for
compliance before it is imported.
"""
response = self.http.send(self.url)
if response.status_code == 200:
_txt = response.content
return self.parse_and_check_signature(_txt)
else:
logger.info("Response status: %s", response.status_code)
raise SourceNotFound(self.url) | python | def load(self, *args, **kwargs):
response = self.http.send(self.url)
if response.status_code == 200:
_txt = response.content
return self.parse_and_check_signature(_txt)
else:
logger.info("Response status: %s", response.status_code)
raise SourceNotFound(self.url) | [
"def",
"load",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"response",
"=",
"self",
".",
"http",
".",
"send",
"(",
"self",
".",
"url",
")",
"if",
"response",
".",
"status_code",
"==",
"200",
":",
"_txt",
"=",
"response",
"."... | Imports metadata by the use of HTTP GET.
If the fingerprint is known the file will be checked for
compliance before it is imported. | [
"Imports",
"metadata",
"by",
"the",
"use",
"of",
"HTTP",
"GET",
".",
"If",
"the",
"fingerprint",
"is",
"known",
"the",
"file",
"will",
"be",
"checked",
"for",
"compliance",
"before",
"it",
"is",
"imported",
"."
] | d3aa78eeb7d37c12688f783cb4db1c7263a14ad6 | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/mdstore.py#L747-L758 |
232,643 | IdentityPython/pysaml2 | src/saml2/mdstore.py | MetadataStore.entity_categories | def entity_categories(self, entity_id):
"""
Get a list of entity categories for an entity id.
:param entity_id: Entity id
:return: Entity categories
:type entity_id: string
:rtype: [string]
"""
attributes = self.entity_attributes(entity_id)
return attributes.get(ENTITY_CATEGORY, []) | python | def entity_categories(self, entity_id):
attributes = self.entity_attributes(entity_id)
return attributes.get(ENTITY_CATEGORY, []) | [
"def",
"entity_categories",
"(",
"self",
",",
"entity_id",
")",
":",
"attributes",
"=",
"self",
".",
"entity_attributes",
"(",
"entity_id",
")",
"return",
"attributes",
".",
"get",
"(",
"ENTITY_CATEGORY",
",",
"[",
"]",
")"
] | Get a list of entity categories for an entity id.
:param entity_id: Entity id
:return: Entity categories
:type entity_id: string
:rtype: [string] | [
"Get",
"a",
"list",
"of",
"entity",
"categories",
"for",
"an",
"entity",
"id",
"."
] | d3aa78eeb7d37c12688f783cb4db1c7263a14ad6 | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/mdstore.py#L1199-L1210 |
232,644 | IdentityPython/pysaml2 | src/saml2/mdstore.py | MetadataStore.supported_entity_categories | def supported_entity_categories(self, entity_id):
"""
Get a list of entity category support for an entity id.
:param entity_id: Entity id
:return: Entity category support
:type entity_id: string
:rtype: [string]
"""
attributes = self.entity_attributes(entity_id)
return attributes.get(ENTITY_CATEGORY_SUPPORT, []) | python | def supported_entity_categories(self, entity_id):
attributes = self.entity_attributes(entity_id)
return attributes.get(ENTITY_CATEGORY_SUPPORT, []) | [
"def",
"supported_entity_categories",
"(",
"self",
",",
"entity_id",
")",
":",
"attributes",
"=",
"self",
".",
"entity_attributes",
"(",
"entity_id",
")",
"return",
"attributes",
".",
"get",
"(",
"ENTITY_CATEGORY_SUPPORT",
",",
"[",
"]",
")"
] | Get a list of entity category support for an entity id.
:param entity_id: Entity id
:return: Entity category support
:type entity_id: string
:rtype: [string] | [
"Get",
"a",
"list",
"of",
"entity",
"category",
"support",
"for",
"an",
"entity",
"id",
"."
] | d3aa78eeb7d37c12688f783cb4db1c7263a14ad6 | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/mdstore.py#L1212-L1223 |
232,645 | IdentityPython/pysaml2 | src/saml2/mdstore.py | MetadataStore.entity_attributes | def entity_attributes(self, entity_id):
"""
Get all entity attributes for an entry in the metadata.
Example return data:
{'http://macedir.org/entity-category': ['something', 'something2'],
'http://example.org/saml-foo': ['bar']}
:param entity_id: Entity id
:return: dict with keys and value-lists from metadata
:type entity_id: string
:rtype: dict
"""
res = {}
try:
ext = self.__getitem__(entity_id)["extensions"]
except KeyError:
return res
for elem in ext["extension_elements"]:
if elem["__class__"] == ENTITYATTRIBUTES:
for attr in elem["attribute"]:
if attr["name"] not in res:
res[attr["name"]] = []
res[attr["name"]] += [v["text"] for v in attr[
"attribute_value"]]
return res | python | def entity_attributes(self, entity_id):
res = {}
try:
ext = self.__getitem__(entity_id)["extensions"]
except KeyError:
return res
for elem in ext["extension_elements"]:
if elem["__class__"] == ENTITYATTRIBUTES:
for attr in elem["attribute"]:
if attr["name"] not in res:
res[attr["name"]] = []
res[attr["name"]] += [v["text"] for v in attr[
"attribute_value"]]
return res | [
"def",
"entity_attributes",
"(",
"self",
",",
"entity_id",
")",
":",
"res",
"=",
"{",
"}",
"try",
":",
"ext",
"=",
"self",
".",
"__getitem__",
"(",
"entity_id",
")",
"[",
"\"extensions\"",
"]",
"except",
"KeyError",
":",
"return",
"res",
"for",
"elem",
... | Get all entity attributes for an entry in the metadata.
Example return data:
{'http://macedir.org/entity-category': ['something', 'something2'],
'http://example.org/saml-foo': ['bar']}
:param entity_id: Entity id
:return: dict with keys and value-lists from metadata
:type entity_id: string
:rtype: dict | [
"Get",
"all",
"entity",
"attributes",
"for",
"an",
"entry",
"in",
"the",
"metadata",
"."
] | d3aa78eeb7d37c12688f783cb4db1c7263a14ad6 | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/mdstore.py#L1225-L1252 |
232,646 | IdentityPython/pysaml2 | src/saml2/mdstore.py | MetadataStore.dumps | def dumps(self, format="local"):
"""
Dumps the content in standard metadata format or the pysaml2 metadata
format
:param format: Which format to dump in
:return: a string
"""
if format == "local":
res = EntitiesDescriptor()
for _md in self.metadata.values():
try:
res.entity_descriptor.extend(
_md.entities_descr.entity_descriptor)
except AttributeError:
res.entity_descriptor.append(_md.entity_descr)
return "%s" % res
elif format == "md":
return json.dumps(self.items(), indent=2) | python | def dumps(self, format="local"):
if format == "local":
res = EntitiesDescriptor()
for _md in self.metadata.values():
try:
res.entity_descriptor.extend(
_md.entities_descr.entity_descriptor)
except AttributeError:
res.entity_descriptor.append(_md.entity_descr)
return "%s" % res
elif format == "md":
return json.dumps(self.items(), indent=2) | [
"def",
"dumps",
"(",
"self",
",",
"format",
"=",
"\"local\"",
")",
":",
"if",
"format",
"==",
"\"local\"",
":",
"res",
"=",
"EntitiesDescriptor",
"(",
")",
"for",
"_md",
"in",
"self",
".",
"metadata",
".",
"values",
"(",
")",
":",
"try",
":",
"res",
... | Dumps the content in standard metadata format or the pysaml2 metadata
format
:param format: Which format to dump in
:return: a string | [
"Dumps",
"the",
"content",
"in",
"standard",
"metadata",
"format",
"or",
"the",
"pysaml2",
"metadata",
"format"
] | d3aa78eeb7d37c12688f783cb4db1c7263a14ad6 | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/mdstore.py#L1301-L1320 |
232,647 | IdentityPython/pysaml2 | src/saml2/pack.py | http_form_post_message | def http_form_post_message(message, location, relay_state="",
typ="SAMLRequest", **kwargs):
"""The HTTP POST binding defines a mechanism by which SAML protocol
messages may be transmitted within the base64-encoded content of a
HTML form control.
:param message: The message
:param location: Where the form should be posted to
:param relay_state: for preserving and conveying state information
:return: A tuple containing header information and a HTML message.
"""
if not isinstance(message, six.string_types):
message = str(message)
if not isinstance(message, six.binary_type):
message = message.encode('utf-8')
if typ == "SAMLRequest" or typ == "SAMLResponse":
_msg = base64.b64encode(message)
else:
_msg = message
_msg = _msg.decode('ascii')
saml_response_input = HTML_INPUT_ELEMENT_SPEC.format(
name=cgi.escape(typ),
val=cgi.escape(_msg),
type='hidden')
relay_state_input = ""
if relay_state:
relay_state_input = HTML_INPUT_ELEMENT_SPEC.format(
name='RelayState',
val=cgi.escape(relay_state),
type='hidden')
response = HTML_FORM_SPEC.format(
saml_response_input=saml_response_input,
relay_state_input=relay_state_input,
action=location)
return {"headers": [("Content-type", "text/html")], "data": response} | python | def http_form_post_message(message, location, relay_state="",
typ="SAMLRequest", **kwargs):
if not isinstance(message, six.string_types):
message = str(message)
if not isinstance(message, six.binary_type):
message = message.encode('utf-8')
if typ == "SAMLRequest" or typ == "SAMLResponse":
_msg = base64.b64encode(message)
else:
_msg = message
_msg = _msg.decode('ascii')
saml_response_input = HTML_INPUT_ELEMENT_SPEC.format(
name=cgi.escape(typ),
val=cgi.escape(_msg),
type='hidden')
relay_state_input = ""
if relay_state:
relay_state_input = HTML_INPUT_ELEMENT_SPEC.format(
name='RelayState',
val=cgi.escape(relay_state),
type='hidden')
response = HTML_FORM_SPEC.format(
saml_response_input=saml_response_input,
relay_state_input=relay_state_input,
action=location)
return {"headers": [("Content-type", "text/html")], "data": response} | [
"def",
"http_form_post_message",
"(",
"message",
",",
"location",
",",
"relay_state",
"=",
"\"\"",
",",
"typ",
"=",
"\"SAMLRequest\"",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"isinstance",
"(",
"message",
",",
"six",
".",
"string_types",
")",
":",
... | The HTTP POST binding defines a mechanism by which SAML protocol
messages may be transmitted within the base64-encoded content of a
HTML form control.
:param message: The message
:param location: Where the form should be posted to
:param relay_state: for preserving and conveying state information
:return: A tuple containing header information and a HTML message. | [
"The",
"HTTP",
"POST",
"binding",
"defines",
"a",
"mechanism",
"by",
"which",
"SAML",
"protocol",
"messages",
"may",
"be",
"transmitted",
"within",
"the",
"base64",
"-",
"encoded",
"content",
"of",
"a",
"HTML",
"form",
"control",
"."
] | d3aa78eeb7d37c12688f783cb4db1c7263a14ad6 | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/pack.py#L67-L106 |
232,648 | IdentityPython/pysaml2 | src/saml2/pack.py | http_redirect_message | def http_redirect_message(message, location, relay_state="", typ="SAMLRequest",
sigalg='', signer=None, **kwargs):
"""The HTTP Redirect binding defines a mechanism by which SAML protocol
messages can be transmitted within URL parameters.
Messages are encoded for use with this binding using a URL encoding
technique, and transmitted using the HTTP GET method.
The DEFLATE Encoding is used in this function.
:param message: The message
:param location: Where the message should be posted to
:param relay_state: for preserving and conveying state information
:param typ: What type of message it is SAMLRequest/SAMLResponse/SAMLart
:param sigalg: Which algorithm the signature function will use to sign
the message
:param signer: A signature function that can be used to sign the message
:return: A tuple containing header information and a HTML message.
"""
if not isinstance(message, six.string_types):
message = "%s" % (message,)
_order = None
if typ in ["SAMLRequest", "SAMLResponse"]:
if typ == "SAMLRequest":
_order = REQ_ORDER
else:
_order = RESP_ORDER
args = {typ: deflate_and_base64_encode(message)}
elif typ == "SAMLart":
args = {typ: message}
else:
raise Exception("Unknown message type: %s" % typ)
if relay_state:
args["RelayState"] = relay_state
if signer:
# sigalgs, should be one defined in xmldsig
assert sigalg in [b for a, b in SIG_ALLOWED_ALG]
args["SigAlg"] = sigalg
string = "&".join([urlencode({k: args[k]})
for k in _order if k in args]).encode('ascii')
args["Signature"] = base64.b64encode(signer.sign(string))
string = urlencode(args)
else:
string = urlencode(args)
glue_char = "&" if urlparse(location).query else "?"
login_url = glue_char.join([location, string])
headers = [('Location', str(login_url))]
body = []
return {"headers": headers, "data": body} | python | def http_redirect_message(message, location, relay_state="", typ="SAMLRequest",
sigalg='', signer=None, **kwargs):
if not isinstance(message, six.string_types):
message = "%s" % (message,)
_order = None
if typ in ["SAMLRequest", "SAMLResponse"]:
if typ == "SAMLRequest":
_order = REQ_ORDER
else:
_order = RESP_ORDER
args = {typ: deflate_and_base64_encode(message)}
elif typ == "SAMLart":
args = {typ: message}
else:
raise Exception("Unknown message type: %s" % typ)
if relay_state:
args["RelayState"] = relay_state
if signer:
# sigalgs, should be one defined in xmldsig
assert sigalg in [b for a, b in SIG_ALLOWED_ALG]
args["SigAlg"] = sigalg
string = "&".join([urlencode({k: args[k]})
for k in _order if k in args]).encode('ascii')
args["Signature"] = base64.b64encode(signer.sign(string))
string = urlencode(args)
else:
string = urlencode(args)
glue_char = "&" if urlparse(location).query else "?"
login_url = glue_char.join([location, string])
headers = [('Location', str(login_url))]
body = []
return {"headers": headers, "data": body} | [
"def",
"http_redirect_message",
"(",
"message",
",",
"location",
",",
"relay_state",
"=",
"\"\"",
",",
"typ",
"=",
"\"SAMLRequest\"",
",",
"sigalg",
"=",
"''",
",",
"signer",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"isinstance",
"(",... | The HTTP Redirect binding defines a mechanism by which SAML protocol
messages can be transmitted within URL parameters.
Messages are encoded for use with this binding using a URL encoding
technique, and transmitted using the HTTP GET method.
The DEFLATE Encoding is used in this function.
:param message: The message
:param location: Where the message should be posted to
:param relay_state: for preserving and conveying state information
:param typ: What type of message it is SAMLRequest/SAMLResponse/SAMLart
:param sigalg: Which algorithm the signature function will use to sign
the message
:param signer: A signature function that can be used to sign the message
:return: A tuple containing header information and a HTML message. | [
"The",
"HTTP",
"Redirect",
"binding",
"defines",
"a",
"mechanism",
"by",
"which",
"SAML",
"protocol",
"messages",
"can",
"be",
"transmitted",
"within",
"URL",
"parameters",
".",
"Messages",
"are",
"encoded",
"for",
"use",
"with",
"this",
"binding",
"using",
"a... | d3aa78eeb7d37c12688f783cb4db1c7263a14ad6 | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/pack.py#L135-L189 |
232,649 | IdentityPython/pysaml2 | src/saml2/pack.py | parse_soap_enveloped_saml | def parse_soap_enveloped_saml(text, body_class, header_class=None):
"""Parses a SOAP enveloped SAML thing and returns header parts and body
:param text: The SOAP object as XML
:return: header parts and body as saml.samlbase instances
"""
envelope = defusedxml.ElementTree.fromstring(text)
assert envelope.tag == '{%s}Envelope' % NAMESPACE
# print(len(envelope))
body = None
header = {}
for part in envelope:
# print(">",part.tag)
if part.tag == '{%s}Body' % NAMESPACE:
for sub in part:
try:
body = saml2.create_class_from_element_tree(
body_class, sub)
except Exception:
raise Exception(
"Wrong body type (%s) in SOAP envelope" % sub.tag)
elif part.tag == '{%s}Header' % NAMESPACE:
if not header_class:
raise Exception("Header where I didn't expect one")
# print("--- HEADER ---")
for sub in part:
# print(">>",sub.tag)
for klass in header_class:
# print("?{%s}%s" % (klass.c_namespace,klass.c_tag))
if sub.tag == "{%s}%s" % (klass.c_namespace, klass.c_tag):
header[sub.tag] = \
saml2.create_class_from_element_tree(klass, sub)
break
return body, header | python | def parse_soap_enveloped_saml(text, body_class, header_class=None):
envelope = defusedxml.ElementTree.fromstring(text)
assert envelope.tag == '{%s}Envelope' % NAMESPACE
# print(len(envelope))
body = None
header = {}
for part in envelope:
# print(">",part.tag)
if part.tag == '{%s}Body' % NAMESPACE:
for sub in part:
try:
body = saml2.create_class_from_element_tree(
body_class, sub)
except Exception:
raise Exception(
"Wrong body type (%s) in SOAP envelope" % sub.tag)
elif part.tag == '{%s}Header' % NAMESPACE:
if not header_class:
raise Exception("Header where I didn't expect one")
# print("--- HEADER ---")
for sub in part:
# print(">>",sub.tag)
for klass in header_class:
# print("?{%s}%s" % (klass.c_namespace,klass.c_tag))
if sub.tag == "{%s}%s" % (klass.c_namespace, klass.c_tag):
header[sub.tag] = \
saml2.create_class_from_element_tree(klass, sub)
break
return body, header | [
"def",
"parse_soap_enveloped_saml",
"(",
"text",
",",
"body_class",
",",
"header_class",
"=",
"None",
")",
":",
"envelope",
"=",
"defusedxml",
".",
"ElementTree",
".",
"fromstring",
"(",
"text",
")",
"assert",
"envelope",
".",
"tag",
"==",
"'{%s}Envelope'",
"%... | Parses a SOAP enveloped SAML thing and returns header parts and body
:param text: The SOAP object as XML
:return: header parts and body as saml.samlbase instances | [
"Parses",
"a",
"SOAP",
"enveloped",
"SAML",
"thing",
"and",
"returns",
"header",
"parts",
"and",
"body"
] | d3aa78eeb7d37c12688f783cb4db1c7263a14ad6 | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/pack.py#L257-L292 |
232,650 | IdentityPython/pysaml2 | src/saml2/config.py | Config.load | def load(self, cnf, metadata_construction=False):
""" The base load method, loads the configuration
:param cnf: The configuration as a dictionary
:param metadata_construction: Is this only to be able to construct
metadata. If so some things can be left out.
:return: The Configuration instance
"""
_uc = self.unicode_convert
for arg in COMMON_ARGS:
if arg == "virtual_organization":
if "virtual_organization" in cnf:
for key, val in cnf["virtual_organization"].items():
self.vorg[key] = VirtualOrg(None, key, val)
continue
elif arg == "extension_schemas":
# List of filename of modules representing the schemas
if "extension_schemas" in cnf:
for mod_file in cnf["extension_schemas"]:
_mod = self._load(mod_file)
self.extension_schema[_mod.NAMESPACE] = _mod
try:
setattr(self, arg, _uc(cnf[arg]))
except KeyError:
pass
except TypeError: # Something that can't be a string
setattr(self, arg, cnf[arg])
if "service" in cnf:
for typ in ["aa", "idp", "sp", "pdp", "aq"]:
try:
self.load_special(
cnf["service"][typ], typ,
metadata_construction=metadata_construction)
self.serves.append(typ)
except KeyError:
pass
if "extensions" in cnf:
self.do_extensions(cnf["extensions"])
self.load_complex(cnf, metadata_construction=metadata_construction)
self.context = self.def_context
return self | python | def load(self, cnf, metadata_construction=False):
_uc = self.unicode_convert
for arg in COMMON_ARGS:
if arg == "virtual_organization":
if "virtual_organization" in cnf:
for key, val in cnf["virtual_organization"].items():
self.vorg[key] = VirtualOrg(None, key, val)
continue
elif arg == "extension_schemas":
# List of filename of modules representing the schemas
if "extension_schemas" in cnf:
for mod_file in cnf["extension_schemas"]:
_mod = self._load(mod_file)
self.extension_schema[_mod.NAMESPACE] = _mod
try:
setattr(self, arg, _uc(cnf[arg]))
except KeyError:
pass
except TypeError: # Something that can't be a string
setattr(self, arg, cnf[arg])
if "service" in cnf:
for typ in ["aa", "idp", "sp", "pdp", "aq"]:
try:
self.load_special(
cnf["service"][typ], typ,
metadata_construction=metadata_construction)
self.serves.append(typ)
except KeyError:
pass
if "extensions" in cnf:
self.do_extensions(cnf["extensions"])
self.load_complex(cnf, metadata_construction=metadata_construction)
self.context = self.def_context
return self | [
"def",
"load",
"(",
"self",
",",
"cnf",
",",
"metadata_construction",
"=",
"False",
")",
":",
"_uc",
"=",
"self",
".",
"unicode_convert",
"for",
"arg",
"in",
"COMMON_ARGS",
":",
"if",
"arg",
"==",
"\"virtual_organization\"",
":",
"if",
"\"virtual_organization\... | The base load method, loads the configuration
:param cnf: The configuration as a dictionary
:param metadata_construction: Is this only to be able to construct
metadata. If so some things can be left out.
:return: The Configuration instance | [
"The",
"base",
"load",
"method",
"loads",
"the",
"configuration"
] | d3aa78eeb7d37c12688f783cb4db1c7263a14ad6 | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/config.py#L332-L377 |
232,651 | IdentityPython/pysaml2 | src/saml2/config.py | Config.load_metadata | def load_metadata(self, metadata_conf):
""" Loads metadata into an internal structure """
acs = self.attribute_converters
if acs is None:
raise ConfigurationError(
"Missing attribute converter specification")
try:
ca_certs = self.ca_certs
except:
ca_certs = None
try:
disable_validation = self.disable_ssl_certificate_validation
except:
disable_validation = False
mds = MetadataStore(acs, self, ca_certs,
disable_ssl_certificate_validation=disable_validation)
mds.imp(metadata_conf)
return mds | python | def load_metadata(self, metadata_conf):
acs = self.attribute_converters
if acs is None:
raise ConfigurationError(
"Missing attribute converter specification")
try:
ca_certs = self.ca_certs
except:
ca_certs = None
try:
disable_validation = self.disable_ssl_certificate_validation
except:
disable_validation = False
mds = MetadataStore(acs, self, ca_certs,
disable_ssl_certificate_validation=disable_validation)
mds.imp(metadata_conf)
return mds | [
"def",
"load_metadata",
"(",
"self",
",",
"metadata_conf",
")",
":",
"acs",
"=",
"self",
".",
"attribute_converters",
"if",
"acs",
"is",
"None",
":",
"raise",
"ConfigurationError",
"(",
"\"Missing attribute converter specification\"",
")",
"try",
":",
"ca_certs",
... | Loads metadata into an internal structure | [
"Loads",
"metadata",
"into",
"an",
"internal",
"structure"
] | d3aa78eeb7d37c12688f783cb4db1c7263a14ad6 | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/config.py#L396-L419 |
232,652 | IdentityPython/pysaml2 | src/saml2/config.py | Config.endpoint | def endpoint(self, service, binding=None, context=None):
""" Goes through the list of endpoint specifications for the
given type of service and returns a list of endpoint that matches
the given binding. If no binding is given all endpoints available for
that service will be returned.
:param service: The service the endpoint should support
:param binding: The expected binding
:return: All the endpoints that matches the given restrictions
"""
spec = []
unspec = []
endps = self.getattr("endpoints", context)
if endps and service in endps:
for endpspec in endps[service]:
try:
endp, bind = endpspec
if binding is None or bind == binding:
spec.append(endp)
except ValueError:
unspec.append(endpspec)
if spec:
return spec
else:
return unspec | python | def endpoint(self, service, binding=None, context=None):
spec = []
unspec = []
endps = self.getattr("endpoints", context)
if endps and service in endps:
for endpspec in endps[service]:
try:
endp, bind = endpspec
if binding is None or bind == binding:
spec.append(endp)
except ValueError:
unspec.append(endpspec)
if spec:
return spec
else:
return unspec | [
"def",
"endpoint",
"(",
"self",
",",
"service",
",",
"binding",
"=",
"None",
",",
"context",
"=",
"None",
")",
":",
"spec",
"=",
"[",
"]",
"unspec",
"=",
"[",
"]",
"endps",
"=",
"self",
".",
"getattr",
"(",
"\"endpoints\"",
",",
"context",
")",
"if... | Goes through the list of endpoint specifications for the
given type of service and returns a list of endpoint that matches
the given binding. If no binding is given all endpoints available for
that service will be returned.
:param service: The service the endpoint should support
:param binding: The expected binding
:return: All the endpoints that matches the given restrictions | [
"Goes",
"through",
"the",
"list",
"of",
"endpoint",
"specifications",
"for",
"the",
"given",
"type",
"of",
"service",
"and",
"returns",
"a",
"list",
"of",
"endpoint",
"that",
"matches",
"the",
"given",
"binding",
".",
"If",
"no",
"binding",
"is",
"given",
... | d3aa78eeb7d37c12688f783cb4db1c7263a14ad6 | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/config.py#L421-L446 |
232,653 | IdentityPython/pysaml2 | src/saml2/config.py | Config.service_per_endpoint | def service_per_endpoint(self, context=None):
"""
List all endpoint this entity publishes and which service and binding
that are behind the endpoint
:param context: Type of entity
:return: Dictionary with endpoint url as key and a tuple of
service and binding as value
"""
endps = self.getattr("endpoints", context)
res = {}
for service, specs in endps.items():
for endp, binding in specs:
res[endp] = (service, binding)
return res | python | def service_per_endpoint(self, context=None):
endps = self.getattr("endpoints", context)
res = {}
for service, specs in endps.items():
for endp, binding in specs:
res[endp] = (service, binding)
return res | [
"def",
"service_per_endpoint",
"(",
"self",
",",
"context",
"=",
"None",
")",
":",
"endps",
"=",
"self",
".",
"getattr",
"(",
"\"endpoints\"",
",",
"context",
")",
"res",
"=",
"{",
"}",
"for",
"service",
",",
"specs",
"in",
"endps",
".",
"items",
"(",
... | List all endpoint this entity publishes and which service and binding
that are behind the endpoint
:param context: Type of entity
:return: Dictionary with endpoint url as key and a tuple of
service and binding as value | [
"List",
"all",
"endpoint",
"this",
"entity",
"publishes",
"and",
"which",
"service",
"and",
"binding",
"that",
"are",
"behind",
"the",
"endpoint"
] | d3aa78eeb7d37c12688f783cb4db1c7263a14ad6 | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/config.py#L519-L533 |
232,654 | IdentityPython/pysaml2 | src/saml2/config.py | SPConfig.ecp_endpoint | def ecp_endpoint(self, ipaddress):
"""
Returns the entity ID of the IdP which the ECP client should talk to
:param ipaddress: The IP address of the user client
:return: IdP entity ID or None
"""
_ecp = self.getattr("ecp")
if _ecp:
for key, eid in _ecp.items():
if re.match(key, ipaddress):
return eid
return None | python | def ecp_endpoint(self, ipaddress):
_ecp = self.getattr("ecp")
if _ecp:
for key, eid in _ecp.items():
if re.match(key, ipaddress):
return eid
return None | [
"def",
"ecp_endpoint",
"(",
"self",
",",
"ipaddress",
")",
":",
"_ecp",
"=",
"self",
".",
"getattr",
"(",
"\"ecp\"",
")",
"if",
"_ecp",
":",
"for",
"key",
",",
"eid",
"in",
"_ecp",
".",
"items",
"(",
")",
":",
"if",
"re",
".",
"match",
"(",
"key"... | Returns the entity ID of the IdP which the ECP client should talk to
:param ipaddress: The IP address of the user client
:return: IdP entity ID or None | [
"Returns",
"the",
"entity",
"ID",
"of",
"the",
"IdP",
"which",
"the",
"ECP",
"client",
"should",
"talk",
"to"
] | d3aa78eeb7d37c12688f783cb4db1c7263a14ad6 | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/config.py#L548-L561 |
232,655 | IdentityPython/pysaml2 | src/saml2/virtual_org.py | VirtualOrg.members_to_ask | def members_to_ask(self, name_id):
"""Find the member of the Virtual Organization that I haven't already
spoken too
"""
vo_members = self._affiliation_members()
for member in self.member:
if member not in vo_members:
vo_members.append(member)
# Remove the ones I have cached data from about this subject
vo_members = [m for m in vo_members if not self.sp.users.cache.active(
name_id, m)]
logger.info("VO members (not cached): %s", vo_members)
return vo_members | python | def members_to_ask(self, name_id):
vo_members = self._affiliation_members()
for member in self.member:
if member not in vo_members:
vo_members.append(member)
# Remove the ones I have cached data from about this subject
vo_members = [m for m in vo_members if not self.sp.users.cache.active(
name_id, m)]
logger.info("VO members (not cached): %s", vo_members)
return vo_members | [
"def",
"members_to_ask",
"(",
"self",
",",
"name_id",
")",
":",
"vo_members",
"=",
"self",
".",
"_affiliation_members",
"(",
")",
"for",
"member",
"in",
"self",
".",
"member",
":",
"if",
"member",
"not",
"in",
"vo_members",
":",
"vo_members",
".",
"append"... | Find the member of the Virtual Organization that I haven't already
spoken too | [
"Find",
"the",
"member",
"of",
"the",
"Virtual",
"Organization",
"that",
"I",
"haven",
"t",
"already",
"spoken",
"too"
] | d3aa78eeb7d37c12688f783cb4db1c7263a14ad6 | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/virtual_org.py#L32-L46 |
232,656 | IdentityPython/pysaml2 | src/saml2/s2repoze/plugins/sp.py | construct_came_from | def construct_came_from(environ):
""" The URL that the user used when the process where interupted
for single-sign-on processing. """
came_from = environ.get("PATH_INFO")
qstr = environ.get("QUERY_STRING", "")
if qstr:
came_from += "?" + qstr
return came_from | python | def construct_came_from(environ):
came_from = environ.get("PATH_INFO")
qstr = environ.get("QUERY_STRING", "")
if qstr:
came_from += "?" + qstr
return came_from | [
"def",
"construct_came_from",
"(",
"environ",
")",
":",
"came_from",
"=",
"environ",
".",
"get",
"(",
"\"PATH_INFO\"",
")",
"qstr",
"=",
"environ",
".",
"get",
"(",
"\"QUERY_STRING\"",
",",
"\"\"",
")",
"if",
"qstr",
":",
"came_from",
"+=",
"\"?\"",
"+",
... | The URL that the user used when the process where interupted
for single-sign-on processing. | [
"The",
"URL",
"that",
"the",
"user",
"used",
"when",
"the",
"process",
"where",
"interupted",
"for",
"single",
"-",
"sign",
"-",
"on",
"processing",
"."
] | d3aa78eeb7d37c12688f783cb4db1c7263a14ad6 | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/s2repoze/plugins/sp.py#L51-L59 |
232,657 | IdentityPython/pysaml2 | src/saml2/response.py | for_me | def for_me(conditions, myself):
""" Am I among the intended audiences """
if not conditions.audience_restriction: # No audience restriction
return True
for restriction in conditions.audience_restriction:
if not restriction.audience:
continue
for audience in restriction.audience:
if audience.text.strip() == myself:
return True
else:
# print("Not for me: %s != %s" % (audience.text.strip(),
# myself))
pass
return False | python | def for_me(conditions, myself):
if not conditions.audience_restriction: # No audience restriction
return True
for restriction in conditions.audience_restriction:
if not restriction.audience:
continue
for audience in restriction.audience:
if audience.text.strip() == myself:
return True
else:
# print("Not for me: %s != %s" % (audience.text.strip(),
# myself))
pass
return False | [
"def",
"for_me",
"(",
"conditions",
",",
"myself",
")",
":",
"if",
"not",
"conditions",
".",
"audience_restriction",
":",
"# No audience restriction",
"return",
"True",
"for",
"restriction",
"in",
"conditions",
".",
"audience_restriction",
":",
"if",
"not",
"restr... | Am I among the intended audiences | [
"Am",
"I",
"among",
"the",
"intended",
"audiences"
] | d3aa78eeb7d37c12688f783cb4db1c7263a14ad6 | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/response.py#L202-L219 |
232,658 | IdentityPython/pysaml2 | src/saml2/response.py | StatusResponse.issue_instant_ok | def issue_instant_ok(self):
""" Check that the response was issued at a reasonable time """
upper = time_util.shift_time(time_util.time_in_a_while(days=1),
self.timeslack).timetuple()
lower = time_util.shift_time(time_util.time_a_while_ago(days=1),
-self.timeslack).timetuple()
# print("issue_instant: %s" % self.response.issue_instant)
# print("%s < x < %s" % (lower, upper))
issued_at = str_to_time(self.response.issue_instant)
return lower < issued_at < upper | python | def issue_instant_ok(self):
upper = time_util.shift_time(time_util.time_in_a_while(days=1),
self.timeslack).timetuple()
lower = time_util.shift_time(time_util.time_a_while_ago(days=1),
-self.timeslack).timetuple()
# print("issue_instant: %s" % self.response.issue_instant)
# print("%s < x < %s" % (lower, upper))
issued_at = str_to_time(self.response.issue_instant)
return lower < issued_at < upper | [
"def",
"issue_instant_ok",
"(",
"self",
")",
":",
"upper",
"=",
"time_util",
".",
"shift_time",
"(",
"time_util",
".",
"time_in_a_while",
"(",
"days",
"=",
"1",
")",
",",
"self",
".",
"timeslack",
")",
".",
"timetuple",
"(",
")",
"lower",
"=",
"time_util... | Check that the response was issued at a reasonable time | [
"Check",
"that",
"the",
"response",
"was",
"issued",
"at",
"a",
"reasonable",
"time"
] | d3aa78eeb7d37c12688f783cb4db1c7263a14ad6 | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/response.py#L381-L390 |
232,659 | IdentityPython/pysaml2 | src/saml2/response.py | AuthnResponse.decrypt_attributes | def decrypt_attributes(self, attribute_statement):
"""
Decrypts possible encrypted attributes and adds the decrypts to the
list of attributes.
:param attribute_statement: A SAML.AttributeStatement which might
contain both encrypted attributes and attributes.
"""
# _node_name = [
# "urn:oasis:names:tc:SAML:2.0:assertion:EncryptedData",
# "urn:oasis:names:tc:SAML:2.0:assertion:EncryptedAttribute"]
for encattr in attribute_statement.encrypted_attribute:
if not encattr.encrypted_key:
_decr = self.sec.decrypt(encattr.encrypted_data)
_attr = attribute_from_string(_decr)
attribute_statement.attribute.append(_attr)
else:
_decr = self.sec.decrypt(encattr)
enc_attr = encrypted_attribute_from_string(_decr)
attrlist = enc_attr.extensions_as_elements("Attribute", saml)
attribute_statement.attribute.extend(attrlist) | python | def decrypt_attributes(self, attribute_statement):
# _node_name = [
# "urn:oasis:names:tc:SAML:2.0:assertion:EncryptedData",
# "urn:oasis:names:tc:SAML:2.0:assertion:EncryptedAttribute"]
for encattr in attribute_statement.encrypted_attribute:
if not encattr.encrypted_key:
_decr = self.sec.decrypt(encattr.encrypted_data)
_attr = attribute_from_string(_decr)
attribute_statement.attribute.append(_attr)
else:
_decr = self.sec.decrypt(encattr)
enc_attr = encrypted_attribute_from_string(_decr)
attrlist = enc_attr.extensions_as_elements("Attribute", saml)
attribute_statement.attribute.extend(attrlist) | [
"def",
"decrypt_attributes",
"(",
"self",
",",
"attribute_statement",
")",
":",
"# _node_name = [",
"# \"urn:oasis:names:tc:SAML:2.0:assertion:EncryptedData\",",
"# \"urn:oasis:names:tc:SAML:2.0:assertion:EncryptedAttribute\"]",
"for",
"encattr",
"in",
"attri... | Decrypts possible encrypted attributes and adds the decrypts to the
list of attributes.
:param attribute_statement: A SAML.AttributeStatement which might
contain both encrypted attributes and attributes. | [
"Decrypts",
"possible",
"encrypted",
"attributes",
"and",
"adds",
"the",
"decrypts",
"to",
"the",
"list",
"of",
"attributes",
"."
] | d3aa78eeb7d37c12688f783cb4db1c7263a14ad6 | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/response.py#L632-L653 |
232,660 | IdentityPython/pysaml2 | src/saml2/response.py | AuthnResponse.get_identity | def get_identity(self):
""" The assertion can contain zero or more attributeStatements
"""
ava = {}
for _assertion in self.assertions:
if _assertion.advice:
if _assertion.advice.assertion:
for tmp_assertion in _assertion.advice.assertion:
if tmp_assertion.attribute_statement:
assert len(tmp_assertion.attribute_statement) == 1
ava.update(self.read_attribute_statement(
tmp_assertion.attribute_statement[0]))
if _assertion.attribute_statement:
logger.debug("Assertion contains %s attribute statement(s)",
(len(self.assertion.attribute_statement)))
for _attr_statem in _assertion.attribute_statement:
logger.debug("Attribute Statement: %s" % (_attr_statem,))
ava.update(self.read_attribute_statement(_attr_statem))
if not ava:
logger.debug("Assertion contains no attribute statements")
return ava | python | def get_identity(self):
ava = {}
for _assertion in self.assertions:
if _assertion.advice:
if _assertion.advice.assertion:
for tmp_assertion in _assertion.advice.assertion:
if tmp_assertion.attribute_statement:
assert len(tmp_assertion.attribute_statement) == 1
ava.update(self.read_attribute_statement(
tmp_assertion.attribute_statement[0]))
if _assertion.attribute_statement:
logger.debug("Assertion contains %s attribute statement(s)",
(len(self.assertion.attribute_statement)))
for _attr_statem in _assertion.attribute_statement:
logger.debug("Attribute Statement: %s" % (_attr_statem,))
ava.update(self.read_attribute_statement(_attr_statem))
if not ava:
logger.debug("Assertion contains no attribute statements")
return ava | [
"def",
"get_identity",
"(",
"self",
")",
":",
"ava",
"=",
"{",
"}",
"for",
"_assertion",
"in",
"self",
".",
"assertions",
":",
"if",
"_assertion",
".",
"advice",
":",
"if",
"_assertion",
".",
"advice",
".",
"assertion",
":",
"for",
"tmp_assertion",
"in",... | The assertion can contain zero or more attributeStatements | [
"The",
"assertion",
"can",
"contain",
"zero",
"or",
"more",
"attributeStatements"
] | d3aa78eeb7d37c12688f783cb4db1c7263a14ad6 | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/response.py#L664-L685 |
232,661 | IdentityPython/pysaml2 | src/saml2/response.py | AuthnResponse.get_subject | def get_subject(self):
""" The assertion must contain a Subject
"""
assert self.assertion.subject
subject = self.assertion.subject
subjconf = []
if not self.verify_attesting_entity(subject.subject_confirmation):
raise VerificationError("No valid attesting address")
for subject_confirmation in subject.subject_confirmation:
_data = subject_confirmation.subject_confirmation_data
if subject_confirmation.method == SCM_BEARER:
if not self._bearer_confirmed(_data):
continue
elif subject_confirmation.method == SCM_HOLDER_OF_KEY:
if not self._holder_of_key_confirmed(_data):
continue
elif subject_confirmation.method == SCM_SENDER_VOUCHES:
pass
else:
raise ValueError("Unknown subject confirmation method: %s" % (
subject_confirmation.method,))
_recip = _data.recipient
if not _recip or not self.verify_recipient(_recip):
raise VerificationError("No valid recipient")
subjconf.append(subject_confirmation)
if not subjconf:
raise VerificationError("No valid subject confirmation")
subject.subject_confirmation = subjconf
# The subject may contain a name_id
if subject.name_id:
self.name_id = subject.name_id
elif subject.encrypted_id:
# decrypt encrypted ID
_name_id_str = self.sec.decrypt(
subject.encrypted_id.encrypted_data.to_string())
_name_id = saml.name_id_from_string(_name_id_str)
self.name_id = _name_id
logger.info("Subject NameID: %s", self.name_id)
return self.name_id | python | def get_subject(self):
assert self.assertion.subject
subject = self.assertion.subject
subjconf = []
if not self.verify_attesting_entity(subject.subject_confirmation):
raise VerificationError("No valid attesting address")
for subject_confirmation in subject.subject_confirmation:
_data = subject_confirmation.subject_confirmation_data
if subject_confirmation.method == SCM_BEARER:
if not self._bearer_confirmed(_data):
continue
elif subject_confirmation.method == SCM_HOLDER_OF_KEY:
if not self._holder_of_key_confirmed(_data):
continue
elif subject_confirmation.method == SCM_SENDER_VOUCHES:
pass
else:
raise ValueError("Unknown subject confirmation method: %s" % (
subject_confirmation.method,))
_recip = _data.recipient
if not _recip or not self.verify_recipient(_recip):
raise VerificationError("No valid recipient")
subjconf.append(subject_confirmation)
if not subjconf:
raise VerificationError("No valid subject confirmation")
subject.subject_confirmation = subjconf
# The subject may contain a name_id
if subject.name_id:
self.name_id = subject.name_id
elif subject.encrypted_id:
# decrypt encrypted ID
_name_id_str = self.sec.decrypt(
subject.encrypted_id.encrypted_data.to_string())
_name_id = saml.name_id_from_string(_name_id_str)
self.name_id = _name_id
logger.info("Subject NameID: %s", self.name_id)
return self.name_id | [
"def",
"get_subject",
"(",
"self",
")",
":",
"assert",
"self",
".",
"assertion",
".",
"subject",
"subject",
"=",
"self",
".",
"assertion",
".",
"subject",
"subjconf",
"=",
"[",
"]",
"if",
"not",
"self",
".",
"verify_attesting_entity",
"(",
"subject",
".",
... | The assertion must contain a Subject | [
"The",
"assertion",
"must",
"contain",
"a",
"Subject"
] | d3aa78eeb7d37c12688f783cb4db1c7263a14ad6 | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/response.py#L736-L784 |
232,662 | IdentityPython/pysaml2 | src/saml2/response.py | AuthnResponse.decrypt_assertions | def decrypt_assertions(self, encrypted_assertions, decr_txt, issuer=None,
verified=False):
""" Moves the decrypted assertion from the encrypted assertion to a
list.
:param encrypted_assertions: A list of encrypted assertions.
:param decr_txt: The string representation containing the decrypted
data. Used when verifying signatures.
:param issuer: The issuer of the response.
:param verified: If True do not verify signatures, otherwise verify
the signature if it exists.
:return: A list of decrypted assertions.
"""
res = []
for encrypted_assertion in encrypted_assertions:
if encrypted_assertion.extension_elements:
assertions = extension_elements_to_elements(
encrypted_assertion.extension_elements, [saml, samlp])
for assertion in assertions:
if assertion.signature and not verified:
if not self.sec.check_signature(
assertion, origdoc=decr_txt,
node_name=class_name(assertion), issuer=issuer):
logger.error("Failed to verify signature on '%s'",
assertion)
raise SignatureError()
res.append(assertion)
return res | python | def decrypt_assertions(self, encrypted_assertions, decr_txt, issuer=None,
verified=False):
res = []
for encrypted_assertion in encrypted_assertions:
if encrypted_assertion.extension_elements:
assertions = extension_elements_to_elements(
encrypted_assertion.extension_elements, [saml, samlp])
for assertion in assertions:
if assertion.signature and not verified:
if not self.sec.check_signature(
assertion, origdoc=decr_txt,
node_name=class_name(assertion), issuer=issuer):
logger.error("Failed to verify signature on '%s'",
assertion)
raise SignatureError()
res.append(assertion)
return res | [
"def",
"decrypt_assertions",
"(",
"self",
",",
"encrypted_assertions",
",",
"decr_txt",
",",
"issuer",
"=",
"None",
",",
"verified",
"=",
"False",
")",
":",
"res",
"=",
"[",
"]",
"for",
"encrypted_assertion",
"in",
"encrypted_assertions",
":",
"if",
"encrypted... | Moves the decrypted assertion from the encrypted assertion to a
list.
:param encrypted_assertions: A list of encrypted assertions.
:param decr_txt: The string representation containing the decrypted
data. Used when verifying signatures.
:param issuer: The issuer of the response.
:param verified: If True do not verify signatures, otherwise verify
the signature if it exists.
:return: A list of decrypted assertions. | [
"Moves",
"the",
"decrypted",
"assertion",
"from",
"the",
"encrypted",
"assertion",
"to",
"a",
"list",
"."
] | d3aa78eeb7d37c12688f783cb4db1c7263a14ad6 | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/response.py#L839-L866 |
232,663 | IdentityPython/pysaml2 | src/saml2/response.py | AuthnResponse.find_encrypt_data_assertion_list | def find_encrypt_data_assertion_list(self, _assertions):
""" Verifies if a list of assertions contains encrypted data in the
advice element.
:param _assertions: A list of assertions.
:return: True encrypted data exists otherwise false.
"""
for _assertion in _assertions:
if _assertion.advice:
if _assertion.advice.encrypted_assertion:
res = self.find_encrypt_data_assertion(
_assertion.advice.encrypted_assertion)
if res:
return True | python | def find_encrypt_data_assertion_list(self, _assertions):
for _assertion in _assertions:
if _assertion.advice:
if _assertion.advice.encrypted_assertion:
res = self.find_encrypt_data_assertion(
_assertion.advice.encrypted_assertion)
if res:
return True | [
"def",
"find_encrypt_data_assertion_list",
"(",
"self",
",",
"_assertions",
")",
":",
"for",
"_assertion",
"in",
"_assertions",
":",
"if",
"_assertion",
".",
"advice",
":",
"if",
"_assertion",
".",
"advice",
".",
"encrypted_assertion",
":",
"res",
"=",
"self",
... | Verifies if a list of assertions contains encrypted data in the
advice element.
:param _assertions: A list of assertions.
:return: True encrypted data exists otherwise false. | [
"Verifies",
"if",
"a",
"list",
"of",
"assertions",
"contains",
"encrypted",
"data",
"in",
"the",
"advice",
"element",
"."
] | d3aa78eeb7d37c12688f783cb4db1c7263a14ad6 | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/response.py#L878-L891 |
232,664 | IdentityPython/pysaml2 | src/saml2/response.py | AuthnResponse.find_encrypt_data | def find_encrypt_data(self, resp):
""" Verifies if a saml response contains encrypted assertions with
encrypted data.
:param resp: A saml response.
:return: True encrypted data exists otherwise false.
"""
if resp.encrypted_assertion:
res = self.find_encrypt_data_assertion(resp.encrypted_assertion)
if res:
return True
if resp.assertion:
for tmp_assertion in resp.assertion:
if tmp_assertion.advice:
if tmp_assertion.advice.encrypted_assertion:
res = self.find_encrypt_data_assertion(
tmp_assertion.advice.encrypted_assertion)
if res:
return True
return False | python | def find_encrypt_data(self, resp):
if resp.encrypted_assertion:
res = self.find_encrypt_data_assertion(resp.encrypted_assertion)
if res:
return True
if resp.assertion:
for tmp_assertion in resp.assertion:
if tmp_assertion.advice:
if tmp_assertion.advice.encrypted_assertion:
res = self.find_encrypt_data_assertion(
tmp_assertion.advice.encrypted_assertion)
if res:
return True
return False | [
"def",
"find_encrypt_data",
"(",
"self",
",",
"resp",
")",
":",
"if",
"resp",
".",
"encrypted_assertion",
":",
"res",
"=",
"self",
".",
"find_encrypt_data_assertion",
"(",
"resp",
".",
"encrypted_assertion",
")",
"if",
"res",
":",
"return",
"True",
"if",
"re... | Verifies if a saml response contains encrypted assertions with
encrypted data.
:param resp: A saml response.
:return: True encrypted data exists otherwise false. | [
"Verifies",
"if",
"a",
"saml",
"response",
"contains",
"encrypted",
"assertions",
"with",
"encrypted",
"data",
"."
] | d3aa78eeb7d37c12688f783cb4db1c7263a14ad6 | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/response.py#L893-L912 |
232,665 | IdentityPython/pysaml2 | src/saml2/response.py | AuthnResponse.verify | def verify(self, keys=None):
""" Verify that the assertion is syntactically correct and the
signature is correct if present.
:param keys: If not the default key file should be used then use one
of these.
"""
try:
res = self._verify()
except AssertionError as err:
logger.error("Verification error on the response: %s", err)
raise
else:
if res is None:
return None
if not isinstance(self.response, samlp.Response):
return self
if self.parse_assertion(keys):
return self
else:
logger.error("Could not parse the assertion")
return None | python | def verify(self, keys=None):
try:
res = self._verify()
except AssertionError as err:
logger.error("Verification error on the response: %s", err)
raise
else:
if res is None:
return None
if not isinstance(self.response, samlp.Response):
return self
if self.parse_assertion(keys):
return self
else:
logger.error("Could not parse the assertion")
return None | [
"def",
"verify",
"(",
"self",
",",
"keys",
"=",
"None",
")",
":",
"try",
":",
"res",
"=",
"self",
".",
"_verify",
"(",
")",
"except",
"AssertionError",
"as",
"err",
":",
"logger",
".",
"error",
"(",
"\"Verification error on the response: %s\"",
",",
"err",... | Verify that the assertion is syntactically correct and the
signature is correct if present.
:param keys: If not the default key file should be used then use one
of these. | [
"Verify",
"that",
"the",
"assertion",
"is",
"syntactically",
"correct",
"and",
"the",
"signature",
"is",
"correct",
"if",
"present",
"."
] | d3aa78eeb7d37c12688f783cb4db1c7263a14ad6 | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/response.py#L1032-L1056 |
232,666 | IdentityPython/pysaml2 | src/saml2/response.py | AuthnResponse.verify_recipient | def verify_recipient(self, recipient):
"""
Verify that I'm the recipient of the assertion
:param recipient: A URI specifying the entity or location to which an
attesting entity can present the assertion.
:return: True/False
"""
if not self.conv_info:
return True
_info = self.conv_info
try:
if recipient == _info['entity_id']:
return True
except KeyError:
pass
try:
if recipient in self.return_addrs:
return True
except KeyError:
pass
return False | python | def verify_recipient(self, recipient):
if not self.conv_info:
return True
_info = self.conv_info
try:
if recipient == _info['entity_id']:
return True
except KeyError:
pass
try:
if recipient in self.return_addrs:
return True
except KeyError:
pass
return False | [
"def",
"verify_recipient",
"(",
"self",
",",
"recipient",
")",
":",
"if",
"not",
"self",
".",
"conv_info",
":",
"return",
"True",
"_info",
"=",
"self",
".",
"conv_info",
"try",
":",
"if",
"recipient",
"==",
"_info",
"[",
"'entity_id'",
"]",
":",
"return"... | Verify that I'm the recipient of the assertion
:param recipient: A URI specifying the entity or location to which an
attesting entity can present the assertion.
:return: True/False | [
"Verify",
"that",
"I",
"m",
"the",
"recipient",
"of",
"the",
"assertion"
] | d3aa78eeb7d37c12688f783cb4db1c7263a14ad6 | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/response.py#L1118-L1143 |
232,667 | IdentityPython/pysaml2 | src/saml2/sigver.py | signed | def signed(item):
"""
Is any part of the document signed ?
:param item: A Samlbase instance
:return: True if some part of it is signed
"""
if SIG in item.c_children.keys() and item.signature:
return True
else:
for prop in item.c_child_order:
child = getattr(item, prop, None)
if isinstance(child, list):
for chi in child:
if signed(chi):
return True
elif child and signed(child):
return True
return False | python | def signed(item):
if SIG in item.c_children.keys() and item.signature:
return True
else:
for prop in item.c_child_order:
child = getattr(item, prop, None)
if isinstance(child, list):
for chi in child:
if signed(chi):
return True
elif child and signed(child):
return True
return False | [
"def",
"signed",
"(",
"item",
")",
":",
"if",
"SIG",
"in",
"item",
".",
"c_children",
".",
"keys",
"(",
")",
"and",
"item",
".",
"signature",
":",
"return",
"True",
"else",
":",
"for",
"prop",
"in",
"item",
".",
"c_child_order",
":",
"child",
"=",
... | Is any part of the document signed ?
:param item: A Samlbase instance
:return: True if some part of it is signed | [
"Is",
"any",
"part",
"of",
"the",
"document",
"signed",
"?"
] | d3aa78eeb7d37c12688f783cb4db1c7263a14ad6 | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/sigver.py#L138-L157 |
232,668 | IdentityPython/pysaml2 | src/saml2/sigver.py | get_xmlsec_binary | def get_xmlsec_binary(paths=None):
"""
Tries to find the xmlsec1 binary.
:param paths: Non-system path paths which should be searched when
looking for xmlsec1
:return: full name of the xmlsec1 binary found. If no binaries are
found then an exception is raised.
"""
if os.name == 'posix':
bin_name = ['xmlsec1']
elif os.name == 'nt':
bin_name = ['xmlsec.exe', 'xmlsec1.exe']
else: # Default !?
bin_name = ['xmlsec1']
if paths:
for bname in bin_name:
for path in paths:
fil = os.path.join(path, bname)
try:
if os.lstat(fil):
return fil
except OSError:
pass
for path in os.environ['PATH'].split(os.pathsep):
for bname in bin_name:
fil = os.path.join(path, bname)
try:
if os.lstat(fil):
return fil
except OSError:
pass
raise SigverError('Cannot find {binary}'.format(binary=bin_name)) | python | def get_xmlsec_binary(paths=None):
if os.name == 'posix':
bin_name = ['xmlsec1']
elif os.name == 'nt':
bin_name = ['xmlsec.exe', 'xmlsec1.exe']
else: # Default !?
bin_name = ['xmlsec1']
if paths:
for bname in bin_name:
for path in paths:
fil = os.path.join(path, bname)
try:
if os.lstat(fil):
return fil
except OSError:
pass
for path in os.environ['PATH'].split(os.pathsep):
for bname in bin_name:
fil = os.path.join(path, bname)
try:
if os.lstat(fil):
return fil
except OSError:
pass
raise SigverError('Cannot find {binary}'.format(binary=bin_name)) | [
"def",
"get_xmlsec_binary",
"(",
"paths",
"=",
"None",
")",
":",
"if",
"os",
".",
"name",
"==",
"'posix'",
":",
"bin_name",
"=",
"[",
"'xmlsec1'",
"]",
"elif",
"os",
".",
"name",
"==",
"'nt'",
":",
"bin_name",
"=",
"[",
"'xmlsec.exe'",
",",
"'xmlsec1.e... | Tries to find the xmlsec1 binary.
:param paths: Non-system path paths which should be searched when
looking for xmlsec1
:return: full name of the xmlsec1 binary found. If no binaries are
found then an exception is raised. | [
"Tries",
"to",
"find",
"the",
"xmlsec1",
"binary",
"."
] | d3aa78eeb7d37c12688f783cb4db1c7263a14ad6 | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/sigver.py#L160-L195 |
232,669 | IdentityPython/pysaml2 | src/saml2/sigver.py | _get_xmlsec_cryptobackend | def _get_xmlsec_cryptobackend(path=None, search_paths=None):
"""
Initialize a CryptoBackendXmlSec1 crypto backend.
This function is now internal to this module.
"""
if path is None:
path = get_xmlsec_binary(paths=search_paths)
return CryptoBackendXmlSec1(path) | python | def _get_xmlsec_cryptobackend(path=None, search_paths=None):
if path is None:
path = get_xmlsec_binary(paths=search_paths)
return CryptoBackendXmlSec1(path) | [
"def",
"_get_xmlsec_cryptobackend",
"(",
"path",
"=",
"None",
",",
"search_paths",
"=",
"None",
")",
":",
"if",
"path",
"is",
"None",
":",
"path",
"=",
"get_xmlsec_binary",
"(",
"paths",
"=",
"search_paths",
")",
"return",
"CryptoBackendXmlSec1",
"(",
"path",
... | Initialize a CryptoBackendXmlSec1 crypto backend.
This function is now internal to this module. | [
"Initialize",
"a",
"CryptoBackendXmlSec1",
"crypto",
"backend",
"."
] | d3aa78eeb7d37c12688f783cb4db1c7263a14ad6 | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/sigver.py#L198-L206 |
232,670 | IdentityPython/pysaml2 | src/saml2/sigver.py | make_temp | def make_temp(string, suffix='', decode=True, delete=True):
""" xmlsec needs files in some cases where only strings exist, hence the
need for this function. It creates a temporary file with the
string as only content.
:param string: The information to be placed in the file
:param suffix: The temporary file might have to have a specific
suffix in certain circumstances.
:param decode: The input string might be base64 coded. If so it
must, in some cases, be decoded before being placed in the file.
:return: 2-tuple with file pointer ( so the calling function can
close the file) and filename (which is for instance needed by the
xmlsec function).
"""
ntf = NamedTemporaryFile(suffix=suffix, delete=delete)
# Python3 tempfile requires byte-like object
if not isinstance(string, six.binary_type):
string = string.encode('utf-8')
if decode:
ntf.write(base64.b64decode(string))
else:
ntf.write(string)
ntf.seek(0)
return ntf, ntf.name | python | def make_temp(string, suffix='', decode=True, delete=True):
ntf = NamedTemporaryFile(suffix=suffix, delete=delete)
# Python3 tempfile requires byte-like object
if not isinstance(string, six.binary_type):
string = string.encode('utf-8')
if decode:
ntf.write(base64.b64decode(string))
else:
ntf.write(string)
ntf.seek(0)
return ntf, ntf.name | [
"def",
"make_temp",
"(",
"string",
",",
"suffix",
"=",
"''",
",",
"decode",
"=",
"True",
",",
"delete",
"=",
"True",
")",
":",
"ntf",
"=",
"NamedTemporaryFile",
"(",
"suffix",
"=",
"suffix",
",",
"delete",
"=",
"delete",
")",
"# Python3 tempfile requires b... | xmlsec needs files in some cases where only strings exist, hence the
need for this function. It creates a temporary file with the
string as only content.
:param string: The information to be placed in the file
:param suffix: The temporary file might have to have a specific
suffix in certain circumstances.
:param decode: The input string might be base64 coded. If so it
must, in some cases, be decoded before being placed in the file.
:return: 2-tuple with file pointer ( so the calling function can
close the file) and filename (which is for instance needed by the
xmlsec function). | [
"xmlsec",
"needs",
"files",
"in",
"some",
"cases",
"where",
"only",
"strings",
"exist",
"hence",
"the",
"need",
"for",
"this",
"function",
".",
"It",
"creates",
"a",
"temporary",
"file",
"with",
"the",
"string",
"as",
"only",
"content",
"."
] | d3aa78eeb7d37c12688f783cb4db1c7263a14ad6 | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/sigver.py#L325-L349 |
232,671 | IdentityPython/pysaml2 | src/saml2/sigver.py | active_cert | 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
"""
try:
cert_str = pem_format(key)
cert = crypto.load_certificate(crypto.FILETYPE_PEM, cert_str)
assert cert.has_expired() == 0
assert not OpenSSLWrapper().certificate_not_valid_yet(cert)
return True
except AssertionError:
return False
except AttributeError:
return False | python | def active_cert(key):
try:
cert_str = pem_format(key)
cert = crypto.load_certificate(crypto.FILETYPE_PEM, cert_str)
assert cert.has_expired() == 0
assert not OpenSSLWrapper().certificate_not_valid_yet(cert)
return True
except AssertionError:
return False
except AttributeError:
return False | [
"def",
"active_cert",
"(",
"key",
")",
":",
"try",
":",
"cert_str",
"=",
"pem_format",
"(",
"key",
")",
"cert",
"=",
"crypto",
".",
"load_certificate",
"(",
"crypto",
".",
"FILETYPE_PEM",
",",
"cert_str",
")",
"assert",
"cert",
".",
"has_expired",
"(",
"... | 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 | [
"Verifies",
"that",
"a",
"key",
"is",
"active",
"that",
"is",
"present",
"time",
"is",
"after",
"not_before",
"and",
"before",
"not_after",
"."
] | d3aa78eeb7d37c12688f783cb4db1c7263a14ad6 | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/sigver.py#L365-L382 |
232,672 | IdentityPython/pysaml2 | src/saml2/sigver.py | cert_from_key_info | def cert_from_key_info(key_info, ignore_age=False):
""" Get all X509 certs from a KeyInfo instance. Care is taken to make sure
that the certs are continues sequences of bytes.
All certificates appearing in an X509Data element MUST relate to the
validation key by either containing it or being part of a certification
chain that terminates in a certificate containing the validation key.
:param key_info: The KeyInfo instance
:return: A possibly empty list of certs
"""
res = []
for x509_data in key_info.x509_data:
x509_certificate = x509_data.x509_certificate
cert = x509_certificate.text.strip()
cert = '\n'.join(split_len(''.join([s.strip() for s in
cert.split()]), 64))
if ignore_age or active_cert(cert):
res.append(cert)
else:
logger.info('Inactive cert')
return res | python | def cert_from_key_info(key_info, ignore_age=False):
res = []
for x509_data in key_info.x509_data:
x509_certificate = x509_data.x509_certificate
cert = x509_certificate.text.strip()
cert = '\n'.join(split_len(''.join([s.strip() for s in
cert.split()]), 64))
if ignore_age or active_cert(cert):
res.append(cert)
else:
logger.info('Inactive cert')
return res | [
"def",
"cert_from_key_info",
"(",
"key_info",
",",
"ignore_age",
"=",
"False",
")",
":",
"res",
"=",
"[",
"]",
"for",
"x509_data",
"in",
"key_info",
".",
"x509_data",
":",
"x509_certificate",
"=",
"x509_data",
".",
"x509_certificate",
"cert",
"=",
"x509_certif... | Get all X509 certs from a KeyInfo instance. Care is taken to make sure
that the certs are continues sequences of bytes.
All certificates appearing in an X509Data element MUST relate to the
validation key by either containing it or being part of a certification
chain that terminates in a certificate containing the validation key.
:param key_info: The KeyInfo instance
:return: A possibly empty list of certs | [
"Get",
"all",
"X509",
"certs",
"from",
"a",
"KeyInfo",
"instance",
".",
"Care",
"is",
"taken",
"to",
"make",
"sure",
"that",
"the",
"certs",
"are",
"continues",
"sequences",
"of",
"bytes",
"."
] | d3aa78eeb7d37c12688f783cb4db1c7263a14ad6 | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/sigver.py#L385-L406 |
232,673 | IdentityPython/pysaml2 | src/saml2/sigver.py | cert_from_instance | def cert_from_instance(instance):
""" Find certificates that are part of an instance
:param instance: An instance
:return: possible empty list of certificates
"""
if instance.signature:
if instance.signature.key_info:
return cert_from_key_info(instance.signature.key_info,
ignore_age=True)
return [] | python | def cert_from_instance(instance):
if instance.signature:
if instance.signature.key_info:
return cert_from_key_info(instance.signature.key_info,
ignore_age=True)
return [] | [
"def",
"cert_from_instance",
"(",
"instance",
")",
":",
"if",
"instance",
".",
"signature",
":",
"if",
"instance",
".",
"signature",
".",
"key_info",
":",
"return",
"cert_from_key_info",
"(",
"instance",
".",
"signature",
".",
"key_info",
",",
"ignore_age",
"=... | Find certificates that are part of an instance
:param instance: An instance
:return: possible empty list of certificates | [
"Find",
"certificates",
"that",
"are",
"part",
"of",
"an",
"instance"
] | d3aa78eeb7d37c12688f783cb4db1c7263a14ad6 | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/sigver.py#L436-L446 |
232,674 | IdentityPython/pysaml2 | src/saml2/sigver.py | parse_xmlsec_output | def parse_xmlsec_output(output):
""" Parse the output from xmlsec to try to find out if the
command was successfull or not.
:param output: The output from Popen
:return: A boolean; True if the command was a success otherwise False
"""
for line in output.splitlines():
if line == 'OK':
return True
elif line == 'FAIL':
raise XmlsecError(output)
raise XmlsecError(output) | python | def parse_xmlsec_output(output):
for line in output.splitlines():
if line == 'OK':
return True
elif line == 'FAIL':
raise XmlsecError(output)
raise XmlsecError(output) | [
"def",
"parse_xmlsec_output",
"(",
"output",
")",
":",
"for",
"line",
"in",
"output",
".",
"splitlines",
"(",
")",
":",
"if",
"line",
"==",
"'OK'",
":",
"return",
"True",
"elif",
"line",
"==",
"'FAIL'",
":",
"raise",
"XmlsecError",
"(",
"output",
")",
... | Parse the output from xmlsec to try to find out if the
command was successfull or not.
:param output: The output from Popen
:return: A boolean; True if the command was a success otherwise False | [
"Parse",
"the",
"output",
"from",
"xmlsec",
"to",
"try",
"to",
"find",
"out",
"if",
"the",
"command",
"was",
"successfull",
"or",
"not",
"."
] | d3aa78eeb7d37c12688f783cb4db1c7263a14ad6 | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/sigver.py#L468-L480 |
232,675 | IdentityPython/pysaml2 | src/saml2/sigver.py | read_cert_from_file | def read_cert_from_file(cert_file, cert_type):
""" Reads a certificate from a file. The assumption is that there is
only one certificate in the file
:param cert_file: The name of the file
:param cert_type: The certificate type
:return: A base64 encoded certificate as a string or the empty string
"""
if not cert_file:
return ''
if cert_type == 'pem':
_a = read_file(cert_file, 'rb').decode()
_b = _a.replace('\r\n', '\n')
lines = _b.split('\n')
for pattern in (
'-----BEGIN CERTIFICATE-----',
'-----BEGIN PUBLIC KEY-----'):
if pattern in lines:
lines = lines[lines.index(pattern) + 1:]
break
else:
raise CertificateError('Strange beginning of PEM file')
for pattern in (
'-----END CERTIFICATE-----',
'-----END PUBLIC KEY-----'):
if pattern in lines:
lines = lines[:lines.index(pattern)]
break
else:
raise CertificateError('Strange end of PEM file')
return make_str(''.join(lines).encode())
if cert_type in ['der', 'cer', 'crt']:
data = read_file(cert_file, 'rb')
_cert = base64.b64encode(data)
return make_str(_cert) | python | def read_cert_from_file(cert_file, cert_type):
if not cert_file:
return ''
if cert_type == 'pem':
_a = read_file(cert_file, 'rb').decode()
_b = _a.replace('\r\n', '\n')
lines = _b.split('\n')
for pattern in (
'-----BEGIN CERTIFICATE-----',
'-----BEGIN PUBLIC KEY-----'):
if pattern in lines:
lines = lines[lines.index(pattern) + 1:]
break
else:
raise CertificateError('Strange beginning of PEM file')
for pattern in (
'-----END CERTIFICATE-----',
'-----END PUBLIC KEY-----'):
if pattern in lines:
lines = lines[:lines.index(pattern)]
break
else:
raise CertificateError('Strange end of PEM file')
return make_str(''.join(lines).encode())
if cert_type in ['der', 'cer', 'crt']:
data = read_file(cert_file, 'rb')
_cert = base64.b64encode(data)
return make_str(_cert) | [
"def",
"read_cert_from_file",
"(",
"cert_file",
",",
"cert_type",
")",
":",
"if",
"not",
"cert_file",
":",
"return",
"''",
"if",
"cert_type",
"==",
"'pem'",
":",
"_a",
"=",
"read_file",
"(",
"cert_file",
",",
"'rb'",
")",
".",
"decode",
"(",
")",
"_b",
... | Reads a certificate from a file. The assumption is that there is
only one certificate in the file
:param cert_file: The name of the file
:param cert_type: The certificate type
:return: A base64 encoded certificate as a string or the empty string | [
"Reads",
"a",
"certificate",
"from",
"a",
"file",
".",
"The",
"assumption",
"is",
"that",
"there",
"is",
"only",
"one",
"certificate",
"in",
"the",
"file"
] | d3aa78eeb7d37c12688f783cb4db1c7263a14ad6 | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/sigver.py#L602-L641 |
232,676 | IdentityPython/pysaml2 | src/saml2/sigver.py | security_context | def security_context(conf):
""" Creates a security context based on the configuration
:param conf: The configuration, this is a Config instance
:return: A SecurityContext instance
"""
if not conf:
return None
try:
metadata = conf.metadata
except AttributeError:
metadata = None
try:
id_attr = conf.id_attr_name
except AttributeError:
id_attr = None
sec_backend = None
if conf.crypto_backend == 'xmlsec1':
xmlsec_binary = conf.xmlsec_binary
if not xmlsec_binary:
try:
_path = conf.xmlsec_path
except AttributeError:
_path = []
xmlsec_binary = get_xmlsec_binary(_path)
# verify that xmlsec is where it's supposed to be
if not os.path.exists(xmlsec_binary):
# if not os.access(, os.F_OK):
err_msg = 'xmlsec binary not found: {binary}'
err_msg = err_msg.format(binary=xmlsec_binary)
raise SigverError(err_msg)
crypto = _get_xmlsec_cryptobackend(xmlsec_binary)
_file_name = conf.getattr('key_file', '')
if _file_name:
try:
rsa_key = import_rsa_key_from_file(_file_name)
except Exception as err:
logger.error('Cannot import key from {file}: {err_msg}'.format(
file=_file_name, err_msg=err))
raise
else:
sec_backend = RSACrypto(rsa_key)
elif conf.crypto_backend == 'XMLSecurity':
# new and somewhat untested pyXMLSecurity crypto backend.
crypto = CryptoBackendXMLSecurity()
else:
err_msg = 'Unknown crypto_backend {backend}'
err_msg = err_msg.format(backend=conf.crypto_backend)
raise SigverError(err_msg)
enc_key_files = []
if conf.encryption_keypairs is not None:
for _encryption_keypair in conf.encryption_keypairs:
if 'key_file' in _encryption_keypair:
enc_key_files.append(_encryption_keypair['key_file'])
return SecurityContext(
crypto,
conf.key_file,
cert_file=conf.cert_file,
metadata=metadata,
only_use_keys_in_metadata=conf.only_use_keys_in_metadata,
cert_handler_extra_class=conf.cert_handler_extra_class,
generate_cert_info=conf.generate_cert_info,
tmp_cert_file=conf.tmp_cert_file,
tmp_key_file=conf.tmp_key_file,
validate_certificate=conf.validate_certificate,
enc_key_files=enc_key_files,
encryption_keypairs=conf.encryption_keypairs,
sec_backend=sec_backend,
id_attr=id_attr) | python | def security_context(conf):
if not conf:
return None
try:
metadata = conf.metadata
except AttributeError:
metadata = None
try:
id_attr = conf.id_attr_name
except AttributeError:
id_attr = None
sec_backend = None
if conf.crypto_backend == 'xmlsec1':
xmlsec_binary = conf.xmlsec_binary
if not xmlsec_binary:
try:
_path = conf.xmlsec_path
except AttributeError:
_path = []
xmlsec_binary = get_xmlsec_binary(_path)
# verify that xmlsec is where it's supposed to be
if not os.path.exists(xmlsec_binary):
# if not os.access(, os.F_OK):
err_msg = 'xmlsec binary not found: {binary}'
err_msg = err_msg.format(binary=xmlsec_binary)
raise SigverError(err_msg)
crypto = _get_xmlsec_cryptobackend(xmlsec_binary)
_file_name = conf.getattr('key_file', '')
if _file_name:
try:
rsa_key = import_rsa_key_from_file(_file_name)
except Exception as err:
logger.error('Cannot import key from {file}: {err_msg}'.format(
file=_file_name, err_msg=err))
raise
else:
sec_backend = RSACrypto(rsa_key)
elif conf.crypto_backend == 'XMLSecurity':
# new and somewhat untested pyXMLSecurity crypto backend.
crypto = CryptoBackendXMLSecurity()
else:
err_msg = 'Unknown crypto_backend {backend}'
err_msg = err_msg.format(backend=conf.crypto_backend)
raise SigverError(err_msg)
enc_key_files = []
if conf.encryption_keypairs is not None:
for _encryption_keypair in conf.encryption_keypairs:
if 'key_file' in _encryption_keypair:
enc_key_files.append(_encryption_keypair['key_file'])
return SecurityContext(
crypto,
conf.key_file,
cert_file=conf.cert_file,
metadata=metadata,
only_use_keys_in_metadata=conf.only_use_keys_in_metadata,
cert_handler_extra_class=conf.cert_handler_extra_class,
generate_cert_info=conf.generate_cert_info,
tmp_cert_file=conf.tmp_cert_file,
tmp_key_file=conf.tmp_key_file,
validate_certificate=conf.validate_certificate,
enc_key_files=enc_key_files,
encryption_keypairs=conf.encryption_keypairs,
sec_backend=sec_backend,
id_attr=id_attr) | [
"def",
"security_context",
"(",
"conf",
")",
":",
"if",
"not",
"conf",
":",
"return",
"None",
"try",
":",
"metadata",
"=",
"conf",
".",
"metadata",
"except",
"AttributeError",
":",
"metadata",
"=",
"None",
"try",
":",
"id_attr",
"=",
"conf",
".",
"id_att... | Creates a security context based on the configuration
:param conf: The configuration, this is a Config instance
:return: A SecurityContext instance | [
"Creates",
"a",
"security",
"context",
"based",
"on",
"the",
"configuration"
] | d3aa78eeb7d37c12688f783cb4db1c7263a14ad6 | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/sigver.py#L990-L1068 |
232,677 | IdentityPython/pysaml2 | src/saml2/sigver.py | pre_signature_part | def pre_signature_part(ident, public_key=None, identifier=None, digest_alg=None, sign_alg=None):
"""
If an assertion is to be signed the signature part has to be preset
with which algorithms to be used, this function returns such a
preset part.
:param ident: The identifier of the assertion, so you know which assertion
was signed
:param public_key: The base64 part of a PEM file
:param identifier:
:return: A preset signature part
"""
if not digest_alg:
digest_alg = ds.DefaultSignature().get_digest_alg()
if not sign_alg:
sign_alg = ds.DefaultSignature().get_sign_alg()
signature_method = ds.SignatureMethod(algorithm=sign_alg)
canonicalization_method = ds.CanonicalizationMethod(
algorithm=ds.ALG_EXC_C14N)
trans0 = ds.Transform(algorithm=ds.TRANSFORM_ENVELOPED)
trans1 = ds.Transform(algorithm=ds.ALG_EXC_C14N)
transforms = ds.Transforms(transform=[trans0, trans1])
digest_method = ds.DigestMethod(algorithm=digest_alg)
reference = ds.Reference(
uri='#{id}'.format(id=ident),
digest_value=ds.DigestValue(),
transforms=transforms,
digest_method=digest_method)
signed_info = ds.SignedInfo(
signature_method=signature_method,
canonicalization_method=canonicalization_method,
reference=reference)
signature = ds.Signature(
signed_info=signed_info,
signature_value=ds.SignatureValue())
if identifier:
signature.id = 'Signature{n}'.format(n=identifier)
if public_key:
x509_data = ds.X509Data(
x509_certificate=[ds.X509Certificate(text=public_key)])
key_info = ds.KeyInfo(x509_data=x509_data)
signature.key_info = key_info
return signature | python | def pre_signature_part(ident, public_key=None, identifier=None, digest_alg=None, sign_alg=None):
if not digest_alg:
digest_alg = ds.DefaultSignature().get_digest_alg()
if not sign_alg:
sign_alg = ds.DefaultSignature().get_sign_alg()
signature_method = ds.SignatureMethod(algorithm=sign_alg)
canonicalization_method = ds.CanonicalizationMethod(
algorithm=ds.ALG_EXC_C14N)
trans0 = ds.Transform(algorithm=ds.TRANSFORM_ENVELOPED)
trans1 = ds.Transform(algorithm=ds.ALG_EXC_C14N)
transforms = ds.Transforms(transform=[trans0, trans1])
digest_method = ds.DigestMethod(algorithm=digest_alg)
reference = ds.Reference(
uri='#{id}'.format(id=ident),
digest_value=ds.DigestValue(),
transforms=transforms,
digest_method=digest_method)
signed_info = ds.SignedInfo(
signature_method=signature_method,
canonicalization_method=canonicalization_method,
reference=reference)
signature = ds.Signature(
signed_info=signed_info,
signature_value=ds.SignatureValue())
if identifier:
signature.id = 'Signature{n}'.format(n=identifier)
if public_key:
x509_data = ds.X509Data(
x509_certificate=[ds.X509Certificate(text=public_key)])
key_info = ds.KeyInfo(x509_data=x509_data)
signature.key_info = key_info
return signature | [
"def",
"pre_signature_part",
"(",
"ident",
",",
"public_key",
"=",
"None",
",",
"identifier",
"=",
"None",
",",
"digest_alg",
"=",
"None",
",",
"sign_alg",
"=",
"None",
")",
":",
"if",
"not",
"digest_alg",
":",
"digest_alg",
"=",
"ds",
".",
"DefaultSignatu... | If an assertion is to be signed the signature part has to be preset
with which algorithms to be used, this function returns such a
preset part.
:param ident: The identifier of the assertion, so you know which assertion
was signed
:param public_key: The base64 part of a PEM file
:param identifier:
:return: A preset signature part | [
"If",
"an",
"assertion",
"is",
"to",
"be",
"signed",
"the",
"signature",
"part",
"has",
"to",
"be",
"preset",
"with",
"which",
"algorithms",
"to",
"be",
"used",
"this",
"function",
"returns",
"such",
"a",
"preset",
"part",
"."
] | d3aa78eeb7d37c12688f783cb4db1c7263a14ad6 | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/sigver.py#L1748-L1797 |
232,678 | IdentityPython/pysaml2 | src/saml2/sigver.py | SecurityContext.verify_signature | def verify_signature(self, signedtext, cert_file=None, cert_type='pem', node_name=NODE_NAME, node_id=None, id_attr=''):
""" Verifies the signature of a XML document.
:param signedtext: The XML document as a string
:param cert_file: The public key that was used to sign the document
:param cert_type: The file type of the certificate
:param node_name: The name of the class that is signed
:param node_id: The identifier of the node
:param id_attr: The attribute name for the identifier, normally one of
'id','Id' or 'ID'
:return: Boolean True if the signature was correct otherwise False.
"""
# This is only for testing purposes, otherwise when would you receive
# stuff that is signed with your key !?
if not cert_file:
cert_file = self.cert_file
cert_type = self.cert_type
if not id_attr:
id_attr = self.id_attr
return self.crypto.validate_signature(
signedtext,
cert_file=cert_file,
cert_type=cert_type,
node_name=node_name,
node_id=node_id,
id_attr=id_attr) | python | def verify_signature(self, signedtext, cert_file=None, cert_type='pem', node_name=NODE_NAME, node_id=None, id_attr=''):
# This is only for testing purposes, otherwise when would you receive
# stuff that is signed with your key !?
if not cert_file:
cert_file = self.cert_file
cert_type = self.cert_type
if not id_attr:
id_attr = self.id_attr
return self.crypto.validate_signature(
signedtext,
cert_file=cert_file,
cert_type=cert_type,
node_name=node_name,
node_id=node_id,
id_attr=id_attr) | [
"def",
"verify_signature",
"(",
"self",
",",
"signedtext",
",",
"cert_file",
"=",
"None",
",",
"cert_type",
"=",
"'pem'",
",",
"node_name",
"=",
"NODE_NAME",
",",
"node_id",
"=",
"None",
",",
"id_attr",
"=",
"''",
")",
":",
"# This is only for testing purposes... | Verifies the signature of a XML document.
:param signedtext: The XML document as a string
:param cert_file: The public key that was used to sign the document
:param cert_type: The file type of the certificate
:param node_name: The name of the class that is signed
:param node_id: The identifier of the node
:param id_attr: The attribute name for the identifier, normally one of
'id','Id' or 'ID'
:return: Boolean True if the signature was correct otherwise False. | [
"Verifies",
"the",
"signature",
"of",
"a",
"XML",
"document",
"."
] | d3aa78eeb7d37c12688f783cb4db1c7263a14ad6 | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/sigver.py#L1410-L1437 |
232,679 | IdentityPython/pysaml2 | src/saml2/sigver.py | SecurityContext.correctly_signed_message | def correctly_signed_message(self, decoded_xml, msgtype, must=False, origdoc=None, only_valid_cert=False):
"""Check if a request is correctly signed, if we have metadata for
the entity that sent the info use that, if not use the key that are in
the message if any.
:param decoded_xml: The SAML message as an XML infoset (a string)
:param msgtype: SAML protocol message type
:param must: Whether there must be a signature
:param origdoc:
:return:
"""
attr = '{type}_from_string'.format(type=msgtype)
_func = getattr(saml, attr, None)
_func = getattr(samlp, attr, _func)
msg = _func(decoded_xml)
if not msg:
raise TypeError('Not a {type}'.format(type=msgtype))
if not msg.signature:
if must:
err_msg = 'Required signature missing on {type}'
err_msg = err_msg.format(type=msgtype)
raise SignatureError(err_msg)
else:
return msg
return self._check_signature(
decoded_xml,
msg,
class_name(msg),
origdoc,
must=must,
only_valid_cert=only_valid_cert) | python | def correctly_signed_message(self, decoded_xml, msgtype, must=False, origdoc=None, only_valid_cert=False):
attr = '{type}_from_string'.format(type=msgtype)
_func = getattr(saml, attr, None)
_func = getattr(samlp, attr, _func)
msg = _func(decoded_xml)
if not msg:
raise TypeError('Not a {type}'.format(type=msgtype))
if not msg.signature:
if must:
err_msg = 'Required signature missing on {type}'
err_msg = err_msg.format(type=msgtype)
raise SignatureError(err_msg)
else:
return msg
return self._check_signature(
decoded_xml,
msg,
class_name(msg),
origdoc,
must=must,
only_valid_cert=only_valid_cert) | [
"def",
"correctly_signed_message",
"(",
"self",
",",
"decoded_xml",
",",
"msgtype",
",",
"must",
"=",
"False",
",",
"origdoc",
"=",
"None",
",",
"only_valid_cert",
"=",
"False",
")",
":",
"attr",
"=",
"'{type}_from_string'",
".",
"format",
"(",
"type",
"=",
... | Check if a request is correctly signed, if we have metadata for
the entity that sent the info use that, if not use the key that are in
the message if any.
:param decoded_xml: The SAML message as an XML infoset (a string)
:param msgtype: SAML protocol message type
:param must: Whether there must be a signature
:param origdoc:
:return: | [
"Check",
"if",
"a",
"request",
"is",
"correctly",
"signed",
"if",
"we",
"have",
"metadata",
"for",
"the",
"entity",
"that",
"sent",
"the",
"info",
"use",
"that",
"if",
"not",
"use",
"the",
"key",
"that",
"are",
"in",
"the",
"message",
"if",
"any",
"."
... | d3aa78eeb7d37c12688f783cb4db1c7263a14ad6 | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/sigver.py#L1540-L1574 |
232,680 | IdentityPython/pysaml2 | src/saml2/sigver.py | SecurityContext.correctly_signed_response | def correctly_signed_response(self, decoded_xml, must=False, origdoc=None, only_valid_cert=False, require_response_signature=False, **kwargs):
""" Check if a instance is correctly signed, if we have metadata for
the IdP that sent the info use that, if not use the key that are in
the message if any.
:param decoded_xml: The SAML message as a XML string
:param must: Whether there must be a signature
:param origdoc:
:param only_valid_cert:
:param require_response_signature:
:return: None if the signature can not be verified otherwise an instance
"""
response = samlp.any_response_from_string(decoded_xml)
if not response:
raise TypeError('Not a Response')
if response.signature:
if 'do_not_verify' in kwargs:
pass
else:
self._check_signature(decoded_xml, response,
class_name(response), origdoc)
elif require_response_signature:
raise SignatureError('Signature missing for response')
return response | python | def correctly_signed_response(self, decoded_xml, must=False, origdoc=None, only_valid_cert=False, require_response_signature=False, **kwargs):
response = samlp.any_response_from_string(decoded_xml)
if not response:
raise TypeError('Not a Response')
if response.signature:
if 'do_not_verify' in kwargs:
pass
else:
self._check_signature(decoded_xml, response,
class_name(response), origdoc)
elif require_response_signature:
raise SignatureError('Signature missing for response')
return response | [
"def",
"correctly_signed_response",
"(",
"self",
",",
"decoded_xml",
",",
"must",
"=",
"False",
",",
"origdoc",
"=",
"None",
",",
"only_valid_cert",
"=",
"False",
",",
"require_response_signature",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"response",
... | Check if a instance is correctly signed, if we have metadata for
the IdP that sent the info use that, if not use the key that are in
the message if any.
:param decoded_xml: The SAML message as a XML string
:param must: Whether there must be a signature
:param origdoc:
:param only_valid_cert:
:param require_response_signature:
:return: None if the signature can not be verified otherwise an instance | [
"Check",
"if",
"a",
"instance",
"is",
"correctly",
"signed",
"if",
"we",
"have",
"metadata",
"for",
"the",
"IdP",
"that",
"sent",
"the",
"info",
"use",
"that",
"if",
"not",
"use",
"the",
"key",
"that",
"are",
"in",
"the",
"message",
"if",
"any",
"."
] | d3aa78eeb7d37c12688f783cb4db1c7263a14ad6 | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/sigver.py#L1621-L1647 |
232,681 | IdentityPython/pysaml2 | src/saml2/sigver.py | SecurityContext.sign_statement | def sign_statement(self, statement, node_name, key=None, key_file=None, node_id=None, id_attr=''):
"""Sign a SAML statement.
:param statement: The statement to be signed
:param node_name: string like 'urn:oasis:names:...:Assertion'
:param key: The key to be used for the signing, either this or
:param key_file: The file where the key can be found
:param node_id:
:param id_attr: The attribute name for the identifier, normally one of
'id','Id' or 'ID'
:return: The signed statement
"""
if not id_attr:
id_attr = self.id_attr
if not key_file and key:
_, key_file = make_temp(str(key).encode(), '.pem')
if not key and not key_file:
key_file = self.key_file
return self.crypto.sign_statement(
statement,
node_name,
key_file,
node_id,
id_attr) | python | def sign_statement(self, statement, node_name, key=None, key_file=None, node_id=None, id_attr=''):
if not id_attr:
id_attr = self.id_attr
if not key_file and key:
_, key_file = make_temp(str(key).encode(), '.pem')
if not key and not key_file:
key_file = self.key_file
return self.crypto.sign_statement(
statement,
node_name,
key_file,
node_id,
id_attr) | [
"def",
"sign_statement",
"(",
"self",
",",
"statement",
",",
"node_name",
",",
"key",
"=",
"None",
",",
"key_file",
"=",
"None",
",",
"node_id",
"=",
"None",
",",
"id_attr",
"=",
"''",
")",
":",
"if",
"not",
"id_attr",
":",
"id_attr",
"=",
"self",
".... | Sign a SAML statement.
:param statement: The statement to be signed
:param node_name: string like 'urn:oasis:names:...:Assertion'
:param key: The key to be used for the signing, either this or
:param key_file: The file where the key can be found
:param node_id:
:param id_attr: The attribute name for the identifier, normally one of
'id','Id' or 'ID'
:return: The signed statement | [
"Sign",
"a",
"SAML",
"statement",
"."
] | d3aa78eeb7d37c12688f783cb4db1c7263a14ad6 | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/sigver.py#L1653-L1679 |
232,682 | IdentityPython/pysaml2 | src/saml2/sigver.py | SecurityContext.sign_assertion | def sign_assertion(self, statement, **kwargs):
"""Sign a SAML assertion.
See sign_statement() for the kwargs.
:param statement: The statement to be signed
:return: The signed statement
"""
return self.sign_statement(
statement, class_name(saml.Assertion()), **kwargs) | python | def sign_assertion(self, statement, **kwargs):
return self.sign_statement(
statement, class_name(saml.Assertion()), **kwargs) | [
"def",
"sign_assertion",
"(",
"self",
",",
"statement",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"sign_statement",
"(",
"statement",
",",
"class_name",
"(",
"saml",
".",
"Assertion",
"(",
")",
")",
",",
"*",
"*",
"kwargs",
")"
] | Sign a SAML assertion.
See sign_statement() for the kwargs.
:param statement: The statement to be signed
:return: The signed statement | [
"Sign",
"a",
"SAML",
"assertion",
"."
] | d3aa78eeb7d37c12688f783cb4db1c7263a14ad6 | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/sigver.py#L1686-L1695 |
232,683 | IdentityPython/pysaml2 | src/saml2/sigver.py | SecurityContext.sign_attribute_query | def sign_attribute_query(self, statement, **kwargs):
"""Sign a SAML attribute query.
See sign_statement() for the kwargs.
:param statement: The statement to be signed
:return: The signed statement
"""
return self.sign_statement(
statement, class_name(samlp.AttributeQuery()), **kwargs) | python | def sign_attribute_query(self, statement, **kwargs):
return self.sign_statement(
statement, class_name(samlp.AttributeQuery()), **kwargs) | [
"def",
"sign_attribute_query",
"(",
"self",
",",
"statement",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"sign_statement",
"(",
"statement",
",",
"class_name",
"(",
"samlp",
".",
"AttributeQuery",
"(",
")",
")",
",",
"*",
"*",
"kwargs",
")... | Sign a SAML attribute query.
See sign_statement() for the kwargs.
:param statement: The statement to be signed
:return: The signed statement | [
"Sign",
"a",
"SAML",
"attribute",
"query",
"."
] | d3aa78eeb7d37c12688f783cb4db1c7263a14ad6 | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/sigver.py#L1701-L1710 |
232,684 | IdentityPython/pysaml2 | src/saml2/sigver.py | SecurityContext.multiple_signatures | def multiple_signatures(self, statement, to_sign, key=None, key_file=None, sign_alg=None, digest_alg=None):
"""
Sign multiple parts of a statement
:param statement: The statement that should be sign, this is XML text
:param to_sign: A list of (items, id, id attribute name) tuples that
specifies what to sign
:param key: A key that should be used for doing the signing
:param key_file: A file that contains the key to be used
:return: A possibly multiple signed statement
"""
for (item, sid, id_attr) in to_sign:
if not sid:
if not item.id:
sid = item.id = sid()
else:
sid = item.id
if not item.signature:
item.signature = pre_signature_part(
sid,
self.cert_file,
sign_alg=sign_alg,
digest_alg=digest_alg)
statement = self.sign_statement(
statement,
class_name(item),
key=key,
key_file=key_file,
node_id=sid,
id_attr=id_attr)
return statement | python | def multiple_signatures(self, statement, to_sign, key=None, key_file=None, sign_alg=None, digest_alg=None):
for (item, sid, id_attr) in to_sign:
if not sid:
if not item.id:
sid = item.id = sid()
else:
sid = item.id
if not item.signature:
item.signature = pre_signature_part(
sid,
self.cert_file,
sign_alg=sign_alg,
digest_alg=digest_alg)
statement = self.sign_statement(
statement,
class_name(item),
key=key,
key_file=key_file,
node_id=sid,
id_attr=id_attr)
return statement | [
"def",
"multiple_signatures",
"(",
"self",
",",
"statement",
",",
"to_sign",
",",
"key",
"=",
"None",
",",
"key_file",
"=",
"None",
",",
"sign_alg",
"=",
"None",
",",
"digest_alg",
"=",
"None",
")",
":",
"for",
"(",
"item",
",",
"sid",
",",
"id_attr",
... | Sign multiple parts of a statement
:param statement: The statement that should be sign, this is XML text
:param to_sign: A list of (items, id, id attribute name) tuples that
specifies what to sign
:param key: A key that should be used for doing the signing
:param key_file: A file that contains the key to be used
:return: A possibly multiple signed statement | [
"Sign",
"multiple",
"parts",
"of",
"a",
"statement"
] | d3aa78eeb7d37c12688f783cb4db1c7263a14ad6 | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/sigver.py#L1712-L1745 |
232,685 | IdentityPython/pysaml2 | src/saml2/soap.py | parse_soap_enveloped_saml_thingy | def parse_soap_enveloped_saml_thingy(text, expected_tags):
"""Parses a SOAP enveloped SAML thing and returns the thing as
a string.
:param text: The SOAP object as XML string
:param expected_tags: What the tag of the SAML thingy is expected to be.
:return: SAML thingy as a string
"""
envelope = defusedxml.ElementTree.fromstring(text)
# Make sure it's a SOAP message
assert envelope.tag == '{%s}Envelope' % soapenv.NAMESPACE
assert len(envelope) >= 1
body = None
for part in envelope:
if part.tag == '{%s}Body' % soapenv.NAMESPACE:
assert len(part) == 1
body = part
break
if body is None:
return ""
saml_part = body[0]
if saml_part.tag in expected_tags:
return ElementTree.tostring(saml_part, encoding="UTF-8")
else:
raise WrongMessageType("Was '%s' expected one of %s" % (saml_part.tag,
expected_tags)) | python | def parse_soap_enveloped_saml_thingy(text, expected_tags):
envelope = defusedxml.ElementTree.fromstring(text)
# Make sure it's a SOAP message
assert envelope.tag == '{%s}Envelope' % soapenv.NAMESPACE
assert len(envelope) >= 1
body = None
for part in envelope:
if part.tag == '{%s}Body' % soapenv.NAMESPACE:
assert len(part) == 1
body = part
break
if body is None:
return ""
saml_part = body[0]
if saml_part.tag in expected_tags:
return ElementTree.tostring(saml_part, encoding="UTF-8")
else:
raise WrongMessageType("Was '%s' expected one of %s" % (saml_part.tag,
expected_tags)) | [
"def",
"parse_soap_enveloped_saml_thingy",
"(",
"text",
",",
"expected_tags",
")",
":",
"envelope",
"=",
"defusedxml",
".",
"ElementTree",
".",
"fromstring",
"(",
"text",
")",
"# Make sure it's a SOAP message",
"assert",
"envelope",
".",
"tag",
"==",
"'{%s}Envelope'",... | Parses a SOAP enveloped SAML thing and returns the thing as
a string.
:param text: The SOAP object as XML string
:param expected_tags: What the tag of the SAML thingy is expected to be.
:return: SAML thingy as a string | [
"Parses",
"a",
"SOAP",
"enveloped",
"SAML",
"thing",
"and",
"returns",
"the",
"thing",
"as",
"a",
"string",
"."
] | d3aa78eeb7d37c12688f783cb4db1c7263a14ad6 | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/soap.py#L129-L158 |
232,686 | IdentityPython/pysaml2 | src/saml2/soap.py | class_instances_from_soap_enveloped_saml_thingies | def class_instances_from_soap_enveloped_saml_thingies(text, modules):
"""Parses a SOAP enveloped header and body SAML thing and returns the
thing as a dictionary class instance.
:param text: The SOAP object as XML
:param modules: modules representing xsd schemas
:return: The body and headers as class instances
"""
try:
envelope = defusedxml.ElementTree.fromstring(text)
except Exception as exc:
raise XmlParseError("%s" % exc)
assert envelope.tag == '{%s}Envelope' % soapenv.NAMESPACE
assert len(envelope) >= 1
env = {"header": [], "body": None}
for part in envelope:
if part.tag == '{%s}Body' % soapenv.NAMESPACE:
assert len(part) == 1
env["body"] = instanciate_class(part[0], modules)
elif part.tag == "{%s}Header" % soapenv.NAMESPACE:
for item in part:
env["header"].append(instanciate_class(item, modules))
return env | python | def class_instances_from_soap_enveloped_saml_thingies(text, modules):
try:
envelope = defusedxml.ElementTree.fromstring(text)
except Exception as exc:
raise XmlParseError("%s" % exc)
assert envelope.tag == '{%s}Envelope' % soapenv.NAMESPACE
assert len(envelope) >= 1
env = {"header": [], "body": None}
for part in envelope:
if part.tag == '{%s}Body' % soapenv.NAMESPACE:
assert len(part) == 1
env["body"] = instanciate_class(part[0], modules)
elif part.tag == "{%s}Header" % soapenv.NAMESPACE:
for item in part:
env["header"].append(instanciate_class(item, modules))
return env | [
"def",
"class_instances_from_soap_enveloped_saml_thingies",
"(",
"text",
",",
"modules",
")",
":",
"try",
":",
"envelope",
"=",
"defusedxml",
".",
"ElementTree",
".",
"fromstring",
"(",
"text",
")",
"except",
"Exception",
"as",
"exc",
":",
"raise",
"XmlParseError"... | Parses a SOAP enveloped header and body SAML thing and returns the
thing as a dictionary class instance.
:param text: The SOAP object as XML
:param modules: modules representing xsd schemas
:return: The body and headers as class instances | [
"Parses",
"a",
"SOAP",
"enveloped",
"header",
"and",
"body",
"SAML",
"thing",
"and",
"returns",
"the",
"thing",
"as",
"a",
"dictionary",
"class",
"instance",
"."
] | d3aa78eeb7d37c12688f783cb4db1c7263a14ad6 | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/soap.py#L178-L203 |
232,687 | IdentityPython/pysaml2 | src/saml2/soap.py | soap_fault | def soap_fault(message=None, actor=None, code=None, detail=None):
""" Create a SOAP Fault message
:param message: Human readable error message
:param actor: Who discovered the error
:param code: Error code
:param detail: More specific error message
:return: A SOAP Fault message as a string
"""
_string = _actor = _code = _detail = None
if message:
_string = soapenv.Fault_faultstring(text=message)
if actor:
_actor = soapenv.Fault_faultactor(text=actor)
if code:
_code = soapenv.Fault_faultcode(text=code)
if detail:
_detail = soapenv.Fault_detail(text=detail)
fault = soapenv.Fault(
faultcode=_code,
faultstring=_string,
faultactor=_actor,
detail=_detail,
)
return "%s" % fault | python | def soap_fault(message=None, actor=None, code=None, detail=None):
_string = _actor = _code = _detail = None
if message:
_string = soapenv.Fault_faultstring(text=message)
if actor:
_actor = soapenv.Fault_faultactor(text=actor)
if code:
_code = soapenv.Fault_faultcode(text=code)
if detail:
_detail = soapenv.Fault_detail(text=detail)
fault = soapenv.Fault(
faultcode=_code,
faultstring=_string,
faultactor=_actor,
detail=_detail,
)
return "%s" % fault | [
"def",
"soap_fault",
"(",
"message",
"=",
"None",
",",
"actor",
"=",
"None",
",",
"code",
"=",
"None",
",",
"detail",
"=",
"None",
")",
":",
"_string",
"=",
"_actor",
"=",
"_code",
"=",
"_detail",
"=",
"None",
"if",
"message",
":",
"_string",
"=",
... | Create a SOAP Fault message
:param message: Human readable error message
:param actor: Who discovered the error
:param code: Error code
:param detail: More specific error message
:return: A SOAP Fault message as a string | [
"Create",
"a",
"SOAP",
"Fault",
"message"
] | d3aa78eeb7d37c12688f783cb4db1c7263a14ad6 | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/soap.py#L253-L280 |
232,688 | IdentityPython/pysaml2 | src/saml2/cryptography/symmetric.py | AESCipher._deprecation_notice | def _deprecation_notice(cls):
"""Warn about deprecation of this class."""
_deprecation_msg = (
'{name} {type} is deprecated. '
'It will be removed in the next version. '
'Use saml2.cryptography.symmetric instead.'
).format(name=cls.__name__, type=type(cls).__name__)
_warnings.warn(_deprecation_msg, DeprecationWarning) | python | def _deprecation_notice(cls):
_deprecation_msg = (
'{name} {type} is deprecated. '
'It will be removed in the next version. '
'Use saml2.cryptography.symmetric instead.'
).format(name=cls.__name__, type=type(cls).__name__)
_warnings.warn(_deprecation_msg, DeprecationWarning) | [
"def",
"_deprecation_notice",
"(",
"cls",
")",
":",
"_deprecation_msg",
"=",
"(",
"'{name} {type} is deprecated. '",
"'It will be removed in the next version. '",
"'Use saml2.cryptography.symmetric instead.'",
")",
".",
"format",
"(",
"name",
"=",
"cls",
".",
"__name__",
",... | Warn about deprecation of this class. | [
"Warn",
"about",
"deprecation",
"of",
"this",
"class",
"."
] | d3aa78eeb7d37c12688f783cb4db1c7263a14ad6 | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/cryptography/symmetric.py#L68-L75 |
232,689 | IdentityPython/pysaml2 | src/saml2/cert.py | OpenSSLWrapper.create_certificate | def create_certificate(self, cert_info, request=False, valid_from=0,
valid_to=315360000, sn=1, key_length=1024,
hash_alg="sha256", write_to_file=False, cert_dir="",
cipher_passphrase=None):
"""
Can create certificate requests, to be signed later by another
certificate with the method
create_cert_signed_certificate. If request is True.
Can also create self signed root certificates if request is False.
This is default behaviour.
:param cert_info: Contains information about the certificate.
Is a dictionary that must contain the keys:
cn = Common name. This part
must match the host being authenticated
country_code = Two letter description
of the country.
state = State
city = City
organization = Organization, can be a
company name.
organization_unit = A unit at the
organization, can be a department.
Example:
cert_info_ca = {
"cn": "company.com",
"country_code": "se",
"state": "AC",
"city": "Dorotea",
"organization":
"Company",
"organization_unit":
"Sales"
}
:param request: True if this is a request for certificate,
that should be signed.
False if this is a self signed certificate,
root certificate.
:param valid_from: When the certificate starts to be valid.
Amount of seconds from when the
certificate is generated.
:param valid_to: How long the certificate will be valid from
when it is generated.
The value is in seconds. Default is
315360000 seconds, a.k.a 10 years.
:param sn: Serial number for the certificate. Default
is 1.
:param key_length: Length of the key to be generated. Defaults
to 1024.
:param hash_alg: Hash algorithm to use for the key. Default
is sha256.
:param write_to_file: True if you want to write the certificate
to a file. The method will then return
a tuple with path to certificate file and
path to key file.
False if you want to get the result as
strings. The method will then return a tuple
with the certificate string and the key as
string.
WILL OVERWRITE ALL EXISTING FILES WITHOUT
ASKING!
:param cert_dir: Where to save the files if write_to_file is
true.
:param cipher_passphrase A dictionary with cipher and passphrase.
Example::
{"cipher": "blowfish", "passphrase": "qwerty"}
:return: string representation of certificate,
string representation of private key
if write_to_file parameter is False otherwise
path to certificate file, path to private
key file
"""
cn = cert_info["cn"]
c_f = None
k_f = None
if write_to_file:
cert_file = "%s.crt" % cn
key_file = "%s.key" % cn
try:
remove(cert_file)
except:
pass
try:
remove(key_file)
except:
pass
c_f = join(cert_dir, cert_file)
k_f = join(cert_dir, key_file)
# create a key pair
k = crypto.PKey()
k.generate_key(crypto.TYPE_RSA, key_length)
# create a self-signed cert
cert = crypto.X509()
if request:
cert = crypto.X509Req()
if (len(cert_info["country_code"]) != 2):
raise WrongInput("Country code must be two letters!")
cert.get_subject().C = cert_info["country_code"]
cert.get_subject().ST = cert_info["state"]
cert.get_subject().L = cert_info["city"]
cert.get_subject().O = cert_info["organization"]
cert.get_subject().OU = cert_info["organization_unit"]
cert.get_subject().CN = cn
if not request:
cert.set_serial_number(sn)
cert.gmtime_adj_notBefore(valid_from) #Valid before present time
cert.gmtime_adj_notAfter(valid_to) #3 650 days
cert.set_issuer(cert.get_subject())
cert.set_pubkey(k)
cert.sign(k, hash_alg)
try:
if request:
tmp_cert = crypto.dump_certificate_request(crypto.FILETYPE_PEM,
cert)
else:
tmp_cert = crypto.dump_certificate(crypto.FILETYPE_PEM, cert)
tmp_key = None
if cipher_passphrase is not None:
passphrase = cipher_passphrase["passphrase"]
if isinstance(cipher_passphrase["passphrase"],
six.string_types):
passphrase = passphrase.encode('utf-8')
tmp_key = crypto.dump_privatekey(crypto.FILETYPE_PEM, k,
cipher_passphrase["cipher"],
passphrase)
else:
tmp_key = crypto.dump_privatekey(crypto.FILETYPE_PEM, k)
if write_to_file:
with open(c_f, 'wt') as fc:
fc.write(tmp_cert.decode('utf-8'))
with open(k_f, 'wt') as fk:
fk.write(tmp_key.decode('utf-8'))
return c_f, k_f
return tmp_cert, tmp_key
except Exception as ex:
raise CertificateError("Certificate cannot be generated.", ex) | python | def create_certificate(self, cert_info, request=False, valid_from=0,
valid_to=315360000, sn=1, key_length=1024,
hash_alg="sha256", write_to_file=False, cert_dir="",
cipher_passphrase=None):
cn = cert_info["cn"]
c_f = None
k_f = None
if write_to_file:
cert_file = "%s.crt" % cn
key_file = "%s.key" % cn
try:
remove(cert_file)
except:
pass
try:
remove(key_file)
except:
pass
c_f = join(cert_dir, cert_file)
k_f = join(cert_dir, key_file)
# create a key pair
k = crypto.PKey()
k.generate_key(crypto.TYPE_RSA, key_length)
# create a self-signed cert
cert = crypto.X509()
if request:
cert = crypto.X509Req()
if (len(cert_info["country_code"]) != 2):
raise WrongInput("Country code must be two letters!")
cert.get_subject().C = cert_info["country_code"]
cert.get_subject().ST = cert_info["state"]
cert.get_subject().L = cert_info["city"]
cert.get_subject().O = cert_info["organization"]
cert.get_subject().OU = cert_info["organization_unit"]
cert.get_subject().CN = cn
if not request:
cert.set_serial_number(sn)
cert.gmtime_adj_notBefore(valid_from) #Valid before present time
cert.gmtime_adj_notAfter(valid_to) #3 650 days
cert.set_issuer(cert.get_subject())
cert.set_pubkey(k)
cert.sign(k, hash_alg)
try:
if request:
tmp_cert = crypto.dump_certificate_request(crypto.FILETYPE_PEM,
cert)
else:
tmp_cert = crypto.dump_certificate(crypto.FILETYPE_PEM, cert)
tmp_key = None
if cipher_passphrase is not None:
passphrase = cipher_passphrase["passphrase"]
if isinstance(cipher_passphrase["passphrase"],
six.string_types):
passphrase = passphrase.encode('utf-8')
tmp_key = crypto.dump_privatekey(crypto.FILETYPE_PEM, k,
cipher_passphrase["cipher"],
passphrase)
else:
tmp_key = crypto.dump_privatekey(crypto.FILETYPE_PEM, k)
if write_to_file:
with open(c_f, 'wt') as fc:
fc.write(tmp_cert.decode('utf-8'))
with open(k_f, 'wt') as fk:
fk.write(tmp_key.decode('utf-8'))
return c_f, k_f
return tmp_cert, tmp_key
except Exception as ex:
raise CertificateError("Certificate cannot be generated.", ex) | [
"def",
"create_certificate",
"(",
"self",
",",
"cert_info",
",",
"request",
"=",
"False",
",",
"valid_from",
"=",
"0",
",",
"valid_to",
"=",
"315360000",
",",
"sn",
"=",
"1",
",",
"key_length",
"=",
"1024",
",",
"hash_alg",
"=",
"\"sha256\"",
",",
"write... | Can create certificate requests, to be signed later by another
certificate with the method
create_cert_signed_certificate. If request is True.
Can also create self signed root certificates if request is False.
This is default behaviour.
:param cert_info: Contains information about the certificate.
Is a dictionary that must contain the keys:
cn = Common name. This part
must match the host being authenticated
country_code = Two letter description
of the country.
state = State
city = City
organization = Organization, can be a
company name.
organization_unit = A unit at the
organization, can be a department.
Example:
cert_info_ca = {
"cn": "company.com",
"country_code": "se",
"state": "AC",
"city": "Dorotea",
"organization":
"Company",
"organization_unit":
"Sales"
}
:param request: True if this is a request for certificate,
that should be signed.
False if this is a self signed certificate,
root certificate.
:param valid_from: When the certificate starts to be valid.
Amount of seconds from when the
certificate is generated.
:param valid_to: How long the certificate will be valid from
when it is generated.
The value is in seconds. Default is
315360000 seconds, a.k.a 10 years.
:param sn: Serial number for the certificate. Default
is 1.
:param key_length: Length of the key to be generated. Defaults
to 1024.
:param hash_alg: Hash algorithm to use for the key. Default
is sha256.
:param write_to_file: True if you want to write the certificate
to a file. The method will then return
a tuple with path to certificate file and
path to key file.
False if you want to get the result as
strings. The method will then return a tuple
with the certificate string and the key as
string.
WILL OVERWRITE ALL EXISTING FILES WITHOUT
ASKING!
:param cert_dir: Where to save the files if write_to_file is
true.
:param cipher_passphrase A dictionary with cipher and passphrase.
Example::
{"cipher": "blowfish", "passphrase": "qwerty"}
:return: string representation of certificate,
string representation of private key
if write_to_file parameter is False otherwise
path to certificate file, path to private
key file | [
"Can",
"create",
"certificate",
"requests",
"to",
"be",
"signed",
"later",
"by",
"another",
"certificate",
"with",
"the",
"method",
"create_cert_signed_certificate",
".",
"If",
"request",
"is",
"True",
"."
] | d3aa78eeb7d37c12688f783cb4db1c7263a14ad6 | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/cert.py#L31-L176 |
232,690 | IdentityPython/pysaml2 | src/saml2/cert.py | OpenSSLWrapper.verify | def verify(self, signing_cert_str, cert_str):
"""
Verifies if a certificate is valid and signed by a given certificate.
:param signing_cert_str: This certificate will be used to verify the
signature. Must be a string representation
of the certificate. If you only have a file
use the method read_str_from_file to
get a string representation.
:param cert_str: This certificate will be verified if it is
correct. Must be a string representation
of the certificate. If you only have a file
use the method read_str_from_file to
get a string representation.
:return: Valid, Message
Valid = True if the certificate is valid,
otherwise false.
Message = Why the validation failed.
"""
try:
ca_cert = crypto.load_certificate(crypto.FILETYPE_PEM,
signing_cert_str)
cert = crypto.load_certificate(crypto.FILETYPE_PEM, cert_str)
if self.certificate_not_valid_yet(ca_cert):
return False, "CA certificate is not valid yet."
if ca_cert.has_expired() == 1:
return False, "CA certificate is expired."
if cert.has_expired() == 1:
return False, "The signed certificate is expired."
if self.certificate_not_valid_yet(cert):
return False, "The signed certificate is not valid yet."
if ca_cert.get_subject().CN == cert.get_subject().CN:
return False, ("CN may not be equal for CA certificate and the "
"signed certificate.")
cert_algorithm = cert.get_signature_algorithm()
if six.PY3:
cert_algorithm = cert_algorithm.decode('ascii')
cert_str = cert_str.encode('ascii')
cert_crypto = saml2.cryptography.pki.load_pem_x509_certificate(
cert_str)
try:
crypto.verify(ca_cert, cert_crypto.signature,
cert_crypto.tbs_certificate_bytes,
cert_algorithm)
return True, "Signed certificate is valid and correctly signed by CA certificate."
except crypto.Error as e:
return False, "Certificate is incorrectly signed."
except Exception as e:
return False, "Certificate is not valid for an unknown reason. %s" % str(e) | python | def verify(self, signing_cert_str, cert_str):
try:
ca_cert = crypto.load_certificate(crypto.FILETYPE_PEM,
signing_cert_str)
cert = crypto.load_certificate(crypto.FILETYPE_PEM, cert_str)
if self.certificate_not_valid_yet(ca_cert):
return False, "CA certificate is not valid yet."
if ca_cert.has_expired() == 1:
return False, "CA certificate is expired."
if cert.has_expired() == 1:
return False, "The signed certificate is expired."
if self.certificate_not_valid_yet(cert):
return False, "The signed certificate is not valid yet."
if ca_cert.get_subject().CN == cert.get_subject().CN:
return False, ("CN may not be equal for CA certificate and the "
"signed certificate.")
cert_algorithm = cert.get_signature_algorithm()
if six.PY3:
cert_algorithm = cert_algorithm.decode('ascii')
cert_str = cert_str.encode('ascii')
cert_crypto = saml2.cryptography.pki.load_pem_x509_certificate(
cert_str)
try:
crypto.verify(ca_cert, cert_crypto.signature,
cert_crypto.tbs_certificate_bytes,
cert_algorithm)
return True, "Signed certificate is valid and correctly signed by CA certificate."
except crypto.Error as e:
return False, "Certificate is incorrectly signed."
except Exception as e:
return False, "Certificate is not valid for an unknown reason. %s" % str(e) | [
"def",
"verify",
"(",
"self",
",",
"signing_cert_str",
",",
"cert_str",
")",
":",
"try",
":",
"ca_cert",
"=",
"crypto",
".",
"load_certificate",
"(",
"crypto",
".",
"FILETYPE_PEM",
",",
"signing_cert_str",
")",
"cert",
"=",
"crypto",
".",
"load_certificate",
... | Verifies if a certificate is valid and signed by a given certificate.
:param signing_cert_str: This certificate will be used to verify the
signature. Must be a string representation
of the certificate. If you only have a file
use the method read_str_from_file to
get a string representation.
:param cert_str: This certificate will be verified if it is
correct. Must be a string representation
of the certificate. If you only have a file
use the method read_str_from_file to
get a string representation.
:return: Valid, Message
Valid = True if the certificate is valid,
otherwise false.
Message = Why the validation failed. | [
"Verifies",
"if",
"a",
"certificate",
"is",
"valid",
"and",
"signed",
"by",
"a",
"given",
"certificate",
"."
] | d3aa78eeb7d37c12688f783cb4db1c7263a14ad6 | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/cert.py#L281-L337 |
232,691 | IdentityPython/pysaml2 | src/saml2/httpbase.py | HTTPBase.cookies | 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 | python | def cookies(self, url):
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",
"cookies",
"(",
"self",
",",
"url",
")",
":",
"part",
"=",
"urlparse",
"(",
"url",
")",
"#if part.port:",
"# _domain = \"%s:%s\" % (part.hostname, part.port)",
"#else:",
"_domain",
"=",
"part",
".",
"hostname",
"cookie_dict",
"=",
"{",
"}",
"now",
"=",... | Return cookies that are matching the path and are still valid
:param url:
:return: | [
"Return",
"cookies",
"that",
"are",
"matching",
"the",
"path",
"and",
"are",
"still",
"valid"
] | d3aa78eeb7d37c12688f783cb4db1c7263a14ad6 | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/httpbase.py#L120-L149 |
232,692 | IdentityPython/pysaml2 | src/saml2/httpbase.py | HTTPBase.set_cookie | def set_cookie(self, kaka, request):
"""Returns a http_cookiejar.Cookie based on a set-cookie header line"""
if not kaka:
return
part = 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 std_attr["expires"] and std_attr["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 = http_cookiejar.Cookie(**std_attr)
self.cookiejar.set_cookie(new_cookie) | python | def set_cookie(self, kaka, request):
if not kaka:
return
part = 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 std_attr["expires"] and std_attr["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 = http_cookiejar.Cookie(**std_attr)
self.cookiejar.set_cookie(new_cookie) | [
"def",
"set_cookie",
"(",
"self",
",",
"kaka",
",",
"request",
")",
":",
"if",
"not",
"kaka",
":",
"return",
"part",
"=",
"urlparse",
"(",
"request",
".",
"url",
")",
"_domain",
"=",
"part",
".",
"hostname",
"logger",
".",
"debug",
"(",
"\"%s: '%s'\"",... | Returns a http_cookiejar.Cookie based on a set-cookie header line | [
"Returns",
"a",
"http_cookiejar",
".",
"Cookie",
"based",
"on",
"a",
"set",
"-",
"cookie",
"header",
"line"
] | d3aa78eeb7d37c12688f783cb4db1c7263a14ad6 | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/httpbase.py#L151-L215 |
232,693 | IdentityPython/pysaml2 | src/saml2/httpbase.py | HTTPBase.use_http_post | def use_http_post(message, destination, relay_state,
typ="SAMLRequest"):
"""
Return a urlencoded message that should be POSTed to the recipient.
:param message: The response
:param destination: Where the response should be sent
:param relay_state: The relay_state received in the request
:param typ: Whether a Request, Response or Artifact
:return: dictionary
"""
if not isinstance(message, six.string_types):
message = "%s" % (message,)
return http_post_message(message, relay_state, typ) | python | def use_http_post(message, destination, relay_state,
typ="SAMLRequest"):
if not isinstance(message, six.string_types):
message = "%s" % (message,)
return http_post_message(message, relay_state, typ) | [
"def",
"use_http_post",
"(",
"message",
",",
"destination",
",",
"relay_state",
",",
"typ",
"=",
"\"SAMLRequest\"",
")",
":",
"if",
"not",
"isinstance",
"(",
"message",
",",
"six",
".",
"string_types",
")",
":",
"message",
"=",
"\"%s\"",
"%",
"(",
"message... | Return a urlencoded message that should be POSTed to the recipient.
:param message: The response
:param destination: Where the response should be sent
:param relay_state: The relay_state received in the request
:param typ: Whether a Request, Response or Artifact
:return: dictionary | [
"Return",
"a",
"urlencoded",
"message",
"that",
"should",
"be",
"POSTed",
"to",
"the",
"recipient",
"."
] | d3aa78eeb7d37c12688f783cb4db1c7263a14ad6 | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/httpbase.py#L257-L271 |
232,694 | IdentityPython/pysaml2 | src/saml2/httpbase.py | HTTPBase.use_http_form_post | def use_http_form_post(message, destination, relay_state,
typ="SAMLRequest"):
"""
Return a form that will automagically execute and POST the message
to the recipient.
:param message:
:param destination:
:param relay_state:
:param typ: Whether a Request, Response or Artifact
:return: dictionary
"""
if not isinstance(message, six.string_types):
message = "%s" % (message,)
return http_form_post_message(message, destination, relay_state, typ) | python | def use_http_form_post(message, destination, relay_state,
typ="SAMLRequest"):
if not isinstance(message, six.string_types):
message = "%s" % (message,)
return http_form_post_message(message, destination, relay_state, typ) | [
"def",
"use_http_form_post",
"(",
"message",
",",
"destination",
",",
"relay_state",
",",
"typ",
"=",
"\"SAMLRequest\"",
")",
":",
"if",
"not",
"isinstance",
"(",
"message",
",",
"six",
".",
"string_types",
")",
":",
"message",
"=",
"\"%s\"",
"%",
"(",
"me... | Return a form that will automagically execute and POST the message
to the recipient.
:param message:
:param destination:
:param relay_state:
:param typ: Whether a Request, Response or Artifact
:return: dictionary | [
"Return",
"a",
"form",
"that",
"will",
"automagically",
"execute",
"and",
"POST",
"the",
"message",
"to",
"the",
"recipient",
"."
] | d3aa78eeb7d37c12688f783cb4db1c7263a14ad6 | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/httpbase.py#L274-L289 |
232,695 | IdentityPython/pysaml2 | src/saml2/httpbase.py | HTTPBase.use_soap | def use_soap(self, request, destination="", soap_headers=None, sign=False,
**kwargs):
"""
Construct the necessary information for using SOAP+POST
:param request:
:param destination:
:param soap_headers:
:param sign:
:return: dictionary
"""
headers = [("content-type", "application/soap+xml")]
soap_message = make_soap_enveloped_saml_thingy(request, soap_headers)
logger.debug("SOAP message: %s", soap_message)
if sign and self.sec:
_signed = self.sec.sign_statement(soap_message,
class_name=class_name(request),
node_id=request.id)
soap_message = _signed
return {"url": destination, "method": "POST",
"data": soap_message, "headers": headers} | python | def use_soap(self, request, destination="", soap_headers=None, sign=False,
**kwargs):
headers = [("content-type", "application/soap+xml")]
soap_message = make_soap_enveloped_saml_thingy(request, soap_headers)
logger.debug("SOAP message: %s", soap_message)
if sign and self.sec:
_signed = self.sec.sign_statement(soap_message,
class_name=class_name(request),
node_id=request.id)
soap_message = _signed
return {"url": destination, "method": "POST",
"data": soap_message, "headers": headers} | [
"def",
"use_soap",
"(",
"self",
",",
"request",
",",
"destination",
"=",
"\"\"",
",",
"soap_headers",
"=",
"None",
",",
"sign",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"headers",
"=",
"[",
"(",
"\"content-type\"",
",",
"\"application/soap+xml\"",
... | Construct the necessary information for using SOAP+POST
:param request:
:param destination:
:param soap_headers:
:param sign:
:return: dictionary | [
"Construct",
"the",
"necessary",
"information",
"for",
"using",
"SOAP",
"+",
"POST"
] | d3aa78eeb7d37c12688f783cb4db1c7263a14ad6 | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/httpbase.py#L335-L359 |
232,696 | IdentityPython/pysaml2 | src/saml2/httpbase.py | HTTPBase.send_using_soap | def send_using_soap(self, request, destination, headers=None, sign=False):
"""
Send a message using SOAP+POST
:param request:
:param destination:
:param headers:
:param sign:
:return:
"""
# _response = self.server.post(soap_message, headers, path=path)
try:
args = self.use_soap(request, destination, headers, sign)
args["headers"] = dict(args["headers"])
response = self.send(**args)
except Exception as exc:
logger.info("HTTPClient exception: %s", exc)
raise
if response.status_code == 200:
logger.info("SOAP response: %s", response.text)
return response
else:
raise HTTPError("%d:%s" % (response.status_code, response.content)) | python | def send_using_soap(self, request, destination, headers=None, sign=False):
# _response = self.server.post(soap_message, headers, path=path)
try:
args = self.use_soap(request, destination, headers, sign)
args["headers"] = dict(args["headers"])
response = self.send(**args)
except Exception as exc:
logger.info("HTTPClient exception: %s", exc)
raise
if response.status_code == 200:
logger.info("SOAP response: %s", response.text)
return response
else:
raise HTTPError("%d:%s" % (response.status_code, response.content)) | [
"def",
"send_using_soap",
"(",
"self",
",",
"request",
",",
"destination",
",",
"headers",
"=",
"None",
",",
"sign",
"=",
"False",
")",
":",
"# _response = self.server.post(soap_message, headers, path=path)",
"try",
":",
"args",
"=",
"self",
".",
"use_soap",
"(",
... | Send a message using SOAP+POST
:param request:
:param destination:
:param headers:
:param sign:
:return: | [
"Send",
"a",
"message",
"using",
"SOAP",
"+",
"POST"
] | d3aa78eeb7d37c12688f783cb4db1c7263a14ad6 | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/httpbase.py#L361-L385 |
232,697 | IdentityPython/pysaml2 | src/saml2/httpbase.py | HTTPBase.use_http_get | def use_http_get(message, destination, relay_state,
typ="SAMLRequest", sigalg="", signer=None, **kwargs):
"""
Send a message using GET, this is the HTTP-Redirect case so
no direct response is expected to this request.
:param message:
:param destination:
:param relay_state:
:param typ: Whether a Request, Response or Artifact
:param sigalg: Which algorithm the signature function will use to sign
the message
:param signer: A signing function that can be used to sign the message
:return: dictionary
"""
if not isinstance(message, six.string_types):
message = "%s" % (message,)
return http_redirect_message(message, destination, relay_state, typ,
sigalg, signer) | python | def use_http_get(message, destination, relay_state,
typ="SAMLRequest", sigalg="", signer=None, **kwargs):
if not isinstance(message, six.string_types):
message = "%s" % (message,)
return http_redirect_message(message, destination, relay_state, typ,
sigalg, signer) | [
"def",
"use_http_get",
"(",
"message",
",",
"destination",
",",
"relay_state",
",",
"typ",
"=",
"\"SAMLRequest\"",
",",
"sigalg",
"=",
"\"\"",
",",
"signer",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"isinstance",
"(",
"message",
",",
... | Send a message using GET, this is the HTTP-Redirect case so
no direct response is expected to this request.
:param message:
:param destination:
:param relay_state:
:param typ: Whether a Request, Response or Artifact
:param sigalg: Which algorithm the signature function will use to sign
the message
:param signer: A signing function that can be used to sign the message
:return: dictionary | [
"Send",
"a",
"message",
"using",
"GET",
"this",
"is",
"the",
"HTTP",
"-",
"Redirect",
"case",
"so",
"no",
"direct",
"response",
"is",
"expected",
"to",
"this",
"request",
"."
] | d3aa78eeb7d37c12688f783cb4db1c7263a14ad6 | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/httpbase.py#L392-L411 |
232,698 | IdentityPython/pysaml2 | src/saml2/httputil.py | extract | def extract(environ, empty=False, err=False):
"""Extracts strings in form data and returns a dict.
:param environ: WSGI environ
:param empty: Stops on empty fields (default: Fault)
:param err: Stops on errors in fields (default: Fault)
"""
formdata = cgi.parse(environ['wsgi.input'], environ, empty, err)
# Remove single entries from lists
for key, value in iter(formdata.items()):
if len(value) == 1:
formdata[key] = value[0]
return formdata | python | def extract(environ, empty=False, err=False):
formdata = cgi.parse(environ['wsgi.input'], environ, empty, err)
# Remove single entries from lists
for key, value in iter(formdata.items()):
if len(value) == 1:
formdata[key] = value[0]
return formdata | [
"def",
"extract",
"(",
"environ",
",",
"empty",
"=",
"False",
",",
"err",
"=",
"False",
")",
":",
"formdata",
"=",
"cgi",
".",
"parse",
"(",
"environ",
"[",
"'wsgi.input'",
"]",
",",
"environ",
",",
"empty",
",",
"err",
")",
"# Remove single entries from... | Extracts strings in form data and returns a dict.
:param environ: WSGI environ
:param empty: Stops on empty fields (default: Fault)
:param err: Stops on errors in fields (default: Fault) | [
"Extracts",
"strings",
"in",
"form",
"data",
"and",
"returns",
"a",
"dict",
"."
] | d3aa78eeb7d37c12688f783cb4db1c7263a14ad6 | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/httputil.py#L172-L184 |
232,699 | IdentityPython/pysaml2 | src/saml2/httputil.py | cookie_signature | def cookie_signature(seed, *parts):
"""Generates a cookie signature."""
sha1 = hmac.new(seed, digestmod=hashlib.sha1)
for part in parts:
if part:
sha1.update(part)
return sha1.hexdigest() | python | def cookie_signature(seed, *parts):
sha1 = hmac.new(seed, digestmod=hashlib.sha1)
for part in parts:
if part:
sha1.update(part)
return sha1.hexdigest() | [
"def",
"cookie_signature",
"(",
"seed",
",",
"*",
"parts",
")",
":",
"sha1",
"=",
"hmac",
".",
"new",
"(",
"seed",
",",
"digestmod",
"=",
"hashlib",
".",
"sha1",
")",
"for",
"part",
"in",
"parts",
":",
"if",
"part",
":",
"sha1",
".",
"update",
"(",... | Generates a cookie signature. | [
"Generates",
"a",
"cookie",
"signature",
"."
] | d3aa78eeb7d37c12688f783cb4db1c7263a14ad6 | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/httputil.py#L311-L317 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.