3 # Copyright (C) 2014 Simo Sorce <simo@redhat.com>
5 # see file 'COPYING' for use and warranty information
7 # This program is free software; you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation, either version 3 of the License, or
10 # (at your option) any later version.
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
17 # You should have received a copy of the GNU General Public License
18 # along with this program. If not, see <http://www.gnu.org/licenses/>.
20 from ipsilon.providers.common import ProviderPageBase
21 from ipsilon.util.user import UserSession
27 class AuthenticationError(Exception):
29 def __init__(self, message, code):
30 super(AuthenticationError, self).__init__(message)
31 self.message = message
35 return repr(self.message)
38 class InvalidRequest(Exception):
40 def __init__(self, message):
41 super(InvalidRequest, self).__init__(message)
42 self.message = message
45 return repr(self.message)
48 class AuthenticateRequest(ProviderPageBase):
50 def __init__(self, *args, **kwargs):
51 super(AuthenticateRequest, self).__init__(*args, **kwargs)
54 self.stage = self.STAGE_INIT
56 def auth(self, login):
58 self.saml2checks(login)
59 self.saml2assertion(login)
60 except AuthenticationError, e:
61 self.saml2error(login, e.code, e.message)
62 return self.reply(login)
64 def _parse_request(self, message):
66 login = lasso.Login(self.cfg.idp)
69 login.processAuthnRequestMsg(message)
70 except (lasso.ProfileInvalidMsgError,
71 lasso.ProfileMissingIssuerError), e:
73 msg = 'Malformed Request %r [%r]' % (e, message)
74 raise InvalidRequest(msg)
76 except (lasso.ProfileInvalidProtocolprofileError,
79 msg = 'Invalid SAML Request: %r (%r [%r])' % (login.request,
81 raise InvalidRequest(msg)
83 except (lasso.ServerProviderNotFoundError,
84 lasso.ProfileUnknownProviderError), e:
86 msg = 'Invalid SP [%s] (%r [%r])' % (login.remoteProviderId,
88 raise InvalidRequest(msg)
90 self._debug('SP %s requested authentication' % login.remoteProviderId)
94 def saml2login(self, request):
97 raise cherrypy.HTTPError(400,
98 'SAML request token missing or empty')
101 login = self._parse_request(request)
102 except InvalidRequest, e:
104 raise cherrypy.HTTPError(400, 'Invalid SAML request token')
105 except Exception, e: # pylint: disable=broad-except
107 raise cherrypy.HTTPError(500)
111 def saml2checks(self, login):
113 session = UserSession()
114 user = session.get_user()
115 if user.is_anonymous:
116 if self.stage < self.STAGE_AUTH:
117 session.save_data('saml2', 'stage', self.STAGE_AUTH)
118 session.save_data('saml2', 'Request', login.dump())
119 session.save_data('login', 'Return',
120 '%s/saml2/SSO/Continue' % self.basepath)
121 raise cherrypy.HTTPRedirect('%s/login' % self.basepath)
123 raise AuthenticationError(
124 "Unknown user", lasso.SAML2_STATUS_CODE_AUTHN_FAILED)
126 self._audit("Logged in user: %s [%s]" % (user.name, user.fullname))
128 # TODO: check if this is the first time this user access this SP
129 # If required by user prefs, ask user for consent once and then
133 # TODO: check Name-ID Policy
135 # TODO: check login.request.forceAuthn
137 login.validateRequestMsg(not user.is_anonymous, consent)
139 def saml2assertion(self, login):
141 authtime = datetime.datetime.utcnow()
142 skew = datetime.timedelta(0, 60)
143 authtime_notbefore = authtime - skew
144 authtime_notafter = authtime + skew
146 user = UserSession().get_user()
148 # TODO: get authentication type fnd name format from session
149 # need to save which login manager authenticated and map it to a
150 # saml2 authentication context
151 authn_context = lasso.SAML2_AUTHN_CONTEXT_UNSPECIFIED
153 timeformat = '%Y-%m-%dT%H:%M:%SZ'
154 login.buildAssertion(authn_context,
155 authtime.strftime(timeformat),
157 authtime_notbefore.strftime(timeformat),
158 authtime_notafter.strftime(timeformat))
159 login.assertion.subject.nameId.format = \
160 lasso.SAML2_NAME_IDENTIFIER_FORMAT_PERSISTENT
161 login.assertion.subject.nameId.content = user.name
163 # TODO: add user attributes as policy requires taking from 'user'
165 def saml2error(self, login, code, message):
166 status = lasso.Samlp2Status()
167 status.statusCode = lasso.Samlp2StatusCode()
168 status.statusCode.value = lasso.SAML2_STATUS_CODE_RESPONDER
169 status.statusCode.statusCode = lasso.Samlp2StatusCode()
170 status.statusCode.statusCode.value = code
171 login.response.status = status
173 def reply(self, login):
174 if login.protocolProfile == lasso.LOGIN_PROTOCOL_PROFILE_BRWS_ART:
176 raise cherrypy.HTTPError(501)
177 elif login.protocolProfile == lasso.LOGIN_PROTOCOL_PROFILE_BRWS_POST:
178 login.buildAuthnResponseMsg()
179 self._debug('POSTing back to SP [%s]' % (login.msgUrl))
181 "title": 'Redirecting back to the web application',
182 "action": login.msgUrl,
184 [lasso.SAML2_FIELD_RESPONSE, login.msgBody],
185 [lasso.SAML2_FIELD_RELAYSTATE, login.msgRelayState],
187 "submit": 'Return to application',
189 # pylint: disable=star-args
190 return self._template('saml2/post_response.html', **context)
193 raise cherrypy.HTTPError(500)