コード例 #1
0
ファイル: response.py プロジェクト: francoricci/sapspid
    def passthrough(self):
        try:
            try:
                with open(
                        os.path.join(globalsObj.modules_basedir,
                                     globalsObj.easyspid_SAMLresponseFormPath),
                        'rb') as myfile:
                    response_form = myfile.read().decode("utf-8")
            except:
                with open(globalsObj.easyspid_SAMLresponseFormPath,
                          'rb') as myfile:
                    response_form = myfile.read().decode("utf-8")

            response_obj = ResponseObj(httpcode=200)
            response_obj.setError('200')
            response_obj.setResult(format='saml')

            response_form = response_form.replace("%URLTARGET%",
                                                  self.routing['url'])
            response_form = response_form.replace("%RELAYSTATE%",
                                                  self.routing['relaystate'])
            response_form = response_form.replace(
                "%RESPONSE%", self.get_argument('SAMLResponse'))
            self.postTo = response_form

            return response_obj

        except Exception as inst:
            response_obj = ResponseObj(httpcode=500)
            response_obj.setError('500')
            logging.getLogger(
                type(self).__module__ + "." + type(self).__qualname__).error(
                    'Exception', exc_info=True)

            return response_obj
コード例 #2
0
ファイル: getMetadata.py プロジェクト: francoricci/sapspid
    async def get(self, sp):
        x_real_ip = self.request.headers.get(
            globalsObj.easyspid_originIP_header)
        self.remote_ip = x_real_ip or self.request.remote_ip
        self.set_header('Content-Type', 'application/json; charset=UTF-8')
        self.set_default_headers()

        try:
            ##ceck provider type
            provider_type = await self.dbobjSaml.execute_query(
                self.dbobjSaml.query['get_provider']['sql'], sp)

            if provider_type['error'] == 0 and provider_type['result'][0][
                    'type'] == 'sp':
                chk_metadata = await self.dbobjSaml.execute_query(
                    self.dbobjSaml.query['chk_metadata_validity']['sql'], sp)

                if chk_metadata['error'] == 0 and chk_metadata['result'][0][
                        'chk'] == 0:
                    sp_settings = await easyspid.lib.easyspid.spSettings(
                        sp, close=True)
                    await asyncio.get_event_loop().run_in_executor(
                        self.executor, self.buildMetadata, sp_settings)
                    #self.buildMetadata(sp_settings, dbSave = True)

            sp_metadata = await self.dbobjSaml.execute_statment(
                "get_prvd_metadta('%s')" % sp)

        except tornado.web.MissingArgumentError as error:
            response_obj = ResponseObj(debugMessage=error.log_message,
                                       httpcode=error.status_code,
                                       devMessage=error.log_message)
            response_obj.setError(str(error.status_code))
            logging.getLogger(
                type(self).__module__ + "." + type(self).__qualname__).error(
                    '%s' % error, exc_info=True)
            return response_obj

        except Exception as inst:
            response_obj = ResponseObj(httpcode=500)
            response_obj.setError('500')
            logging.getLogger(
                type(self).__module__ + "." + type(self).__qualname__).error(
                    'Exception', exc_info=True)
            return response_obj

        response_obj = self.getMetadata(sp_metadata)
        asyncio.ensure_future(self.writeLog(response_obj),
                              loop=globalsObj.ioloop)
        super().writeResponse(response_obj)
コード例 #3
0
ファイル: response.py プロジェクト: francoricci/sapspid
    def getSpByAudience(self):

        task3 = asyncio.run_coroutine_threadsafe(
            self.dbobjSaml.execute_statment(
                "get_provider_byentityid(%s, '%s')" %
                ('True', '{' + (self.audience.text.strip()) + '}')),
            globalsObj.ioloop)
        audienceChk = waitFuture(task3)

        if audienceChk['error'] == 0 and audienceChk['result'] is not None:
            return audienceChk['result'][0]['cod_provider']

        elif audienceChk['error'] == 0 and audienceChk['result'] is None:
            response_obj = ResponseObj(httpcode=404)
            response_obj.setError('easyspid115')
            raise goExit(response_obj, 'exit by getSpByAudience')

        elif audienceChk['error'] > 0:
            response_obj = ResponseObj(httpcode=500)
            response_obj.setError('easyspid105')
            response_obj.setResult(audienceChk['result'])
            raise goExit(response_obj, 'exit by getSpByAudience')
コード例 #4
0
    def write_error(self, status_code, **kwargs):

        # debug info
        if self.settings.get("serve_traceback") and "exc_info" in kwargs:
            debugTmp = ""
            for line in traceback.format_exception(*kwargs["exc_info"]):
                debugTmp += line
            getResponse = ResponseObj(debugMessage=debugTmp,httpcode=status_code,devMessage=self._reason)
        else:
            getResponse = ResponseObj(httpcode=status_code,devMessage=self._reason)

        self.set_header('Content-Type', 'application/json; charset=UTF-8')
        self.set_status(status_code)

        # inserisci codice errore personalizzato
        getResponse.setError('3')
        getResponse.setResult()
        self.write(getResponse.jsonWrite())
        self.finish()
コード例 #5
0
ファイル: response.py プロジェクト: francoricci/sapspid
    def formatError(self, response_obj, srelay, url):
        try:

            # build response fprm
            try:
                with open(
                        os.path.join(globalsObj.modules_basedir,
                                     globalsObj.easyspid_responseFormPath),
                        'rb') as myfile:
                    response_form = myfile.read().decode("utf-8")
            except:
                with open(globalsObj.easyspid_responseFormPath,
                          'rb') as myfile:
                    response_form = myfile.read().decode("utf-8")

            new_response_obj = ResponseObj(httpcode=200, ID=response_obj.id)
            new_response_obj.setError('200')
            new_response_obj.result = response_obj.result

            response_form = response_form.replace("%URLTARGET%", url)
            response_form = response_form.replace("%RELAYSTATE%", srelay)
            response_form = response_form.replace(
                "%RESPONSE%",
                OneLogin_Saml2_Utils.b64encode(response_obj.jsonWrite()))
            self.postTo = response_form

            return new_response_obj

        except Exception as inst:
            response_obj = ResponseObj(httpcode=500)
            response_obj.setError('500')
            logging.getLogger(
                type(self).__module__ + "." + type(self).__qualname__).error(
                    'Exception', exc_info=True)

            return new_response_obj
コード例 #6
0
ファイル: response.py プロジェクト: francoricci/sapspid
    def getIdentyIdp(self):
        # get IdP
        task2 = asyncio.run_coroutine_threadsafe(
            self.dbobjSaml.execute_statment(
                "get_provider_byentityid(%s, '%s')" %
                ('True', '{' + (self.issuer.text.strip()) + '}')),
            globalsObj.ioloop)
        idpEntityId = waitFuture(task2)

        if idpEntityId['error'] == 0 and idpEntityId['result'] is not None:
            idp_metadata = idpEntityId['result'][0]['xml']
            idp = idpEntityId['result'][0]['cod_provider']
            return (idp_metadata, idp)

        elif idpEntityId['error'] == 0 and idpEntityId['result'] is None:
            response_obj = ResponseObj(httpcode=404)
            response_obj.setError('easyspid103')
            raise goExit(response_obj, 'exit by getIdentyIdp')

        elif idpEntityId['error'] > 0:
            response_obj = ResponseObj(httpcode=500,
                                       debugMessage=idpEntityId['result'])
            response_obj.setError("easyspid105")
            raise goExit(response_obj, 'exit by getIdentyIdp')
コード例 #7
0
def spSettings(cod_sp,
               cod_idp=None,
               binding=OneLogin_Saml2_Constants.BINDING_HTTP_REDIRECT,
               close=True):
    result = {'error': 0, 'result': None}

    # acquisisci una connessione dal pool
    #if conn is None:
    #    conn = easyspid.lib.database.Database(globalsObj.DbConnections['samlDbPollSlave']['pool'])
    #sp_settings = conn.get_sp_settings(cod_sp, close)

    dbobj = globalsObj.DbConnections['samlDb']
    sp_settings = dbobj.makeQuery("EXECUTE get_sp_settings(%s)", [cod_sp],
                                  type=dbobj.stmts['get_providers']['pool'],
                                  close=close)

    if sp_settings['error'] == 0 and sp_settings['result'] != None:
        # genera risposta tutto ok
        sp_settings['result']['settings']['idp'] = globalsObj.easyspidSettings[
            'idp']
        sp_settings['result']['settings']['sp']['x509cert'] = sp_settings[
            'result']['public_key']
        sp_settings['result']['settings']['sp']['privateKey'] = sp_settings[
            'result']['private_key']
        sp_settings['result']['settings']['sp'][
            'x509cert_fingerprint'] = sp_settings['result']['fingerprint']
        sp_settings['result']['settings']['sp'][
            'x509cert_fingerprintalg'] = sp_settings['result'][
                'fingerprintalg']
        sp_settings['result']['settings']['security'] = sp_settings['result'][
            'advanced_settings']['security']
        sp_settings['result']['settings']['contactPerson'] = sp_settings[
            'result']['advanced_settings']['contactPerson']
        sp_settings['result']['settings']['organization'] = sp_settings[
            'result']['advanced_settings']['organization']

        if cod_idp != None:
            #idp_metadata = globalsObj.DbConnections['samlSlave'].get_prvd_metadta(cod_idp)
            #idp_metadata = conn.get_prvd_metadta(cod_idp, close)

            idp_metadata = dbobj.makeQuery(
                "EXECUTE get_prvd_metadta(%s)", [cod_idp],
                type=dbobj.stmts['get_providers']['pool'],
                close=close)

            if idp_metadata['error'] == 0 and idp_metadata['result'] != None:

                metadata = idp_metadata['result']['xml']
                idp_data = OneLogin_Saml2_IdPMetadataParser.parse(
                    metadata,
                    required_sso_binding=binding,
                    required_slo_binding=binding)
                idp_settings = idp_data['idp']

                if 'entityId' in idp_settings:
                    sp_settings['result']['settings']['idp'][
                        'entityId'] = idp_settings['entityId']
                if 'singleLogoutService' in idp_settings:
                    sp_settings['result']['settings']['idp'][
                        'singleLogoutService'] = idp_settings[
                            'singleLogoutService']
                if 'singleSignOnService' in idp_settings:
                    sp_settings['result']['settings']['idp'][
                        'singleSignOnService'] = idp_settings[
                            'singleSignOnService']
                if 'x509cert' in idp_settings:
                    sp_settings['result']['settings']['idp'][
                        'x509cert'] = idp_settings['x509cert']

                sp_settings['result']['settings']['idp'][
                    'x509cert_fingerprint'] = idp_metadata['result'][
                        'fingerprint']
                sp_settings['result']['settings']['idp'][
                    'x509cert_fingerprintalg'] = idp_metadata['result'][
                        'fingerprintalg']
                sp_settings['result']['settings']['idp']['metadata'] = metadata

                result['result'] = sp_settings['result']['settings']
                return result

            elif idp_metadata['error'] > 0:
                result['error'] = 1
                response_obj = ResponseObj(
                    debugMessage=idp_metadata['result'].pgerror,
                    httpcode=500,
                    devMessage=("PostgreSQL error code: %s" %
                                idp_metadata['result'].pgcode))
                response_obj.setError('easyspid105')
                result['result'] = response_obj

            else:
                result['error'] = idp_metadata['error']
                result['result'] = idp_metadata['result']
        else:
            result['result'] = sp_settings['result']['settings']
            return result

    elif sp_settings['error'] > 0:
        result['error'] = 1
        response_obj = ResponseObj(debugMessage=sp_settings['result'].pgerror,
                                   httpcode=500,
                                   devMessage=("PostgreSQL error code: %s" %
                                               sp_settings['result'].pgcode))
        response_obj.setError('easyspid105')
        result['result'] = response_obj

    else:
        result['error'] = sp_settings['error']
        result['result'] = sp_settings['result']

    return result
コード例 #8
0
ファイル: response.py プロジェクト: francoricci/sapspid
    def chkExistsReq(self, checkInResponseTo):
        # try to get sp searching a corresponding request and raise error if checkInResponseTo is True
        inResponseChk = waitFuture(
            asyncio.run_coroutine_threadsafe(
                self.dbobjSaml.execute_statment("chk_idAssertion('%s')" %
                                                self.inResponseTo),
                globalsObj.ioloop))

        if inResponseChk['error'] == 0 and inResponseChk['result'] is not None:
            return inResponseChk['result'][0]['cod_sp']

        elif checkInResponseTo and inResponseChk[
                'error'] == 0 and inResponseChk['result'] == None:
            response_obj = ResponseObj(httpcode=404, ID=self.ResponseID)
            response_obj.setError('easyspid120')
            response_obj.setResult(response=str(self.response, 'utf-8'))
            raise goExit(response_obj, 'exit by chkExistsReq')

        elif not checkInResponseTo and inResponseChk[
                'error'] == 0 and inResponseChk['result'] == None:
            response_obj = ResponseObj(httpcode=404, ID=self.ResponseID)
            response_obj.setError('easyspid120')
            response_obj.setResult(response=str(self.response, 'utf-8'))
            return None

        elif inResponseChk['error'] > 0:
            response_obj = ResponseObj(httpcode=500)
            response_obj.setError('easyspid105')
            response_obj.setResult(inResponseChk['result'])
            raise goExit(response_obj, 'exit by chkExistsReq')
コード例 #9
0
ファイル: response.py プロジェクト: francoricci/sapspid
    def processResponse(self, chkTime=True, checkInResponseTo=True):

        try:
            # get response and Relay state
            responsePost = self.get_argument('SAMLResponse')
            srelayPost = self.get_argument('RelayState')

            # decode saml response
            #response = responsePost
            self.response = responsePost
            try:
                self.response = OneLogin_Saml2_Utils.decode_base64_and_inflate(
                    responsePost)
            except Exception:
                try:
                    self.response = OneLogin_Saml2_Utils.b64decode(
                        responsePost)
                except Exception:
                    pass

            # try:
            #     #response = OneLogin_Saml2_Utils.b64decode(responsePost)
            #     self.response = OneLogin_Saml2_Utils.b64decode(responsePost)
            # except Exception:
            #     pass

            ## parse XML and make some check
            ns = {
                'md0': OneLogin_Saml2_Constants.NS_SAMLP,
                'md1': OneLogin_Saml2_Constants.NS_SAML
            }
            parsedResponse = xml.etree.ElementTree.fromstring(self.response)

            self.inResponseTo = parsedResponse.get('InResponseTo')
            self.ResponseID = parsedResponse.get('ID')
            issuer = self.issuer = parsedResponse.find("md1:Issuer", ns)
            if issuer is None:
                response_obj = ResponseObj(httpcode=401)
                response_obj.setError('easyspid118')
                return response_obj

            #spByInResponseTo = None
            # try to get sp searching a corresponding request and raise error if checkInResponseTo is True
            # inResponseChk = waitFuture(asyncio.run_coroutine_threadsafe(self.dbobjSaml.execute_statment("chk_idAssertion('%s')" %
            #             inResponseTo), globalsObj.ioloop))
            # if inResponseChk['error'] == 0 and inResponseChk['result'] is not None:
            #         spByInResponseTo = inResponseChk['result'][0]['cod_sp']
            #
            # elif checkInResponseTo and inResponseChk['error'] == 0 and inResponseChk['result'] == None:
            #     response_obj = ResponseObj(httpcode=404, ID = ResponseID)
            #     response_obj.setError('easyspid120')
            #     response_obj.setResult(response = str(response, 'utf-8'))
            #     return response_obj
            #
            # elif inResponseChk['error'] > 0:
            #     response_obj = ResponseObj(httpcode=500)
            #     response_obj.setError('easyspid105')
            #     response_obj.setResult(inResponseChk['result'])
            #     return response_obj

            # try to get sp searching a corresponding request and raise error if checkInResponseTo is True
            spByInResponseTo = self.chkExistsReq(checkInResponseTo)

            ### check StatusCode to find errors
            firstChk = easyspid.lib.utils.validateAssertion(
                str(self.response, 'utf-8'), None, None)
            if not firstChk['chkStatus']:
                #get errors codes
                samlErrors = waitFuture(
                    asyncio.run_coroutine_threadsafe(
                        getResponseError(parsedResponse,
                                         sp=spByInResponseTo,
                                         namespace=ns), globalsObj.ioloop))

                if samlErrors['error'] == '0':
                    response_obj = ResponseObj(httpcode=400,
                                               ID=self.ResponseID)
                    response_obj.setError('easyspid121')
                    response_obj.setResult(response=str(
                        self.response, 'utf-8'),
                                           format='json',
                                           samlErrors=samlErrors['status'])

                    return self.formatError(response_obj, srelayPost,
                                            samlErrors['service'])

                elif samlErrors['error'] == 'easyspid114':
                    response_obj = ResponseObj(httpcode=404)
                    response_obj.setError('easyspid114')
                    return response_obj

                else:
                    response_obj = ResponseObj(httpcode=500)
                    response_obj.setError('500')
                    response_obj.setResult(samlErrors['error'])
                    return response_obj

            #decode Relay state
            #srelay = srelayPost
            self.srelay = srelayPost
            try:
                self.srelay = OneLogin_Saml2_Utils.decode_base64_and_inflate(
                    srelayPost)
            except Exception:
                try:
                    self.srelay = OneLogin_Saml2_Utils.b64decode(srelayPost)

                except Exception:
                    pass

                #self.srelay = OneLogin_Saml2_Utils.b64decode(srelayPost)
                #pass
            # try:
            #      #srelay = OneLogin_Saml2_Utils.b64decode(srelayPost)
            #      self.srelay = OneLogin_Saml2_Utils.b64decode(srelayPost)
            # except Exception:
            #      pass

            ## get sp by ID
            #ns = {'md0': OneLogin_Saml2_Constants.NS_SAMLP, 'md1': OneLogin_Saml2_Constants.NS_SAML}
            #parsedResponse = xml.etree.ElementTree.fromstring(response)
            #issuer = self.issuer = parsedResponse.find("md1:Issuer", ns)
            #inResponseTo = parsedResponse.get('InResponseTo')

            #get audience
            audience = self.audience = parsedResponse.find(
                'md1:Assertion/md1:Conditions/md1:AudienceRestriction/md1:Audience',
                ns)
            if audience is None:
                response_obj = ResponseObj(httpcode=401)
                response_obj.setError('easyspid118')
                return response_obj

            # if issuer is None or audience is None:
            #     response_obj = ResponseObj(httpcode=401)
            #     response_obj.setError('easyspid118')
            #     return response_obj

            #task1 = asyncio.run_coroutine_threadsafe(self.dbobjSaml.execute_statment("chk_idAssertion('%s')" %
            #        inResponseTo), globalsObj.ioloop)
            # task2 = asyncio.run_coroutine_threadsafe(self.dbobjSaml.execute_statment("get_provider_byentityid(%s, '%s')" %
            #         ('True', '{'+(self.issuer.text.strip())+'}')),  globalsObj.ioloop)
            #task3 = asyncio.run_coroutine_threadsafe(self.dbobjSaml.execute_statment("get_provider_byentityid(%s, '%s')" %
            #       ('True', '{'+(audience.text.strip())+'}')),  globalsObj.ioloop)

            #assert not task1.done()
            #inResponseChk = task1.result()
            #inResponseChk = waitFuture(task1)
            #audienceChk = waitFuture(task3)
            #spByAudience = None
            #spByInResponseTo = None

            #if inResponseChk['error'] == 0 and inResponseChk['result'] is not None:
            #    spByInResponseTo = inResponseChk['result'][0]['cod_sp']

            # if audienceChk['error'] == 0 and audienceChk['result'] is not None:
            #     spByAudience = audienceChk['result'][0]['cod_provider']

            #check audinece
            # if spByAudience is None:
            #     response_obj = ResponseObj(httpcode=404)
            #     response_obj.setError('easyspid115')
            #     return response_obj

            # get sp by audience
            spByAudience = self.getSpByAudience()

            #check inresponseTo and spByAudience == spByInResponseTo
            if checkInResponseTo and spByAudience == spByInResponseTo:
                sp = spByAudience

            elif checkInResponseTo and spByAudience != spByInResponseTo:
                response_obj = ResponseObj(httpcode=401)
                response_obj.setError('easyspid110')
                return response_obj

            sp = spByAudience

            # get service by sp and relay_state
            try:
                task = asyncio.run_coroutine_threadsafe(
                    self.dbobjSaml.execute_statment(
                        "get_service(%s, '%s', '%s')" %
                        ('True', str(self.srelay), sp)), globalsObj.ioloop)
                #assert not task.done()
                #service = task.result()
                service = waitFuture(task)

                if service['error'] == 0 and service['result'] is not None:
                    # costruisci il routing
                    self.routing = dict()
                    self.routing['url'] = service['result'][0]['url']
                    self.routing['relaystate'] = self.srelay
                    self.routing['format'] = service['result'][0]['format']

                elif service['error'] > 0 or service['result'] is None:
                    response_obj = ResponseObj(httpcode=500,
                                               debugMessage=service['result'])
                    response_obj.setError("easyspid111")
                    return response_obj

            except Exception:
                pass

            # get IdP
            # idpEntityId = waitFuture(task2)
            #
            # if idpEntityId['error'] == 0 and idpEntityId['result'] is not None:
            #     idp_metadata = idpEntityId['result'][0]['xml']
            #     idp = idpEntityId['result'][0]['cod_provider']
            #
            # elif idpEntityId['error'] == 0 and idpEntityId['result'] is None:
            #     response_obj = ResponseObj(httpcode=404)
            #     response_obj.setError('easyspid103')
            #     return response_obj
            #
            # elif idpEntityId['error'] > 0:
            #     response_obj = ResponseObj(httpcode=500, debugMessage=idpEntityId['result'])
            #     response_obj.setError("easyspid105")
            #     return response_obj

            # get IdP and metadata
            (idp_metadata, idp) = self.getIdentyIdp()

            # get sp settings
            task = asyncio.run_coroutine_threadsafe(
                easyspid.lib.easyspid.spSettings(sp, idp, close=True),
                globalsObj.ioloop)
            sp_settings = waitFuture(task)

            if sp_settings['error'] == 0 and sp_settings['result'] != None:

                ## insert response into DB
                task = asyncio.run_coroutine_threadsafe(
                    self.dbobjSaml.execute_statment(
                        "write_assertion('%s', '%s', '%s', '%s')" %
                        (str(self.response, 'utf-8').replace(
                            "'", "''"), sp, idp, self.remote_ip)),
                    globalsObj.ioloop)
                wrtAuthn = waitFuture(task)

                if wrtAuthn['error'] == 0:

                    if self.routing['format'] == 'saml':
                        return self.passthrough()

                    task = asyncio.run_coroutine_threadsafe(
                        self.dbobjJwt.execute_statment(
                            "get_token_by_cod('%s')" %
                            (wrtAuthn['result'][0]['cod_token'])),
                        globalsObj.ioloop)
                    #assert not task.done()
                    #jwt = task.result()
                    jwt = waitFuture(task)

                else:
                    response_obj = ResponseObj(httpcode=500,
                                               debugMessage=wrtAuthn['result'])
                    response_obj.setError("easyspid105")
                    logging.getLogger(
                        type(self).__module__ + "." +
                        type(self).__qualname__).error('Exception',
                                                       exc_info=True)
                    return response_obj

                # create settings OneLogin dict
                #settings = sp_settings['result']
                prvdSettings = Saml2_Settings(sp_settings['result'])

                chk = easyspid.lib.utils.validateAssertion(
                    str(self.response, 'utf-8'),
                    sp_settings['result']['idp']['x509cert_fingerprint'],
                    sp_settings['result']['idp']['x509cert_fingerprintalg'])

                chk['issuer'] = issuer.text.strip()
                chk['audience'] = audience.text.strip()

                if not chk['chkStatus']:
                    response_obj = ResponseObj(httpcode=401)
                    response_obj.setError('easyspid107')
                    return response_obj

                elif not chk['schemaValidate']:
                    response_obj = ResponseObj(httpcode=401)
                    response_obj.setError('easyspid104')
                    response_obj.setResult(responseValidate=chk)
                    return response_obj

                elif not chk['signCheck']:
                    response_obj = ResponseObj(httpcode=401)
                    response_obj.setError('easyspid106')
                    response_obj.setResult(responseValidate=chk)
                    return response_obj

                elif not chk[
                        'certAllowed'] and globalsObj.easyspid_checkCertificateAllowed:
                    response_obj = ResponseObj(httpcode=401)
                    response_obj.setError('easyspid116')
                    response_obj.setResult(responseValidate=chk)
                    return response_obj

                elif not chk[
                        'certValidity'] and globalsObj.easyspid_checkCertificateValidity:
                    response_obj = ResponseObj(httpcode=401)
                    response_obj.setError('easyspid117')
                    response_obj.setResult(responseValidate=chk)
                    return response_obj

                elif chkTime and not chk['chkTime']:
                    response_obj = ResponseObj(httpcode=401)
                    response_obj.setError('easyspid108')
                    return response_obj

                #get all attributes
                attributes = chk['serviceAttributes']
                attributes_tmp = dict()
                for key in attributes:
                    attributes_tmp[key] = attributes[key][0]
                attributes = attributes_tmp

                # build response form
                try:
                    with open(
                            os.path.join(globalsObj.modules_basedir,
                                         globalsObj.easyspid_responseFormPath),
                            'rb') as myfile:
                        response_form = myfile.read().decode("utf-8")
                except:
                    with open(globalsObj.easyspid_responseFormPath,
                              'rb') as myfile:
                        response_form = myfile.read().decode("utf-8")

                response_obj = ResponseObj(
                    httpcode=200, ID=wrtAuthn['result'][0]['ID_assertion'])
                response_obj.setError('200')
                response_obj.setResult(attributes=attributes,
                                       jwt=jwt['result'][0]['token'],
                                       responseValidate=chk,
                                       response=str(self.response, 'utf-8'),
                                       format='json')

                response_form = response_form.replace("%URLTARGET%",
                                                      self.routing['url'])
                response_form = response_form.replace("%RELAYSTATE%",
                                                      srelayPost)
                response_form = response_form.replace(
                    "%RESPONSE%",
                    OneLogin_Saml2_Utils.b64encode(response_obj.jsonWrite()))
                self.postTo = response_form

            elif sp_settings['error'] == 0 and sp_settings['result'] == None:
                response_obj = ResponseObj(httpcode=404)
                response_obj.setError('easyspid114')

            elif sp_settings['error'] > 0:
                #response_obj = sp_settings['result']
                response_obj = sp_settings

        except goExit as e:
            return e.expression

        except tornado.web.MissingArgumentError as error:
            response_obj = ResponseObj(debugMessage=error.log_message,
                                       httpcode=error.status_code,
                                       devMessage=error.log_message)
            response_obj.setError(str(error.status_code))
            logging.getLogger(
                type(self).__module__ + "." + type(self).__qualname__).error(
                    '%s' % error, exc_info=True)

        except Exception as inst:
            response_obj = ResponseObj(httpcode=500)
            response_obj.setError('500')
            logging.getLogger(
                type(self).__module__ + "." + type(self).__qualname__).error(
                    'Exception', exc_info=True)

        return response_obj
コード例 #10
0
ファイル: buildMetadata.py プロジェクト: francoricci/sapspid
    def makeMetadata(sp_settings):

        if sp_settings['error'] == 0 and sp_settings['result'] is not None:
            spSettings = Saml2_Settings(sp_settings['result'])
            metadata = spSettings.get_sp_metadata()
            metadata = str(metadata,'utf-8')

            response_obj = ResponseObj(httpcode=200)
            response_obj.setError('200')
            response_obj.setResult(metadata = metadata)

        elif sp_settings['error'] == 0 and sp_settings['result'] is None:
            response_obj = ResponseObj(httpcode=404)
            response_obj.setError('easyspid101')

        elif sp_settings['error'] > 0:
            response_obj = ResponseObj(httpcode=500, debugMessage=sp_settings['result'])
            response_obj.setError("easyspid105")

        return response_obj
コード例 #11
0
ファイル: verify.py プロジェクト: francoricci/sapspid
    async def verify(self):
        try:
            if self.request.method == 'GET':
                token = super(self.__class__, self).get_argument('token')

            elif self.request.method == 'POST':
                # leggi il json della richiesta
                temp = RequestObjNew(self.request.body)

                if temp.error["code"] == 2:
                    response_obj = ResponseObj(
                        debugMessage=temp.error["message"], httpcode=400)
                    response_obj.setError('400')
                    logging.getLogger(
                        type(self).__module__ + "." +
                        type(self).__qualname__).error(
                            'Validation error. Json input error')
                    return response_obj

                elif temp.error["code"] > 0:
                    raise tornado.web.HTTPError(
                        httpcode=503, log_message=temp.error["message"])

                token = temp.request['token']

            verifica = await self.dbobjJwt.execute_statment(
                "verify_token('%s')" % token)

            if verifica['error'] == 0:
                if verifica['result'][0]['verify_token_bycod'] == None:
                    response_obj = ResponseObj(httpcode=404)
                    response_obj.setError('jwtoken101')

                elif verifica['result'][0]['verify_token_bycod']['error'] == 0:
                    response_obj = ResponseObj(httpcode=200)
                    response_obj.setError('200')
                    response_obj.setResult(jose=verifica['result'][0]
                                           ['verify_token_bycod']['message'])

                elif verifica['result'][0]['verify_token_bycod']['error'] > 0:
                    response_obj = ResponseObj(
                        httpcode=401,
                        devMessage=(verifica['result'][0]['verify_token_bycod']
                                    ['message']))
                    response_obj.setError('jwtoken100')

            elif verifica['error'] > 0:
                response_obj = ResponseObj(debugMessage=verifica['result'],
                                           httpcode=500)
                response_obj.setError('jwtoken105')

        except tornado.web.MissingArgumentError as error:
            response_obj = ResponseObj(debugMessage=error.log_message,
                                       httpcode=error.status_code,
                                       devMessage=error.log_message)
            response_obj.setError(str(error.status_code))
            logging.getLogger(
                type(self).__module__ + "." + type(self).__qualname__).error(
                    '%s' % error, exc_info=True)

        except Exception as inst:
            response_obj = ResponseObj(httpcode=500)
            response_obj.setError('500')
            logging.getLogger(
                type(self).__module__ + "." + type(self).__qualname__).error(
                    'Exception', exc_info=True)

        if self.request.method == 'POST':
            response_obj.setID(temp.id)

        return response_obj
コード例 #12
0
    def getByType(self):
        try:
            jwtCode = super(self.__class__, self).get_argument('type')

            """ This will be executed in `executor` pool. """
            #connJwt = jwtoken.lib.database.Database(globalsObj.DbConnections['jwtMasterdsn'])
            #newcod_token = connJwt.createTokenByType(jwtCode)
            newcod_cod_token = self.dbobjJwt.makeQuery("EXECUTE create_token_by_type(%s)",
                        [jwtCode],type = self.dbobjJwt.stmts['create_token_by_type']['pool'], close = True)
            newcod_token = self.dbobjJwt.makeQuery("EXECUTE get_token_by_cod(%s)",
                        [newcod_cod_token['result']['cod_token']],type = self.dbobjJwt.stmts['get_token_by_cod']['pool'], close = True)

            if newcod_token['error'] == 0 and newcod_token['result'] is not None:
                # genera risposta tutto ok
                response_obj = ResponseObj(httpcode=200)
                response_obj.setError('200')
                response_obj.setResult(token = newcod_token['result']['token'])

            elif newcod_token['error'] == 0 and newcod_token['result'] is None:
                response_obj = ResponseObj(httpcode=404)
                response_obj.setError('jwtoken102')

            elif newcod_token['error'] > 1:
                response_obj = ResponseObj(debugMessage=newcod_token['result'].pgerror, httpcode=500,
                                           devMessage=("PostgreSQL error code: %s" % newcod_token['result'].pgcode))
                response_obj.setError('jwtoken105')

        except tornado.web.MissingArgumentError as error:
            response_obj = ResponseObj(debugMessage=error.log_message, httpcode=error.status_code,
                                       devMessage=error.log_message)
            response_obj.setError(str(error.status_code))
            logging.getLogger(__name__).error('%s'% error,exc_info=True)

        except ApplicationException as inst:
            response_obj = ResponseObj(httpcode=500)
            response_obj.setError(inst.code)
            #responsejson = response_obj.jsonWrite()
            logging.getLogger(__name__).error('Exception',exc_info=True)

        except Exception as inst:
            response_obj = ResponseObj(httpcode=500)
            response_obj.setError('500')
            logging.getLogger(__name__).error('Exception',exc_info=True)

        finally:
            logging.getLogger(__name__).warning('jwt/getByType handler executed')

        return response_obj
コード例 #13
0
    def verifySpMetadata(self, sp_settings):
        try:

            temp = RequestObjNew(self.request.body)
            if temp.error["code"] == 2:
                response_obj = ResponseObj(debugMessage=temp.error["message"], httpcode=400)
                response_obj.setError('400')
                logging.getLogger(type(self).__module__+"."+type(self).__qualname__).error('Validation error. Json input error')
                return response_obj

            elif temp.error["code"] > 0:
                raise tornado.web.HTTPError(httpcode=503, log_message=temp.error["message"])

            metadata = temp.request['metadata']

            if sp_settings['error'] == 0 and sp_settings['result'] is not None:
                # genera risposta tutto ok

                spSettings = Saml2_Settings(sp_settings['result'])

                chk = spSettings.validate_metadata(metadata,
                        fingerprint = sp_settings['result']['sp']['x509cert_fingerprint'],
                        fingerprintalg = sp_settings['result']['sp']['x509cert_fingerprintalg'],
                        validatecert=False)

                if not chk['schemaValidate']:
                    response_obj = ResponseObj(httpcode=401)
                    response_obj.setError('easyspid104')
                    response_obj.setResult(metadataValidate = chk)

                elif not chk['signCheck']:
                    response_obj = ResponseObj(httpcode=401)
                    response_obj.setError('easyspid106')
                    response_obj.setResult(metadataValidate = chk)

                elif chk['schemaValidate'] and chk['signCheck']:
                    response_obj = ResponseObj(httpcode=200)
                    response_obj.setError('200')
                    response_obj.setResult(metadataValidate = chk)

            elif sp_settings['error'] == 0 and sp_settings['result'] == None:
                response_obj = ResponseObj(httpcode=404)
                response_obj.setError('easyspid101')

            elif sp_settings['error'] > 0:
                response_obj = ResponseObj(httpcode=500, debugMessage=sp_settings['result'])
                response_obj.setError("easyspid105")

        except tornado.web.MissingArgumentError as error:
            response_obj = ResponseObj(debugMessage=error.log_message, httpcode=error.status_code,
                                       devMessage=error.log_message)
            response_obj.setError(str(error.status_code))
            logging.getLogger(type(self).__module__+"."+type(self).__qualname__).error('%s'% error,exc_info=True)

        except Exception as inst:
            response_obj = ResponseObj(httpcode=500)
            response_obj.setError('500')
            logging.getLogger(type(self).__module__+"."+type(self).__qualname__).error('Exception',exc_info=True)

        response_obj.setID(temp.id)
        return response_obj
コード例 #14
0
ファイル: easyspid.py プロジェクト: francoricci/sapspid
async def spSettings(cod_sp,
                     cod_idp=None,
                     binding=OneLogin_Saml2_Constants.BINDING_HTTP_REDIRECT,
                     close=True):
    result = {'error': 0, 'result': None}

    dbobj = globalsObj.DbConnections['samlDb']

    task1 = asyncio.ensure_future(dbobj.execute_statment(
        "get_sp_settings('%s')" % cod_sp),
                                  loop=globalsObj.ioloop)

    if cod_idp is not None:
        task2 = asyncio.ensure_future(dbobj.execute_statment(
            "get_prvd_metadta('%s')" % cod_idp),
                                      loop=globalsObj.ioloop)
        await task2
        idp_metadata = task2.result()

    await task1
    sp_settings = task1.result()

    if sp_settings['error'] == 0 and sp_settings['result'] is not None:
        # genera risposta tutto o
        sp_settings['result'] = sp_settings['result'][0]
        sp_settings['result']['settings']['idp'] = globalsObj.easyspidSettings[
            'idp']
        sp_settings['result']['settings']['sp']['cod_sp'] = cod_sp
        sp_settings['result']['settings']['sp']['x509cert'] = sp_settings[
            'result']['public_key']
        sp_settings['result']['settings']['sp']['privateKey'] = sp_settings[
            'result']['private_key']
        sp_settings['result']['settings']['sp'][
            'x509cert_fingerprint'] = sp_settings['result']['fingerprint']
        sp_settings['result']['settings']['sp'][
            'x509cert_fingerprintalg'] = sp_settings['result'][
                'fingerprintalg']
        sp_settings['result']['settings']['security'] = sp_settings['result'][
            'advanced_settings']['security']
        sp_settings['result']['settings']['contactPerson'] = sp_settings[
            'result']['advanced_settings']['contactPerson']
        sp_settings['result']['settings']['organization'] = sp_settings[
            'result']['advanced_settings']['organization']

        if cod_idp is not None:

            #idp_metadata = dbobj.makeQuery("EXECUTE get_prvd_metadta(%s)",
            #            [cod_idp],type = dbobj.stmts['get_providers']['pool'], close=close)
            #idp_metadata = await dbobj.execute_statment("get_prvd_metadta('%s')" % cod_idp)

            if idp_metadata['error'] == 0 and idp_metadata[
                    'result'] is not None:

                metadata = idp_metadata['result'][0]['xml']
                idp_data = OneLogin_Saml2_IdPMetadataParser.parse(
                    metadata,
                    required_sso_binding=binding,
                    required_slo_binding=binding)
                idp_settings = idp_data['idp']

                if 'entityId' in idp_settings:
                    sp_settings['result']['settings']['idp'][
                        'entityId'] = idp_settings['entityId']
                if 'singleLogoutService' in idp_settings:
                    sp_settings['result']['settings']['idp'][
                        'singleLogoutService'] = idp_settings[
                            'singleLogoutService']
                if 'singleSignOnService' in idp_settings:
                    sp_settings['result']['settings']['idp'][
                        'singleSignOnService'] = idp_settings[
                            'singleSignOnService']
                if 'x509cert' in idp_settings:
                    sp_settings['result']['settings']['idp'][
                        'x509cert'] = idp_settings['x509cert']

                sp_settings['result']['settings']['idp'][
                    'x509cert_fingerprint'] = idp_metadata['result'][0][
                        'fingerprint']
                sp_settings['result']['settings']['idp'][
                    'x509cert_fingerprintalg'] = idp_metadata['result'][0][
                        'fingerprintalg']
                sp_settings['result']['settings']['idp']['metadata'] = metadata
                sp_settings['result']['settings']['idp']['cod_idp'] = cod_idp

                result['result'] = sp_settings['result']['settings']
                return result

            elif idp_metadata['error'] > 0:
                result['error'] = 1

                sqlstate = "?"
                if hasattr(idp_metadata['result'], 'sqlstate'):
                    sqlstate = idp_metadata['result'].sqlstate

                response_obj = ResponseObj(
                    debugMessage="PostgreSQL error code: %s" % sqlstate,
                    httpcode=500,
                    devMessage=("PostgreSQL error message: %s" %
                                idp_metadata['result'].message))
                response_obj.setError('easyspid105')
                result['result'] = response_obj

            else:
                result['error'] = idp_metadata['error']
                result['result'] = idp_metadata['result']
        else:
            result['result'] = sp_settings['result']['settings']
            return result

    elif sp_settings['error'] > 0:
        result['error'] = 1

        sqlstate = "?"
        if hasattr(sp_settings['result'], 'sqlstate'):
            sqlstate = sp_settings['result'].sqlstate

        response_obj = ResponseObj(debugMessage="PostgreSQL error code: %s" %
                                   sqlstate,
                                   httpcode=500,
                                   devMessage=("PostgreSQL error message: %s" %
                                               sp_settings['result'].message))
        response_obj.setError('easyspid105')
        result['result'] = response_obj

    else:
        result['error'] = sp_settings['error']
        result['result'] = sp_settings['result']

    return result
コード例 #15
0
ファイル: login.py プロジェクト: francoricci/sapspid
    def loginAuthnReq(self, sp_settings, idp_metadata, attributeIndex, binding,
                      srelay_cod):
        try:

            if binding == 'redirect':
                authn_request = authnreqBuildhandler.buildAthnReq(
                    self, sp_settings, attributeIndex, signed=False)
            elif binding == 'post':
                authn_request = authnreqBuildhandler.buildAthnReq(
                    self, sp_settings, attributeIndex, signed=True)

            bindingMap = {
                'redirect': OneLogin_Saml2_Constants.BINDING_HTTP_REDIRECT,
                'post': OneLogin_Saml2_Constants.BINDING_HTTP_POST
            }

            if (sp_settings['error'] == 0 and sp_settings['result'] is not None
                    and idp_metadata.error.code == '200'
                    and authn_request.error.code == '200'):

                sp = sp_settings['result']['sp']['cod_sp']
                idp = sp_settings['result']['idp']['cod_idp']

                # get relay state
                task = asyncio.run_coroutine_threadsafe(
                    self.dbobjSaml.execute_statment(
                        "get_service(%s, '%s', '%s')" %
                        ('True', str(srelay_cod), sp)), globalsObj.ioloop)
                #assert not task.done()
                #srelay = task.result()
                srelay = waitFuture(task)

                if srelay['error'] == 0 and srelay['result'] is None:
                    response_obj = ResponseObj(httpcode=404)
                    response_obj.setError('easyspid113')
                    return response_obj

                elif srelay['error'] > 0:
                    response_obj = ResponseObj(
                        httpcode=500, debugMessage=sp_settings['result'])
                    response_obj.setError("easyspid105")
                    return response_obj

            #if (sp_settings['error'] == 0 and sp_settings['result'] is not None
            #and idp_metadata.error.code == '200' and authn_request.error.code == '200'):

                idp_data = OneLogin_Saml2_IdPMetadataParser.parse(
                    idp_metadata.result.metadata,
                    required_sso_binding=bindingMap[binding],
                    required_slo_binding=bindingMap[binding])
                idp_settings = idp_data['idp']

                # fake authn_request
                req = {
                    "http_host": "",
                    "script_name": "",
                    "server_port": "",
                    "get_data": "",
                    "post_data": ""
                }

                settings = sp_settings['result']
                if 'entityId' in idp_settings:
                    settings['idp']['entityId'] = idp_settings['entityId']
                if 'singleLogoutService' in idp_settings:
                    settings['idp']['singleLogoutService'] = idp_settings[
                        'singleLogoutService']
                if 'singleSignOnService' in idp_settings:
                    settings['idp']['singleSignOnService'] = idp_settings[
                        'singleSignOnService']
                if 'x509cert' in idp_settings:
                    settings['idp']['x509cert'] = idp_settings['x509cert']

                auth = OneLogin_Saml2_Auth(req, sp_settings['result'])
                spSettings = Saml2_Settings(sp_settings['result'])

                sign_alg = (
                    spSettings.get_security_data())['signatureAlgorithm']

                # build login message
                # redirect binding
                if binding == 'redirect':
                    saml_request = OneLogin_Saml2_Utils.deflate_and_base64_encode(
                        authn_request.result.authnrequest)
                    parameters = {'SAMLRequest': saml_request}
                    parameters['RelayState'] = srelay['result'][0][
                        'relay_state']
                    auth.add_request_signature(parameters, sign_alg)
                    redirectLocation = auth.redirect_to(
                        auth.get_sso_url(), parameters)

                    response_obj = ResponseObj(httpcode=200)
                    response_obj.setError('200')
                    response_obj.setResult(redirectTo=redirectLocation,
                                           jwt=authn_request.result.jwt)

                # POST binding
                elif binding == 'post':
                    saml_request_signed = OneLogin_Saml2_Utils.b64encode(
                        authn_request.result.authnrequest)
                    relay_state = OneLogin_Saml2_Utils.b64encode(
                        srelay['result'][0]['relay_state'])
                    idpsso = idp_settings['singleSignOnService']['url']

                    try:
                        with open(
                                os.path.join(globalsObj.modules_basedir,
                                             globalsObj.easyspid_postFormPath),
                                'rb') as myfile:
                            post_form = myfile.read().decode("utf-8").replace(
                                '\n', '')
                    except:
                        with open(globalsObj.easyspid_postFormPath,
                                  'rb') as myfile:
                            post_form = myfile.read().decode("utf-8").replace(
                                '\n', '')

                    post_form = post_form.replace("%IDPSSO%", idpsso)
                    post_form = post_form.replace("%AUTHNREQUEST%",
                                                  saml_request_signed)
                    post_form = post_form.replace("%RELAYSTATE%", relay_state)

                    response_obj = ResponseObj(httpcode=200)
                    response_obj.setError('200')
                    response_obj.setResult(postTo=post_form,
                                           jwt=authn_request.result.jwt)

            elif sp_settings['error'] == 0 and sp_settings['result'] is None:
                response_obj = ResponseObj(httpcode=404)
                response_obj.setError('easyspid101')

            elif sp_settings['error'] > 0:
                response_obj = ResponseObj(httpcode=500,
                                           debugMessage=sp_settings['result'])
                response_obj.setError("easyspid105")

        except tornado.web.MissingArgumentError as error:
            response_obj = ResponseObj(debugMessage=error.log_message,
                                       httpcode=error.status_code,
                                       devMessage=error.log_message)
            response_obj.setError(str(error.status_code))
            logging.getLogger(
                type(self).__module__ + "." + type(self).__qualname__).error(
                    '%s' % error, exc_info=True)

        except Exception as inst:
            response_obj = ResponseObj(httpcode=500)
            response_obj.setError('500')
            logging.getLogger(
                type(self).__module__ + "." + type(self).__qualname__).error(
                    'Exception', exc_info=True)

        return response_obj
コード例 #16
0
ファイル: getMetadata.py プロジェクト: francoricci/sapspid
    def getMetadata(sp_metadata):

        if sp_metadata['error'] == 0 and sp_metadata['result'] is not None:
            # genera risposta tutto ok
            metadata = sp_metadata['result'][0]['xml']
            public_key = sp_metadata['result'][0]['public_key']
            fingerprint = sp_metadata['result'][0]['fingerprint']
            fingerprintalg = sp_metadata['result'][0]['fingerprintalg']
            #private_key = sp_metadata['result'][0]['private_key']

            response_obj = ResponseObj(httpcode=200)
            response_obj.setError('200')
            #response_obj.setResult(metadata = metadata, x509cert = public_key, key = private_key,
            #            x509certFingerPrint = fingerprint, fingerPrintAlg = fingerprintalg)
            response_obj.setResult(metadata=metadata,
                                   x509cert=public_key,
                                   x509certFingerPrint=fingerprint,
                                   fingerPrintAlg=fingerprintalg)

        elif sp_metadata['error'] == 0 and sp_metadata['result'] is None:
            response_obj = ResponseObj(httpcode=404)
            response_obj.setError('easyspid101')

        elif sp_metadata['error'] > 0:
            response_obj = ResponseObj(httpcode=500,
                                       debugMessage=sp_metadata['result'])
            response_obj.setError("easyspid105")

        return response_obj
コード例 #17
0
ファイル: buildMetadata.py プロジェクト: francoricci/sapspid
    def buildMetadata(self, sp_settings, dbSave = True):

        try:
            makeMetadata = self.makeMetadata(sp_settings)

            if makeMetadata.error.code == '200':
                metadata = makeMetadata.result.metadata
                sp = sp_settings['result']['sp']['cod_sp']

                ## insert into DB
                if dbSave:
                    task = asyncio.run_coroutine_threadsafe(self.dbobjSaml.execute_statment("write_assertion('%s', '%s', %s, '%s')" %
                        (metadata.replace("'", "''"), sp, 'NULL', self.remote_ip)), globalsObj.ioloop)
                    wrtMetada = waitFuture(task)

                    if wrtMetada['error'] == 0:

                        task = asyncio.run_coroutine_threadsafe(self.dbobjJwt.execute_statment("get_token_by_cod('%s')" %
                            (wrtMetada['result'][0]['cod_token'])), globalsObj.ioloop)
                        jwt = waitFuture(task)

                        response_obj = ResponseObj(httpcode=200, ID = wrtMetada['result'][0]['ID_assertion'])
                        response_obj.setError('200')
                        response_obj.setResult(metadata = metadata, jwt=jwt['result'][0]['token'],
                                               idassertion=wrtMetada['result'][0]['ID_assertion'])

                        # insert metadata in saml.metadata table
                        task = asyncio.run_coroutine_threadsafe(self.dbobjSaml.execute_query(self.dbobjSaml.query['insert_metadata']['sql'],
                                sp+"_metadata", metadata, sp), globalsObj.ioloop)
                        insert_metadata = waitFuture(task)

                    else:
                        response_obj = ResponseObj(httpcode=500, debugMessage=wrtMetada['result'])
                        response_obj.setError("easyspid105")
                        logging.getLogger(type(self).__module__+"."+type(self).__qualname__).error('Exception',exc_info=True)
                else:
                    response_obj = ResponseObj(httpcode=200)
                    response_obj.setError('200')
                    response_obj.setResult(metadata = metadata, jwt="")

            else:

                response_obj = makeMetadata

        except tornado.web.MissingArgumentError as error:
            response_obj = ResponseObj(debugMessage=error.log_message, httpcode=error.status_code,
                                       devMessage=error.log_message)
            response_obj.setError(str(error.status_code))
            logging.getLogger(type(self).__module__+"."+type(self).__qualname__).error('%s'% error,exc_info=True)

        except Exception as inst:
            response_obj = ResponseObj(httpcode=500)
            response_obj.setError('500')
            logging.getLogger(type(self).__module__+"."+type(self).__qualname__).error('Exception',exc_info=True)

        return response_obj
コード例 #18
0
    def verify(self):
        try:
            #connJwt = jwtoken.lib.database.Database(globalsObj.DbConnections['jwtSlavedsn'])

            if self.request.method == 'GET':
                token = super(self.__class__, self).get_argument('token')

            elif  self.request.method == 'POST':
                # leggi il json della richiesta
                temp = RequestObjNew(self.request.body)

                if temp.error["code"] == 2:
                    response_obj = ResponseObj(debugMessage=temp.error["message"], httpcode=400)
                    response_obj.setError('400')
                    logging.getLogger(__name__).error('Validation error. Json input error')
                    return response_obj

                elif temp.error["code"] > 0:
                    raise tornado.web.HTTPError(httpcode=503, log_message=temp.error["message"])

                token = temp.request['token']

            #verifica = connJwt.verifyToken(token)
            verifica = self.dbobjJwt.makeQuery("EXECUTE verify_token(%s)",
                        [token],type = self.dbobjJwt.stmts['verify_token']['pool'], close = True)

            if verifica['error'] == 0:
                if verifica['result'][0] == None:
                    response_obj = ResponseObj(httpcode=404)
                    response_obj.setError('jwtoken101')

                elif verifica['result'][0]['error'] == 0:
                    response_obj = ResponseObj(httpcode=200)
                    response_obj.setError('200')
                    response_obj.setResult(jose = verifica['result'][0]['message'])

                elif verifica['result'][0]['error'] > 0:
                    response_obj = ResponseObj(httpcode=401, devMessage=(verifica['result'][0]['message']))
                    response_obj.setError('jwtoken100')

            elif verifica['error'] == 1:
                response_obj = ResponseObj(debugMessage=verifica['result'].pgerror, httpcode=500,
                                           devMessage=("PostgreSQL error code: %s" % verifica['result'].pgcode))
                response_obj.setError('jwtoken105')

        except tornado.web.MissingArgumentError as error:
            response_obj = ResponseObj(debugMessage=error.log_message, httpcode=error.status_code,
                                       devMessage=error.log_message)
            response_obj.setError(str(error.status_code))
            logging.getLogger(__name__).error('%s'% error,exc_info=True)

        except ApplicationException as inst:
            response_obj = ResponseObj(httpcode=500)
            response_obj.setError(inst.code)
            #responsejson = response_obj.jsonWrite()
            logging.getLogger(__name__).error('Exception',exc_info=True)

        except Exception as inst:
            response_obj = ResponseObj(httpcode=500)
            response_obj.setError('500')
            logging.getLogger(__name__).error('Exception',exc_info=True)

        finally:
            logging.getLogger(__name__).warning('jwt/verify handler executed')

        if  self.request.method == 'POST':
            response_obj.setID(temp.id)
        return response_obj
コード例 #19
0
    def signSpMetadata(self, sp_settings):
        try:

            temp = RequestObjNew(self.request.body)
            addKeyDescriptor = distutils.util.strtobool(
                self.get_argument('addSignCert', default='true'))
            addKeyValue = distutils.util.strtobool(
                self.get_argument('addKeyValue', default='false'))

            if temp.error["code"] == 2:
                response_obj = ResponseObj(debugMessage=temp.error["message"],
                                           httpcode=400)
                response_obj.setError('400')
                logging.getLogger(
                    type(self).__module__ + "." +
                    type(self).__qualname__).error(
                        'Validation error. Json input error')
                return response_obj

            elif temp.error["code"] > 0:
                raise tornado.web.HTTPError(httpcode=503,
                                            log_message=temp.error["message"])

            metadata = temp.request['metadata']

            if sp_settings['error'] == 0 and sp_settings['result'] is not None:
                spSettings = Saml2_Settings(sp_settings['result'])

                ## add KeyDescriptor used to sign to xml
                cert = spSettings.get_sp_cert()
                if addKeyDescriptor:
                    metadata = OneLogin_Saml2_Metadata.add_x509_key_descriptors(
                        metadata, cert, True)

                ## get key
                key = spSettings.get_sp_key()

                signature_algorithm = spSettings._OneLogin_Saml2_Settings__security[
                    'signatureAlgorithm']
                digest_algorithm = spSettings._OneLogin_Saml2_Settings__security[
                    'digestAlgorithm']

                metadata = AddSign(metadata,
                                   key,
                                   cert,
                                   debug=False,
                                   sign_algorithm=signature_algorithm,
                                   digest_algorithm=digest_algorithm,
                                   addKeyValue=addKeyValue)
                metadata = str(metadata, 'utf-8')
                response_obj = ResponseObj(httpcode=200)
                response_obj.setError('200')
                response_obj.setResult(metadata=metadata)

            elif sp_settings['error'] == 0 and sp_settings['result'] == None:
                response_obj = ResponseObj(httpcode=404)
                response_obj.setError('easyspid101')

            elif sp_settings['error'] > 0:
                response_obj = ResponseObj(httpcode=500,
                                           debugMessage=sp_settings['result'])
                response_obj.setError("easyspid105")

        except tornado.web.MissingArgumentError as error:
            response_obj = ResponseObj(debugMessage=error.log_message,
                                       httpcode=error.status_code,
                                       devMessage=error.log_message)
            response_obj.setError(str(error.status_code))
            logging.getLogger(
                type(self).__module__ + "." + type(self).__qualname__).error(
                    '%s' % error, exc_info=True)

        except Exception as inst:
            response_obj = ResponseObj(httpcode=500)
            response_obj.setError('500')
            logging.getLogger(
                type(self).__module__ + "." + type(self).__qualname__).error(
                    'Exception', exc_info=True)

        response_obj.setID(temp.id)
        return response_obj
コード例 #20
0
    async def getProviders(self, active=True):
        try:
            sp_metadata = await self.dbobjSaml.execute_statment(
                "get_providers(%s)" % active)

            if sp_metadata['error'] == 0 and sp_metadata['result'] is not None:
                tmp = list()
                for index, record in enumerate(sp_metadata['result']):
                    tmp.append({
                        'code': record['cod_provider'],
                        'name': record['name'],
                        'type': record['type'],
                        'description': record['description']
                    })

                response_obj = ResponseObj(httpcode=200)
                response_obj.setError('200')
                response_obj.setResult(providers=tmp)

            elif sp_metadata['error'] == 0 and sp_metadata['result'] is None:
                response_obj = ResponseObj(httpcode=404)
                response_obj.setError('easyspid101')

            elif sp_metadata['error'] > 0:
                response_obj = ResponseObj(httpcode=500,
                                           debugMessage=sp_metadata['result'])
                response_obj.setError("easyspid105")

        except tornado.web.MissingArgumentError as error:
            response_obj = ResponseObj(debugMessage=error.log_message,
                                       httpcode=error.status_code,
                                       devMessage=error.log_message)
            response_obj.setError(str(error.status_code))
            logging.getLogger(
                type(self).__module__ + "." + type(self).__qualname__).error(
                    '%s' % error, exc_info=True)

        except Exception as inst:
            response_obj = ResponseObj(httpcode=500)
            response_obj.setError('500')
            logging.getLogger(
                type(self).__module__ + "." + type(self).__qualname__).error(
                    'Exception', exc_info=True)

        return response_obj
コード例 #21
0
ファイル: verifyAuthreq.py プロジェクト: francoricci/sapspid
    def verifyAuthnRequest(self, prvd_settings):
        try:

            temp = RequestObjNew(self.request.body)
            if temp.error["code"] == 2:
                response_obj = ResponseObj(debugMessage=temp.error["message"], httpcode=400)
                response_obj.setError('400')
                logging.getLogger(type(self).__module__+"."+type(self).__qualname__).error('Validation error. Json input error')
                return response_obj

            elif temp.error["code"] > 0:
                raise tornado.web.HTTPError(httpcode=503, log_message=temp.error["message"])

            authn_request_signed = temp.request['authnrequest']

            if prvd_settings['error'] == 0 and prvd_settings['result'] != None:

                chk = easyspid.lib.utils.validateAssertion(authn_request_signed,
                                prvd_settings['result']['sp']['x509cert_fingerprint'],
                                prvd_settings['result']['sp']['x509cert_fingerprintalg'])

                if not chk['schemaValidate']:
                    response_obj = ResponseObj(httpcode=401)
                    response_obj.setError('easyspid104')
                    response_obj.setResult(authnValidate = chk)

                elif chk['assertionName'] == 'AuthnRequest' and chk['signCheck'] is None:
                    response_obj = ResponseObj(httpcode=200)
                    response_obj.setError('easyspid119')
                    response_obj.setResult(assertionChk = chk)

                elif not chk['signCheck']:
                    response_obj = ResponseObj(httpcode=401)
                    response_obj.setError('easyspid106')
                    response_obj.setResult(authnValidate = chk)

                elif chk['schemaValidate'] and chk['signCheck']:
                    response_obj = ResponseObj(httpcode=200)
                    response_obj.setError('200')
                    response_obj.setResult(authnValid = chk)

            elif prvd_settings['error'] == 0 and prvd_settings['result'] == None:
                response_obj = ResponseObj(httpcode=404)
                response_obj.setError('easyspid101')

            elif prvd_settings['error'] > 0:
                response_obj = ResponseObj(httpcode=500, debugMessage=prvd_settings['result'])
                response_obj.setError("easyspid105")

        except tornado.web.MissingArgumentError as error:
            response_obj = ResponseObj(debugMessage=error.log_message, httpcode=error.status_code,
                                       devMessage=error.log_message)
            response_obj.setError(str(error.status_code))
            logging.getLogger(type(self).__module__+"."+type(self).__qualname__).error('%s'% error,exc_info=True)

        except Exception as inst:
            response_obj = ResponseObj(httpcode=500)
            response_obj.setError('500')
            logging.getLogger(type(self).__module__+"."+type(self).__qualname__).error('Exception',exc_info=True)

        response_obj.setID(temp.id)
        return response_obj
コード例 #22
0
ファイル: authnreqBuild.py プロジェクト: francoricci/sapspid
    def buildAthnReq(self,
                     sp_settings,
                     attributeIndex,
                     sp_metadata=None,
                     signed=True):

        try:
            if sp_settings['error'] == 0 and sp_settings['result'] is not None:
                sp = sp_settings['result']['sp']['cod_sp']
                idp = sp_settings['result']['idp']['cod_idp']

                # get sp metadata to read attributeIndex location.
                if sp_metadata is None:
                    sp_metadata = buildMetadatahandler.makeMetadata(
                        sp_settings).result.metadata

                ns = {
                    'md0': OneLogin_Saml2_Constants.NS_MD,
                    'md1': OneLogin_Saml2_Constants.NS_SAML
                }
                parsedMetadata = xml.etree.ElementTree.fromstring(sp_metadata)
                attributeConsumingService = parsedMetadata.find(
                    "md0:SPSSODescriptor/md0:AssertionConsumerService[@index='%s']"
                    % attributeIndex, ns)
                if attributeConsumingService == None:
                    response_obj = ResponseObj(httpcode=404)
                    response_obj.setError('easyspid102')
                    return response_obj

                spSettings = Saml2_Settings(sp_settings['result'])

                key = spSettings.get_sp_key()
                cert = spSettings.get_sp_cert()
                sign_alg = (
                    spSettings.get_security_data())['signatureAlgorithm']
                digest = (spSettings.get_security_data())['digestAlgorithm']

                # build auth request
                authn_request = Saml2_Authn_Request(spSettings,
                                                    force_authn=True,
                                                    is_passive=False,
                                                    set_nameid_policy=True)
                authn_request_xml = authn_request.get_xml()

                ## inserisci attribute index
                ns = {
                    'md0': OneLogin_Saml2_Constants.NS_MD,
                    'md1': OneLogin_Saml2_Constants.NS_SAML
                }
                xml.etree.ElementTree.register_namespace(
                    'md0', OneLogin_Saml2_Constants.NS_MD)
                xml.etree.ElementTree.register_namespace(
                    'md1', OneLogin_Saml2_Constants.NS_SAML)

                parsedMetadata = xml.etree.ElementTree.fromstring(
                    authn_request_xml)
                parsedMetadata.attrib[
                    'AttributeConsumingServiceIndex'] = attributeIndex
                parsedMetadata.attrib[
                    'AssertionConsumerServiceURL'] = attributeConsumingService.attrib[
                        'Location']

                issuer = parsedMetadata.find("md1:Issuer", ns)
                issuer.set("Format",
                           "urn:oasis:names:tc:SAML:2.0:nameid-format:entity")
                issuer.set("NameQualifier",
                           (spSettings.get_sp_data())['entityId'])

                ## inserisci attributi del nodo isuuer
                authn_request_xml = xml.etree.ElementTree.tostring(
                    parsedMetadata, encoding="unicode")
                if signed:
                    #authn_request_signed = OneLogin_Saml2_Utils.add_sign(authn_request_xml, key, cert, debug=False,
                    #                    sign_algorithm=sign_alg, digest_algorithm=digest)
                    authn_request_signed = AddSign(authn_request_xml, key,
                                                   cert, False, sign_alg,
                                                   digest)
                    authn_request_signed = str(authn_request_signed, 'utf-8')
                else:
                    authn_request_signed = authn_request_xml

                ## insert into DB
                task = asyncio.run_coroutine_threadsafe(
                    self.dbobjSaml.execute_statment(
                        "write_assertion('%s', '%s', '%s', '%s')" %
                        (authn_request_signed.replace(
                            "'", "''"), sp, idp, self.remote_ip)),
                    globalsObj.ioloop)
                #assert not task.done()
                #wrtAuthn = task.result()
                wrtAuthn = waitFuture(task)

                if wrtAuthn['error'] == 0:
                    task = asyncio.run_coroutine_threadsafe(
                        self.dbobjJwt.execute_statment(
                            "get_token_by_cod('%s')" %
                            (wrtAuthn['result'][0]['cod_token'])),
                        globalsObj.ioloop)
                    #assert not task.done()
                    #jwt = task.result()
                    jwt = waitFuture(task)

                    response_obj = ResponseObj(
                        httpcode=200, ID=wrtAuthn['result'][0]['ID_assertion'])
                    response_obj.setError('200')
                    response_obj.setResult(
                        authnrequest=authn_request_signed,
                        jwt=jwt['result'][0]['token'],
                        idassertion=wrtAuthn['result'][0]['ID_assertion'])
                else:
                    response_obj = ResponseObj(httpcode=500,
                                               debugMessage=wrtAuthn['result'])
                    response_obj.setError("easyspid105")
                    logging.getLogger(
                        type(self).__module__ + "." +
                        type(self).__qualname__).error('Exception',
                                                       exc_info=True)

            elif sp_settings['error'] == 0 and sp_settings['result'] == None:
                response_obj = ResponseObj(httpcode=404)
                response_obj.setError('easyspid101')

            elif sp_settings['error'] > 0:
                response_obj = ResponseObj(httpcode=500,
                                           debugMessage=sp_settings['result'])
                response_obj.setError("easyspid105")

        except tornado.web.MissingArgumentError as error:
            response_obj = ResponseObj(debugMessage=error.log_message,
                                       httpcode=error.status_code,
                                       devMessage=error.log_message)
            response_obj.setError(str(error.status_code))
            logging.getLogger(
                type(self).__module__ + "." + type(self).__qualname__).error(
                    '%s' % error, exc_info=True)

        except Exception as inst:
            response_obj = ResponseObj(httpcode=500)
            response_obj.setError('500')
            logging.getLogger(
                type(self).__module__ + "." + type(self).__qualname__).error(
                    'Exception', exc_info=True)

        return response_obj
コード例 #23
0
    async def getByType(self):
        try:
            jwtCode = super(self.__class__, self).get_argument('type')

            newcod_cod_token = await self.dbobjJwt.execute_statment(
                "create_token_by_type('%s')" % jwtCode)
            newcod_token = await self.dbobjJwt.execute_statment(
                "get_token_by_cod('%s')" %
                newcod_cod_token['result'][0]['cod_token'])

            if newcod_token['error'] == 0 and newcod_token[
                    'result'] is not None:
                # genera risposta tutto ok
                response_obj = ResponseObj(httpcode=200)
                response_obj.setError('200')
                response_obj.setResult(
                    token=newcod_token['result'][0]['token'])

            elif newcod_token['error'] == 0 and newcod_token['result'] is None:
                response_obj = ResponseObj(httpcode=404)
                response_obj.setError('jwtoken102')

            elif newcod_token['error'] > 0:
                response_obj = ResponseObj(debugMessage=newcod_token['result'],
                                           httpcode=500)
                response_obj.setError('jwtoken105')

        except tornado.web.MissingArgumentError as error:
            response_obj = ResponseObj(debugMessage=error.log_message,
                                       httpcode=error.status_code,
                                       devMessage=error.log_message)
            response_obj.setError(str(error.status_code))
            logging.getLogger(
                type(self).__module__ + "." + type(self).__qualname__).error(
                    '%s' % error, exc_info=True)

        except Exception as inst:
            response_obj = ResponseObj(httpcode=500)
            response_obj.setError('500')
            logging.getLogger(
                type(self).__module__ + "." + type(self).__qualname__).error(
                    'Exception', exc_info=True)

        return response_obj