<s> import logging <EOL> import random <EOL> import string <EOL> import time <EOL> import base64 <EOL> import sys <EOL> import hmac <EOL> import string <EOL> import imp <EOL> import traceback <EOL> if sys . version_info >= ( <NUM_LIT:2> , <NUM_LIT:5> ) : <EOL> import hashlib <EOL> else : <EOL> import sha <EOL> from saml2 import saml <EOL> from saml2 import samlp <EOL> from saml2 import VERSION <EOL> from saml2 . time_util import instant <EOL> try : <EOL> from hashlib import md5 <EOL> except ImportError : <EOL> from md5 import md5 <EOL> import zlib <EOL> logger = logging . getLogger ( __name__ ) <EOL> class SamlException ( Exception ) : <EOL> pass <EOL> class RequestVersionTooLow ( SamlException ) : <EOL> pass <EOL> class RequestVersionTooHigh ( SamlException ) : <EOL> pass <EOL> class UnknownPrincipal ( SamlException ) : <EOL> pass <EOL> class UnknownSystemEntity ( SamlException ) : <EOL> pass <EOL> class Unsupported ( SamlException ) : <EOL> pass <EOL> class UnsupportedBinding ( Unsupported ) : <EOL> pass <EOL> class VersionMismatch ( Exception ) : <EOL> pass <EOL> class Unknown ( Exception ) : <EOL> pass <EOL> class OtherError ( Exception ) : <EOL> pass <EOL> class MissingValue ( Exception ) : <EOL> pass <EOL> class PolicyError ( Exception ) : <EOL> pass <EOL> class BadRequest ( Exception ) : <EOL> pass <EOL> class UnravelError ( Exception ) : <EOL> pass <EOL> EXCEPTION2STATUS = { <EOL> VersionMismatch : samlp . STATUS_VERSION_MISMATCH , <EOL> UnknownPrincipal : samlp . STATUS_UNKNOWN_PRINCIPAL , <EOL> UnsupportedBinding : samlp . STATUS_UNSUPPORTED_BINDING , <EOL> RequestVersionTooLow : samlp . STATUS_REQUEST_VERSION_TOO_LOW , <EOL> RequestVersionTooHigh : samlp . STATUS_REQUEST_VERSION_TOO_HIGH , <EOL> OtherError : samlp . STATUS_UNKNOWN_PRINCIPAL , <EOL> MissingValue : samlp . STATUS_REQUEST_UNSUPPORTED , <EOL> Exception : samlp . STATUS_AUTHN_FAILED , <EOL> } <EOL> GENERIC_DOMAINS = [ "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , <EOL> "<STR_LIT>" , "<STR_LIT:info>" , "<STR_LIT:int>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , <EOL> "<STR_LIT:name>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" ] <EOL> def valid_email ( emailaddress , domains = GENERIC_DOMAINS ) : <EOL> """<STR_LIT>""" <EOL> if len ( emailaddress ) < <NUM_LIT:6> : <EOL> return False <EOL> try : <EOL> localpart , domainname = emailaddress . rsplit ( '<STR_LIT:@>' , <NUM_LIT:1> ) <EOL> host , toplevel = domainname . rsplit ( '<STR_LIT:.>' , <NUM_LIT:1> ) <EOL> except ValueError : <EOL> return False <EOL> if len ( toplevel ) != <NUM_LIT:2> and toplevel not in domains : <EOL> return False <EOL> for i in '<STR_LIT>' : <EOL> localpart = localpart . replace ( i , "<STR_LIT>" ) <EOL> for i in '<STR_LIT>' : <EOL> host = host . replace ( i , "<STR_LIT>" ) <EOL> if localpart . isalnum ( ) and host . isalnum ( ) : <EOL> return True <EOL> else : <EOL> return False <EOL> def decode_base64_and_inflate ( string ) : <EOL> """<STR_LIT>""" <EOL> return zlib . decompress ( base64 . b64decode ( string ) , - <NUM_LIT:15> ) <EOL> def deflate_and_base64_encode ( string_val ) : <EOL> """<STR_LIT>""" <EOL> return base64 . b64encode ( zlib . compress ( string_val ) [ <NUM_LIT:2> : - <NUM_LIT:4> ] ) <EOL> def rndstr ( size = <NUM_LIT:16> , alphabet = "<STR_LIT>" ) : <EOL> """<STR_LIT>""" <EOL> rng = random . SystemRandom ( ) <EOL> if not alphabet : <EOL> alphabet = string . letters [ <NUM_LIT:0> : <NUM_LIT> ] + string . digits <EOL> return str ( ) . join ( rng . choice ( alphabet ) for _ in range ( size ) ) <EOL> def sid ( ) : <EOL> """<STR_LIT>""" <EOL> return "<STR_LIT>" + rndstr ( <NUM_LIT> ) <EOL> def parse_attribute_map ( filenames ) : <EOL> """<STR_LIT>""" <EOL> forward = { } <EOL> backward = { } <EOL> for filename in filenames : <EOL> for line in open ( filename ) . readlines ( ) : <EOL> ( name , friendly_name , name_format ) = line . strip ( ) . split ( ) <EOL> forward [ ( name , name_format ) ] = friendly_name <EOL> backward [ friendly_name ] = ( name , name_format ) <EOL> return forward , backward <EOL> def identity_attribute ( form , attribute , forward_map = None ) : <EOL> if form == "<STR_LIT>" : <EOL> if attribute . friendly_name : <EOL> return attribute . friendly_name <EOL> elif forward_map : <EOL> try : <EOL> return forward_map [ ( attribute . name , attribute . name_format ) ] <EOL> except KeyError : <EOL> return attribute . name <EOL> return attribute . name <EOL> def error_status_factory ( info ) : <EOL> if isinstance ( info , Exception ) : <EOL> try : <EOL> exc_val = EXCEPTION2STATUS [ info . __class__ ] <EOL> except KeyError : <EOL> exc_val = samlp . STATUS_AUTHN_FAILED <EOL> try : <EOL> msg = info . args [ <NUM_LIT:0> ] <EOL> except IndexError : <EOL> msg = "<STR_LIT:%s>" % info <EOL> status = samlp . Status ( <EOL> status_message = samlp . StatusMessage ( text = msg ) , <EOL> status_code = samlp . StatusCode ( <EOL> value = samlp . STATUS_RESPONDER , <EOL> status_code = samlp . StatusCode ( <EOL> value = exc_val ) ) ) <EOL> else : <EOL> ( errcode , text ) = info <EOL> status = samlp . Status ( <EOL> status_message = samlp . StatusMessage ( text = text ) , <EOL> status_code = samlp . StatusCode ( <EOL> value = samlp . STATUS_RESPONDER , <EOL> status_code = samlp . StatusCode ( value = errcode ) ) ) <EOL> return status <EOL> def success_status_factory ( ) : <EOL> return samlp . Status ( status_code = samlp . StatusCode ( <EOL> value = samlp . STATUS_SUCCESS ) ) <EOL> def status_message_factory ( message , code , fro = samlp . STATUS_RESPONDER ) : <EOL> return samlp . Status ( <EOL> status_message = samlp . StatusMessage ( text = message ) , <EOL> status_code = samlp . StatusCode ( value = fro , <EOL> status_code = samlp . StatusCode ( value = code ) ) ) <EOL> def assertion_factory ( ** kwargs ) : <EOL> assertion = saml . Assertion ( version = VERSION , id = sid ( ) , <EOL> issue_instant = instant ( ) ) <EOL> for key , val in kwargs . items ( ) : <EOL> setattr ( assertion , key , val ) <EOL> return assertion <EOL> def _attrval ( val , typ = "<STR_LIT>" ) : <EOL> if isinstance ( val , list ) or isinstance ( val , set ) : <EOL> attrval = [ saml . AttributeValue ( text = v ) for v in val ] <EOL> elif val is None : <EOL> attrval = None <EOL> else : <EOL> attrval = [ saml . AttributeValue ( text = val ) ] <EOL> if typ : <EOL> for ava in attrval : <EOL> ava . set_type ( typ ) <EOL> return attrval <EOL> def do_ava ( val , typ = "<STR_LIT>" ) : <EOL> if isinstance ( val , basestring ) : <EOL> ava = saml . AttributeValue ( ) <EOL> ava . set_text ( val ) <EOL> attrval = [ ava ] <EOL> elif isinstance ( val , list ) : <EOL> attrval = [ do_ava ( v ) [ <NUM_LIT:0> ] for v in val ] <EOL> elif val or val is False : <EOL> ava = saml . AttributeValue ( ) <EOL> ava . set_text ( val ) <EOL> attrval = [ ava ] <EOL> elif val is None : <EOL> attrval = None <EOL> else : <EOL> raise OtherError ( "<STR_LIT>" % val ) <EOL> if typ : <EOL> for ava in attrval : <EOL> ava . set_type ( typ ) <EOL> return attrval <EOL> def do_attribute ( val , typ , key ) : <EOL> attr = saml . Attribute ( ) <EOL> attrval = do_ava ( val , typ ) <EOL> if attrval : <EOL> attr . attribute_value = attrval <EOL> if isinstance ( key , basestring ) : <EOL> attr . name = key <EOL> elif isinstance ( key , tuple ) : <EOL> try : <EOL> ( name , nformat , friendly ) = key <EOL> except ValueError : <EOL> ( name , nformat ) = key <EOL> friendly = "<STR_LIT>" <EOL> if name : <EOL> attr . name = name <EOL> if format : <EOL> attr . name_format = nformat <EOL> if friendly : <EOL> attr . friendly_name = friendly <EOL> return attr <EOL> def do_attributes ( identity ) : <EOL> attrs = [ ] <EOL> if not identity : <EOL> return attrs <EOL> for key , spec in identity . items ( ) : <EOL> try : <EOL> val , typ = spec <EOL> except ValueError : <EOL> val = spec <EOL> typ = "<STR_LIT>" <EOL> except TypeError : <EOL> val = "<STR_LIT>" <EOL> typ = "<STR_LIT>" <EOL> attr = do_attribute ( val , typ , key ) <EOL> attrs . append ( attr ) <EOL> return attrs <EOL> def do_attribute_statement ( identity ) : <EOL> """<STR_LIT>""" <EOL> return saml . AttributeStatement ( attribute = do_attributes ( identity ) ) <EOL> def factory ( klass , ** kwargs ) : <EOL> instance = klass ( ) <EOL> for key , val in kwargs . items ( ) : <EOL> setattr ( instance , key , val ) <EOL> return instance <EOL> def signature ( secret , parts ) : <EOL> """<STR_LIT>""" <EOL> if sys . version_info >= ( <NUM_LIT:2> , <NUM_LIT:5> ) : <EOL> csum = hmac . new ( secret , digestmod = hashlib . sha1 ) <EOL> else : <EOL> csum = hmac . new ( secret , digestmod = sha ) <EOL> for part in parts : <EOL> csum . update ( part ) <EOL> return csum . hexdigest ( ) <EOL> def verify_signature ( secret , parts ) : <EOL> """<STR_LIT>""" <EOL> if signature ( secret , parts [ : - <NUM_LIT:1> ] ) == parts [ - <NUM_LIT:1> ] : <EOL> return True <EOL> else : <EOL> return False <EOL> FTICKS_FORMAT = "<STR_LIT>" <EOL> def fticks_log ( sp , logf , idp_entity_id , user_id , secret , assertion ) : <EOL> """<STR_LIT>""" <EOL> csum = hmac . new ( secret , digestmod = hashlib . sha1 ) <EOL> csum . update ( user_id ) <EOL> ac = assertion . AuthnStatement [ <NUM_LIT:0> ] . AuthnContext [ <NUM_LIT:0> ] <EOL> info = { <EOL> "<STR_LIT>" : time . time ( ) , <EOL> "<STR_LIT>" : sp . entity_id , <EOL> "<STR_LIT>" : idp_entity_id , <EOL> "<STR_LIT>" : csum . hexdigest ( ) , <EOL> "<STR_LIT>" : ac . AuthnContextClassRef . text <EOL> } <EOL> logf . info ( FTICKS_FORMAT % "<STR_LIT:#>" . join ( [ "<STR_LIT>" % ( a , v ) for a , v in info ] ) ) <EOL> def dynamic_importer ( name , class_name = None ) : <EOL> """<STR_LIT>""" <EOL> try : <EOL> fp , pathname , description = imp . find_module ( name ) <EOL> except ImportError : <EOL> print "<STR_LIT>" + name <EOL> return None , None <EOL> try : <EOL> package = imp . load_module ( name , fp , pathname , description ) <EOL> except Exception : <EOL> raise <EOL> if class_name : <EOL> try : <EOL> _class = imp . load_module ( "<STR_LIT>" % ( name , class_name ) , fp , <EOL> pathname , description ) <EOL> except Exception : <EOL> raise <EOL> return package , _class <EOL> else : <EOL> return package , None <EOL> def exception_trace ( exc ) : <EOL> message = traceback . format_exception ( * sys . exc_info ( ) ) <EOL> try : <EOL> _exc = "<STR_LIT>" % exc <EOL> except UnicodeEncodeError : <EOL> _exc = "<STR_LIT>" % exc . message . encode ( "<STR_LIT:utf-8>" , "<STR_LIT:replace>" ) <EOL> return { "<STR_LIT:message>" : _exc , "<STR_LIT:content>" : "<STR_LIT>" . join ( message ) } <EOL> def rec_factory ( cls , ** kwargs ) : <EOL> _inst = cls ( ) <EOL> for key , val in kwargs . items ( ) : <EOL> if key in [ "<STR_LIT:text>" , "<STR_LIT>" ] : <EOL> setattr ( _inst , key , val ) <EOL> elif key in _inst . c_attributes : <EOL> try : <EOL> val = str ( val ) <EOL> except Exception : <EOL> continue <EOL> else : <EOL> setattr ( _inst , _inst . c_attributes [ key ] [ <NUM_LIT:0> ] , val ) <EOL> elif key in _inst . c_child_order : <EOL> for tag , _cls in _inst . c_children . values ( ) : <EOL> if tag == key : <EOL> if isinstance ( _cls , list ) : <EOL> _cls = _cls [ <NUM_LIT:0> ] <EOL> claim = [ ] <EOL> if isinstance ( val , list ) : <EOL> for v in val : <EOL> claim . append ( rec_factory ( _cls , ** v ) ) <EOL> else : <EOL> claim . append ( rec_factory ( _cls , ** val ) ) <EOL> else : <EOL> claim = rec_factory ( _cls , ** val ) <EOL> setattr ( _inst , key , claim ) <EOL> break <EOL> return _inst </s>
