2008-11-24 13:51:03 -06:00
|
|
|
# Authors:
|
|
|
|
# Jason Gerard DeRose <jderose@redhat.com>
|
|
|
|
#
|
2016-03-22 05:11:36 -05:00
|
|
|
# Copyright (C) 2008-2016 Red Hat
|
2008-11-24 13:51:03 -06:00
|
|
|
# see file 'COPYING' for use and warranty information
|
|
|
|
#
|
2010-12-09 06:59:11 -06:00
|
|
|
# This program is free software; you can redistribute it and/or modify
|
|
|
|
# it under the terms of the GNU General Public License as published by
|
|
|
|
# the Free Software Foundation, either version 3 of the License, or
|
|
|
|
# (at your option) any later version.
|
2008-11-24 13:51:03 -06:00
|
|
|
#
|
|
|
|
# This program is distributed in the hope that it will be useful,
|
|
|
|
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
|
|
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
|
|
# GNU General Public License for more details.
|
|
|
|
#
|
|
|
|
# You should have received a copy of the GNU General Public License
|
2010-12-09 06:59:11 -06:00
|
|
|
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
2008-11-24 13:51:03 -06:00
|
|
|
|
|
|
|
"""
|
2009-01-16 02:47:03 -06:00
|
|
|
RPC server.
|
2009-01-16 02:56:39 -06:00
|
|
|
|
|
|
|
Also see the `ipalib.rpc` module.
|
2008-11-24 13:51:03 -06:00
|
|
|
"""
|
|
|
|
|
2010-02-23 11:53:47 -06:00
|
|
|
from xml.sax.saxutils import escape
|
2015-09-14 06:22:38 -05:00
|
|
|
from six.moves.xmlrpc_client import Fault
|
2012-07-04 07:52:47 -05:00
|
|
|
import os
|
|
|
|
import datetime
|
2013-01-08 09:11:05 -06:00
|
|
|
import json
|
2015-01-20 16:13:23 -06:00
|
|
|
import traceback
|
2015-07-20 09:04:07 -05:00
|
|
|
import gssapi
|
|
|
|
import time
|
2012-07-04 07:52:47 -05:00
|
|
|
|
2014-05-28 10:38:40 -05:00
|
|
|
import ldap.controls
|
|
|
|
from pyasn1.type import univ, namedtype
|
|
|
|
from pyasn1.codec.ber import encoder
|
2015-09-11 06:43:28 -05:00
|
|
|
import six
|
2015-09-14 05:52:29 -05:00
|
|
|
from six.moves.urllib.parse import parse_qs
|
2014-05-28 10:38:40 -05:00
|
|
|
|
2014-03-28 03:51:10 -05:00
|
|
|
from ipalib import plugable, errors
|
|
|
|
from ipalib.capabilities import VERSION_WITHOUT_CAPABILITIES
|
2016-06-30 02:32:00 -05:00
|
|
|
from ipalib.frontend import Local
|
2009-01-23 17:16:00 -06:00
|
|
|
from ipalib.backend import Executioner
|
2012-12-19 03:25:24 -06:00
|
|
|
from ipalib.errors import (PublicError, InternalError, CommandError, JSONError,
|
|
|
|
CCacheError, RefererError, InvalidSessionPassword, NotFound, ACIError,
|
2016-04-20 00:39:53 -05:00
|
|
|
ExecutionError, PasswordExpired, KrbPrincipalExpired, UserLocked)
|
2012-12-19 03:25:24 -06:00
|
|
|
from ipalib.request import context, destroy_context
|
|
|
|
from ipalib.rpc import (xml_dumps, xml_loads,
|
|
|
|
json_encode_binary, json_decode_binary)
|
2012-11-15 04:21:16 -06:00
|
|
|
from ipalib.util import parse_time_duration, normalize_name
|
Use DN objects instead of strings
* Convert every string specifying a DN into a DN object
* Every place a dn was manipulated in some fashion it was replaced by
the use of DN operators
* Add new DNParam parameter type for parameters which are DN's
* DN objects are used 100% of the time throughout the entire data
pipeline whenever something is logically a dn.
* Many classes now enforce DN usage for their attributes which are
dn's. This is implmented via ipautil.dn_attribute_property(). The
only permitted types for a class attribute specified to be a DN are
either None or a DN object.
* Require that every place a dn is used it must be a DN object.
This translates into lot of::
assert isinstance(dn, DN)
sprinkled through out the code. Maintaining these asserts is
valuable to preserve DN type enforcement. The asserts can be
disabled in production.
The goal of 100% DN usage 100% of the time has been realized, these
asserts are meant to preserve that.
The asserts also proved valuable in detecting functions which did
not obey their function signatures, such as the baseldap pre and
post callbacks.
* Moved ipalib.dn to ipapython.dn because DN class is shared with all
components, not just the server which uses ipalib.
* All API's now accept DN's natively, no need to convert to str (or
unicode).
* Removed ipalib.encoder and encode/decode decorators. Type conversion
is now explicitly performed in each IPASimpleLDAPObject method which
emulates a ldap.SimpleLDAPObject method.
* Entity & Entry classes now utilize DN's
* Removed __getattr__ in Entity & Entity clases. There were two
problems with it. It presented synthetic Python object attributes
based on the current LDAP data it contained. There is no way to
validate synthetic attributes using code checkers, you can't search
the code to find LDAP attribute accesses (because synthetic
attriutes look like Python attributes instead of LDAP data) and
error handling is circumscribed. Secondly __getattr__ was hiding
Python internal methods which broke class semantics.
* Replace use of methods inherited from ldap.SimpleLDAPObject via
IPAdmin class with IPAdmin methods. Directly using inherited methods
was causing us to bypass IPA logic. Mostly this meant replacing the
use of search_s() with getEntry() or getList(). Similarly direct
access of the LDAP data in classes using IPAdmin were replaced with
calls to getValue() or getValues().
* Objects returned by ldap2.find_entries() are now compatible with
either the python-ldap access methodology or the Entity/Entry access
methodology.
* All ldap operations now funnel through the common
IPASimpleLDAPObject giving us a single location where we interface
to python-ldap and perform conversions.
* The above 4 modifications means we've greatly reduced the
proliferation of multiple inconsistent ways to perform LDAP
operations. We are well on the way to having a single API in IPA for
doing LDAP (a long range goal).
* All certificate subject bases are now DN's
* DN objects were enhanced thusly:
- find, rfind, index, rindex, replace and insert methods were added
- AVA, RDN and DN classes were refactored in immutable and mutable
variants, the mutable variants are EditableAVA, EditableRDN and
EditableDN. By default we use the immutable variants preserving
important semantics. To edit a DN cast it to an EditableDN and
cast it back to DN when done editing. These issues are fully
described in other documentation.
- first_key_match was removed
- DN equalty comparison permits comparison to a basestring
* Fixed ldapupdate to work with DN's. This work included:
- Enhance test_updates.py to do more checking after applying
update. Add test for update_from_dict(). Convert code to use
unittest classes.
- Consolidated duplicate code.
- Moved code which should have been in the class into the class.
- Fix the handling of the 'deleteentry' update action. It's no longer
necessary to supply fake attributes to make it work. Detect case
where subsequent update applies a change to entry previously marked
for deletetion. General clean-up and simplification of the
'deleteentry' logic.
- Rewrote a couple of functions to be clearer and more Pythonic.
- Added documentation on the data structure being used.
- Simplfy the use of update_from_dict()
* Removed all usage of get_schema() which was being called prior to
accessing the .schema attribute of an object. If a class is using
internal lazy loading as an optimization it's not right to require
users of the interface to be aware of internal
optimization's. schema is now a property and when the schema
property is accessed it calls a private internal method to perform
the lazy loading.
* Added SchemaCache class to cache the schema's from individual
servers. This was done because of the observation we talk to
different LDAP servers, each of which may have it's own
schema. Previously we globally cached the schema from the first
server we connected to and returned that schema in all contexts. The
cache includes controls to invalidate it thus forcing a schema
refresh.
* Schema caching is now senstive to the run time context. During
install and upgrade the schema can change leading to errors due to
out-of-date cached schema. The schema cache is refreshed in these
contexts.
* We are aware of the LDAP syntax of all LDAP attributes. Every
attribute returned from an LDAP operation is passed through a
central table look-up based on it's LDAP syntax. The table key is
the LDAP syntax it's value is a Python callable that returns a
Python object matching the LDAP syntax. There are a handful of LDAP
attributes whose syntax is historically incorrect
(e.g. DistguishedNames that are defined as DirectoryStrings). The
table driven conversion mechanism is augmented with a table of
hard coded exceptions.
Currently only the following conversions occur via the table:
- dn's are converted to DN objects
- binary objects are converted to Python str objects (IPA
convention).
- everything else is converted to unicode using UTF-8 decoding (IPA
convention).
However, now that the table driven conversion mechanism is in place
it would be trivial to do things such as converting attributes
which have LDAP integer syntax into a Python integer, etc.
* Expected values in the unit tests which are a DN no longer need to
use lambda expressions to promote the returned value to a DN for
equality comparison. The return value is automatically promoted to
a DN. The lambda expressions have been removed making the code much
simpler and easier to read.
* Add class level logging to a number of classes which did not support
logging, less need for use of root_logger.
* Remove ipaserver/conn.py, it was unused.
* Consolidated duplicate code wherever it was found.
* Fixed many places that used string concatenation to form a new
string rather than string formatting operators. This is necessary
because string formatting converts it's arguments to a string prior
to building the result string. You can't concatenate a string and a
non-string.
* Simplify logic in rename_managed plugin. Use DN operators to edit
dn's.
* The live version of ipa-ldap-updater did not generate a log file.
The offline version did, now both do.
https://fedorahosted.org/freeipa/ticket/1670
https://fedorahosted.org/freeipa/ticket/1671
https://fedorahosted.org/freeipa/ticket/1672
https://fedorahosted.org/freeipa/ticket/1673
https://fedorahosted.org/freeipa/ticket/1674
https://fedorahosted.org/freeipa/ticket/1392
https://fedorahosted.org/freeipa/ticket/2872
2012-05-13 06:36:35 -05:00
|
|
|
from ipapython.dn import DN
|
2012-04-13 14:19:32 -05:00
|
|
|
from ipaserver.plugins.ldap2 import ldap2
|
2016-06-29 08:47:07 -05:00
|
|
|
from ipaserver.session import (
|
2016-06-29 08:53:52 -05:00
|
|
|
get_session_mgr, AuthManager, get_ipa_ccache_name,
|
2012-12-19 03:25:24 -06:00
|
|
|
load_ccache_data, bind_ipa_ccache, release_ipa_ccache, fmt_time,
|
2014-01-09 07:54:30 -06:00
|
|
|
default_max_session_duration, krbccache_dir, krbccache_prefix)
|
add session manager and cache krb auth
This patch adds a session manager and support for caching
authentication in the session. Major elements of the patch are:
* Add a session manager to support cookie based sessions which
stores session data in a memcached entry.
* Add ipalib/krb_utils.py which contains functions to parse ccache
names, format principals, format KRB timestamps, and a KRB_CCache
class which reads ccache entry and allows one to extract information
such as the principal, credentials, credential timestamps, etc.
* Move krb constants defined in ipalib/rpc.py to ipa_krb_utils.py so
that all kerberos items are co-located.
* Modify javascript in ipa.js so that the IPA.command() RPC call
checks for authentication needed error response and if it receives
it sends a GET request to /ipa/login URL to refresh credentials.
* Add session_auth_duration config item to constants.py, used to
configure how long a session remains valid.
* Add parse_time_duration utility to ipalib/util.py. Used to parse the
session_auth_duration config item.
* Update the default.conf.5 man page to document session_auth_duration
config item (also added documentation for log_manager config items
which had been inadvertantly omitted from a previous commit).
* Add SessionError object to ipalib/errors.py
* Move Kerberos protection in Apache config from /ipa to /ipa/xml and
/ipa/login
* Add SessionCCache class to session.py to manage temporary Kerberos
ccache file in effect for the duration of an RPC command.
* Adds a krblogin plugin used to implement the /ipa/login
handler. login handler sets the session expiration time, currently
60 minutes or the expiration of the TGT, whichever is shorter. It
also copies the ccache provied by mod_auth_kerb into the session
data. The json handler will later extract and validate the ccache
belonging to the session.
* Refactored the WSGI handlers so that json and xlmrpc could have
independent behavior, this also moves where create and destroy
context occurs, now done in the individual handler rather than the
parent class.
* The json handler now looks up the session data, validates the ccache
bound to the session, if it's expired replies with authenicated
needed error.
* Add documentation to session.py. Fully documents the entire process,
got questions, read the doc.
* Add exclusions to make-lint as needed.
2012-02-06 12:29:56 -06:00
|
|
|
from ipalib.backend import Backend
|
2012-12-19 03:25:24 -06:00
|
|
|
from ipalib.krb_utils import (
|
2015-07-20 09:04:07 -05:00
|
|
|
krb_ticket_expiration_threshold, krb5_format_principal_name,
|
|
|
|
krb5_format_service_principal_name, get_credentials, get_credentials_if_valid)
|
2012-02-25 12:39:19 -06:00
|
|
|
from ipapython import ipautil
|
2014-05-29 07:47:17 -05:00
|
|
|
from ipaplatform.paths import paths
|
2011-12-20 19:45:57 -06:00
|
|
|
from ipapython.version import VERSION
|
2012-07-04 07:52:47 -05:00
|
|
|
from ipalib.text import _
|
2012-02-25 12:39:19 -06:00
|
|
|
|
2015-09-11 06:43:28 -05:00
|
|
|
if six.PY3:
|
|
|
|
unicode = str
|
|
|
|
|
2012-02-25 12:39:19 -06:00
|
|
|
HTTP_STATUS_SUCCESS = '200 Success'
|
|
|
|
HTTP_STATUS_SERVER_ERROR = '500 Internal Server Error'
|
|
|
|
|
2010-02-23 11:53:47 -06:00
|
|
|
_not_found_template = """<html>
|
|
|
|
<head>
|
|
|
|
<title>404 Not Found</title>
|
|
|
|
</head>
|
|
|
|
<body>
|
|
|
|
<h1>Not Found</h1>
|
|
|
|
<p>
|
|
|
|
The requested URL <strong>%(url)s</strong> was not found on this server.
|
|
|
|
</p>
|
|
|
|
</body>
|
|
|
|
</html>"""
|
|
|
|
|
2012-02-25 12:39:19 -06:00
|
|
|
_bad_request_template = """<html>
|
|
|
|
<head>
|
|
|
|
<title>400 Bad Request</title>
|
|
|
|
</head>
|
|
|
|
<body>
|
|
|
|
<h1>Bad Request</h1>
|
|
|
|
<p>
|
|
|
|
<strong>%(message)s</strong>
|
|
|
|
</p>
|
|
|
|
</body>
|
|
|
|
</html>"""
|
|
|
|
|
|
|
|
_internal_error_template = """<html>
|
|
|
|
<head>
|
|
|
|
<title>500 Internal Server Error</title>
|
|
|
|
</head>
|
|
|
|
<body>
|
|
|
|
<h1>Internal Server Error</h1>
|
|
|
|
<p>
|
|
|
|
<strong>%(message)s</strong>
|
|
|
|
</p>
|
|
|
|
</body>
|
|
|
|
</html>"""
|
|
|
|
|
|
|
|
_unauthorized_template = """<html>
|
|
|
|
<head>
|
|
|
|
<title>401 Unauthorized</title>
|
|
|
|
</head>
|
|
|
|
<body>
|
|
|
|
<h1>Invalid Authentication</h1>
|
|
|
|
<p>
|
|
|
|
<strong>%(message)s</strong>
|
|
|
|
</p>
|
|
|
|
</body>
|
|
|
|
</html>"""
|
2010-02-23 11:53:47 -06:00
|
|
|
|
2014-05-28 10:38:40 -05:00
|
|
|
_success_template = """<html>
|
2012-06-06 07:38:08 -05:00
|
|
|
<head>
|
|
|
|
<title>200 Success</title>
|
|
|
|
</head>
|
|
|
|
<body>
|
|
|
|
<h1>%(title)s</h1>
|
|
|
|
<p>
|
|
|
|
<strong>%(message)s</strong>
|
|
|
|
</p>
|
|
|
|
</body>
|
|
|
|
</html>"""
|
|
|
|
|
2012-02-29 15:12:58 -06:00
|
|
|
class HTTP_Status(plugable.Plugin):
|
2012-02-28 07:41:07 -06:00
|
|
|
def not_found(self, environ, start_response, url, message):
|
|
|
|
"""
|
|
|
|
Return a 404 Not Found error.
|
|
|
|
"""
|
|
|
|
status = '404 Not Found'
|
|
|
|
response_headers = [('Content-Type', 'text/html; charset=utf-8')]
|
2012-02-25 12:39:19 -06:00
|
|
|
|
2012-02-28 07:41:07 -06:00
|
|
|
self.info('%s: URL="%s", %s', status, url, message)
|
|
|
|
start_response(status, response_headers)
|
|
|
|
output = _not_found_template % dict(url=escape(url))
|
|
|
|
return [output]
|
2012-02-25 12:39:19 -06:00
|
|
|
|
2012-02-28 07:41:07 -06:00
|
|
|
def bad_request(self, environ, start_response, message):
|
|
|
|
"""
|
|
|
|
Return a 400 Bad Request error.
|
|
|
|
"""
|
|
|
|
status = '400 Bad Request'
|
|
|
|
response_headers = [('Content-Type', 'text/html; charset=utf-8')]
|
|
|
|
|
|
|
|
self.info('%s: %s', status, message)
|
|
|
|
|
|
|
|
start_response(status, response_headers)
|
|
|
|
output = _bad_request_template % dict(message=escape(message))
|
|
|
|
return [output]
|
|
|
|
|
|
|
|
def internal_error(self, environ, start_response, message):
|
|
|
|
"""
|
|
|
|
Return a 500 Internal Server Error.
|
|
|
|
"""
|
|
|
|
status = HTTP_STATUS_SERVER_ERROR
|
|
|
|
response_headers = [('Content-Type', 'text/html; charset=utf-8')]
|
|
|
|
|
|
|
|
self.error('%s: %s', status, message)
|
|
|
|
|
|
|
|
start_response(status, response_headers)
|
|
|
|
output = _internal_error_template % dict(message=escape(message))
|
|
|
|
return [output]
|
|
|
|
|
2012-04-13 14:19:32 -05:00
|
|
|
def unauthorized(self, environ, start_response, message, reason):
|
2012-02-28 07:41:07 -06:00
|
|
|
"""
|
|
|
|
Return a 401 Unauthorized error.
|
|
|
|
"""
|
|
|
|
status = '401 Unauthorized'
|
|
|
|
response_headers = [('Content-Type', 'text/html; charset=utf-8')]
|
2012-04-13 14:19:32 -05:00
|
|
|
if reason:
|
|
|
|
response_headers.append(('X-IPA-Rejection-Reason', reason))
|
2012-02-28 07:41:07 -06:00
|
|
|
|
|
|
|
self.info('%s: %s', status, message)
|
|
|
|
|
|
|
|
start_response(status, response_headers)
|
|
|
|
output = _unauthorized_template % dict(message=escape(message))
|
|
|
|
return [output]
|
2012-02-25 12:39:19 -06:00
|
|
|
|
2009-10-13 12:28:00 -05:00
|
|
|
def read_input(environ):
|
|
|
|
"""
|
|
|
|
Read the request body from environ['wsgi.input'].
|
|
|
|
"""
|
|
|
|
try:
|
|
|
|
length = int(environ.get('CONTENT_LENGTH'))
|
|
|
|
except (ValueError, TypeError):
|
|
|
|
return
|
|
|
|
return environ['wsgi.input'].read(length)
|
2008-11-24 13:51:03 -06:00
|
|
|
|
|
|
|
|
2008-11-25 12:54:51 -06:00
|
|
|
def params_2_args_options(params):
|
|
|
|
if len(params) == 0:
|
|
|
|
return (tuple(), dict())
|
2010-03-26 04:56:53 -05:00
|
|
|
if len(params) == 1:
|
|
|
|
return (params[0], dict())
|
|
|
|
return (params[0], params[1])
|
2008-11-25 12:54:51 -06:00
|
|
|
|
|
|
|
|
2009-10-13 12:28:00 -05:00
|
|
|
def nicify_query(query, encoding='utf-8'):
|
|
|
|
if not query:
|
|
|
|
return
|
Use Python3-compatible dict method names
Python 2 has keys()/values()/items(), which return lists,
iterkeys()/itervalues()/iteritems(), which return iterators,
and viewkeys()/viewvalues()/viewitems() which return views.
Python 3 has only keys()/values()/items(), which return views.
To get iterators, one can use iter() or a for loop/comprehension;
for lists there's the list() constructor.
When iterating through the entire dict, without modifying the dict,
the difference between Python 2's items() and iteritems() is
negligible, especially on small dicts (the main overhead is
extra memory, not CPU time). In the interest of simpler code,
this patch changes many instances of iteritems() to items(),
iterkeys() to keys() etc.
In other cases, helpers like six.itervalues are used.
Reviewed-By: Christian Heimes <cheimes@redhat.com>
Reviewed-By: Jan Cholasta <jcholast@redhat.com>
2015-08-11 06:51:14 -05:00
|
|
|
for (key, value) in query.items():
|
2009-10-13 12:28:00 -05:00
|
|
|
if len(value) == 0:
|
|
|
|
yield (key, None)
|
|
|
|
elif len(value) == 1:
|
|
|
|
yield (key, value[0].decode(encoding))
|
|
|
|
else:
|
|
|
|
yield (key, tuple(v.decode(encoding) for v in value))
|
|
|
|
|
|
|
|
|
|
|
|
def extract_query(environ):
|
|
|
|
"""
|
|
|
|
Return the query as a ``dict``, or ``None`` if no query is presest.
|
|
|
|
"""
|
|
|
|
qstr = None
|
|
|
|
if environ['REQUEST_METHOD'] == 'POST':
|
|
|
|
if environ['CONTENT_TYPE'] == 'application/x-www-form-urlencoded':
|
|
|
|
qstr = read_input(environ)
|
|
|
|
elif environ['REQUEST_METHOD'] == 'GET':
|
|
|
|
qstr = environ['QUERY_STRING']
|
|
|
|
if qstr:
|
2015-09-14 05:52:29 -05:00
|
|
|
query = dict(nicify_query(parse_qs(qstr))) # keep_blank_values=True)
|
2009-10-13 12:28:00 -05:00
|
|
|
else:
|
|
|
|
query = {}
|
|
|
|
environ['wsgi.query'] = query
|
|
|
|
return query
|
|
|
|
|
|
|
|
|
2012-02-28 07:41:07 -06:00
|
|
|
class wsgi_dispatch(Executioner, HTTP_Status):
|
2010-02-23 11:53:47 -06:00
|
|
|
"""
|
|
|
|
WSGI routing middleware and entry point into IPA server.
|
|
|
|
|
2012-02-15 09:26:42 -06:00
|
|
|
The `wsgi_dispatch` plugin is the entry point into the IPA server.
|
|
|
|
It dispatchs the request to the appropriate wsgi application
|
|
|
|
handler which is specific to the authentication and RPC mechanism.
|
2010-02-23 11:53:47 -06:00
|
|
|
"""
|
|
|
|
|
2015-06-22 05:58:43 -05:00
|
|
|
def __init__(self, api):
|
|
|
|
super(wsgi_dispatch, self).__init__(api)
|
2010-02-23 11:53:47 -06:00
|
|
|
self.__apps = {}
|
|
|
|
|
|
|
|
def __iter__(self):
|
|
|
|
for key in sorted(self.__apps):
|
|
|
|
yield key
|
|
|
|
|
|
|
|
def __getitem__(self, key):
|
|
|
|
return self.__apps[key]
|
|
|
|
|
|
|
|
def __contains__(self, key):
|
|
|
|
return key in self.__apps
|
|
|
|
|
|
|
|
def __call__(self, environ, start_response):
|
2012-02-15 09:26:42 -06:00
|
|
|
self.debug('WSGI wsgi_dispatch.__call__:')
|
2010-02-23 11:53:47 -06:00
|
|
|
try:
|
|
|
|
return self.route(environ, start_response)
|
|
|
|
finally:
|
|
|
|
destroy_context()
|
|
|
|
|
2011-11-03 05:42:17 -05:00
|
|
|
def _on_finalize(self):
|
2010-02-23 11:53:47 -06:00
|
|
|
self.url = self.env['mount_ipa']
|
2012-02-15 09:26:42 -06:00
|
|
|
super(wsgi_dispatch, self)._on_finalize()
|
2010-02-23 11:53:47 -06:00
|
|
|
|
|
|
|
def route(self, environ, start_response):
|
2012-02-15 09:26:42 -06:00
|
|
|
key = environ.get('PATH_INFO')
|
2010-02-23 11:53:47 -06:00
|
|
|
if key in self.__apps:
|
|
|
|
app = self.__apps[key]
|
|
|
|
return app(environ, start_response)
|
2012-02-28 07:41:07 -06:00
|
|
|
url = environ['SCRIPT_NAME'] + environ['PATH_INFO']
|
|
|
|
return self.not_found(environ, start_response, url,
|
|
|
|
'URL fragment "%s" does not have a handler' % (key))
|
2010-02-23 11:53:47 -06:00
|
|
|
|
|
|
|
def mount(self, app, key):
|
|
|
|
"""
|
|
|
|
Mount the WSGI application *app* at *key*.
|
|
|
|
"""
|
|
|
|
# if self.__islocked__():
|
2015-08-24 05:40:33 -05:00
|
|
|
# raise Exception('%s.mount(): locked, cannot mount %r at %r' % (
|
2010-02-23 11:53:47 -06:00
|
|
|
# self.name, app, key)
|
|
|
|
# )
|
|
|
|
if key in self.__apps:
|
2015-08-24 05:40:33 -05:00
|
|
|
raise Exception('%s.mount(): cannot replace %r with %r at %r' % (
|
2010-02-23 11:53:47 -06:00
|
|
|
self.name, self.__apps[key], app, key)
|
|
|
|
)
|
2011-02-11 16:24:20 -06:00
|
|
|
self.debug('Mounting %r at %r', app, key)
|
2010-02-23 11:53:47 -06:00
|
|
|
self.__apps[key] = app
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
2009-10-13 12:28:00 -05:00
|
|
|
class WSGIExecutioner(Executioner):
|
|
|
|
"""
|
|
|
|
Base class for execution backends with a WSGI application interface.
|
|
|
|
"""
|
|
|
|
|
2011-04-21 03:13:06 -05:00
|
|
|
content_type = None
|
2010-02-23 11:53:47 -06:00
|
|
|
key = ''
|
|
|
|
|
2014-01-14 06:41:19 -06:00
|
|
|
_system_commands = {}
|
|
|
|
|
2011-11-03 05:42:17 -05:00
|
|
|
def _on_finalize(self):
|
2010-02-23 11:53:47 -06:00
|
|
|
self.url = self.env.mount_ipa + self.key
|
2011-11-03 05:42:17 -05:00
|
|
|
super(WSGIExecutioner, self)._on_finalize()
|
2015-06-22 05:58:43 -05:00
|
|
|
if 'wsgi_dispatch' in self.api.Backend:
|
|
|
|
self.api.Backend.wsgi_dispatch.mount(self, self.key)
|
2009-10-13 12:28:00 -05:00
|
|
|
|
2009-10-17 18:59:38 -05:00
|
|
|
def wsgi_execute(self, environ):
|
2009-10-13 12:28:00 -05:00
|
|
|
result = None
|
|
|
|
error = None
|
|
|
|
_id = None
|
2011-02-15 13:10:38 -06:00
|
|
|
lang = os.environ['LANG']
|
2011-08-19 15:20:01 -05:00
|
|
|
name = None
|
|
|
|
args = ()
|
|
|
|
options = {}
|
add session manager and cache krb auth
This patch adds a session manager and support for caching
authentication in the session. Major elements of the patch are:
* Add a session manager to support cookie based sessions which
stores session data in a memcached entry.
* Add ipalib/krb_utils.py which contains functions to parse ccache
names, format principals, format KRB timestamps, and a KRB_CCache
class which reads ccache entry and allows one to extract information
such as the principal, credentials, credential timestamps, etc.
* Move krb constants defined in ipalib/rpc.py to ipa_krb_utils.py so
that all kerberos items are co-located.
* Modify javascript in ipa.js so that the IPA.command() RPC call
checks for authentication needed error response and if it receives
it sends a GET request to /ipa/login URL to refresh credentials.
* Add session_auth_duration config item to constants.py, used to
configure how long a session remains valid.
* Add parse_time_duration utility to ipalib/util.py. Used to parse the
session_auth_duration config item.
* Update the default.conf.5 man page to document session_auth_duration
config item (also added documentation for log_manager config items
which had been inadvertantly omitted from a previous commit).
* Add SessionError object to ipalib/errors.py
* Move Kerberos protection in Apache config from /ipa to /ipa/xml and
/ipa/login
* Add SessionCCache class to session.py to manage temporary Kerberos
ccache file in effect for the duration of an RPC command.
* Adds a krblogin plugin used to implement the /ipa/login
handler. login handler sets the session expiration time, currently
60 minutes or the expiration of the TGT, whichever is shorter. It
also copies the ccache provied by mod_auth_kerb into the session
data. The json handler will later extract and validate the ccache
belonging to the session.
* Refactored the WSGI handlers so that json and xlmrpc could have
independent behavior, this also moves where create and destroy
context occurs, now done in the individual handler rather than the
parent class.
* The json handler now looks up the session data, validates the ccache
bound to the session, if it's expired replies with authenicated
needed error.
* Add documentation to session.py. Fully documents the entire process,
got questions, read the doc.
* Add exclusions to make-lint as needed.
2012-02-06 12:29:56 -06:00
|
|
|
|
2013-04-17 05:19:15 -05:00
|
|
|
e = None
|
2011-10-20 10:29:26 -05:00
|
|
|
if not 'HTTP_REFERER' in environ:
|
|
|
|
return self.marshal(result, RefererError(referer='missing'), _id)
|
|
|
|
if not environ['HTTP_REFERER'].startswith('https://%s/ipa' % self.api.env.host) and not self.env.in_tree:
|
|
|
|
return self.marshal(result, RefererError(referer=environ['HTTP_REFERER']), _id)
|
2009-10-13 12:28:00 -05:00
|
|
|
try:
|
2010-09-20 13:11:32 -05:00
|
|
|
if ('HTTP_ACCEPT_LANGUAGE' in environ):
|
2011-02-15 13:10:38 -06:00
|
|
|
lang_reg_w_q = environ['HTTP_ACCEPT_LANGUAGE'].split(',')[0]
|
|
|
|
lang_reg = lang_reg_w_q.split(';')[0]
|
|
|
|
lang_ = lang_reg.split('-')[0]
|
|
|
|
if '-' in lang_reg:
|
2016-03-20 15:32:27 -05:00
|
|
|
reg = lang_reg.split('-')[1].upper()
|
2011-02-15 13:10:38 -06:00
|
|
|
else:
|
|
|
|
reg = lang_.upper()
|
|
|
|
os.environ['LANG'] = '%s_%s' % (lang_, reg)
|
2010-02-23 11:53:47 -06:00
|
|
|
if (
|
|
|
|
environ.get('CONTENT_TYPE', '').startswith(self.content_type)
|
|
|
|
and environ['REQUEST_METHOD'] == 'POST'
|
|
|
|
):
|
|
|
|
data = read_input(environ)
|
|
|
|
(name, args, options, _id) = self.unmarshal(data)
|
|
|
|
else:
|
|
|
|
(name, args, options, _id) = self.simple_unmarshal(environ)
|
2014-01-14 06:41:19 -06:00
|
|
|
if name in self._system_commands:
|
|
|
|
result = self._system_commands[name](self, *args, **options)
|
2016-06-30 02:32:00 -05:00
|
|
|
elif (name not in self.api.Command or
|
|
|
|
isinstance(self.api.Command[name], Local)):
|
2010-02-23 11:53:47 -06:00
|
|
|
raise CommandError(name=name)
|
2014-01-14 06:41:19 -06:00
|
|
|
else:
|
|
|
|
result = self.Command[name](*args, **options)
|
2015-07-30 09:49:29 -05:00
|
|
|
except PublicError as e:
|
2015-01-20 16:13:23 -06:00
|
|
|
if self.api.env.debug:
|
|
|
|
self.debug('WSGI wsgi_execute PublicError: %s', traceback.format_exc())
|
2010-02-23 11:53:47 -06:00
|
|
|
error = e
|
2015-08-24 05:40:33 -05:00
|
|
|
except Exception as e:
|
2010-02-23 11:53:47 -06:00
|
|
|
self.exception(
|
|
|
|
'non-public: %s: %s', e.__class__.__name__, str(e)
|
|
|
|
)
|
|
|
|
error = InternalError()
|
2010-09-20 13:11:32 -05:00
|
|
|
finally:
|
2011-02-15 13:10:38 -06:00
|
|
|
os.environ['LANG'] = lang
|
2013-04-17 05:19:15 -05:00
|
|
|
|
|
|
|
principal = getattr(context, 'principal', 'UNKNOWN')
|
2012-03-01 20:54:06 -06:00
|
|
|
if name and name in self.Command:
|
2011-10-11 03:54:34 -05:00
|
|
|
try:
|
|
|
|
params = self.Command[name].args_options_2_params(*args, **options)
|
2015-07-30 09:49:29 -05:00
|
|
|
except Exception as e:
|
2011-10-11 03:54:34 -05:00
|
|
|
self.info(
|
|
|
|
'exception %s caught when converting options: %s', e.__class__.__name__, str(e)
|
|
|
|
)
|
|
|
|
# get at least some context of what is going on
|
|
|
|
params = options
|
2011-06-14 16:51:12 -05:00
|
|
|
if error:
|
2013-04-17 05:19:15 -05:00
|
|
|
result_string = type(e).__name__
|
2011-06-14 16:51:12 -05:00
|
|
|
else:
|
2013-04-17 05:19:15 -05:00
|
|
|
result_string = 'SUCCESS'
|
|
|
|
self.info('[%s] %s: %s(%s): %s',
|
|
|
|
type(self).__name__,
|
|
|
|
principal,
|
|
|
|
name,
|
|
|
|
', '.join(self.Command[name]._repr_iter(**params)),
|
|
|
|
result_string)
|
2011-08-19 15:20:01 -05:00
|
|
|
else:
|
2013-04-17 05:19:15 -05:00
|
|
|
self.info('[%s] %s: %s: %s',
|
|
|
|
type(self).__name__,
|
|
|
|
principal,
|
|
|
|
name,
|
|
|
|
type(e).__name__)
|
|
|
|
|
2014-03-28 03:51:10 -05:00
|
|
|
version = options.get('version', VERSION_WITHOUT_CAPABILITIES)
|
|
|
|
return self.marshal(result, error, _id, version)
|
2009-10-13 12:28:00 -05:00
|
|
|
|
|
|
|
def simple_unmarshal(self, environ):
|
|
|
|
name = environ['PATH_INFO'].strip('/')
|
|
|
|
options = extract_query(environ)
|
|
|
|
return (name, tuple(), options, None)
|
|
|
|
|
|
|
|
def __call__(self, environ, start_response):
|
|
|
|
"""
|
|
|
|
WSGI application for execution.
|
|
|
|
"""
|
add session manager and cache krb auth
This patch adds a session manager and support for caching
authentication in the session. Major elements of the patch are:
* Add a session manager to support cookie based sessions which
stores session data in a memcached entry.
* Add ipalib/krb_utils.py which contains functions to parse ccache
names, format principals, format KRB timestamps, and a KRB_CCache
class which reads ccache entry and allows one to extract information
such as the principal, credentials, credential timestamps, etc.
* Move krb constants defined in ipalib/rpc.py to ipa_krb_utils.py so
that all kerberos items are co-located.
* Modify javascript in ipa.js so that the IPA.command() RPC call
checks for authentication needed error response and if it receives
it sends a GET request to /ipa/login URL to refresh credentials.
* Add session_auth_duration config item to constants.py, used to
configure how long a session remains valid.
* Add parse_time_duration utility to ipalib/util.py. Used to parse the
session_auth_duration config item.
* Update the default.conf.5 man page to document session_auth_duration
config item (also added documentation for log_manager config items
which had been inadvertantly omitted from a previous commit).
* Add SessionError object to ipalib/errors.py
* Move Kerberos protection in Apache config from /ipa to /ipa/xml and
/ipa/login
* Add SessionCCache class to session.py to manage temporary Kerberos
ccache file in effect for the duration of an RPC command.
* Adds a krblogin plugin used to implement the /ipa/login
handler. login handler sets the session expiration time, currently
60 minutes or the expiration of the TGT, whichever is shorter. It
also copies the ccache provied by mod_auth_kerb into the session
data. The json handler will later extract and validate the ccache
belonging to the session.
* Refactored the WSGI handlers so that json and xlmrpc could have
independent behavior, this also moves where create and destroy
context occurs, now done in the individual handler rather than the
parent class.
* The json handler now looks up the session data, validates the ccache
bound to the session, if it's expired replies with authenicated
needed error.
* Add documentation to session.py. Fully documents the entire process,
got questions, read the doc.
* Add exclusions to make-lint as needed.
2012-02-06 12:29:56 -06:00
|
|
|
|
|
|
|
self.debug('WSGI WSGIExecutioner.__call__:')
|
2009-10-13 12:28:00 -05:00
|
|
|
try:
|
2012-02-25 12:39:19 -06:00
|
|
|
status = HTTP_STATUS_SUCCESS
|
2009-10-17 18:59:38 -05:00
|
|
|
response = self.wsgi_execute(environ)
|
2009-10-13 12:28:00 -05:00
|
|
|
headers = [('Content-Type', self.content_type + '; charset=utf-8')]
|
2015-08-24 05:40:33 -05:00
|
|
|
except Exception as e:
|
add session manager and cache krb auth
This patch adds a session manager and support for caching
authentication in the session. Major elements of the patch are:
* Add a session manager to support cookie based sessions which
stores session data in a memcached entry.
* Add ipalib/krb_utils.py which contains functions to parse ccache
names, format principals, format KRB timestamps, and a KRB_CCache
class which reads ccache entry and allows one to extract information
such as the principal, credentials, credential timestamps, etc.
* Move krb constants defined in ipalib/rpc.py to ipa_krb_utils.py so
that all kerberos items are co-located.
* Modify javascript in ipa.js so that the IPA.command() RPC call
checks for authentication needed error response and if it receives
it sends a GET request to /ipa/login URL to refresh credentials.
* Add session_auth_duration config item to constants.py, used to
configure how long a session remains valid.
* Add parse_time_duration utility to ipalib/util.py. Used to parse the
session_auth_duration config item.
* Update the default.conf.5 man page to document session_auth_duration
config item (also added documentation for log_manager config items
which had been inadvertantly omitted from a previous commit).
* Add SessionError object to ipalib/errors.py
* Move Kerberos protection in Apache config from /ipa to /ipa/xml and
/ipa/login
* Add SessionCCache class to session.py to manage temporary Kerberos
ccache file in effect for the duration of an RPC command.
* Adds a krblogin plugin used to implement the /ipa/login
handler. login handler sets the session expiration time, currently
60 minutes or the expiration of the TGT, whichever is shorter. It
also copies the ccache provied by mod_auth_kerb into the session
data. The json handler will later extract and validate the ccache
belonging to the session.
* Refactored the WSGI handlers so that json and xlmrpc could have
independent behavior, this also moves where create and destroy
context occurs, now done in the individual handler rather than the
parent class.
* The json handler now looks up the session data, validates the ccache
bound to the session, if it's expired replies with authenicated
needed error.
* Add documentation to session.py. Fully documents the entire process,
got questions, read the doc.
* Add exclusions to make-lint as needed.
2012-02-06 12:29:56 -06:00
|
|
|
self.exception('WSGI %s.__call__():', self.name)
|
2012-02-25 12:39:19 -06:00
|
|
|
status = HTTP_STATUS_SERVER_ERROR
|
2009-10-13 12:28:00 -05:00
|
|
|
response = status
|
2012-02-25 12:39:19 -06:00
|
|
|
headers = [('Content-Type', 'text/plain; charset=utf-8')]
|
add session manager and cache krb auth
This patch adds a session manager and support for caching
authentication in the session. Major elements of the patch are:
* Add a session manager to support cookie based sessions which
stores session data in a memcached entry.
* Add ipalib/krb_utils.py which contains functions to parse ccache
names, format principals, format KRB timestamps, and a KRB_CCache
class which reads ccache entry and allows one to extract information
such as the principal, credentials, credential timestamps, etc.
* Move krb constants defined in ipalib/rpc.py to ipa_krb_utils.py so
that all kerberos items are co-located.
* Modify javascript in ipa.js so that the IPA.command() RPC call
checks for authentication needed error response and if it receives
it sends a GET request to /ipa/login URL to refresh credentials.
* Add session_auth_duration config item to constants.py, used to
configure how long a session remains valid.
* Add parse_time_duration utility to ipalib/util.py. Used to parse the
session_auth_duration config item.
* Update the default.conf.5 man page to document session_auth_duration
config item (also added documentation for log_manager config items
which had been inadvertantly omitted from a previous commit).
* Add SessionError object to ipalib/errors.py
* Move Kerberos protection in Apache config from /ipa to /ipa/xml and
/ipa/login
* Add SessionCCache class to session.py to manage temporary Kerberos
ccache file in effect for the duration of an RPC command.
* Adds a krblogin plugin used to implement the /ipa/login
handler. login handler sets the session expiration time, currently
60 minutes or the expiration of the TGT, whichever is shorter. It
also copies the ccache provied by mod_auth_kerb into the session
data. The json handler will later extract and validate the ccache
belonging to the session.
* Refactored the WSGI handlers so that json and xlmrpc could have
independent behavior, this also moves where create and destroy
context occurs, now done in the individual handler rather than the
parent class.
* The json handler now looks up the session data, validates the ccache
bound to the session, if it's expired replies with authenicated
needed error.
* Add documentation to session.py. Fully documents the entire process,
got questions, read the doc.
* Add exclusions to make-lint as needed.
2012-02-06 12:29:56 -06:00
|
|
|
|
|
|
|
session_data = getattr(context, 'session_data', None)
|
|
|
|
if session_data is not None:
|
|
|
|
# Send session cookie back and store session data
|
|
|
|
# FIXME: the URL path should be retreived from somewhere (but where?), not hardcoded
|
2016-06-29 08:53:52 -05:00
|
|
|
session_mgr = get_session_mgr()
|
2012-12-04 17:20:17 -06:00
|
|
|
session_cookie = session_mgr.generate_cookie('/ipa', session_data['session_id'],
|
|
|
|
session_data['session_expiration_timestamp'])
|
add session manager and cache krb auth
This patch adds a session manager and support for caching
authentication in the session. Major elements of the patch are:
* Add a session manager to support cookie based sessions which
stores session data in a memcached entry.
* Add ipalib/krb_utils.py which contains functions to parse ccache
names, format principals, format KRB timestamps, and a KRB_CCache
class which reads ccache entry and allows one to extract information
such as the principal, credentials, credential timestamps, etc.
* Move krb constants defined in ipalib/rpc.py to ipa_krb_utils.py so
that all kerberos items are co-located.
* Modify javascript in ipa.js so that the IPA.command() RPC call
checks for authentication needed error response and if it receives
it sends a GET request to /ipa/login URL to refresh credentials.
* Add session_auth_duration config item to constants.py, used to
configure how long a session remains valid.
* Add parse_time_duration utility to ipalib/util.py. Used to parse the
session_auth_duration config item.
* Update the default.conf.5 man page to document session_auth_duration
config item (also added documentation for log_manager config items
which had been inadvertantly omitted from a previous commit).
* Add SessionError object to ipalib/errors.py
* Move Kerberos protection in Apache config from /ipa to /ipa/xml and
/ipa/login
* Add SessionCCache class to session.py to manage temporary Kerberos
ccache file in effect for the duration of an RPC command.
* Adds a krblogin plugin used to implement the /ipa/login
handler. login handler sets the session expiration time, currently
60 minutes or the expiration of the TGT, whichever is shorter. It
also copies the ccache provied by mod_auth_kerb into the session
data. The json handler will later extract and validate the ccache
belonging to the session.
* Refactored the WSGI handlers so that json and xlmrpc could have
independent behavior, this also moves where create and destroy
context occurs, now done in the individual handler rather than the
parent class.
* The json handler now looks up the session data, validates the ccache
bound to the session, if it's expired replies with authenicated
needed error.
* Add documentation to session.py. Fully documents the entire process,
got questions, read the doc.
* Add exclusions to make-lint as needed.
2012-02-06 12:29:56 -06:00
|
|
|
headers.append(('Set-Cookie', session_cookie))
|
|
|
|
|
2009-10-13 12:28:00 -05:00
|
|
|
start_response(status, headers)
|
|
|
|
return [response]
|
|
|
|
|
|
|
|
def unmarshal(self, data):
|
2016-05-30 02:40:07 -05:00
|
|
|
raise NotImplementedError('%s.unmarshal()' % type(self).__name__)
|
2009-10-13 12:28:00 -05:00
|
|
|
|
2014-03-28 03:51:10 -05:00
|
|
|
def marshal(self, result, error, _id=None,
|
|
|
|
version=VERSION_WITHOUT_CAPABILITIES):
|
2016-05-30 02:40:07 -05:00
|
|
|
raise NotImplementedError('%s.marshal()' % type(self).__name__)
|
2009-10-13 12:28:00 -05:00
|
|
|
|
|
|
|
|
2012-03-01 20:54:06 -06:00
|
|
|
class jsonserver(WSGIExecutioner, HTTP_Status):
|
2009-10-13 12:28:00 -05:00
|
|
|
"""
|
|
|
|
JSON RPC server.
|
|
|
|
|
|
|
|
For information on the JSON-RPC spec, see:
|
|
|
|
|
|
|
|
http://json-rpc.org/wiki/specification
|
|
|
|
"""
|
|
|
|
|
|
|
|
content_type = 'application/json'
|
add session manager and cache krb auth
This patch adds a session manager and support for caching
authentication in the session. Major elements of the patch are:
* Add a session manager to support cookie based sessions which
stores session data in a memcached entry.
* Add ipalib/krb_utils.py which contains functions to parse ccache
names, format principals, format KRB timestamps, and a KRB_CCache
class which reads ccache entry and allows one to extract information
such as the principal, credentials, credential timestamps, etc.
* Move krb constants defined in ipalib/rpc.py to ipa_krb_utils.py so
that all kerberos items are co-located.
* Modify javascript in ipa.js so that the IPA.command() RPC call
checks for authentication needed error response and if it receives
it sends a GET request to /ipa/login URL to refresh credentials.
* Add session_auth_duration config item to constants.py, used to
configure how long a session remains valid.
* Add parse_time_duration utility to ipalib/util.py. Used to parse the
session_auth_duration config item.
* Update the default.conf.5 man page to document session_auth_duration
config item (also added documentation for log_manager config items
which had been inadvertantly omitted from a previous commit).
* Add SessionError object to ipalib/errors.py
* Move Kerberos protection in Apache config from /ipa to /ipa/xml and
/ipa/login
* Add SessionCCache class to session.py to manage temporary Kerberos
ccache file in effect for the duration of an RPC command.
* Adds a krblogin plugin used to implement the /ipa/login
handler. login handler sets the session expiration time, currently
60 minutes or the expiration of the TGT, whichever is shorter. It
also copies the ccache provied by mod_auth_kerb into the session
data. The json handler will later extract and validate the ccache
belonging to the session.
* Refactored the WSGI handlers so that json and xlmrpc could have
independent behavior, this also moves where create and destroy
context occurs, now done in the individual handler rather than the
parent class.
* The json handler now looks up the session data, validates the ccache
bound to the session, if it's expired replies with authenicated
needed error.
* Add documentation to session.py. Fully documents the entire process,
got questions, read the doc.
* Add exclusions to make-lint as needed.
2012-02-06 12:29:56 -06:00
|
|
|
|
|
|
|
def __call__(self, environ, start_response):
|
|
|
|
'''
|
|
|
|
'''
|
|
|
|
|
|
|
|
self.debug('WSGI jsonserver.__call__:')
|
|
|
|
|
2012-02-15 09:26:42 -06:00
|
|
|
response = super(jsonserver, self).__call__(environ, start_response)
|
add session manager and cache krb auth
This patch adds a session manager and support for caching
authentication in the session. Major elements of the patch are:
* Add a session manager to support cookie based sessions which
stores session data in a memcached entry.
* Add ipalib/krb_utils.py which contains functions to parse ccache
names, format principals, format KRB timestamps, and a KRB_CCache
class which reads ccache entry and allows one to extract information
such as the principal, credentials, credential timestamps, etc.
* Move krb constants defined in ipalib/rpc.py to ipa_krb_utils.py so
that all kerberos items are co-located.
* Modify javascript in ipa.js so that the IPA.command() RPC call
checks for authentication needed error response and if it receives
it sends a GET request to /ipa/login URL to refresh credentials.
* Add session_auth_duration config item to constants.py, used to
configure how long a session remains valid.
* Add parse_time_duration utility to ipalib/util.py. Used to parse the
session_auth_duration config item.
* Update the default.conf.5 man page to document session_auth_duration
config item (also added documentation for log_manager config items
which had been inadvertantly omitted from a previous commit).
* Add SessionError object to ipalib/errors.py
* Move Kerberos protection in Apache config from /ipa to /ipa/xml and
/ipa/login
* Add SessionCCache class to session.py to manage temporary Kerberos
ccache file in effect for the duration of an RPC command.
* Adds a krblogin plugin used to implement the /ipa/login
handler. login handler sets the session expiration time, currently
60 minutes or the expiration of the TGT, whichever is shorter. It
also copies the ccache provied by mod_auth_kerb into the session
data. The json handler will later extract and validate the ccache
belonging to the session.
* Refactored the WSGI handlers so that json and xlmrpc could have
independent behavior, this also moves where create and destroy
context occurs, now done in the individual handler rather than the
parent class.
* The json handler now looks up the session data, validates the ccache
bound to the session, if it's expired replies with authenicated
needed error.
* Add documentation to session.py. Fully documents the entire process,
got questions, read the doc.
* Add exclusions to make-lint as needed.
2012-02-06 12:29:56 -06:00
|
|
|
return response
|
|
|
|
|
2014-03-28 03:51:10 -05:00
|
|
|
def marshal(self, result, error, _id=None,
|
|
|
|
version=VERSION_WITHOUT_CAPABILITIES):
|
2009-10-13 12:28:00 -05:00
|
|
|
if error:
|
|
|
|
assert isinstance(error, PublicError)
|
|
|
|
error = dict(
|
|
|
|
code=error.errno,
|
|
|
|
message=error.strerror,
|
2016-05-18 02:42:56 -05:00
|
|
|
data=error.kw,
|
2013-08-22 06:48:44 -05:00
|
|
|
name=unicode(error.__class__.__name__),
|
2009-10-13 12:28:00 -05:00
|
|
|
)
|
2012-03-01 20:54:06 -06:00
|
|
|
principal = getattr(context, 'principal', 'UNKNOWN')
|
2009-10-13 12:28:00 -05:00
|
|
|
response = dict(
|
|
|
|
result=result,
|
|
|
|
error=error,
|
|
|
|
id=_id,
|
2012-03-01 20:54:06 -06:00
|
|
|
principal=unicode(principal),
|
2011-12-20 19:45:57 -06:00
|
|
|
version=unicode(VERSION),
|
2009-10-13 12:28:00 -05:00
|
|
|
)
|
2014-03-28 03:51:10 -05:00
|
|
|
response = json_encode_binary(response, version)
|
2009-10-13 12:28:00 -05:00
|
|
|
return json.dumps(response, sort_keys=True, indent=4)
|
|
|
|
|
|
|
|
def unmarshal(self, data):
|
|
|
|
try:
|
|
|
|
d = json.loads(data)
|
2015-07-30 09:49:29 -05:00
|
|
|
except ValueError as e:
|
2009-10-13 12:28:00 -05:00
|
|
|
raise JSONError(error=e)
|
|
|
|
if not isinstance(d, dict):
|
2012-07-04 07:52:47 -05:00
|
|
|
raise JSONError(error=_('Request must be a dict'))
|
2009-10-13 12:28:00 -05:00
|
|
|
if 'method' not in d:
|
2012-07-04 07:52:47 -05:00
|
|
|
raise JSONError(error=_('Request is missing "method"'))
|
2009-10-13 12:28:00 -05:00
|
|
|
if 'params' not in d:
|
2012-07-04 07:52:47 -05:00
|
|
|
raise JSONError(error=_('Request is missing "params"'))
|
2010-03-01 17:55:39 -06:00
|
|
|
d = json_decode_binary(d)
|
2009-10-13 12:28:00 -05:00
|
|
|
method = d['method']
|
|
|
|
params = d['params']
|
|
|
|
_id = d.get('id')
|
|
|
|
if not isinstance(params, (list, tuple)):
|
2012-07-04 07:52:47 -05:00
|
|
|
raise JSONError(error=_('params must be a list'))
|
2009-10-13 12:28:00 -05:00
|
|
|
if len(params) != 2:
|
2012-07-04 07:52:47 -05:00
|
|
|
raise JSONError(error=_('params must contain [args, options]'))
|
2009-10-13 12:28:00 -05:00
|
|
|
args = params[0]
|
|
|
|
if not isinstance(args, (list, tuple)):
|
2012-07-04 07:52:47 -05:00
|
|
|
raise JSONError(error=_('params[0] (aka args) must be a list'))
|
2009-10-13 12:28:00 -05:00
|
|
|
options = params[1]
|
|
|
|
if not isinstance(options, dict):
|
2012-07-04 07:52:47 -05:00
|
|
|
raise JSONError(error=_('params[1] (aka options) must be a dict'))
|
Use Python3-compatible dict method names
Python 2 has keys()/values()/items(), which return lists,
iterkeys()/itervalues()/iteritems(), which return iterators,
and viewkeys()/viewvalues()/viewitems() which return views.
Python 3 has only keys()/values()/items(), which return views.
To get iterators, one can use iter() or a for loop/comprehension;
for lists there's the list() constructor.
When iterating through the entire dict, without modifying the dict,
the difference between Python 2's items() and iteritems() is
negligible, especially on small dicts (the main overhead is
extra memory, not CPU time). In the interest of simpler code,
this patch changes many instances of iteritems() to items(),
iterkeys() to keys() etc.
In other cases, helpers like six.itervalues are used.
Reviewed-By: Christian Heimes <cheimes@redhat.com>
Reviewed-By: Jan Cholasta <jcholast@redhat.com>
2015-08-11 06:51:14 -05:00
|
|
|
options = dict((str(k), v) for (k, v) in options.items())
|
2009-10-13 12:28:00 -05:00
|
|
|
return (method, args, options, _id)
|
add session manager and cache krb auth
This patch adds a session manager and support for caching
authentication in the session. Major elements of the patch are:
* Add a session manager to support cookie based sessions which
stores session data in a memcached entry.
* Add ipalib/krb_utils.py which contains functions to parse ccache
names, format principals, format KRB timestamps, and a KRB_CCache
class which reads ccache entry and allows one to extract information
such as the principal, credentials, credential timestamps, etc.
* Move krb constants defined in ipalib/rpc.py to ipa_krb_utils.py so
that all kerberos items are co-located.
* Modify javascript in ipa.js so that the IPA.command() RPC call
checks for authentication needed error response and if it receives
it sends a GET request to /ipa/login URL to refresh credentials.
* Add session_auth_duration config item to constants.py, used to
configure how long a session remains valid.
* Add parse_time_duration utility to ipalib/util.py. Used to parse the
session_auth_duration config item.
* Update the default.conf.5 man page to document session_auth_duration
config item (also added documentation for log_manager config items
which had been inadvertantly omitted from a previous commit).
* Add SessionError object to ipalib/errors.py
* Move Kerberos protection in Apache config from /ipa to /ipa/xml and
/ipa/login
* Add SessionCCache class to session.py to manage temporary Kerberos
ccache file in effect for the duration of an RPC command.
* Adds a krblogin plugin used to implement the /ipa/login
handler. login handler sets the session expiration time, currently
60 minutes or the expiration of the TGT, whichever is shorter. It
also copies the ccache provied by mod_auth_kerb into the session
data. The json handler will later extract and validate the ccache
belonging to the session.
* Refactored the WSGI handlers so that json and xlmrpc could have
independent behavior, this also moves where create and destroy
context occurs, now done in the individual handler rather than the
parent class.
* The json handler now looks up the session data, validates the ccache
bound to the session, if it's expired replies with authenicated
needed error.
* Add documentation to session.py. Fully documents the entire process,
got questions, read the doc.
* Add exclusions to make-lint as needed.
2012-02-06 12:29:56 -06:00
|
|
|
|
2012-02-15 09:26:42 -06:00
|
|
|
class AuthManagerKerb(AuthManager):
|
|
|
|
'''
|
|
|
|
Instances of the AuthManger class are used to handle
|
|
|
|
authentication events delivered by the SessionManager. This class
|
|
|
|
specifcally handles the management of Kerbeos credentials which
|
|
|
|
may be stored in the session.
|
|
|
|
'''
|
|
|
|
|
|
|
|
def __init__(self, name):
|
|
|
|
super(AuthManagerKerb, self).__init__(name)
|
|
|
|
|
|
|
|
def logout(self, session_data):
|
|
|
|
'''
|
|
|
|
The current user has requested to be logged out. To accomplish
|
|
|
|
this we remove the user's kerberos credentials from their
|
|
|
|
session. This does not destroy the session, it just prevents
|
|
|
|
it from being used for fast authentication. Because the
|
|
|
|
credentials are no longer in the session cache any future
|
|
|
|
attempt will require the acquisition of credentials using one
|
|
|
|
of the login mechanisms.
|
|
|
|
'''
|
|
|
|
|
2015-07-30 10:29:39 -05:00
|
|
|
if 'ccache_data' in session_data:
|
2012-02-15 09:26:42 -06:00
|
|
|
self.debug('AuthManager.logout.%s: deleting ccache_data', self.name)
|
|
|
|
del session_data['ccache_data']
|
|
|
|
else:
|
|
|
|
self.error('AuthManager.logout.%s: session_data does not contain ccache_data', self.name)
|
|
|
|
|
|
|
|
|
2012-02-19 09:02:38 -06:00
|
|
|
class KerberosSession(object):
|
|
|
|
'''
|
|
|
|
Functionally shared by all RPC handlers using both sessions and
|
|
|
|
Kerberos. This class must be implemented as a mixin class rather
|
|
|
|
than the more obvious technique of subclassing because the classes
|
|
|
|
needing this do not share a common base class.
|
|
|
|
'''
|
|
|
|
|
|
|
|
def kerb_session_on_finalize(self):
|
|
|
|
'''
|
|
|
|
Initialize values from the Env configuration.
|
|
|
|
|
|
|
|
Why do it this way and not simply reference
|
|
|
|
api.env.session_auth_duration? Because that config item cannot
|
|
|
|
be used directly, it must be parsed and converted to an
|
|
|
|
integer. It would be inefficient to reparse it on every
|
|
|
|
request. So we parse it once and store the result in the class
|
|
|
|
instance.
|
|
|
|
'''
|
|
|
|
# Set the session expiration time
|
|
|
|
try:
|
|
|
|
seconds = parse_time_duration(self.api.env.session_auth_duration)
|
|
|
|
self.session_auth_duration = int(seconds)
|
|
|
|
self.debug("session_auth_duration: %s", datetime.timedelta(seconds=self.session_auth_duration))
|
2015-07-30 09:49:29 -05:00
|
|
|
except Exception as e:
|
2012-02-19 09:02:38 -06:00
|
|
|
self.session_auth_duration = default_max_session_duration
|
|
|
|
self.error('unable to parse session_auth_duration, defaulting to %d: %s',
|
|
|
|
self.session_auth_duration, e)
|
|
|
|
|
|
|
|
def update_session_expiration(self, session_data, krb_endtime):
|
|
|
|
'''
|
|
|
|
Each time a session is created or accessed we need to update
|
|
|
|
it's expiration time. The expiration time is set inside the
|
|
|
|
session_data.
|
|
|
|
|
|
|
|
:parameters:
|
|
|
|
session_data
|
|
|
|
The session data whose expiration is being updatded.
|
|
|
|
krb_endtime
|
|
|
|
The UNIX timestamp for when the Kerberos credentials expire.
|
|
|
|
:returns:
|
|
|
|
None
|
|
|
|
'''
|
|
|
|
|
|
|
|
# Account for clock skew and/or give us some time leeway
|
|
|
|
krb_expiration = krb_endtime - krb_ticket_expiration_threshold
|
|
|
|
|
|
|
|
# Set the session expiration time
|
2016-06-29 08:53:52 -05:00
|
|
|
session_mgr = get_session_mgr()
|
2012-02-19 09:02:38 -06:00
|
|
|
session_mgr.set_session_expiration_time(session_data,
|
|
|
|
duration=self.session_auth_duration,
|
|
|
|
max_age=krb_expiration,
|
|
|
|
duration_type=self.api.env.session_duration_type)
|
|
|
|
|
2012-02-25 12:39:19 -06:00
|
|
|
|
|
|
|
def finalize_kerberos_acquisition(self, who, ccache_name, environ, start_response, headers=None):
|
|
|
|
if headers is None:
|
|
|
|
headers = []
|
|
|
|
|
|
|
|
# Retrieve the session data (or newly create)
|
2016-06-29 08:53:52 -05:00
|
|
|
session_mgr = get_session_mgr()
|
2012-02-25 12:39:19 -06:00
|
|
|
session_data = session_mgr.load_session_data(environ.get('HTTP_COOKIE'))
|
|
|
|
session_id = session_data['session_id']
|
|
|
|
|
|
|
|
self.debug('finalize_kerberos_acquisition: %s ccache_name="%s" session_id="%s"',
|
|
|
|
who, ccache_name, session_id)
|
|
|
|
|
|
|
|
# Copy the ccache file contents into the session data
|
|
|
|
session_data['ccache_data'] = load_ccache_data(ccache_name)
|
|
|
|
|
|
|
|
# Set when the session will expire
|
2015-07-20 09:04:07 -05:00
|
|
|
creds = get_credentials(ccache_name=ccache_name)
|
|
|
|
endtime = creds.lifetime + time.time()
|
2012-02-25 12:39:19 -06:00
|
|
|
self.update_session_expiration(session_data, endtime)
|
|
|
|
|
|
|
|
# Store the session data now that it's been updated with the ccache
|
|
|
|
session_mgr.store_session_data(session_data)
|
|
|
|
|
|
|
|
# The request is finished with the ccache, destroy it.
|
|
|
|
release_ipa_ccache(ccache_name)
|
|
|
|
|
|
|
|
# Return success and set session cookie
|
2012-12-04 17:20:17 -06:00
|
|
|
session_cookie = session_mgr.generate_cookie('/ipa', session_id,
|
|
|
|
session_data['session_expiration_timestamp'])
|
2012-02-25 12:39:19 -06:00
|
|
|
headers.append(('Set-Cookie', session_cookie))
|
|
|
|
|
|
|
|
start_response(HTTP_STATUS_SUCCESS, headers)
|
|
|
|
return ['']
|
|
|
|
|
|
|
|
|
2013-12-10 10:36:32 -06:00
|
|
|
class KerberosWSGIExecutioner(WSGIExecutioner, HTTP_Status, KerberosSession):
|
|
|
|
"""Base class for xmlserver and jsonserver_kerb
|
2012-06-06 21:54:16 -05:00
|
|
|
"""
|
|
|
|
|
|
|
|
def _on_finalize(self):
|
2013-12-10 10:36:32 -06:00
|
|
|
super(KerberosWSGIExecutioner, self)._on_finalize()
|
2012-06-06 21:54:16 -05:00
|
|
|
self.kerb_session_on_finalize()
|
|
|
|
|
|
|
|
def __call__(self, environ, start_response):
|
2013-12-10 10:36:32 -06:00
|
|
|
self.debug('KerberosWSGIExecutioner.__call__:')
|
2012-06-06 21:54:16 -05:00
|
|
|
user_ccache=environ.get('KRB5CCNAME')
|
2013-12-10 10:36:32 -06:00
|
|
|
|
|
|
|
headers = [('Content-Type', '%s; charset=utf-8' % self.content_type)]
|
|
|
|
|
2012-06-06 21:54:16 -05:00
|
|
|
if user_ccache is None:
|
2013-12-10 10:36:32 -06:00
|
|
|
|
|
|
|
status = HTTP_STATUS_SERVER_ERROR
|
|
|
|
response_headers = [('Content-Type', 'text/html; charset=utf-8')]
|
|
|
|
|
|
|
|
self.log.error(
|
|
|
|
'%s: %s', status,
|
|
|
|
'KerberosWSGIExecutioner.__call__: '
|
|
|
|
'KRB5CCNAME not defined in HTTP request environment')
|
|
|
|
|
2012-06-06 21:54:16 -05:00
|
|
|
return self.marshal(None, CCacheError())
|
|
|
|
try:
|
|
|
|
self.create_context(ccache=user_ccache)
|
2013-12-10 10:36:32 -06:00
|
|
|
response = super(KerberosWSGIExecutioner, self).__call__(
|
|
|
|
environ, start_response)
|
|
|
|
session_data = getattr(context, 'session_data', None)
|
|
|
|
if (session_data is None and self.env.context != 'lite'):
|
|
|
|
self.finalize_kerberos_acquisition(
|
|
|
|
'xmlserver', user_ccache, environ, start_response, headers)
|
2015-07-30 09:49:29 -05:00
|
|
|
except PublicError as e:
|
2012-06-06 21:54:16 -05:00
|
|
|
status = HTTP_STATUS_SUCCESS
|
|
|
|
response = status
|
|
|
|
start_response(status, headers)
|
|
|
|
return self.marshal(None, e)
|
|
|
|
finally:
|
|
|
|
destroy_context()
|
|
|
|
return response
|
|
|
|
|
2013-12-10 10:36:32 -06:00
|
|
|
|
|
|
|
class xmlserver(KerberosWSGIExecutioner):
|
|
|
|
"""
|
|
|
|
Execution backend plugin for XML-RPC server.
|
|
|
|
|
|
|
|
Also see the `ipalib.rpc.xmlclient` plugin.
|
|
|
|
"""
|
|
|
|
|
|
|
|
content_type = 'text/xml'
|
|
|
|
key = '/xml'
|
|
|
|
|
2012-06-06 21:54:16 -05:00
|
|
|
def listMethods(self, *params):
|
2014-01-14 06:41:19 -06:00
|
|
|
"""list methods for XML-RPC introspection"""
|
|
|
|
if params:
|
|
|
|
raise errors.ZeroArgumentError(name='system.listMethods')
|
2016-06-21 05:07:21 -05:00
|
|
|
return (tuple(unicode(cmd.name) for cmd in self.Command()
|
|
|
|
if cmd is self.Command[cmd.name]) +
|
2014-01-14 06:41:19 -06:00
|
|
|
tuple(unicode(name) for name in self._system_commands))
|
|
|
|
|
|
|
|
def _get_method_name(self, name, *params):
|
|
|
|
"""Get a method name for XML-RPC introspection commands"""
|
|
|
|
if not params:
|
|
|
|
raise errors.RequirementError(name='method name')
|
|
|
|
elif len(params) > 1:
|
|
|
|
raise errors.MaxArgumentError(name=name, count=1)
|
|
|
|
[method_name] = params
|
|
|
|
return method_name
|
2012-06-06 21:54:16 -05:00
|
|
|
|
|
|
|
def methodSignature(self, *params):
|
2014-01-14 06:41:19 -06:00
|
|
|
"""get method signature for XML-RPC introspection"""
|
|
|
|
method_name = self._get_method_name('system.methodSignature', *params)
|
|
|
|
if method_name in self._system_commands:
|
|
|
|
# TODO
|
|
|
|
# for now let's not go out of our way to document standard XML-RPC
|
|
|
|
return u'undef'
|
2016-06-30 02:32:00 -05:00
|
|
|
elif (method_name in self.api.Command and
|
|
|
|
not isinstance(self.api.Command[method_name], Local)):
|
2014-01-14 06:41:19 -06:00
|
|
|
# All IPA commands return a dict (struct),
|
|
|
|
# and take a params, options - list and dict (array, struct)
|
|
|
|
return [[u'struct', u'array', u'struct']]
|
|
|
|
else:
|
|
|
|
raise errors.CommandError(name=method_name)
|
2012-06-06 21:54:16 -05:00
|
|
|
|
|
|
|
def methodHelp(self, *params):
|
2014-01-14 06:41:19 -06:00
|
|
|
"""get method docstring for XML-RPC introspection"""
|
|
|
|
method_name = self._get_method_name('system.methodHelp', *params)
|
|
|
|
if method_name in self._system_commands:
|
|
|
|
return u''
|
2016-06-30 02:32:00 -05:00
|
|
|
elif (method_name in self.api.Command and
|
|
|
|
not isinstance(self.api.Command[method_name], Local)):
|
2016-05-30 02:40:07 -05:00
|
|
|
return unicode(self.Command[method_name].doc or '')
|
2014-01-14 06:41:19 -06:00
|
|
|
else:
|
|
|
|
raise errors.CommandError(name=method_name)
|
|
|
|
|
|
|
|
_system_commands = {
|
|
|
|
'system.listMethods': listMethods,
|
|
|
|
'system.methodSignature': methodSignature,
|
|
|
|
'system.methodHelp': methodHelp,
|
|
|
|
}
|
2012-06-06 21:54:16 -05:00
|
|
|
|
|
|
|
def unmarshal(self, data):
|
|
|
|
(params, name) = xml_loads(data)
|
2014-01-14 06:41:19 -06:00
|
|
|
if name in self._system_commands:
|
|
|
|
# For XML-RPC introspection, return params directly
|
|
|
|
return (name, params, {}, None)
|
2012-06-06 21:54:16 -05:00
|
|
|
(args, options) = params_2_args_options(params)
|
2012-12-07 09:54:07 -06:00
|
|
|
if 'version' not in options:
|
|
|
|
# Keep backwards compatibility with client containing
|
|
|
|
# bug https://fedorahosted.org/freeipa/ticket/3294:
|
|
|
|
# If `version` is not given in XML-RPC, assume an old version
|
2014-03-28 03:51:10 -05:00
|
|
|
options['version'] = VERSION_WITHOUT_CAPABILITIES
|
2012-06-06 21:54:16 -05:00
|
|
|
return (name, args, options, None)
|
|
|
|
|
2014-03-28 03:51:10 -05:00
|
|
|
def marshal(self, result, error, _id=None,
|
|
|
|
version=VERSION_WITHOUT_CAPABILITIES):
|
2012-06-06 21:54:16 -05:00
|
|
|
if error:
|
|
|
|
self.debug('response: %s: %s', error.__class__.__name__, str(error))
|
|
|
|
response = Fault(error.errno, error.strerror)
|
|
|
|
else:
|
|
|
|
if isinstance(result, dict):
|
|
|
|
self.debug('response: entries returned %d', result.get('count', 1))
|
|
|
|
response = (result,)
|
2014-03-28 03:51:10 -05:00
|
|
|
return xml_dumps(response, version, methodresponse=True)
|
2012-06-06 21:54:16 -05:00
|
|
|
|
|
|
|
|
2012-02-19 09:02:38 -06:00
|
|
|
class jsonserver_session(jsonserver, KerberosSession):
|
2012-02-15 09:26:42 -06:00
|
|
|
"""
|
|
|
|
JSON RPC server protected with session auth.
|
|
|
|
"""
|
|
|
|
|
|
|
|
key = '/session/json'
|
|
|
|
|
2015-06-22 05:58:43 -05:00
|
|
|
def __init__(self, api):
|
|
|
|
super(jsonserver_session, self).__init__(api)
|
2015-06-22 04:59:33 -05:00
|
|
|
name = '{0}_{1}'.format(self.__class__.__name__, id(self))
|
|
|
|
auth_mgr = AuthManagerKerb(name)
|
2016-06-29 08:53:52 -05:00
|
|
|
session_mgr = get_session_mgr()
|
2012-02-15 09:26:42 -06:00
|
|
|
session_mgr.auth_mgr.register(auth_mgr.name, auth_mgr)
|
|
|
|
|
2012-02-19 09:02:38 -06:00
|
|
|
def _on_finalize(self):
|
|
|
|
super(jsonserver_session, self)._on_finalize()
|
|
|
|
self.kerb_session_on_finalize()
|
|
|
|
|
2012-02-15 09:26:42 -06:00
|
|
|
def need_login(self, start_response):
|
|
|
|
status = '401 Unauthorized'
|
|
|
|
headers = []
|
|
|
|
response = ''
|
|
|
|
|
2012-02-28 07:41:07 -06:00
|
|
|
self.debug('jsonserver_session: %s need login', status)
|
2012-02-15 09:26:42 -06:00
|
|
|
|
|
|
|
start_response(status, headers)
|
|
|
|
return [response]
|
|
|
|
|
|
|
|
def __call__(self, environ, start_response):
|
|
|
|
'''
|
|
|
|
'''
|
|
|
|
|
|
|
|
self.debug('WSGI jsonserver_session.__call__:')
|
|
|
|
|
|
|
|
# Load the session data
|
2016-06-29 08:53:52 -05:00
|
|
|
session_mgr = get_session_mgr()
|
2012-02-15 09:26:42 -06:00
|
|
|
session_data = session_mgr.load_session_data(environ.get('HTTP_COOKIE'))
|
|
|
|
session_id = session_data['session_id']
|
|
|
|
|
2012-02-19 09:02:38 -06:00
|
|
|
self.debug('jsonserver_session.__call__: session_id=%s start_timestamp=%s access_timestamp=%s expiration_timestamp=%s',
|
2012-02-15 09:26:42 -06:00
|
|
|
session_id,
|
|
|
|
fmt_time(session_data['session_start_timestamp']),
|
2012-02-19 09:02:38 -06:00
|
|
|
fmt_time(session_data['session_access_timestamp']),
|
2012-02-15 09:26:42 -06:00
|
|
|
fmt_time(session_data['session_expiration_timestamp']))
|
|
|
|
|
|
|
|
ccache_data = session_data.get('ccache_data')
|
|
|
|
|
|
|
|
# Redirect to login if no Kerberos credentials
|
|
|
|
if ccache_data is None:
|
|
|
|
self.debug('no ccache, need login')
|
|
|
|
return self.need_login(start_response)
|
|
|
|
|
2012-02-25 12:39:19 -06:00
|
|
|
ipa_ccache_name = bind_ipa_ccache(ccache_data)
|
2012-02-15 09:26:42 -06:00
|
|
|
|
|
|
|
# Redirect to login if Kerberos credentials are expired
|
2015-07-20 09:04:07 -05:00
|
|
|
creds = get_credentials_if_valid(ccache_name=ipa_ccache_name)
|
|
|
|
if not creds:
|
2012-02-15 09:26:42 -06:00
|
|
|
self.debug('ccache expired, deleting session, need login')
|
2012-02-25 12:39:19 -06:00
|
|
|
# The request is finished with the ccache, destroy it.
|
|
|
|
release_ipa_ccache(ipa_ccache_name)
|
2012-02-15 09:26:42 -06:00
|
|
|
return self.need_login(start_response)
|
|
|
|
|
2012-02-19 09:02:38 -06:00
|
|
|
# Update the session expiration based on the Kerberos expiration
|
2015-07-20 09:04:07 -05:00
|
|
|
endtime = creds.lifetime + time.time()
|
2012-02-19 09:02:38 -06:00
|
|
|
self.update_session_expiration(session_data, endtime)
|
|
|
|
|
2012-02-15 09:26:42 -06:00
|
|
|
# Store the session data in the per-thread context
|
|
|
|
setattr(context, 'session_data', session_data)
|
|
|
|
|
2012-11-15 04:21:16 -06:00
|
|
|
# This may fail if a ticket from wrong realm was handled via browser
|
|
|
|
try:
|
|
|
|
self.create_context(ccache=ipa_ccache_name)
|
2015-07-30 09:49:29 -05:00
|
|
|
except ACIError as e:
|
2012-11-15 04:21:16 -06:00
|
|
|
return self.unauthorized(environ, start_response, str(e), 'denied')
|
2012-02-15 09:26:42 -06:00
|
|
|
|
|
|
|
try:
|
|
|
|
response = super(jsonserver_session, self).__call__(environ, start_response)
|
|
|
|
finally:
|
|
|
|
# Kerberos may have updated the ccache data during the
|
|
|
|
# execution of the command therefore we need refresh our
|
|
|
|
# copy of it in the session data so the next command sees
|
|
|
|
# the same state of the ccache.
|
|
|
|
#
|
|
|
|
# However we must be careful not to restore the ccache
|
|
|
|
# data in the session data if it was explicitly deleted
|
|
|
|
# during the execution of the command. For example the
|
|
|
|
# logout command removes the ccache data from the session
|
|
|
|
# data to invalidate the session credentials.
|
|
|
|
|
2015-07-30 10:29:39 -05:00
|
|
|
if 'ccache_data' in session_data:
|
2012-02-25 12:39:19 -06:00
|
|
|
session_data['ccache_data'] = load_ccache_data(ipa_ccache_name)
|
2012-02-15 09:26:42 -06:00
|
|
|
|
2012-02-25 12:39:19 -06:00
|
|
|
# The request is finished with the ccache, destroy it.
|
|
|
|
release_ipa_ccache(ipa_ccache_name)
|
2012-02-15 09:26:42 -06:00
|
|
|
# Store the session data.
|
|
|
|
session_mgr.store_session_data(session_data)
|
|
|
|
destroy_context()
|
|
|
|
|
|
|
|
return response
|
|
|
|
|
2013-04-15 09:41:25 -05:00
|
|
|
|
2013-12-10 10:36:32 -06:00
|
|
|
class jsonserver_kerb(jsonserver, KerberosWSGIExecutioner):
|
2012-02-15 09:26:42 -06:00
|
|
|
"""
|
|
|
|
JSON RPC server protected with kerberos auth.
|
|
|
|
"""
|
|
|
|
|
|
|
|
key = '/json'
|
|
|
|
|
|
|
|
|
2012-02-28 07:41:07 -06:00
|
|
|
class login_kerberos(Backend, KerberosSession, HTTP_Status):
|
2012-02-25 12:39:19 -06:00
|
|
|
key = '/session/login_kerberos'
|
add session manager and cache krb auth
This patch adds a session manager and support for caching
authentication in the session. Major elements of the patch are:
* Add a session manager to support cookie based sessions which
stores session data in a memcached entry.
* Add ipalib/krb_utils.py which contains functions to parse ccache
names, format principals, format KRB timestamps, and a KRB_CCache
class which reads ccache entry and allows one to extract information
such as the principal, credentials, credential timestamps, etc.
* Move krb constants defined in ipalib/rpc.py to ipa_krb_utils.py so
that all kerberos items are co-located.
* Modify javascript in ipa.js so that the IPA.command() RPC call
checks for authentication needed error response and if it receives
it sends a GET request to /ipa/login URL to refresh credentials.
* Add session_auth_duration config item to constants.py, used to
configure how long a session remains valid.
* Add parse_time_duration utility to ipalib/util.py. Used to parse the
session_auth_duration config item.
* Update the default.conf.5 man page to document session_auth_duration
config item (also added documentation for log_manager config items
which had been inadvertantly omitted from a previous commit).
* Add SessionError object to ipalib/errors.py
* Move Kerberos protection in Apache config from /ipa to /ipa/xml and
/ipa/login
* Add SessionCCache class to session.py to manage temporary Kerberos
ccache file in effect for the duration of an RPC command.
* Adds a krblogin plugin used to implement the /ipa/login
handler. login handler sets the session expiration time, currently
60 minutes or the expiration of the TGT, whichever is shorter. It
also copies the ccache provied by mod_auth_kerb into the session
data. The json handler will later extract and validate the ccache
belonging to the session.
* Refactored the WSGI handlers so that json and xlmrpc could have
independent behavior, this also moves where create and destroy
context occurs, now done in the individual handler rather than the
parent class.
* The json handler now looks up the session data, validates the ccache
bound to the session, if it's expired replies with authenicated
needed error.
* Add documentation to session.py. Fully documents the entire process,
got questions, read the doc.
* Add exclusions to make-lint as needed.
2012-02-06 12:29:56 -06:00
|
|
|
|
|
|
|
def _on_finalize(self):
|
2012-02-25 12:39:19 -06:00
|
|
|
super(login_kerberos, self)._on_finalize()
|
2012-02-15 09:26:42 -06:00
|
|
|
self.api.Backend.wsgi_dispatch.mount(self, self.key)
|
2012-02-19 09:02:38 -06:00
|
|
|
self.kerb_session_on_finalize()
|
add session manager and cache krb auth
This patch adds a session manager and support for caching
authentication in the session. Major elements of the patch are:
* Add a session manager to support cookie based sessions which
stores session data in a memcached entry.
* Add ipalib/krb_utils.py which contains functions to parse ccache
names, format principals, format KRB timestamps, and a KRB_CCache
class which reads ccache entry and allows one to extract information
such as the principal, credentials, credential timestamps, etc.
* Move krb constants defined in ipalib/rpc.py to ipa_krb_utils.py so
that all kerberos items are co-located.
* Modify javascript in ipa.js so that the IPA.command() RPC call
checks for authentication needed error response and if it receives
it sends a GET request to /ipa/login URL to refresh credentials.
* Add session_auth_duration config item to constants.py, used to
configure how long a session remains valid.
* Add parse_time_duration utility to ipalib/util.py. Used to parse the
session_auth_duration config item.
* Update the default.conf.5 man page to document session_auth_duration
config item (also added documentation for log_manager config items
which had been inadvertantly omitted from a previous commit).
* Add SessionError object to ipalib/errors.py
* Move Kerberos protection in Apache config from /ipa to /ipa/xml and
/ipa/login
* Add SessionCCache class to session.py to manage temporary Kerberos
ccache file in effect for the duration of an RPC command.
* Adds a krblogin plugin used to implement the /ipa/login
handler. login handler sets the session expiration time, currently
60 minutes or the expiration of the TGT, whichever is shorter. It
also copies the ccache provied by mod_auth_kerb into the session
data. The json handler will later extract and validate the ccache
belonging to the session.
* Refactored the WSGI handlers so that json and xlmrpc could have
independent behavior, this also moves where create and destroy
context occurs, now done in the individual handler rather than the
parent class.
* The json handler now looks up the session data, validates the ccache
bound to the session, if it's expired replies with authenicated
needed error.
* Add documentation to session.py. Fully documents the entire process,
got questions, read the doc.
* Add exclusions to make-lint as needed.
2012-02-06 12:29:56 -06:00
|
|
|
|
|
|
|
def __call__(self, environ, start_response):
|
2012-02-25 12:39:19 -06:00
|
|
|
self.debug('WSGI login_kerberos.__call__:')
|
add session manager and cache krb auth
This patch adds a session manager and support for caching
authentication in the session. Major elements of the patch are:
* Add a session manager to support cookie based sessions which
stores session data in a memcached entry.
* Add ipalib/krb_utils.py which contains functions to parse ccache
names, format principals, format KRB timestamps, and a KRB_CCache
class which reads ccache entry and allows one to extract information
such as the principal, credentials, credential timestamps, etc.
* Move krb constants defined in ipalib/rpc.py to ipa_krb_utils.py so
that all kerberos items are co-located.
* Modify javascript in ipa.js so that the IPA.command() RPC call
checks for authentication needed error response and if it receives
it sends a GET request to /ipa/login URL to refresh credentials.
* Add session_auth_duration config item to constants.py, used to
configure how long a session remains valid.
* Add parse_time_duration utility to ipalib/util.py. Used to parse the
session_auth_duration config item.
* Update the default.conf.5 man page to document session_auth_duration
config item (also added documentation for log_manager config items
which had been inadvertantly omitted from a previous commit).
* Add SessionError object to ipalib/errors.py
* Move Kerberos protection in Apache config from /ipa to /ipa/xml and
/ipa/login
* Add SessionCCache class to session.py to manage temporary Kerberos
ccache file in effect for the duration of an RPC command.
* Adds a krblogin plugin used to implement the /ipa/login
handler. login handler sets the session expiration time, currently
60 minutes or the expiration of the TGT, whichever is shorter. It
also copies the ccache provied by mod_auth_kerb into the session
data. The json handler will later extract and validate the ccache
belonging to the session.
* Refactored the WSGI handlers so that json and xlmrpc could have
independent behavior, this also moves where create and destroy
context occurs, now done in the individual handler rather than the
parent class.
* The json handler now looks up the session data, validates the ccache
bound to the session, if it's expired replies with authenicated
needed error.
* Add documentation to session.py. Fully documents the entire process,
got questions, read the doc.
* Add exclusions to make-lint as needed.
2012-02-06 12:29:56 -06:00
|
|
|
|
2015-03-30 03:17:55 -05:00
|
|
|
# Get the ccache created by mod_auth_gssapi
|
2012-02-25 12:39:19 -06:00
|
|
|
user_ccache_name=environ.get('KRB5CCNAME')
|
|
|
|
if user_ccache_name is None:
|
2012-02-28 07:41:07 -06:00
|
|
|
return self.internal_error(environ, start_response,
|
|
|
|
'login_kerberos: KRB5CCNAME not defined in HTTP request environment')
|
add session manager and cache krb auth
This patch adds a session manager and support for caching
authentication in the session. Major elements of the patch are:
* Add a session manager to support cookie based sessions which
stores session data in a memcached entry.
* Add ipalib/krb_utils.py which contains functions to parse ccache
names, format principals, format KRB timestamps, and a KRB_CCache
class which reads ccache entry and allows one to extract information
such as the principal, credentials, credential timestamps, etc.
* Move krb constants defined in ipalib/rpc.py to ipa_krb_utils.py so
that all kerberos items are co-located.
* Modify javascript in ipa.js so that the IPA.command() RPC call
checks for authentication needed error response and if it receives
it sends a GET request to /ipa/login URL to refresh credentials.
* Add session_auth_duration config item to constants.py, used to
configure how long a session remains valid.
* Add parse_time_duration utility to ipalib/util.py. Used to parse the
session_auth_duration config item.
* Update the default.conf.5 man page to document session_auth_duration
config item (also added documentation for log_manager config items
which had been inadvertantly omitted from a previous commit).
* Add SessionError object to ipalib/errors.py
* Move Kerberos protection in Apache config from /ipa to /ipa/xml and
/ipa/login
* Add SessionCCache class to session.py to manage temporary Kerberos
ccache file in effect for the duration of an RPC command.
* Adds a krblogin plugin used to implement the /ipa/login
handler. login handler sets the session expiration time, currently
60 minutes or the expiration of the TGT, whichever is shorter. It
also copies the ccache provied by mod_auth_kerb into the session
data. The json handler will later extract and validate the ccache
belonging to the session.
* Refactored the WSGI handlers so that json and xlmrpc could have
independent behavior, this also moves where create and destroy
context occurs, now done in the individual handler rather than the
parent class.
* The json handler now looks up the session data, validates the ccache
bound to the session, if it's expired replies with authenicated
needed error.
* Add documentation to session.py. Fully documents the entire process,
got questions, read the doc.
* Add exclusions to make-lint as needed.
2012-02-06 12:29:56 -06:00
|
|
|
|
2012-02-25 12:39:19 -06:00
|
|
|
return self.finalize_kerberos_acquisition('login_kerberos', user_ccache_name, environ, start_response)
|
add session manager and cache krb auth
This patch adds a session manager and support for caching
authentication in the session. Major elements of the patch are:
* Add a session manager to support cookie based sessions which
stores session data in a memcached entry.
* Add ipalib/krb_utils.py which contains functions to parse ccache
names, format principals, format KRB timestamps, and a KRB_CCache
class which reads ccache entry and allows one to extract information
such as the principal, credentials, credential timestamps, etc.
* Move krb constants defined in ipalib/rpc.py to ipa_krb_utils.py so
that all kerberos items are co-located.
* Modify javascript in ipa.js so that the IPA.command() RPC call
checks for authentication needed error response and if it receives
it sends a GET request to /ipa/login URL to refresh credentials.
* Add session_auth_duration config item to constants.py, used to
configure how long a session remains valid.
* Add parse_time_duration utility to ipalib/util.py. Used to parse the
session_auth_duration config item.
* Update the default.conf.5 man page to document session_auth_duration
config item (also added documentation for log_manager config items
which had been inadvertantly omitted from a previous commit).
* Add SessionError object to ipalib/errors.py
* Move Kerberos protection in Apache config from /ipa to /ipa/xml and
/ipa/login
* Add SessionCCache class to session.py to manage temporary Kerberos
ccache file in effect for the duration of an RPC command.
* Adds a krblogin plugin used to implement the /ipa/login
handler. login handler sets the session expiration time, currently
60 minutes or the expiration of the TGT, whichever is shorter. It
also copies the ccache provied by mod_auth_kerb into the session
data. The json handler will later extract and validate the ccache
belonging to the session.
* Refactored the WSGI handlers so that json and xlmrpc could have
independent behavior, this also moves where create and destroy
context occurs, now done in the individual handler rather than the
parent class.
* The json handler now looks up the session data, validates the ccache
bound to the session, if it's expired replies with authenicated
needed error.
* Add documentation to session.py. Fully documents the entire process,
got questions, read the doc.
* Add exclusions to make-lint as needed.
2012-02-06 12:29:56 -06:00
|
|
|
|
2012-02-28 07:41:07 -06:00
|
|
|
class login_password(Backend, KerberosSession, HTTP_Status):
|
add session manager and cache krb auth
This patch adds a session manager and support for caching
authentication in the session. Major elements of the patch are:
* Add a session manager to support cookie based sessions which
stores session data in a memcached entry.
* Add ipalib/krb_utils.py which contains functions to parse ccache
names, format principals, format KRB timestamps, and a KRB_CCache
class which reads ccache entry and allows one to extract information
such as the principal, credentials, credential timestamps, etc.
* Move krb constants defined in ipalib/rpc.py to ipa_krb_utils.py so
that all kerberos items are co-located.
* Modify javascript in ipa.js so that the IPA.command() RPC call
checks for authentication needed error response and if it receives
it sends a GET request to /ipa/login URL to refresh credentials.
* Add session_auth_duration config item to constants.py, used to
configure how long a session remains valid.
* Add parse_time_duration utility to ipalib/util.py. Used to parse the
session_auth_duration config item.
* Update the default.conf.5 man page to document session_auth_duration
config item (also added documentation for log_manager config items
which had been inadvertantly omitted from a previous commit).
* Add SessionError object to ipalib/errors.py
* Move Kerberos protection in Apache config from /ipa to /ipa/xml and
/ipa/login
* Add SessionCCache class to session.py to manage temporary Kerberos
ccache file in effect for the duration of an RPC command.
* Adds a krblogin plugin used to implement the /ipa/login
handler. login handler sets the session expiration time, currently
60 minutes or the expiration of the TGT, whichever is shorter. It
also copies the ccache provied by mod_auth_kerb into the session
data. The json handler will later extract and validate the ccache
belonging to the session.
* Refactored the WSGI handlers so that json and xlmrpc could have
independent behavior, this also moves where create and destroy
context occurs, now done in the individual handler rather than the
parent class.
* The json handler now looks up the session data, validates the ccache
bound to the session, if it's expired replies with authenicated
needed error.
* Add documentation to session.py. Fully documents the entire process,
got questions, read the doc.
* Add exclusions to make-lint as needed.
2012-02-06 12:29:56 -06:00
|
|
|
|
2012-02-25 12:39:19 -06:00
|
|
|
content_type = 'text/plain'
|
|
|
|
key = '/session/login_password'
|
add session manager and cache krb auth
This patch adds a session manager and support for caching
authentication in the session. Major elements of the patch are:
* Add a session manager to support cookie based sessions which
stores session data in a memcached entry.
* Add ipalib/krb_utils.py which contains functions to parse ccache
names, format principals, format KRB timestamps, and a KRB_CCache
class which reads ccache entry and allows one to extract information
such as the principal, credentials, credential timestamps, etc.
* Move krb constants defined in ipalib/rpc.py to ipa_krb_utils.py so
that all kerberos items are co-located.
* Modify javascript in ipa.js so that the IPA.command() RPC call
checks for authentication needed error response and if it receives
it sends a GET request to /ipa/login URL to refresh credentials.
* Add session_auth_duration config item to constants.py, used to
configure how long a session remains valid.
* Add parse_time_duration utility to ipalib/util.py. Used to parse the
session_auth_duration config item.
* Update the default.conf.5 man page to document session_auth_duration
config item (also added documentation for log_manager config items
which had been inadvertantly omitted from a previous commit).
* Add SessionError object to ipalib/errors.py
* Move Kerberos protection in Apache config from /ipa to /ipa/xml and
/ipa/login
* Add SessionCCache class to session.py to manage temporary Kerberos
ccache file in effect for the duration of an RPC command.
* Adds a krblogin plugin used to implement the /ipa/login
handler. login handler sets the session expiration time, currently
60 minutes or the expiration of the TGT, whichever is shorter. It
also copies the ccache provied by mod_auth_kerb into the session
data. The json handler will later extract and validate the ccache
belonging to the session.
* Refactored the WSGI handlers so that json and xlmrpc could have
independent behavior, this also moves where create and destroy
context occurs, now done in the individual handler rather than the
parent class.
* The json handler now looks up the session data, validates the ccache
bound to the session, if it's expired replies with authenicated
needed error.
* Add documentation to session.py. Fully documents the entire process,
got questions, read the doc.
* Add exclusions to make-lint as needed.
2012-02-06 12:29:56 -06:00
|
|
|
|
2012-02-25 12:39:19 -06:00
|
|
|
def _on_finalize(self):
|
|
|
|
super(login_password, self)._on_finalize()
|
|
|
|
self.api.Backend.wsgi_dispatch.mount(self, self.key)
|
|
|
|
self.kerb_session_on_finalize()
|
add session manager and cache krb auth
This patch adds a session manager and support for caching
authentication in the session. Major elements of the patch are:
* Add a session manager to support cookie based sessions which
stores session data in a memcached entry.
* Add ipalib/krb_utils.py which contains functions to parse ccache
names, format principals, format KRB timestamps, and a KRB_CCache
class which reads ccache entry and allows one to extract information
such as the principal, credentials, credential timestamps, etc.
* Move krb constants defined in ipalib/rpc.py to ipa_krb_utils.py so
that all kerberos items are co-located.
* Modify javascript in ipa.js so that the IPA.command() RPC call
checks for authentication needed error response and if it receives
it sends a GET request to /ipa/login URL to refresh credentials.
* Add session_auth_duration config item to constants.py, used to
configure how long a session remains valid.
* Add parse_time_duration utility to ipalib/util.py. Used to parse the
session_auth_duration config item.
* Update the default.conf.5 man page to document session_auth_duration
config item (also added documentation for log_manager config items
which had been inadvertantly omitted from a previous commit).
* Add SessionError object to ipalib/errors.py
* Move Kerberos protection in Apache config from /ipa to /ipa/xml and
/ipa/login
* Add SessionCCache class to session.py to manage temporary Kerberos
ccache file in effect for the duration of an RPC command.
* Adds a krblogin plugin used to implement the /ipa/login
handler. login handler sets the session expiration time, currently
60 minutes or the expiration of the TGT, whichever is shorter. It
also copies the ccache provied by mod_auth_kerb into the session
data. The json handler will later extract and validate the ccache
belonging to the session.
* Refactored the WSGI handlers so that json and xlmrpc could have
independent behavior, this also moves where create and destroy
context occurs, now done in the individual handler rather than the
parent class.
* The json handler now looks up the session data, validates the ccache
bound to the session, if it's expired replies with authenicated
needed error.
* Add documentation to session.py. Fully documents the entire process,
got questions, read the doc.
* Add exclusions to make-lint as needed.
2012-02-06 12:29:56 -06:00
|
|
|
|
2012-02-25 12:39:19 -06:00
|
|
|
def __call__(self, environ, start_response):
|
|
|
|
self.debug('WSGI login_password.__call__:')
|
add session manager and cache krb auth
This patch adds a session manager and support for caching
authentication in the session. Major elements of the patch are:
* Add a session manager to support cookie based sessions which
stores session data in a memcached entry.
* Add ipalib/krb_utils.py which contains functions to parse ccache
names, format principals, format KRB timestamps, and a KRB_CCache
class which reads ccache entry and allows one to extract information
such as the principal, credentials, credential timestamps, etc.
* Move krb constants defined in ipalib/rpc.py to ipa_krb_utils.py so
that all kerberos items are co-located.
* Modify javascript in ipa.js so that the IPA.command() RPC call
checks for authentication needed error response and if it receives
it sends a GET request to /ipa/login URL to refresh credentials.
* Add session_auth_duration config item to constants.py, used to
configure how long a session remains valid.
* Add parse_time_duration utility to ipalib/util.py. Used to parse the
session_auth_duration config item.
* Update the default.conf.5 man page to document session_auth_duration
config item (also added documentation for log_manager config items
which had been inadvertantly omitted from a previous commit).
* Add SessionError object to ipalib/errors.py
* Move Kerberos protection in Apache config from /ipa to /ipa/xml and
/ipa/login
* Add SessionCCache class to session.py to manage temporary Kerberos
ccache file in effect for the duration of an RPC command.
* Adds a krblogin plugin used to implement the /ipa/login
handler. login handler sets the session expiration time, currently
60 minutes or the expiration of the TGT, whichever is shorter. It
also copies the ccache provied by mod_auth_kerb into the session
data. The json handler will later extract and validate the ccache
belonging to the session.
* Refactored the WSGI handlers so that json and xlmrpc could have
independent behavior, this also moves where create and destroy
context occurs, now done in the individual handler rather than the
parent class.
* The json handler now looks up the session data, validates the ccache
bound to the session, if it's expired replies with authenicated
needed error.
* Add documentation to session.py. Fully documents the entire process,
got questions, read the doc.
* Add exclusions to make-lint as needed.
2012-02-06 12:29:56 -06:00
|
|
|
|
2012-02-25 12:39:19 -06:00
|
|
|
# Get the user and password parameters from the request
|
|
|
|
content_type = environ.get('CONTENT_TYPE', '').lower()
|
2012-02-29 08:25:40 -06:00
|
|
|
if not content_type.startswith('application/x-www-form-urlencoded'):
|
2012-02-28 07:41:07 -06:00
|
|
|
return self.bad_request(environ, start_response, "Content-Type must be application/x-www-form-urlencoded")
|
add session manager and cache krb auth
This patch adds a session manager and support for caching
authentication in the session. Major elements of the patch are:
* Add a session manager to support cookie based sessions which
stores session data in a memcached entry.
* Add ipalib/krb_utils.py which contains functions to parse ccache
names, format principals, format KRB timestamps, and a KRB_CCache
class which reads ccache entry and allows one to extract information
such as the principal, credentials, credential timestamps, etc.
* Move krb constants defined in ipalib/rpc.py to ipa_krb_utils.py so
that all kerberos items are co-located.
* Modify javascript in ipa.js so that the IPA.command() RPC call
checks for authentication needed error response and if it receives
it sends a GET request to /ipa/login URL to refresh credentials.
* Add session_auth_duration config item to constants.py, used to
configure how long a session remains valid.
* Add parse_time_duration utility to ipalib/util.py. Used to parse the
session_auth_duration config item.
* Update the default.conf.5 man page to document session_auth_duration
config item (also added documentation for log_manager config items
which had been inadvertantly omitted from a previous commit).
* Add SessionError object to ipalib/errors.py
* Move Kerberos protection in Apache config from /ipa to /ipa/xml and
/ipa/login
* Add SessionCCache class to session.py to manage temporary Kerberos
ccache file in effect for the duration of an RPC command.
* Adds a krblogin plugin used to implement the /ipa/login
handler. login handler sets the session expiration time, currently
60 minutes or the expiration of the TGT, whichever is shorter. It
also copies the ccache provied by mod_auth_kerb into the session
data. The json handler will later extract and validate the ccache
belonging to the session.
* Refactored the WSGI handlers so that json and xlmrpc could have
independent behavior, this also moves where create and destroy
context occurs, now done in the individual handler rather than the
parent class.
* The json handler now looks up the session data, validates the ccache
bound to the session, if it's expired replies with authenicated
needed error.
* Add documentation to session.py. Fully documents the entire process,
got questions, read the doc.
* Add exclusions to make-lint as needed.
2012-02-06 12:29:56 -06:00
|
|
|
|
2012-02-25 12:39:19 -06:00
|
|
|
method = environ.get('REQUEST_METHOD', '').upper()
|
|
|
|
if method == 'POST':
|
|
|
|
query_string = read_input(environ)
|
|
|
|
else:
|
2012-02-28 07:41:07 -06:00
|
|
|
return self.bad_request(environ, start_response, "HTTP request method must be POST")
|
add session manager and cache krb auth
This patch adds a session manager and support for caching
authentication in the session. Major elements of the patch are:
* Add a session manager to support cookie based sessions which
stores session data in a memcached entry.
* Add ipalib/krb_utils.py which contains functions to parse ccache
names, format principals, format KRB timestamps, and a KRB_CCache
class which reads ccache entry and allows one to extract information
such as the principal, credentials, credential timestamps, etc.
* Move krb constants defined in ipalib/rpc.py to ipa_krb_utils.py so
that all kerberos items are co-located.
* Modify javascript in ipa.js so that the IPA.command() RPC call
checks for authentication needed error response and if it receives
it sends a GET request to /ipa/login URL to refresh credentials.
* Add session_auth_duration config item to constants.py, used to
configure how long a session remains valid.
* Add parse_time_duration utility to ipalib/util.py. Used to parse the
session_auth_duration config item.
* Update the default.conf.5 man page to document session_auth_duration
config item (also added documentation for log_manager config items
which had been inadvertantly omitted from a previous commit).
* Add SessionError object to ipalib/errors.py
* Move Kerberos protection in Apache config from /ipa to /ipa/xml and
/ipa/login
* Add SessionCCache class to session.py to manage temporary Kerberos
ccache file in effect for the duration of an RPC command.
* Adds a krblogin plugin used to implement the /ipa/login
handler. login handler sets the session expiration time, currently
60 minutes or the expiration of the TGT, whichever is shorter. It
also copies the ccache provied by mod_auth_kerb into the session
data. The json handler will later extract and validate the ccache
belonging to the session.
* Refactored the WSGI handlers so that json and xlmrpc could have
independent behavior, this also moves where create and destroy
context occurs, now done in the individual handler rather than the
parent class.
* The json handler now looks up the session data, validates the ccache
bound to the session, if it's expired replies with authenicated
needed error.
* Add documentation to session.py. Fully documents the entire process,
got questions, read the doc.
* Add exclusions to make-lint as needed.
2012-02-06 12:29:56 -06:00
|
|
|
|
2012-02-25 12:39:19 -06:00
|
|
|
try:
|
2015-09-14 05:52:29 -05:00
|
|
|
query_dict = parse_qs(query_string)
|
2015-07-30 09:49:29 -05:00
|
|
|
except Exception as e:
|
2012-02-28 07:41:07 -06:00
|
|
|
return self.bad_request(environ, start_response, "cannot parse query data")
|
2012-02-25 12:39:19 -06:00
|
|
|
|
|
|
|
user = query_dict.get('user', None)
|
|
|
|
if user is not None:
|
|
|
|
if len(user) == 1:
|
|
|
|
user = user[0]
|
|
|
|
else:
|
2012-02-28 07:41:07 -06:00
|
|
|
return self.bad_request(environ, start_response, "more than one user parameter")
|
2012-02-25 12:39:19 -06:00
|
|
|
else:
|
2012-02-28 07:41:07 -06:00
|
|
|
return self.bad_request(environ, start_response, "no user specified")
|
2012-02-25 12:39:19 -06:00
|
|
|
|
2012-11-15 04:21:16 -06:00
|
|
|
# allows login in the form user@SERVER_REALM or user@server_realm
|
|
|
|
# FIXME: uppercasing may be removed when better handling of UPN
|
|
|
|
# is introduced
|
|
|
|
|
|
|
|
parts = normalize_name(user)
|
|
|
|
|
|
|
|
if "domain" in parts:
|
|
|
|
# username is of the form user@SERVER_REALM or user@server_realm
|
|
|
|
|
|
|
|
# check whether the realm is server's realm
|
|
|
|
# Users from other realms are not supported
|
|
|
|
# (they do not have necessary LDAP entry, LDAP connect will fail)
|
|
|
|
|
|
|
|
if parts["domain"].upper()==self.api.env.realm:
|
|
|
|
user=parts["name"]
|
|
|
|
else:
|
|
|
|
return self.unauthorized(environ, start_response, '', 'denied')
|
|
|
|
|
|
|
|
elif "flatname" in parts:
|
|
|
|
# username is of the form NetBIOS\user
|
|
|
|
return self.unauthorized(environ, start_response, '', 'denied')
|
|
|
|
|
|
|
|
else:
|
|
|
|
# username is of the form user or of some wild form, e.g.
|
|
|
|
# user@REALM1@REALM2 or NetBIOS1\NetBIOS2\user (see normalize_name)
|
|
|
|
|
|
|
|
# wild form username will fail at kinit, so nothing needs to be done
|
|
|
|
pass
|
|
|
|
|
2012-02-25 12:39:19 -06:00
|
|
|
password = query_dict.get('password', None)
|
|
|
|
if password is not None:
|
|
|
|
if len(password) == 1:
|
|
|
|
password = password[0]
|
|
|
|
else:
|
2012-02-28 07:41:07 -06:00
|
|
|
return self.bad_request(environ, start_response, "more than one password parameter")
|
2012-02-25 12:39:19 -06:00
|
|
|
else:
|
2012-02-28 07:41:07 -06:00
|
|
|
return self.bad_request(environ, start_response, "no password specified")
|
2012-02-25 12:39:19 -06:00
|
|
|
|
|
|
|
# Get the ccache we'll use and attempt to get credentials in it with user,password
|
|
|
|
ipa_ccache_name = get_ipa_ccache_name()
|
|
|
|
try:
|
|
|
|
self.kinit(user, self.api.env.realm, password, ipa_ccache_name)
|
2014-07-14 13:39:00 -05:00
|
|
|
except PasswordExpired as e:
|
|
|
|
return self.unauthorized(environ, start_response, str(e), 'password-expired')
|
|
|
|
except InvalidSessionPassword as e:
|
|
|
|
return self.unauthorized(environ, start_response, str(e), 'invalid-password')
|
2016-03-22 05:11:36 -05:00
|
|
|
except KrbPrincipalExpired as e:
|
|
|
|
return self.unauthorized(environ,
|
|
|
|
start_response,
|
|
|
|
str(e),
|
|
|
|
'krbprincipal-expired')
|
2016-04-20 00:39:53 -05:00
|
|
|
except UserLocked as e:
|
|
|
|
return self.unauthorized(environ,
|
|
|
|
start_response,
|
|
|
|
str(e),
|
|
|
|
'user-locked')
|
2012-02-25 12:39:19 -06:00
|
|
|
|
|
|
|
return self.finalize_kerberos_acquisition('login_password', ipa_ccache_name, environ, start_response)
|
|
|
|
|
|
|
|
def kinit(self, user, realm, password, ccache_name):
|
2014-01-09 07:54:30 -06:00
|
|
|
# get http service ccache as an armor for FAST to enable OTP authentication
|
2015-03-16 10:43:10 -05:00
|
|
|
armor_principal = str(krb5_format_service_principal_name(
|
|
|
|
'HTTP', self.api.env.host, realm))
|
2014-05-29 07:47:17 -05:00
|
|
|
keytab = paths.IPA_KEYTAB
|
2014-01-09 07:54:30 -06:00
|
|
|
armor_name = "%sA_%s" % (krbccache_prefix, user)
|
|
|
|
armor_path = os.path.join(krbccache_dir, armor_name)
|
|
|
|
|
|
|
|
self.debug('Obtaining armor ccache: principal=%s keytab=%s ccache=%s',
|
|
|
|
armor_principal, keytab, armor_path)
|
|
|
|
|
2015-03-16 10:43:10 -05:00
|
|
|
try:
|
|
|
|
ipautil.kinit_keytab(armor_principal, paths.IPA_KEYTAB, armor_path)
|
2015-07-20 09:04:07 -05:00
|
|
|
except gssapi.exceptions.GSSError as e:
|
2015-08-31 07:04:33 -05:00
|
|
|
raise CCacheError(message=unicode(e))
|
2014-01-09 07:54:30 -06:00
|
|
|
|
2012-02-25 12:39:19 -06:00
|
|
|
# Format the user as a kerberos principal
|
|
|
|
principal = krb5_format_principal_name(user, realm)
|
|
|
|
|
2015-03-16 10:43:10 -05:00
|
|
|
try:
|
|
|
|
ipautil.kinit_password(principal, password, ccache_name,
|
|
|
|
armor_ccache_name=armor_path)
|
|
|
|
|
|
|
|
self.debug('Cleanup the armor ccache')
|
|
|
|
ipautil.run(
|
|
|
|
[paths.KDESTROY, '-A', '-c', armor_path],
|
|
|
|
env={'KRB5CCNAME': armor_path},
|
|
|
|
raiseonerr=False)
|
|
|
|
except RuntimeError as e:
|
|
|
|
if ('kinit: Cannot read password while '
|
|
|
|
'getting initial credentials') in str(e):
|
|
|
|
raise PasswordExpired(principal=principal, message=unicode(e))
|
2016-03-22 05:11:36 -05:00
|
|
|
elif ('kinit: Client\'s entry in database'
|
|
|
|
' has expired while getting initial credentials') in str(e):
|
|
|
|
raise KrbPrincipalExpired(principal=principal,
|
|
|
|
message=unicode(e))
|
2016-04-20 00:39:53 -05:00
|
|
|
elif ('kinit: Clients credentials have been revoked '
|
|
|
|
'while getting initial credentials') in str(e):
|
|
|
|
raise UserLocked(principal=principal,
|
|
|
|
message=unicode(e))
|
2015-03-16 10:43:10 -05:00
|
|
|
raise InvalidSessionPassword(principal=principal,
|
|
|
|
message=unicode(e))
|
2012-02-19 09:02:38 -06:00
|
|
|
|
2016-04-20 00:39:53 -05:00
|
|
|
|
2012-06-06 07:38:08 -05:00
|
|
|
class change_password(Backend, HTTP_Status):
|
|
|
|
|
|
|
|
content_type = 'text/plain'
|
|
|
|
key = '/session/change_password'
|
|
|
|
|
|
|
|
def _on_finalize(self):
|
|
|
|
super(change_password, self)._on_finalize()
|
|
|
|
self.api.Backend.wsgi_dispatch.mount(self, self.key)
|
|
|
|
|
|
|
|
def __call__(self, environ, start_response):
|
|
|
|
self.info('WSGI change_password.__call__:')
|
|
|
|
|
|
|
|
# Get the user and password parameters from the request
|
|
|
|
content_type = environ.get('CONTENT_TYPE', '').lower()
|
|
|
|
if not content_type.startswith('application/x-www-form-urlencoded'):
|
|
|
|
return self.bad_request(environ, start_response, "Content-Type must be application/x-www-form-urlencoded")
|
|
|
|
|
|
|
|
method = environ.get('REQUEST_METHOD', '').upper()
|
|
|
|
if method == 'POST':
|
|
|
|
query_string = read_input(environ)
|
|
|
|
else:
|
|
|
|
return self.bad_request(environ, start_response, "HTTP request method must be POST")
|
|
|
|
|
|
|
|
try:
|
2015-09-14 05:52:29 -05:00
|
|
|
query_dict = parse_qs(query_string)
|
2015-07-30 09:49:29 -05:00
|
|
|
except Exception as e:
|
2012-06-06 07:38:08 -05:00
|
|
|
return self.bad_request(environ, start_response, "cannot parse query data")
|
|
|
|
|
|
|
|
data = {}
|
2014-05-23 08:54:18 -05:00
|
|
|
for field in ('user', 'old_password', 'new_password', 'otp'):
|
2012-06-06 07:38:08 -05:00
|
|
|
value = query_dict.get(field, None)
|
|
|
|
if value is not None:
|
|
|
|
if len(value) == 1:
|
|
|
|
data[field] = value[0]
|
|
|
|
else:
|
|
|
|
return self.bad_request(environ, start_response, "more than one %s parameter"
|
|
|
|
% field)
|
2014-05-23 08:54:18 -05:00
|
|
|
elif field != 'otp': # otp is optional
|
2012-06-06 07:38:08 -05:00
|
|
|
return self.bad_request(environ, start_response, "no %s specified" % field)
|
|
|
|
|
|
|
|
# start building the response
|
|
|
|
self.info("WSGI change_password: start password change of user '%s'", data['user'])
|
|
|
|
status = HTTP_STATUS_SUCCESS
|
|
|
|
response_headers = [('Content-Type', 'text/html; charset=utf-8')]
|
|
|
|
title = 'Password change rejected'
|
|
|
|
result = 'error'
|
|
|
|
policy_error = None
|
|
|
|
|
Use DN objects instead of strings
* Convert every string specifying a DN into a DN object
* Every place a dn was manipulated in some fashion it was replaced by
the use of DN operators
* Add new DNParam parameter type for parameters which are DN's
* DN objects are used 100% of the time throughout the entire data
pipeline whenever something is logically a dn.
* Many classes now enforce DN usage for their attributes which are
dn's. This is implmented via ipautil.dn_attribute_property(). The
only permitted types for a class attribute specified to be a DN are
either None or a DN object.
* Require that every place a dn is used it must be a DN object.
This translates into lot of::
assert isinstance(dn, DN)
sprinkled through out the code. Maintaining these asserts is
valuable to preserve DN type enforcement. The asserts can be
disabled in production.
The goal of 100% DN usage 100% of the time has been realized, these
asserts are meant to preserve that.
The asserts also proved valuable in detecting functions which did
not obey their function signatures, such as the baseldap pre and
post callbacks.
* Moved ipalib.dn to ipapython.dn because DN class is shared with all
components, not just the server which uses ipalib.
* All API's now accept DN's natively, no need to convert to str (or
unicode).
* Removed ipalib.encoder and encode/decode decorators. Type conversion
is now explicitly performed in each IPASimpleLDAPObject method which
emulates a ldap.SimpleLDAPObject method.
* Entity & Entry classes now utilize DN's
* Removed __getattr__ in Entity & Entity clases. There were two
problems with it. It presented synthetic Python object attributes
based on the current LDAP data it contained. There is no way to
validate synthetic attributes using code checkers, you can't search
the code to find LDAP attribute accesses (because synthetic
attriutes look like Python attributes instead of LDAP data) and
error handling is circumscribed. Secondly __getattr__ was hiding
Python internal methods which broke class semantics.
* Replace use of methods inherited from ldap.SimpleLDAPObject via
IPAdmin class with IPAdmin methods. Directly using inherited methods
was causing us to bypass IPA logic. Mostly this meant replacing the
use of search_s() with getEntry() or getList(). Similarly direct
access of the LDAP data in classes using IPAdmin were replaced with
calls to getValue() or getValues().
* Objects returned by ldap2.find_entries() are now compatible with
either the python-ldap access methodology or the Entity/Entry access
methodology.
* All ldap operations now funnel through the common
IPASimpleLDAPObject giving us a single location where we interface
to python-ldap and perform conversions.
* The above 4 modifications means we've greatly reduced the
proliferation of multiple inconsistent ways to perform LDAP
operations. We are well on the way to having a single API in IPA for
doing LDAP (a long range goal).
* All certificate subject bases are now DN's
* DN objects were enhanced thusly:
- find, rfind, index, rindex, replace and insert methods were added
- AVA, RDN and DN classes were refactored in immutable and mutable
variants, the mutable variants are EditableAVA, EditableRDN and
EditableDN. By default we use the immutable variants preserving
important semantics. To edit a DN cast it to an EditableDN and
cast it back to DN when done editing. These issues are fully
described in other documentation.
- first_key_match was removed
- DN equalty comparison permits comparison to a basestring
* Fixed ldapupdate to work with DN's. This work included:
- Enhance test_updates.py to do more checking after applying
update. Add test for update_from_dict(). Convert code to use
unittest classes.
- Consolidated duplicate code.
- Moved code which should have been in the class into the class.
- Fix the handling of the 'deleteentry' update action. It's no longer
necessary to supply fake attributes to make it work. Detect case
where subsequent update applies a change to entry previously marked
for deletetion. General clean-up and simplification of the
'deleteentry' logic.
- Rewrote a couple of functions to be clearer and more Pythonic.
- Added documentation on the data structure being used.
- Simplfy the use of update_from_dict()
* Removed all usage of get_schema() which was being called prior to
accessing the .schema attribute of an object. If a class is using
internal lazy loading as an optimization it's not right to require
users of the interface to be aware of internal
optimization's. schema is now a property and when the schema
property is accessed it calls a private internal method to perform
the lazy loading.
* Added SchemaCache class to cache the schema's from individual
servers. This was done because of the observation we talk to
different LDAP servers, each of which may have it's own
schema. Previously we globally cached the schema from the first
server we connected to and returned that schema in all contexts. The
cache includes controls to invalidate it thus forcing a schema
refresh.
* Schema caching is now senstive to the run time context. During
install and upgrade the schema can change leading to errors due to
out-of-date cached schema. The schema cache is refreshed in these
contexts.
* We are aware of the LDAP syntax of all LDAP attributes. Every
attribute returned from an LDAP operation is passed through a
central table look-up based on it's LDAP syntax. The table key is
the LDAP syntax it's value is a Python callable that returns a
Python object matching the LDAP syntax. There are a handful of LDAP
attributes whose syntax is historically incorrect
(e.g. DistguishedNames that are defined as DirectoryStrings). The
table driven conversion mechanism is augmented with a table of
hard coded exceptions.
Currently only the following conversions occur via the table:
- dn's are converted to DN objects
- binary objects are converted to Python str objects (IPA
convention).
- everything else is converted to unicode using UTF-8 decoding (IPA
convention).
However, now that the table driven conversion mechanism is in place
it would be trivial to do things such as converting attributes
which have LDAP integer syntax into a Python integer, etc.
* Expected values in the unit tests which are a DN no longer need to
use lambda expressions to promote the returned value to a DN for
equality comparison. The return value is automatically promoted to
a DN. The lambda expressions have been removed making the code much
simpler and easier to read.
* Add class level logging to a number of classes which did not support
logging, less need for use of root_logger.
* Remove ipaserver/conn.py, it was unused.
* Consolidated duplicate code wherever it was found.
* Fixed many places that used string concatenation to form a new
string rather than string formatting operators. This is necessary
because string formatting converts it's arguments to a string prior
to building the result string. You can't concatenate a string and a
non-string.
* Simplify logic in rename_managed plugin. Use DN operators to edit
dn's.
* The live version of ipa-ldap-updater did not generate a log file.
The offline version did, now both do.
https://fedorahosted.org/freeipa/ticket/1670
https://fedorahosted.org/freeipa/ticket/1671
https://fedorahosted.org/freeipa/ticket/1672
https://fedorahosted.org/freeipa/ticket/1673
https://fedorahosted.org/freeipa/ticket/1674
https://fedorahosted.org/freeipa/ticket/1392
https://fedorahosted.org/freeipa/ticket/2872
2012-05-13 06:36:35 -05:00
|
|
|
bind_dn = DN((self.api.Object.user.primary_key.name, data['user']),
|
|
|
|
self.api.env.container_user, self.api.env.basedn)
|
2012-06-06 07:38:08 -05:00
|
|
|
|
|
|
|
try:
|
2014-05-23 08:54:18 -05:00
|
|
|
pw = data['old_password']
|
|
|
|
if data.get('otp'):
|
|
|
|
pw = data['old_password'] + data['otp']
|
2015-06-22 05:58:43 -05:00
|
|
|
conn = ldap2(self.api)
|
2014-05-23 08:54:18 -05:00
|
|
|
conn.connect(bind_dn=bind_dn, bind_pw=pw)
|
2012-06-06 07:38:08 -05:00
|
|
|
except (NotFound, ACIError):
|
|
|
|
result = 'invalid-password'
|
|
|
|
message = 'The old password or username is not correct.'
|
2015-07-30 09:49:29 -05:00
|
|
|
except Exception as e:
|
2012-06-06 07:38:08 -05:00
|
|
|
message = "Could not connect to LDAP server."
|
|
|
|
self.error("change_password: cannot authenticate '%s' to LDAP server: %s",
|
|
|
|
data['user'], str(e))
|
|
|
|
else:
|
|
|
|
try:
|
2014-05-23 08:54:18 -05:00
|
|
|
conn.modify_password(bind_dn, data['new_password'], data['old_password'], skip_bind=True)
|
2015-07-30 09:49:29 -05:00
|
|
|
except ExecutionError as e:
|
2012-06-06 07:38:08 -05:00
|
|
|
result = 'policy-error'
|
|
|
|
policy_error = escape(str(e))
|
|
|
|
message = "Password change was rejected: %s" % escape(str(e))
|
2015-07-30 09:49:29 -05:00
|
|
|
except Exception as e:
|
2012-06-06 07:38:08 -05:00
|
|
|
message = "Could not change the password"
|
|
|
|
self.error("change_password: cannot change password of '%s': %s",
|
|
|
|
data['user'], str(e))
|
|
|
|
else:
|
|
|
|
result = 'ok'
|
|
|
|
title = "Password change successful"
|
|
|
|
message = "Password was changed."
|
|
|
|
finally:
|
|
|
|
if conn.isconnected():
|
2015-04-24 06:09:47 -05:00
|
|
|
conn.disconnect()
|
2012-06-06 07:38:08 -05:00
|
|
|
|
|
|
|
self.info('%s: %s', status, message)
|
|
|
|
|
|
|
|
response_headers.append(('X-IPA-Pwchange-Result', result))
|
|
|
|
if policy_error:
|
|
|
|
response_headers.append(('X-IPA-Pwchange-Policy-Error', policy_error))
|
|
|
|
|
|
|
|
start_response(status, response_headers)
|
2014-05-28 10:38:40 -05:00
|
|
|
output = _success_template % dict(title=str(title),
|
|
|
|
message=str(message))
|
2012-06-06 07:38:08 -05:00
|
|
|
return [output]
|
2012-06-06 21:54:16 -05:00
|
|
|
|
2014-05-28 10:38:40 -05:00
|
|
|
class sync_token(Backend, HTTP_Status):
|
|
|
|
content_type = 'text/plain'
|
|
|
|
key = '/session/sync_token'
|
|
|
|
|
|
|
|
class OTPSyncRequest(univ.Sequence):
|
|
|
|
OID = "2.16.840.1.113730.3.8.10.6"
|
|
|
|
|
|
|
|
componentType = namedtype.NamedTypes(
|
|
|
|
namedtype.NamedType('firstCode', univ.OctetString()),
|
|
|
|
namedtype.NamedType('secondCode', univ.OctetString()),
|
|
|
|
namedtype.OptionalNamedType('tokenDN', univ.OctetString())
|
|
|
|
)
|
|
|
|
|
|
|
|
def _on_finalize(self):
|
|
|
|
super(sync_token, self)._on_finalize()
|
|
|
|
self.api.Backend.wsgi_dispatch.mount(self, self.key)
|
|
|
|
|
|
|
|
def __call__(self, environ, start_response):
|
|
|
|
# Make sure this is a form request.
|
|
|
|
content_type = environ.get('CONTENT_TYPE', '').lower()
|
|
|
|
if not content_type.startswith('application/x-www-form-urlencoded'):
|
|
|
|
return self.bad_request(environ, start_response, "Content-Type must be application/x-www-form-urlencoded")
|
|
|
|
|
|
|
|
# Make sure this is a POST request.
|
|
|
|
method = environ.get('REQUEST_METHOD', '').upper()
|
|
|
|
if method == 'POST':
|
|
|
|
query_string = read_input(environ)
|
|
|
|
else:
|
|
|
|
return self.bad_request(environ, start_response, "HTTP request method must be POST")
|
|
|
|
|
|
|
|
# Parse the query string to a dictionary.
|
|
|
|
try:
|
2015-09-14 05:52:29 -05:00
|
|
|
query_dict = parse_qs(query_string)
|
2015-07-30 09:49:29 -05:00
|
|
|
except Exception as e:
|
2014-05-28 10:38:40 -05:00
|
|
|
return self.bad_request(environ, start_response, "cannot parse query data")
|
|
|
|
data = {}
|
|
|
|
for field in ('user', 'password', 'first_code', 'second_code', 'token'):
|
|
|
|
value = query_dict.get(field, None)
|
|
|
|
if value is not None:
|
|
|
|
if len(value) == 1:
|
|
|
|
data[field] = value[0]
|
|
|
|
else:
|
|
|
|
return self.bad_request(environ, start_response, "more than one %s parameter"
|
|
|
|
% field)
|
|
|
|
elif field != 'token':
|
|
|
|
return self.bad_request(environ, start_response, "no %s specified" % field)
|
|
|
|
|
|
|
|
# Create the request control.
|
|
|
|
sr = self.OTPSyncRequest()
|
|
|
|
sr.setComponentByName('firstCode', data['first_code'])
|
|
|
|
sr.setComponentByName('secondCode', data['second_code'])
|
|
|
|
if 'token' in data:
|
|
|
|
try:
|
|
|
|
token_dn = DN(data['token'])
|
|
|
|
except ValueError:
|
|
|
|
token_dn = DN((self.api.Object.otptoken.primary_key.name, data['token']),
|
|
|
|
self.api.env.container_otp, self.api.env.basedn)
|
|
|
|
|
|
|
|
sr.setComponentByName('tokenDN', str(token_dn))
|
|
|
|
rc = ldap.controls.RequestControl(sr.OID, True, encoder.encode(sr))
|
|
|
|
|
|
|
|
# Resolve the user DN
|
|
|
|
bind_dn = DN((self.api.Object.user.primary_key.name, data['user']),
|
|
|
|
self.api.env.container_user, self.api.env.basedn)
|
|
|
|
|
|
|
|
# Start building the response.
|
|
|
|
status = HTTP_STATUS_SUCCESS
|
|
|
|
response_headers = [('Content-Type', 'text/html; charset=utf-8')]
|
|
|
|
title = 'Token sync rejected'
|
|
|
|
|
|
|
|
# Perform the synchronization.
|
2015-06-22 05:58:43 -05:00
|
|
|
conn = ldap2(self.api)
|
2014-05-28 10:38:40 -05:00
|
|
|
try:
|
|
|
|
conn.connect(bind_dn=bind_dn,
|
|
|
|
bind_pw=data['password'],
|
|
|
|
serverctrls=[rc,])
|
|
|
|
result = 'ok'
|
|
|
|
title = "Token sync successful"
|
|
|
|
message = "Token was synchronized."
|
|
|
|
except (NotFound, ACIError):
|
|
|
|
result = 'invalid-credentials'
|
|
|
|
message = 'The username, password or token codes are not correct.'
|
2015-07-30 09:49:29 -05:00
|
|
|
except Exception as e:
|
2014-05-28 10:38:40 -05:00
|
|
|
result = 'error'
|
|
|
|
message = "Could not connect to LDAP server."
|
|
|
|
self.error("token_sync: cannot authenticate '%s' to LDAP server: %s",
|
|
|
|
data['user'], str(e))
|
|
|
|
finally:
|
|
|
|
if conn.isconnected():
|
2015-04-24 06:09:47 -05:00
|
|
|
conn.disconnect()
|
2014-05-28 10:38:40 -05:00
|
|
|
|
|
|
|
# Report status and return.
|
|
|
|
response_headers.append(('X-IPA-TokenSync-Result', result))
|
|
|
|
start_response(status, response_headers)
|
|
|
|
output = _success_template % dict(title=str(title),
|
|
|
|
message=str(message))
|
|
|
|
return [output]
|
2012-06-06 21:54:16 -05:00
|
|
|
|
|
|
|
class xmlserver_session(xmlserver, KerberosSession):
|
|
|
|
"""
|
|
|
|
XML RPC server protected with session auth.
|
|
|
|
"""
|
|
|
|
|
|
|
|
key = '/session/xml'
|
|
|
|
|
2015-06-22 05:58:43 -05:00
|
|
|
def __init__(self, api):
|
|
|
|
super(xmlserver_session, self).__init__(api)
|
2015-06-22 04:59:33 -05:00
|
|
|
name = '{0}_{1}'.format(self.__class__.__name__, id(self))
|
|
|
|
auth_mgr = AuthManagerKerb(name)
|
2016-06-29 08:53:52 -05:00
|
|
|
session_mgr = get_session_mgr()
|
2012-06-06 21:54:16 -05:00
|
|
|
session_mgr.auth_mgr.register(auth_mgr.name, auth_mgr)
|
|
|
|
|
|
|
|
def _on_finalize(self):
|
|
|
|
super(xmlserver_session, self)._on_finalize()
|
|
|
|
self.kerb_session_on_finalize()
|
|
|
|
|
|
|
|
def need_login(self, start_response):
|
|
|
|
status = '401 Unauthorized'
|
|
|
|
headers = []
|
|
|
|
response = ''
|
|
|
|
|
|
|
|
self.debug('xmlserver_session: %s need login', status)
|
|
|
|
|
|
|
|
start_response(status, headers)
|
|
|
|
return [response]
|
|
|
|
|
|
|
|
def __call__(self, environ, start_response):
|
|
|
|
'''
|
|
|
|
'''
|
|
|
|
|
|
|
|
self.debug('WSGI xmlserver_session.__call__:')
|
|
|
|
|
|
|
|
# Load the session data
|
2016-06-29 08:53:52 -05:00
|
|
|
session_mgr = get_session_mgr()
|
2012-06-06 21:54:16 -05:00
|
|
|
session_data = session_mgr.load_session_data(environ.get('HTTP_COOKIE'))
|
|
|
|
session_id = session_data['session_id']
|
|
|
|
|
|
|
|
self.debug('xmlserver_session.__call__: session_id=%s start_timestamp=%s access_timestamp=%s expiration_timestamp=%s',
|
|
|
|
session_id,
|
|
|
|
fmt_time(session_data['session_start_timestamp']),
|
|
|
|
fmt_time(session_data['session_access_timestamp']),
|
|
|
|
fmt_time(session_data['session_expiration_timestamp']))
|
|
|
|
|
|
|
|
ccache_data = session_data.get('ccache_data')
|
|
|
|
|
|
|
|
# Redirect to /ipa/xml if no Kerberos credentials
|
|
|
|
if ccache_data is None:
|
|
|
|
self.debug('xmlserver_session.__call_: no ccache, need TGT')
|
|
|
|
return self.need_login(start_response)
|
|
|
|
|
|
|
|
ipa_ccache_name = bind_ipa_ccache(ccache_data)
|
|
|
|
|
|
|
|
# Redirect to /ipa/xml if Kerberos credentials are expired
|
2015-07-20 09:04:07 -05:00
|
|
|
creds = get_credentials_if_valid(ccache_name=ipa_ccache_name)
|
|
|
|
if not creds:
|
2012-06-06 21:54:16 -05:00
|
|
|
self.debug('xmlserver_session.__call_: ccache expired, deleting session, need login')
|
|
|
|
# The request is finished with the ccache, destroy it.
|
|
|
|
release_ipa_ccache(ipa_ccache_name)
|
|
|
|
return self.need_login(start_response)
|
|
|
|
|
|
|
|
# Update the session expiration based on the Kerberos expiration
|
2015-07-20 09:04:07 -05:00
|
|
|
endtime = creds.lifetime + time.time()
|
2012-06-06 21:54:16 -05:00
|
|
|
self.update_session_expiration(session_data, endtime)
|
|
|
|
|
|
|
|
# Store the session data in the per-thread context
|
|
|
|
setattr(context, 'session_data', session_data)
|
|
|
|
|
|
|
|
environ['KRB5CCNAME'] = ipa_ccache_name
|
|
|
|
|
|
|
|
try:
|
|
|
|
response = super(xmlserver_session, self).__call__(environ, start_response)
|
|
|
|
finally:
|
|
|
|
# Kerberos may have updated the ccache data during the
|
|
|
|
# execution of the command therefore we need refresh our
|
|
|
|
# copy of it in the session data so the next command sees
|
|
|
|
# the same state of the ccache.
|
|
|
|
#
|
|
|
|
# However we must be careful not to restore the ccache
|
|
|
|
# data in the session data if it was explicitly deleted
|
|
|
|
# during the execution of the command. For example the
|
|
|
|
# logout command removes the ccache data from the session
|
|
|
|
# data to invalidate the session credentials.
|
|
|
|
|
2015-07-30 10:29:39 -05:00
|
|
|
if 'ccache_data' in session_data:
|
2012-06-06 21:54:16 -05:00
|
|
|
session_data['ccache_data'] = load_ccache_data(ipa_ccache_name)
|
|
|
|
|
|
|
|
# The request is finished with the ccache, destroy it.
|
|
|
|
release_ipa_ccache(ipa_ccache_name)
|
|
|
|
# Store the session data.
|
|
|
|
session_mgr.store_session_data(session_data)
|
|
|
|
destroy_context()
|
|
|
|
|
|
|
|
return response
|