[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]

Re: [Freeipa-devel] [PATCH 61] Cache authentication in session



On 01/25/2012 09:16 AM, Rob Crittenden wrote:
John Dennis wrote:
On 01/23/2012 06:15 PM, John Dennis wrote:
Rebased patch attached (includes contents of previous patch 60).

The issues with ipa_memcached belonged to patch 59, that patch was
rebased and resubmitted.

I cannot reproduce the looping problem you saw. The only thing I can
think of is that you were running with SELinux enabled and currently
ipa_memcached requires SELinux to be disabled otherwise the whole
caching mechanism fails.

O.K., let's try this again with the patch actually attached :-)

NACK. It doesn't work if ipa_memcached is not configured (-M install
option).

I tested this last night then picked up testing again this morning and
was greeted with the attached image. I'm not sure if this is a browser
issue, the fact that my browser was being redirected from a VM to the
display on my desktop or the current cosmic rays.

We also need a way to do a logout. The user can do a kdestroy and still
have an active session. If this isn't covered in the any current tickets
please open a new one. As far as I can tell you provide a facility for
invalidating a cache entry, I'm just not sure if that is enough for the
UI guys to hook in to.

I think you were right about SELinux. When I put it into permissive mode
then the caching worked. The UI is much more responsive now.

Attached is a modified patch.

The logic concerning how Kerberos auth is acquired was modified, we no longer use redirects. Instead we return an error and the javascript code in the browser sends a GET to the login page to refresh the session credentials. If that succeeds it resubmits the POST that previously was denied. This works much better, no longer are there any browser glitches, it seems to function very smoothly with good performance.

I also added a config item, session_auth_duration so that admins can control how long a session will be valid before credentials need to be refreshed. The default.config man page was updated to document the new option. It's easy to specify using simple notation such as "1 hour, 30 minutes" or "1h30m", etc. I added a new utility parse_time_duration() to read the duration specification.

I also modified how files were being used to for the Kerberos ccache. The previous code allocated one file per session, but there wasn't a good way to clean up these files. Now there is just one ccache file per process and it only exists for the duration of the request after which we remove it. The ccache is stored in the memcached session data. We refresh the memcached copy of the ccache at the end of the request to make sure any credentials modified/added during the request are preserved.

The submit comments reasonably detailed, you should take a look at those for more information.


--
John Dennis <jdennis redhat com>

Looking to carve out IT costs?
www.redhat.com/carveoutcosts/
>From 95780a7b2d101468d281e5b5f5ee215941e9addd Mon Sep 17 00:00:00 2001
From: John Dennis <jdennis redhat com>
Date: Thu, 19 Jan 2012 15:30:29 -0500
Subject: [PATCH 61-2] add session manager and cache krb auth
Content-Type: text/plain; charset="utf-8"
Content-Transfer-Encoding: 8bit

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.
---
 install/conf/ipa.conf          |   19 +-
 install/ui/ipa.js              |   71 +++-
 ipa-client/man/default.conf.5  |   49 ++-
 ipalib/constants.py            |    3 +
 ipalib/errors.py               |   16 +-
 ipalib/krb_utils.py            |  331 ++++++++++++
 ipalib/rpc.py                  |   10 +-
 ipalib/session.py              | 1098 ++++++++++++++++++++++++++++++++++++++++
 ipalib/util.py                 |  100 ++++
 ipaserver/plugins/xmlserver.py |    3 +-
 ipaserver/rpcserver.py         |  174 ++++++-
 make-lint                      |    4 +
 12 files changed, 1847 insertions(+), 31 deletions(-)
 create mode 100644 ipalib/krb_utils.py
 create mode 100644 ipalib/session.py

diff --git a/install/conf/ipa.conf b/install/conf/ipa.conf
index f256dab..676086a 100644
--- a/install/conf/ipa.conf
+++ b/install/conf/ipa.conf
@@ -44,8 +44,23 @@ WSGIScriptReloading Off
 
 KrbConstrainedDelegationLock ipa
 
-# Protect /ipa with Kerberos
-<Location "/ipa">
+# Protect UI login url with Kerberos
+<Location "/ipa/login">
+  AuthType Kerberos
+  AuthName "Kerberos Login"
+  KrbMethodNegotiate on
+  KrbMethodK5Passwd off
+  KrbServiceName HTTP
+  KrbAuthRealms $REALM
+  Krb5KeyTab /etc/httpd/conf/ipa.keytab
+  KrbSaveCredentials on
+  KrbConstrainedDelegation on
+  Require valid-user
+  ErrorDocument 401 /ipa/errors/unauthorized.html
+</Location>
+
+# Protect xmlrpc url with Kerberos
+<Location "/ipa/xml">
   AuthType Kerberos
   AuthName "Kerberos Login"
   KrbMethodNegotiate on
diff --git a/install/ui/ipa.js b/install/ui/ipa.js
index 90d1029..2344c37 100644
--- a/install/ui/ipa.js
+++ b/install/ui/ipa.js
@@ -59,6 +59,7 @@ var IPA = function() {
         // if current path matches live server path, use live data
         if (that.url && window.location.pathname.substring(0, that.url.length) === that.url) {
             that.json_url = params.url || '/ipa/json';
+            that.login_url = params.url || '/ipa/login'; // FIXME, what about the other case below?
 
         } else { // otherwise use fixtures
             that.json_path = params.url || "test/data";
@@ -285,6 +286,31 @@ var IPA = function() {
     return that;
 }();
 
+IPA.get_credentials = function() {
+    var status;
+
+    function error_handler(xhr, text_status, error_thrown) {
+        status = xhr.status;
+    }
+
+
+    function success_handler(data, text_status, xhr) {
+        status = xhr.status;
+    }
+
+    var request = {
+        url: IPA.login_url,
+	async: false,
+	type: "GET",
+        success: success_handler,
+        error: error_handler
+    };
+
+    $.ajax(request);
+
+    return status;
+}
+
 /**
  * Call an IPA command over JSON-RPC.
  *
@@ -374,6 +400,39 @@ IPA.command = function(spec) {
             dialog.open();
         }
 
+        /*
+         * Special error handler used the first time this command is
+         * submitted. It checks to see if the session credentials need
+         * to be acquired and if so sends a request to a special url
+         * to establish the sesion credentials. If acquiring the
+         * session credentials is successful it simply resubmits the
+         * exact same command after setting the error handler back to
+         * the normal error handler. If aquiring the session
+         * credentials fails the normal error handler is invoked to
+         * process the error returned from the attempt to aquire the
+         * session credentials.
+         */
+        function error_handler_login(xhr, text_status, error_thrown) {
+            if (xhr.status === 401) {
+                var login_status = IPA.get_credentials();
+
+                if (login_status === 200) {
+                    that.request.error = error_handler
+                    $.ajax(that.request);
+                } else {
+                    // error_handler() calls IPA.hide_activity_icon()
+                    error_handler.call(this, xhr, text_status, error_thrown);
+                }
+            }
+        }
+
+        /*
+         * Normal error handler, handles all errors.
+         * error_handler_login() is initially used to trap the
+         * special case need to aquire session credentials, this is
+         * not a true error, rather it's an indication an extra step
+         * needs to be taken before normal processing can continue.
+         */
         function error_handler(xhr, text_status, error_thrown) {
 
             IPA.hide_activity_icon();
@@ -468,20 +527,20 @@ IPA.command = function(spec) {
             }
         }
 
-        var data = {
+        that.data = {
             method: that.get_command(),
             params: [that.args, that.options]
         };
 
-        var request = {
-            url: IPA.json_url || IPA.json_path + '/' + (that.name || data.method) + '.json',
-            data: JSON.stringify(data),
+        that.request = {
+            url: IPA.json_url || IPA.json_path + '/' + (that.name || that.data.method) + '.json',
+            data: JSON.stringify(that.data),
             success: success_handler,
-            error: error_handler
+            error: error_handler_login
         };
 
         IPA.display_activity_icon();
-        $.ajax(request);
+        $.ajax(that.request);
     };
 
     that.get_failed = function(command, result, text_status, xhr) {
diff --git a/ipa-client/man/default.conf.5 b/ipa-client/man/default.conf.5
index 938eb2c..91b535a 100644
--- a/ipa-client/man/default.conf.5
+++ b/ipa-client/man/default.conf.5
@@ -49,11 +49,11 @@ Values should not be quoted, the quotes will not be stripped.
 
 .np
     # Wrong \- don't include quotes
-    verbose = "9"
+    verbose = "True"
 
     # Right \- Properly formatted options
-    verbose = 9
-    verbose=9
+    verbose = True
+    verbose=True
 .fi
 
 Options must appear in the section named [global]. There are no other sections defined or used currently.
@@ -80,8 +80,43 @@ Specifies the hostname of the dogtag CA server. The default is the hostname of t
 .B context <context>
 Specifies the context that IPA is being executed in. IPA may operate differently depending on the context. The current defined contexts are cli and server. Additionally this value is used to load /etc/ipa/\fBcontext\fR.conf to provide context\-specific configuration. For example, if you want to always perform client requests in verbose mode but do not want to have verbose enabled on the server, add the verbose option to \fI/etc/ipa/cli.conf\fR.
 .TP
+.B verbose <boolean>
+When True provides more information. Specifically this sets the global log level to "info".
+.TP
 .B debug <boolean>
-If True then logging will be much more verbose. Default is False.
+When True provides detailed information. Specifically this set the global log level to "debug". Default is False.
+.TP
+.B log_logger_XXX <comma separated list of regexps>
+loggers matching regexp will be assigned XXX level.
+.IP
+Logger levels can be explicitly specified for specific loggers as
+opposed to a global logging level. Specific loggers are indiciated
+by a list of regular expressions bound to a level. If a logger's
+name matches the regexp then it is assigned that level. This config item
+must begin with "log_logger_level_" and then be
+followed by a symbolic or numeric log level, for example:
+.IP
+  log_logger_level_debug = ipalib\\.dn\\..*
+.IP
+  log_logger_level_35 = ipalib\\.plugins\\.dogtag
+.IP
+The first line says any logger belonging to the ipalib.dn module
+will have it's level configured to debug.
+.IP
+The second line say the ipa.plugins.dogtag logger will be
+configured to level 35.
+.IP
+This config item is useful when you only want to see the log output from
+one or more selected loggers. Turning on the global debug flag will produce
+an enormous amount of output. This allows you to leave the global debug flag
+off and selectively enable output from a specific logger. Typically loggers
+are bound to classes and plugins.
+.IP
+Note: logger names are a dot ('.') separated list forming a path
+in the logger tree.  The dot character is also a regular
+expression metacharacter (matches any character) therefore you
+will usually need to escape the dot in the logger names by
+preceeding it with a backslash.
 .TP
 .B domain <domain>
 The domain of the IPA server e.g. example.com.
@@ -128,12 +163,12 @@ If the IPA server fails to start and this value is True the server will attempt
 .B validate_api <boolean>
 Used internally in the IPA source package to verify that the API has not changed. This is used to prevent regressions. If it is true then some errors are ignored so enough of the IPA framework can be loaded to verify all of the API, even if optional components are not installed. The default is False.
 .TP
-.B verbose <integer>
-Generates more output. The default is 0 which generates no additional output. On the client a setting of 1 will provide more information on the command and show the servers the client contacts. A setting of 2 or higher will display the XML\-RPC request. This value has no effect on the server.
-.TP
 .B xmlrpc_uri <URI>
 Specifies the URI of the XML\-RPC server for a client. This is used by IPA and some external tools as well, such as ipa\-getcert. e.g. https://ipa.example.com/ipa/xml
 .TP
+.B session_auth_duration <time duration spec>
+Specifies the length of time authentication credentials cached in the session are valid. After the duration expires credentials will be automatically reacquired. Examples are "2 hours", "1h:30m", "10 minutes", "5min, 30sec".
+.TP
 The following define the containers for the IPA server. Containers define where in the DIT that objects can be found. The full location is the value of container + basedn.
   container_accounts: cn=accounts
   container_applications: cn=applications,cn=configs,cn=policies
diff --git a/ipalib/constants.py b/ipalib/constants.py
index d984bbc..7a1e3d2 100644
--- a/ipalib/constants.py
+++ b/ipalib/constants.py
@@ -116,6 +116,9 @@ DEFAULT_CONFIG = (
     ('webui_prod', True),
     ('webui_assets_dir', None),
 
+    # Maximum time before a session expires forcing credentials to be reacquired.
+    ('session_auth_duration', '1h'),
+
     # Debugging:
     ('verbose', 0),
     ('debug', False),
diff --git a/ipalib/errors.py b/ipalib/errors.py
index f115f0c..115802f 100644
--- a/ipalib/errors.py
+++ b/ipalib/errors.py
@@ -65,7 +65,9 @@ current block assignments:
 
             - **1100 - 1199**  `KerberosError` and its subclasses
 
-            - **1200 - 1999**  *Reserved for future use*
+            - **1200 - 1299**  `SessionError` and its subclasses
+
+            - **1300 - 1999**  *Reserved for future use*
 
         - **2000 - 2999**  `AuthorizationError` and its subclasses
 
@@ -598,6 +600,18 @@ class CannotResolveKDC(KerberosError):
     format = _('Cannot resolve KDC for requested realm')
 
 
+class SessionError(AuthenticationError):
+    """
+    **1200** Base class for Session errors (*1200 - 1299*).
+
+    For example:
+
+    """
+
+    errno = 1200
+    format= _('Session error')
+
+
 ##############################################################################
 # 2000 - 2999: Authorization errors
 class AuthorizationError(PublicError):
diff --git a/ipalib/krb_utils.py b/ipalib/krb_utils.py
new file mode 100644
index 0000000..f9bc9af
--- /dev/null
+++ b/ipalib/krb_utils.py
@@ -0,0 +1,331 @@
+# Authors: John Dennis <jdennis redhat com>
+#
+# Copyright (C) 2012  Red Hat
+# see file 'COPYING' for use and warranty information
+#
+# 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.
+#
+# 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
+# along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+import krbV
+import time
+import re
+from ipapython.ipa_log_manager import *
+
+#-------------------------------------------------------------------------------
+
+# Kerberos constants, should be defined in krbV, but aren't
+KRB5_GC_CACHED = 0x2
+
+# Kerberos error codes, should be defined in krbV, but aren't
+KRB5_CC_NOTFOUND                = -1765328243 # Matching credential not found
+KRB5_FCC_NOFILE                 = -1765328189 # No credentials cache found
+KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN = -1765328377 # Server not found in Kerberos database
+KRB5KRB_AP_ERR_TKT_EXPIRED      = -1765328352 # Ticket expired
+KRB5_FCC_PERM                   = -1765328190 # Credentials cache permissions incorrect
+KRB5_CC_FORMAT                  = -1765328185 # Bad format in credentials cache
+KRB5_REALM_CANT_RESOLVE         = -1765328164 # Cannot resolve network address for KDC in requested realm
+
+
+krb_ticket_expiration_threshold = 60*5 # number of seconds to accmodate clock skew
+krb5_time_fmt = '%m/%d/%y %H:%M:%S'
+ccache_name_re = re.compile(r'^((\w+):)?(.+)')
+
+#-------------------------------------------------------------------------------
+
+def krb5_parse_ccache(name):
+    '''
+    Given a Kerberos ccache name parse it into it's scheme and
+    location components. Currently valid values for the scheme
+    are:
+
+      * FILE
+      * MEMORY
+
+    The scheme is always returned as upper case. If the scheme
+    does not exist it defaults to FILE.
+
+    :parameters:
+      name
+        The name of the Kerberos ccache.
+    :returns:
+      A two-tuple of (scheme, ccache)
+    '''
+    match = ccache_name_re.search(name)
+    if match:
+        scheme = match.group(2)
+        location = match.group(3)
+        if scheme is None:
+            scheme = 'FILE'
+        else:
+            scheme = scheme.upper()
+
+        return scheme, location
+    else:
+        raise ValueError('Invalid ccache name = "%s"' % name)
+
+def krb5_format_principal_name(user, realm):
+    '''
+    Given a Kerberos user principal name and a Kerberos realm
+    return the Kerberos V5 user principal name.
+
+    :parameters:
+      user
+        User principal name.
+      realm
+        The Kerberos realm the user exists in.
+    :returns:
+      Kerberos V5 user principal name.
+    '''
+    return '%s %s' % (user, realm)
+
+def krb5_format_service_principal_name(service, host, realm):
+    '''
+
+    Given a Kerberos service principal name, the host where the
+    service is running and a Kerberos realm return the Kerberos V5
+    service principal name.
+
+    :parameters:
+      service
+        Service principal name.
+      host
+        The DNS name of the host where the service is located.
+      realm
+        The Kerberos realm the service exists in.
+    :returns:
+      Kerberos V5 service principal name.
+    '''
+    return '%s/%s %s' % (service, host, realm)
+
+def krb5_format_tgt_principal_name(realm):
+    '''
+    Given a Kerberos realm return the Kerberos V5 TGT name.
+
+    :parameters:
+      realm
+        The Kerberos realm the TGT exists in.
+    :returns:
+      Kerberos V5 TGT name.
+    '''
+    return krb5_format_service_principal_name('krbtgt', realm, realm)
+
+def krb5_format_time(timestamp):
+    '''
+    Given a UNIX timestamp format it into a string in the same
+    manner the MIT Kerberos library does. Kerberos timestamps are
+    always in local time.
+
+    :parameters:
+      timestamp
+        Unix timestamp
+    :returns:
+      formated string
+    '''
+    return time.strftime(krb5_time_fmt, time.localtime(timestamp))
+
+class KRB5_CCache(object):
+    '''
+    Kerberos stores a TGT (Ticket Granting Ticket) and the service
+    tickets bound to it in a ccache (credentials cache). ccaches are
+    bound to a Kerberos user principal. This class opens a Kerberos
+    ccache and allows one to manipulate it. Most useful is the
+    extraction of ticket entries (cred's) in the ccache and the
+    ability to examine their attributes.
+    '''
+
+    def __init__(self, ccache):
+        '''
+        :parameters:
+          ccache
+            The name of a Kerberos ccache used to hold Kerberos tickets.
+        :returns:
+          `KRB5_CCache` object encapsulting the ccache.
+        '''
+        log_mgr.get_logger(self, True)
+        self.context = None
+        self.scheme = None
+        self.name = None
+        self.ccache = None
+        self.principal = None
+
+        self.debug('opening ccache file "%s"', ccache)
+        try:
+            self.context = krbV.default_context()
+            self.scheme, self.name = krb5_parse_ccache(ccache)
+            self.ccache = krbV.CCache(name=str(ccache), context=self.context)
+            self.principal = self.ccache.principal()
+        except krbV.Krb5Error, e:
+            error_code = e.args[0]
+            message = e.args[1]
+            if error_code == KRB5_FCC_NOFILE:
+                raise ValueError('"%s", ccache="%s"' % (message, ccache))
+            else:
+                raise e
+
+    def ccache_str(self):
+        '''
+        A Kerberos ccache is identified by a name comprised of a
+        scheme and location component. This function returns that
+        canonical name. See `krb5_parse_ccache()`
+
+        :returns:
+          The name of ccache with it's scheme and location components.
+        '''
+
+        return '%s:%s' % (self.scheme, self.name)
+
+    def __str__(self):
+        return 'cache="%s" principal="%s"' % (self.ccache_str(), self.principal.name)
+
+    def get_credentials(self, principal):
+        '''
+        Given a Kerberos principal return the krbV credentials
+        tuple describing the credential. If the principal does
+        not exist in the ccache a KeyError is raised.
+
+        :parameters:
+          principal
+            The Kerberos principal whose ticket is being retrieved.
+            The principal may be either a string formatted as a
+            Kerberos V5 principal or it may be a `krbV.Principal`
+            object.
+        :returns:
+          A krbV credentials tuple. If the principal is not in the
+          ccache a KeyError is raised.
+
+        '''
+
+        if isinstance(principal, krbV.Principal):
+            krbV_principal = principal
+        else:
+            try:
+                krbV_principal = krbV.Principal(str(principal), self.context)
+            except Exception, e:
+                self.error('could not create krbV principal from "%s", %s', principal, e)
+                raise e
+
+        creds_tuple = (self.principal,
+                       krbV_principal,
+                       (0, None),    # keyblock: (enctype, contents)
+                       (0, 0, 0, 0), # times: (authtime, starttime, endtime, renew_till)
+                       0,0,          # is_skey, ticket_flags
+                       None,         # addrlist
+                       None,         # ticket_data
+                       None,         # second_ticket_data
+                       None)         # adlist
+        try:
+            cred = self.ccache.get_credentials(creds_tuple, KRB5_GC_CACHED)
+        except krbV.Krb5Error, e:
+            error_code = e.args[0]
+            if error_code == KRB5_CC_NOTFOUND:
+                self.debug('"%s" credential not found in "%s" ccache',
+                           krbV_principal.name, self.ccache_str()) #pylint: disable=E1103
+                raise KeyError('"%s" credential not found in "%s" ccache' % \
+                               (krbV_principal.name, self.ccache_str())) #pylint: disable=E1103
+            raise e
+        except Exception, e:
+            raise e
+
+        return cred
+
+    def get_credential_times(self, principal):
+        '''
+        Given a Kerberos principal return the ticket timestamps if the
+        principal's ticket in the ccache is valid.  If the principal
+        does not exist in the ccache a KeyError is raised.
+
+        The return credential time values are Unix timestamps in
+        localtime.
+
+        The returned timestamps are:
+
+        authtime
+          The time when the ticket was issued.
+        starttime
+          The time when the ticket becomes valid.
+        endtime
+          The time when the ticket expires.
+        renew_till
+          The time when the ticket becomes no longer renewable (if renewable).
+
+        :parameters:
+          principal
+            The Kerberos principal whose ticket is being validated.
+            The principal may be either a string formatted as a
+            Kerberos V5 principal or it may be a `krbV.Principal`
+            object.
+        :returns:
+            return authtime, starttime, endtime, renew_till
+        '''
+
+        if isinstance(principal, krbV.Principal):
+            krbV_principal = principal
+        else:
+            try:
+                krbV_principal = krbV.Principal(str(principal), self.context)
+            except Exception, e:
+                self.error('could not create krbV principal from "%s", %s', principal, e)
+                raise e
+
+        try:
+            cred = self.get_credentials(krbV_principal)
+            authtime, starttime, endtime, renew_till = cred[3]
+
+            self.debug('principal=%s, authtime=%s, starttime=%s, endtime=%s, renew_till=%s',
+                       krbV_principal.name, #pylint: disable=E1103
+                       krb5_format_time(authtime), krb5_format_time(starttime),
+                       krb5_format_time(endtime), krb5_format_time(renew_till))
+
+            return authtime, starttime, endtime, renew_till
+
+        except KeyError, e:
+            raise e
+        except Exception, e:
+            self.error('get_credential_times failed, principal="%s" error="%s"', krbV_principal.name, e) #pylint: disable=E1103
+            raise e
+
+    def credential_is_valid(self, principal):
+        '''
+        Given a Kerberos principal return a boolean indicating if the
+        principal's ticket in the ccache is valid. If the ticket is
+        not in the ccache False is returned. If the ticket
+        exists in the ccache it's validity is checked and returned.
+
+        :parameters:
+          principal
+            The Kerberos principal whose ticket is being validated.
+            The principal may be either a string formatted as a
+            Kerberos V5 principal or it may be a `krbV.Principal`
+            object.
+        :returns:
+          True if the principal's ticket exists and is valid. False if
+          the ticket does not exist or if the ticket is not valid.
+        '''
+
+        try:
+            authtime, starttime, endtime, renew_till = self.get_credential_times(principal)
+        except KeyError, e:
+            return False
+        except Exception, e:
+            self.error('credential_is_valid failed, principal="%s" error="%s"', principal, e)
+            raise e
+
+
+        now = time.time()
+        if starttime > now:
+            return False
+        if endtime < now:
+            return False
+        return True
+
+
diff --git a/ipalib/rpc.py b/ipalib/rpc.py
index 8ec3a2f..e3e1254 100644
--- a/ipalib/rpc.py
+++ b/ipalib/rpc.py
@@ -48,14 +48,8 @@ import socket
 from ipapython.nsslib import NSSHTTPS, NSSConnection
 from nss.error import NSPRError
 from urllib2 import urlparse
-
-# Some Kerberos error definitions from krb5.h
-KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN = (-1765328377L)
-KRB5KRB_AP_ERR_TKT_EXPIRED      = (-1765328352L)
-KRB5_FCC_PERM                   = (-1765328190L)
-KRB5_FCC_NOFILE                 = (-1765328189L)
-KRB5_CC_FORMAT                  = (-1765328185L)
-KRB5_REALM_CANT_RESOLVE         = (-1765328164L)
+from ipalib.krb_utils import KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN, KRB5KRB_AP_ERR_TKT_EXPIRED, \
+                             KRB5_FCC_PERM, KRB5_FCC_NOFILE, KRB5_CC_FORMAT, KRB5_REALM_CANT_RESOLVE
 
 def xml_wrap(value):
     """
diff --git a/ipalib/session.py b/ipalib/session.py
new file mode 100644
index 0000000..a586439
--- /dev/null
+++ b/ipalib/session.py
@@ -0,0 +1,1098 @@
+# Authors: John Dennis <jdennis redhat com>
+#
+# Copyright (C) 2011  Red Hat
+# see file 'COPYING' for use and warranty information
+#
+# 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.
+#
+# 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
+# along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+import memcache
+import Cookie
+import random
+import errors
+import os
+import re
+import time
+from text import _
+from ipapython.ipa_log_manager import *
+from ipalib.krb_utils import *
+
+__doc__ = '''
+Session Support for IPA
+John Dennis <jdennis redhat com>
+
+Goals
+=====
+
+Provide per-user session data caching which persists between
+requests. Desired features are:
+
+* Integrates cleanly with minimum impact on existing infrastructure.
+
+* Provides maximum security balanced against real-world performance
+  demands.
+
+* Sessions must be able to be revoked (flushed).
+
+* Should be flexible and easy to use for developers.
+
+* Should leverage existing technology and code to the maximum extent
+  possible to avoid re-invention, excessive implementation time and to
+  benefit from robustness in field proven components commonly shared
+  in the open source community.
+
+* Must support multiple independent processes which share session
+  data.
+
+* System must function correctly if session data is available or not.
+
+* Must be high performance.
+
+* Should not be tied to specific web servers or browsers. Should
+  integrate with our chosen WSGI model.
+
+Issues
+======
+
+Cookies
+-------
+
+Most session implementations are based on the use of cookies. Cookies
+have some inherent problems.
+
+* User has the option to disable cookies.
+
+* User stored cookie data is not secure. Can be mitigated by setting
+  flags indicating the cookie is only to be used with SSL secured HTTP
+  connections to specific web resources and setting the cookie to
+  expire at session termination. Most modern browsers enforce these.
+
+Where to store session data?
+----------------------------
+
+Session data may be stored on either on the client or on the
+server. Storing session data on the client addresses the problem of
+session data availability when requests are serviced by independent web
+servers because the session data travels with the request. However
+there are data size limitations. Storing session data on the client
+also exposes sensitive data but this can be mitigated by encrypting
+the session data such that only the server can decrypt it.
+
+The more conventional approach is to bind session data to a unique
+name, the session ID. The session ID is transmitted to the client and
+the session data is paired with the session ID on the server in a
+associative data store. The session data is retrieved by the server
+using the session ID when the receiving the request. This eliminates
+exposing sensitive session data on the client along with limitations
+on data size. It however introduces the issue of session data
+availability when requests are serviced by more than one server
+process.
+
+Multi-process session data availability
+---------------------------------------
+
+Apache (and other web servers) fork child processes to handle requests
+in parallel. Also web servers may be deployed in a farm where requests
+are load balanced in round robin fashion across different nodes. In
+both cases session data cannot be stored in the memory of a server
+process because it is not available to other processes, either sibling
+children of a master server process or server processes on distinct
+nodes.
+
+Typically this is addressed by storing session data in a SQL
+database. When a request is received by a server process containing a
+session ID in it's cookie data the session ID is used to perform a SQL
+query and the resulting data is then attached to the request as it
+proceeds through the request processing pipeline. This of course
+introduces coherency issues.
+
+For IPA the introduction of a SQL database dependency is undesired and
+should be avoided.
+
+Session data may also be shared by independent processes by storing
+the session data in files.
+
+An alternative solution which has gained considerable popularity
+recently is the use of a fast memory based caching server. Data is
+stored in a single process memory and may be queried and set via a
+light weight protocol using standard socket mechanisms, memcached is
+one example. A typical use is to optimize SQL queries by storing a SQL
+result in shared memory cache avoiding the more expensive SQL
+operation. But the memory cache has distinct advantages in non-SQL
+situations as well.
+
+Possible implementations for use by IPA
+=======================================
+
+Apache Sessions
+---------------
+
+Apache has 2.3 has implemented session support via these modules:
+
+  mod_session
+    Overarching session support based on cookies.
+
+    See: http://httpd.apache.org/docs/2.3/mod/mod_session.html
+
+  mod_session_cookie
+    Stores session data in the client.
+
+    See: http://httpd.apache.org/docs/2.3/mod/mod_session_cookie.html
+
+  mod_session_crypto
+    Encrypts session data for security. Encryption key is shared
+    configuration parameter visible to all Apache processes and is
+    stored in a configuration file.
+
+    See: http://httpd.apache.org/docs/2.3/mod/mod_session_crypto.html
+
+  mod_session_dbd
+    Stores session data in a SQL database permitting multiple
+    processes to access and share the same session data.
+
+    See: http://httpd.apache.org/docs/2.3/mod/mod_session_dbd.html
+
+Issues with Apache sessions
+~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Although Apache has implemented generic session support and Apache is
+our web server of preference it nonetheless introduces issues for IPA.
+
+  * Session support is only available in httpd >= 2.3 which at the
+    time of this writing is currently only available as a Beta release
+    from upstream. We currently only ship httpd 2.2, the same is true
+    for other distributions.
+
+  * We could package and ship the sessions modules as a temporary
+    package in httpd 2.2 environments. But this has the following
+    consequences:
+
+      - The code has to be backported. the module API has changed
+        slightly between httpd 2.2 and 2.3. The backporting is not
+        terribly difficult and a proof of concept has been
+        implemented.
+
+      - We would then be on the hook to package and maintain a special
+        case Apache package. This is maintenance burden as well as a
+        distribution packaging burden. Both of which would be best
+        avoided if possible.
+
+  * The design of the Apache session modules is such that they can
+    only be manipulated by other Apache modules. The ability of
+    consumers of the session data to control the session data is
+    simplistic, constrained and static during the period the request
+    is processed. Request handlers which are not native Apache modules
+    (e.g. IPA via WSGI) can only examine the session data
+    via request headers and reset it in response headers.
+
+  * Shared session data is available exclusively via SQL.
+
+However using the 2.3 Apache session modules would give us robust
+session support implemented in C based on standardized Apache
+interfaces which are widely used.
+
+Python Web Frameworks
+---------------------
+
+Virtually every Python web framework supports cookie based sessions,
+e.g. Django, Twisted, Zope, Turbogears etc. Early on in IPA we decided
+to avoid the use of these frameworks. Trying to pull in just one part
+of these frameworks just to get session support would be problematic
+because the code does not function outside it's framework.
+
+IPA implemented sessions
+------------------------
+
+Originally it was believed the path of least effort was to utilize
+existing session support, most likely what would be provided by
+Apache. However there are enough basic modular components available in
+native Python and other standard packages it should be possible to
+provide session support meeting the aforementioned goals with a modest
+implementation effort. Because we're leveraging existing components
+the implementation difficulties are subsumed by other components which
+have already been field proven and have community support. This is a
+smart strategy.
+
+Proposed Solution
+=================
+
+Our interface to the web server is via WSGI which invokes a callback
+per request passing us an environmental context for the request. For
+this discussion we'll name the the WSGI callback "application()", a
+conventional name in WSGI parlance.
+
+Shared session data will be handled by memcached. We will create one
+instance of memcached on each server node dedicated to IPA
+exclusively. Communication with memcached will be via a UNIX socket
+located in the file system under /var/run/ipa_memcached. It will be
+protected by file permissions and optionally SELinux policy.
+
+In application() we examine the request cookies and if there is an IPA
+session cookie with a session ID we retrieve the session data from our
+memcached instance.
+
+The session data will be a Python dict. IPA components will read or
+write their session information by using a pre-agreed upon name
+(e.g. key) in the dict. This is a very flexible system and consistent
+with how we pass data in most parts of IPA.
+
+If the session data is not available an empty session data dict will
+be created.
+
+How does this session data travel with the request in the IPA
+pipeline? In IPA we use the HTTP request/response to implement RPC. In
+application() we convert the request into a procedure call passing it
+arguments derived from the HTTP request. The passed parameters are
+specific to the RPC method being invoked. The context the RPC call is
+executing in is not passed as an RPC parameter.
+
+How would the contextual information such as session data be bound to
+the request and hence the RPC call?
+
+In IPA when a RPC invocation is being prepared from a request we
+recognize this will only ever be processed serially by one Python
+thread. A thread local dict called "context" is allocated for each
+thread. The context dict is cleared in between requests (e.g. RPC method
+invocations). The per-thread context dict is populated during the
+lifetime of the request and is used as a global data structure unique to
+the request that various IPA component can read from and write to with
+the assurance the data is unique to the current request and/or method
+call.
+
+The session data dict will be written into the context dict under the
+session key before the RPC method begins execution. Thus session data
+can be read and written by any IPA component by accessing
+``context.session``.
+
+When the RPC method finishes execution the session data bound to the
+request/method is retrieved from the context and written back to the
+memcached instance. The session ID is set in the response sent back to
+the client in the ``Set-Cookie`` header along with the flags
+controlling it's usage.
+
+Issues and details
+------------------
+
+IPA code cannot depend on session data being present, however it
+should always update session data with the hope it will be available
+in the future. Session data may not be available because:
+
+  * This is the first request from the user and no session data has
+    been created yet.
+
+  * The user may have cookies disabled.
+
+  * The session data may have been flushed. memcached operates with
+    a fixed memory allocation and will flush entries on a LRU basis,
+    like with any cache there is no guarantee of persistence.
+
+    Also we may have have deliberately expired or deleted session
+    data, see below.
+
+Cookie manipulation is done via the standard Python Cookie module.
+
+Session cookies will be set to only persist as long as the browser has
+the session open. They will be tagged so the the browser only returns
+the session ID on SSL secured HTTP requests. They will not be visible
+to Javascript in the browser.
+
+Session ID's will be created by using 48 bits of random data and
+converted to 12 hexadecimal digits. Newly generated session ID's will
+be checked for prior existence to handle the unlikely case the random
+number repeats.
+
+memcached will have significantly higher performance than a SQL or file
+based storage solution. Communication is effectively though a pipe
+(UNIX socket) using a very simple protocol and the data is held
+entirely in process memory. memcached also scales easily, it is easy
+to add more memcached processes and distribute the load across them.
+At this point in time we don't anticipate the need for this.
+
+A very nice feature of the Python memcached module is that when a data
+item is written to the cache it is done with standard Python pickling
+(pickling is a standard Python mechanism to marshal and unmarshal
+Python objects). We adopt the convention the object written to cache
+will be a dict to meet our internal data handling conventions. The
+pickling code will recursively handle nested objects in the dict. Thus
+we gain a lot of flexibility using standard Python data structures to
+store and retrieve our session data without having to author and debug
+code to marshal and unmarshal the data if some other storage mechanism
+had been used. This is a significant implementation win. Of course
+some common sense limitations need to observed when deciding on what
+is written to the session cache keeping in mind the data is shared
+between processes and it should not be excessively large (a
+configurable option)
+
+We can set an expiration on memcached entries. We may elect to do that
+to force session data to be refreshed periodically. For example we may
+wish the client to present fresh credentials on a periodic basis even
+if the cached credentials are otherwise within their validity period.
+
+We can explicitly delete session data if for some reason we believe it
+is stale, invalid or compromised.
+
+memcached also gives us certain facilities to prevent race conditions
+between different processes utilizing the cache. For example you can
+check of the entry has been modified since you last read it or use CAS
+(Check And Set) semantics. What has to be protected in terms of cache
+coherency will likely have to be determined as the session support is
+utilized and different data items are added to the cache. This is very
+much data and context specific. Fortunately memcached operations are
+atomic.
+
+Controlling the memcached process
+---------------------------------
+
+We need a mechanism to start the memcached process and secure it so
+that only IPA components can access it.
+
+Although memcached ships with both an initscript and systemd unit
+files those are for generic instances. We want a memcached instance
+dedicated exclusively to IPA usage. To accomplish this we would install
+a systemd unit file or an SysV initscript to control the IPA specific
+memcached service. ipactl would be extended to know about this
+additional service. systemd's cgroup facility would give us additional
+mechanisms to integrate the IPA memcached service within a larger IPA
+process group.
+
+Protecting the memcached data would be done via file permissions (and
+optionally SELinux policy) on the UNIX domain socket. Although recent
+implementations of memcached support authentication via SASL this
+introduces a performance and complexity burden not warranted when
+cached is dedicated to our exclusive use and access controlled by OS
+mechanisms.
+
+Conventionally daemons are protected by assigning a system uid and/or
+gid to the daemon. A daemon launched by root will drop it's privileges
+by assuming the effective uid:gid assigned to it. File system access
+is controlled by the OS via the effective identity and SELinux policy
+can be crafted based on the identity. Thus the memcached UNIX socket
+would be protected by having it owned by a specific system user and/or
+membership in a restricted system group (discounting for the moment
+SELinux).
+
+Unfortunately we currently do not have an IPA system uid whose
+identity our processes operate under nor do we have an IPA system
+group. IPA does manage a collection of related processes (daemons) and
+historically each has been assigned their own uid. When these
+unrelated processes communicate they mutually authenticate via other
+mechanisms. We do not have much of a history of using shared file
+system objects across identities. When file objects are created they
+are typically assigned the identity of daemon needing to access the
+object and are not accessed by other daemons, or they carry root
+identity.
+
+When our WSGI application runs in Apache it is run as a WSGI
+daemon. This means when Apache starts up it forks off WSGI processes
+for us and we are independent of other Apache processes. When WSGI is
+run in this mode there is the ability to set the uid:gid of the WSGI
+process hosting us, however we currently do not take advantage of this
+option. WSGI can be run in other modes as well, only in daemon mode
+can the uid:gid be independently set from the rest of Apache. All
+processes started by Apache can be set to a common uid:gid specified
+in the global Apache configuration, by default it's
+apache:apache. Thus when our IPA code executes it is running as
+apache:apache.
+
+To protect our memcached UNIX socket we can do one of two things:
+
+1. Assign it's uid:gid as apache:apache. This would limit access to
+   our cache only to processes running under httpd. It's somewhat
+   restricted but far from ideal. Any code running in the web server
+   could potentially access our cache. It's difficult to control what the
+   web server runs and admins may not understand the consequences of
+   configuring httpd to serve other things besides IPA.
+
+2. Create an IPA specific uid:gid, for example ipa:ipa. We then configure
+   our WSGI application to run as the ipa:ipa user and group. We also
+   configure our memcached instance to run as the ipa:ipa user and
+   group. In this configuration we are now fully protected, only our WSGI
+   code can read & write to our memcached UNIX socket.
+
+However there may be unforeseen issues by converting our code to run as
+something other than apache:apache. This would require some
+investigation and testing.
+
+IPA is dependent on other system daemons, specifically Directory
+Server (ds) and Certificate Server (cs). Currently we configure ds to
+run under the dirsrv:dirsrv user and group, an identity of our
+creation. We allow cs to default to it's pkiuser:pkiuser user and
+group. Should these other cooperating daemons also run under the
+common ipa:ipa user and group identities? At first blush there would
+seem to be an advantage to coalescing all process identities under a
+common IPA user and group identity. However these other processes do
+not depend on user and group permissions when working with external
+agents, processes, etc. Rather they are designed to be stand-alone
+network services which authenticate their clients via other
+mechanisms. They do depend on user and group permission to manage
+their own file system objects. If somehow the ipa user and/or group
+were compromised or malicious code somehow executed under the ipa
+identity there would be an advantage in having the cooperating
+processes cordoned off under their own identities providing one extra
+layer of protection. (Note, these cooperating daemons may not even be
+co-located on the same node in which case the issue is moot)
+
+The UNIX socket behavior (ldapi) with Directory Server is as follows:
+
+  * The socket ownership is: root:root
+
+  * The socket permissions are: 0666
+
+  * When connecting via ldapi you must authenticate as you would
+    normally with a TCP socket, except ...
+
+  * If autobind is enabled and the uid:gid is available via
+    SO_PEERCRED and the uid:gid can be found in the set of users known
+    to the Directory Server then that connection will be bound as that
+    user.
+
+  * Otherwise an anonymous bind will occur.
+
+memcached UNIX socket behavior is as follows:
+
+  * memcached can be invoked with a user argument, no group may be
+    specified. The effective uid is the uid of the user argument and
+    the effective gid is the primary group of the user, let's call
+    this euid:egid
+
+  * The socket ownership is: euid:egid
+
+  * The socket permissions are 0700 by default, but this can be
+    modified by the -a mask command line arg which sets the umask
+    (defaults to 0700).
+
+Overview of authentication in IPA
+=================================
+
+This describes how we currently authenticate and how we plan to
+improve authentication performance. First some definitions.
+
+There are 4 major players:
+
+  1. client
+  2. mod_auth_kerb (in Apache process)
+  3. wsgi handler (in IPA wsgi python process)
+  4. ds (directory server)
+
+There are several resources:
+
+  1. /ipa/ui (unprotected, web UI static resources)
+  2. /ipa/xml (protected, xmlrpc RPC used by command line clients)
+  3. /ipa/json (protected, json RPC used by javascript in web UI)
+  4. ds (protected, wsgi acts as proxy, our LDAP server)
+
+Current Model
+-------------
+
+This describes how things work in our current system for the web UI.
+
+  1. Client requests /ipa/ui, this is unprotected, is static and
+     contains no sensitive information. Apache replies with html and
+     javascript. The javascript requests /ipa/json.
+
+  2. Client sends post to /ipa/json.
+
+  3. mod_auth_kerb is configured to protect /ipa/json, replies 401
+     authenticate negotiate.
+
+  4. Client resends with credentials
+
+  5. mod_auth_kerb validates credentials
+
+     a. if invalid replies 403 access denied (stops here)
+
+     b. if valid creates temporary ccache, adds KRB5CCNAME to request
+        headers
+
+  6. Request passed to wsgi handler
+
+     a. validates request, KRB5CCNAME must be present, referrer, etc.
+
+     b. ccache saved and used to bind to ds
+
+     c. routes to specified RPC handler.
+
+  7. wsgi handler replies to client
+
+Proposed new session based optimization
+---------------------------------------
+
+The round trip negotiate and credential validation in steps 3,4,5 is
+expensive. This can be avoided if we can cache the client
+credentials. With client sessions we can store the client credentials
+in the session bound to the client.
+
+A few notes about the session implementation.
+
+  * based on session cookies, cookies must be enabled
+
+  * session cookie is secure, only passed on secure connections, only
+    passed to our URL resource, never visible to client javascript
+    etc.
+
+  * session cookie has a session id which is used by wsgi handler to
+    retrieve client session data from shared multi-process cache.
+
+Changes to Apache's resource protection
+---------------------------------------
+
+  * /ipa/json is no longer protected by mod_auth_kerb. This is
+    necessary to avoid the negotiate expense in steps 3,4,5
+    above. Instead the /ipa/json resource will be protected in our wsgi
+    handler via the session cookie.
+
+  * A new protected URI is introduced, /ipa/login. This resource
+    does no serve any data, it is used exclusively for authentication.
+
+The new sequence is:
+
+  1. Client requests /ipa/ui, this is unprotected. Apache replies with
+     html and javascript. The javascript requests /ipa/json.
+
+  2. Client sends post to /ipa/json, which is unprotected.
+
+  3. wsgi handler obtains session data from session cookie.
+
+     a. if ccache is present in session data and is valid
+
+        - request is further validated
+
+        - ccache is established for bind to ds
+
+        - request is routed to RPC handler
+
+        - wsgi handler eventually replies to client
+
+     b. if ccache is not present or not valid processing continues ...
+
+  4. wsgi handler replies with 401 Unauthorized
+
+  5. client sends request to /ipa/login to obtain session credentials
+
+  6. mod_auth_kerb replies 401 negotiate on /ipa/login
+
+  7. client sends credentials to /ipa/login
+
+  8. mod_auth_kerb validates credentials
+
+     a. if valid
+
+        - mod_auth_kerb permits access to /ipa/login. wsgi handler is
+          invoked and does the following:
+
+          * establishes session for client
+
+          * retrieves the ccache from KRB5CCNAME and stores it
+
+     a. if invalid
+
+        - mod_auth_kerb sends 403 access denied (processing stops)
+
+  9. client now posts the same data again to /ipa/json including
+     session cookie. Processing repeats starting at step 2 and since
+     the session data now contains a valid ccache step 3a executes, a
+     successful reply is sent to client.
+
+Command line client using xmlrpc
+--------------------------------
+
+The above describes the web UI utilizing the json RPC mechanism. The
+IPA command line tools utilize a xmlrpc RPC mechanism on the same
+HTTP server. Access to the xmlrpc is via the /ipa/xml URI. The json
+and xmlrpc API's are the same, they differ only on how their procedure
+calls are marshalled and unmarshalled.
+
+Under the new scheme /ipa/xml will continue to be Kerberos protected
+at all times. Apache's mod_auth_kerb will continue to require the
+client provides valid Kerberos credentials.
+
+When the WSGI handler routes to /ipa/xml the Kerberos credentials will
+be extracted from the KRB5CCNAME environment variable as provided by
+mod_auth_kerb. Everything else remains the same.
+
+'''
+
+#-------------------------------------------------------------------------------
+
+default_max_session_lifetime = 60*60 # number of seconds
+
+ISO8601_DATETIME_FMT = '%Y-%m-%dT%H:%M:%S' # FIXME jrd, this should be defined elsewhere
+def fmt_time(timestamp):
+    return time.strftime(ISO8601_DATETIME_FMT, time.localtime(timestamp))
+
+#-------------------------------------------------------------------------------
+
+class SessionManager(object):
+
+    '''
+    This class is used to manage a set of sessions. Each client
+    connecting to the server is assigned a session id wich is then
+    used to store data bound to the client's session in between server
+    requests.
+    '''
+
+    def __init__(self):
+        '''
+        :returns:
+          `SessionManager` object
+        '''
+
+        log_mgr.get_logger(self, True)
+        self.generated_session_ids = set()
+
+    def generate_session_id(self, n_bits=48):
+        '''
+        Return a random string to be used as a session id.
+
+        This implementation creates a string of hexadecimal digits.
+        There is no guarantee of uniqueness, it is the caller's
+        responsibility to validate the returned id is not currently in
+        use.
+
+        :parameters:
+          n_bits
+            number of bits of random data, will be rounded to next
+            highest multiple of 4
+        :returns:
+          string of random hexadecimal digits
+        '''
+        # round up to multiple of 4
+        n_bits = (n_bits + 3) & ~3
+        session_id = '%0*x' % (n_bits >> 2, random.getrandbits(n_bits))
+        return session_id
+
+    def new_session_id(self, max_retries=5):
+        '''
+        Returns a new *unique* session id. See `generate_session_id()`
+        for how the session id's are formulated.
+
+        The scope of the uniqueness of the id is limited to id's
+        generated by this instance of the `SessionManager`.
+
+        :parameters:
+          max_retries
+            Maximum number of attempts to produce a unique id.
+        :returns:
+          Unique session id as a string.
+        '''
+        n_retries = 0
+        while n_retries < max_retries:
+            session_id = self.generate_session_id()
+            if not session_id in self.generated_session_ids:
+                break
+            n_retries += 1
+        if n_retries >= max_retries:
+            self.error('could not allocate unique new session_id, %d retries exhausted', n_retries)
+            raise errors.ExecutionError(message=_('could not allocate unique new session_id'))
+        self.generated_session_ids.add(session_id)
+        return session_id
+
+
+class MemcacheSessionManager(SessionManager):
+    '''
+
+    This class is used to assign a session id to a HTTP server client
+    and then store client specific data associated with the session in
+    a memcached memory cache instance. Multiple processes may share
+    the memory cache permitting session data to be shared between
+    forked HTTP server children handling server requests.
+
+    The session id is guaranteed to be unique.
+
+    The session id is set into a session cookie returned to the client
+    and is secure (see `generate_cookie()`). Future requests from the
+    client will send the session id which is then used to retrieve the
+    session data (see `load_session_data()`)
+    '''
+
+    memcached_socket_path = '/var/run/ipa_memcached/ipa_memcached'
+    session_cookie_name = 'ipa_session'
+    mc_server_stat_name_re = re.compile(r'(.+)\s+\((\d+)\)')
+
+    def __init__(self):
+        '''
+        :returns:
+          `MemcacheSessionManager` object.
+        '''
+
+        super(MemcacheSessionManager, self).__init__()
+        self.servers = ['unix:%s' % self.memcached_socket_path]
+        self.mc = memcache.Client(self.servers, debug=0)
+
+        if not self.servers_running():
+            self.warning("session memcached servers not running")
+
+    def get_server_statistics(self):
+        '''
+        Return memcached server statistics.
+
+        Return value is a dict whose keys are server names and whose
+        value is a dict of key/value statistics as returned by the
+        memcached server.
+
+        :returns:
+          dict of server names, each value is dict of key/value server
+          statistics.
+
+        '''
+        result = {}
+        stats = self.mc.get_stats()
+        for server in stats:
+            match = self.mc_server_stat_name_re.search(server[0])
+            if match:
+                name = match.group(1)
+                result[name] = server[1]
+            else:
+                self.warning('unparseable memcached server name "%s"', server[0])
+        return result
+
+    def servers_running(self):
+        '''
+        Check if all configured memcached servers are running and can
+        be communicated with.
+
+        :returns:
+          True if at least one server is configured and all servers
+          can respond, False otherwise.
+
+        '''
+
+        if len(self.servers) == 0:
+            return False
+        stats = self.get_server_statistics()
+        return len(self.servers) == len(stats)
+
+    def new_session_id(self, max_retries=5):
+        '''
+        Returns a new *unique* session id. See `generate_session_id()`
+        for how the session id's are formulated.
+
+        The scope of the uniqueness of the id is limited to id's
+        generated by this instance of the `SessionManager` and session
+        id's currently stored in the memcache instance.
+
+        :parameters:
+          max_retries
+            Maximum number of attempts to produce a unique id.
+        :returns:
+          Unique session id as a string.
+        '''
+        n_retries = 0
+        while n_retries < max_retries:
+            session_id = super(MemcacheSessionManager, self).new_session_id(max_retries)
+            session_key = self.session_key(session_id)
+            session_data = self.mc.get(session_key)
+            if session_data is None:
+                break
+            n_retries += 1
+        if n_retries >= max_retries:
+            self.error('could not allocate unique new session_id, %d retries exhausted', n_retries)
+            raise errors.ExecutionError(message=_('could not allocate unique new session_id'))
+        return session_id
+
+    def new_session_data(self, session_id):
+        '''
+        Return a new session data dict. The session data will be
+        associated with it's session id. The dict will be
+        pre-populated with:
+
+        session_id
+          The session ID used to identify this session data.
+        session_start_timestamp
+          Timestamp when this session was created.
+        session_write_timestamp
+          Timestamp when the session was last written to cache.
+        session_expiration_timestamp
+          Timestamp when session expires. Defaults to zero which
+          implies no expiration. See `set_session_expiration_time()`.
+
+        :parameters:
+          session_id
+            The session id used to look up this session data.
+        :returns:
+          Session data dict populated with a session_id key.
+        '''
+
+        now = time.time()
+        return {'session_id'                   : session_id,
+                'session_start_timestamp'      : now,
+                'session_write_timestamp'      : now,
+                'session_expiration_timestamp' : 0,
+               }
+
+    def session_key(self, session_id):
+        '''
+        Given a session id return a memcache key used to look up the
+        session data in the memcache.
+
+        :parameters:
+          session_id
+            The session id from which the memcache key will be derived.
+        :returns:
+          A key (string) used to look up the session data in the memcache.
+        '''
+        return 'ipa.session.%s' % (session_id)
+
+    def get_session_id_from_http_cookie(self, cookie_header):
+        '''
+        Parse an HTTP cookie header and search for our session
+        id. Return the session id if found, return None if not
+        found.
+
+        :parameters:
+          cookie_header
+            An HTTP cookie header. May be None, if None return None.
+        :returns:
+          Session id as string or None if not found.
+        '''
+        session_id = None
+        if cookie_header is not None:
+            cookie = Cookie.SimpleCookie()
+            cookie.load(cookie_header)
+            session_cookie = cookie.get(self.session_cookie_name)
+            if session_cookie is not None:
+                session_id = session_cookie.value
+                self.debug('found session cookie_id = %s', session_id)
+        return session_id
+
+
+    def load_session_data(self, cookie_header):
+        '''
+        Parse an HTTP cookie header looking for our session
+        information.
+
+        * If no session id is found then a new session id and new
+          session data dict will be generated, stored in the memcache
+          and returned. The new session data dict will contain the new
+          session id.
+
+        * If the session id is found in the cookie an attempt is made
+          to retrieve the session data from the memcache using the
+          session id.
+
+          - If existing session data is found in the memcache it is
+            returned.
+
+          - If no session data is found in the memcache then a new
+            session data dict will be generated, stored in the
+            memcache and returned. The new session data dict will
+            contain the session id found in the cookie header.
+
+        :parameters:
+          cookie_header
+            An HTTP cookie header. May be None.
+        :returns:
+          Session data dict containing at a minimum the session id it
+          is bound to.
+        '''
+
+        session_id = self.get_session_id_from_http_cookie(cookie_header)
+        if session_id is None:
+            session_id = self.new_session_id()
+            self.debug('no session id in request, generating empty session data with id=%s', session_id)
+            session_data = self.new_session_data(session_id)
+            self.store_session_data(session_data)
+            return session_data
+        else:
+            session_key = self.session_key(session_id)
+            session_data = self.mc.get(session_key)
+            if session_data is None:
+                self.debug('no session data in cache with id=%s, generating empty session data', session_id)
+                session_data = self.new_session_data(session_id)
+                self.store_session_data(session_data)
+                return session_data
+            else:
+                self.debug('found session data in cache with id=%s', session_id)
+                return session_data
+
+    def store_session_data(self, session_data):
+        '''
+        Store the supplied session_data dict in the memcached instance.
+
+        The session_expiration_timestamp is always passed to memcached
+        when the session data is written back to the memcache. This is
+        because otherwise the memcache expiration will default to zero
+        if it's not specified which implies no expiration. Thus a
+        failure to specify an exiration time when writing an item to
+        memcached will cause a previously set expiration time for the
+        item to be discarded and the item will no longer expire.
+
+        :parameters:
+          session_data
+            Session data dict, must contain session_id key.
+
+        :returns:
+          session_id
+        '''
+        session_id = session_data['session_id']
+        session_key = self.session_key(session_id)
+        now = time.time()
+        session_data['session_write_timestamp'] = now
+        session_expiration_timestamp = session_data['session_expiration_timestamp']
+
+        self.debug('store session: session_id=%s start_timestamp=%s write_timestamp=%s expiration_timestamp=%s',
+                   session_id,
+                   fmt_time(session_data['session_start_timestamp']),
+                   fmt_time(session_data['session_write_timestamp']),
+                   fmt_time(session_data['session_expiration_timestamp']))
+
+        self.mc.set(session_key, session_data, time=session_expiration_timestamp)
+        return session_id
+
+    def generate_cookie(self, url_path, session_id, add_header=False):
+        '''
+        Return a session cookie containing the session id. The cookie
+        will be contrainted to the url path, defined for use
+        with HTTP only, and only returned on secure connections (SSL).
+
+        :parameters:
+          url_path
+            The cookie will be returned in a request if it begins
+            with this url path.
+          session_id
+            The session id identified by the session cookie
+          add_header
+            If true format cookie string with Set-Cookie: header
+
+        :returns:
+          cookie string
+        '''
+        cookie = Cookie.SimpleCookie()
+        cookie[self.session_cookie_name] = session_id
+        cookie[self.session_cookie_name]['path'] = url_path
+        cookie[self.session_cookie_name]['httponly'] = True
+        cookie[self.session_cookie_name]['secure'] = True
+        if add_header:
+            result = cookie.output().strip()
+        else:
+            result = cookie.output(header='').strip()
+
+        return result
+
+    def set_session_expiration_time(self, session_data,
+                                    lifetime=default_max_session_lifetime,
+                                    max_age=None):
+        '''
+        memcached permits setting an expiration time on entries. The
+        expiration time may either be Unix time (number of seconds since
+        January 1, 1970, as a 32-bit value), or a number of seconds starting
+        from current time. In the latter case, this number of seconds may
+        not exceed 60*60*24*30 (number of seconds in 30 days); if the number
+        sent by a client is larger than that, the server will consider it to
+        be real Unix time value rather than an offset from current time.
+
+        We never use the duration value (< 30 days), we always use a
+        timestamp, this makes it easier to integrate with other time
+        constraints.
+
+        When a session is created it's start time is recorded in the
+        session data as the session_start_timestamp value. The
+        expiration timestamp is computed by adding the lifetime to the
+        session_start_timestamp. Then if the max_age is specified the
+        expiration is constrained to be not greater than the max_age.
+
+        The final computed expiration is then written into the
+        session_data as the session_expiration_timestamp value. The
+        session_expiration_timestamp is always passed to memcached
+        when the session data is written back to the memcache. This is
+        because otherwise the memcache expiration will default to zero
+        if it's not specified which implies no expiration. Thus a
+        failure to specify an exiration time when writing an item to
+        memcached will cause a previously set expiration time for the
+        item to be discarded and the item will no longer expire.
+
+
+        :parameters:
+          session_data
+            Session data dict, must contain session_id key.
+          lifetime
+            Number of seconds cache entry should live. This is a
+            duration value, not a timestamp.  Zero implies no
+            expiration.
+
+        max_age
+            Unix time value when cache entry must expire by.
+
+        :returns:
+          expiration timestamp, zero implies no expiration
+        '''
+
+        if lifetime == 0 and max_age is None:
+            expiration = 0
+            session_data['session_expiration_timestamp'] = expiration
+            return expiration
+
+        session_start_timestamp = session_data['session_start_timestamp']
+        expiration = session_start_timestamp + lifetime
+
+        if max_age is not None:
+            expiration = min(expiration, max_age)
+
+        session_data['session_expiration_timestamp'] = expiration
+
+        return expiration
+
+    def delete_session_data(self, session_id):
+        '''
+        Given a session id removed the session data bound to the id from the memcache.
+
+        :parameters:
+          session_id
+            The ID of the session which should be removed from the cache.
+        :returns:
+          None
+        '''
+        session_key = self.session_key(session_id)
+
+        self.debug('delete session data from memcache, session_id=%s', session_id)
+        self.mc.delete(session_key)
+
+
+#-------------------------------------------------------------------------------
+krbccache_dir ='/var/run/ipa_memcached'
+krbccache_prefix = 'krbcc_'
+
+def get_krbccache_pathname():
+    return os.path.join(krbccache_dir, '%s%s' % (krbccache_prefix, os.getpid()))
+
+def read_krbccache_file(krbccache_pathname):
+    root_logger.debug('reading krbccache data from "%s"', krbccache_pathname)
+    src = open(krbccache_pathname)
+    ccache_data = src.read()
+    src.close()
+    return ccache_data
+
+def store_krbccache_file(ccache_data):
+    krbccache_pathname = get_krbccache_pathname()
+    root_logger.debug('storing krbccache data into "%s"', krbccache_pathname)
+    dst = open(krbccache_pathname, 'w')
+    dst.write(ccache_data)
+    dst.close()
+
+    return krbccache_pathname
+
+def delete_krbccache_file(krbccache_pathname=None):
+    if krbccache_pathname is None:
+        krbccache_pathname = get_krbccache_pathname()
+
+    try:
+        os.unlink(krbccache_pathname)
+    except Exception, e:
+        root_logger.error('unable to delete session krbccache file "%s", %s',
+                          krbccache_pathname, e)
+
+
+#-------------------------------------------------------------------------------
+
+
+session_mgr = MemcacheSessionManager()
diff --git a/ipalib/util.py b/ipalib/util.py
index da933a8..f3d7970 100644
--- a/ipalib/util.py
+++ b/ipalib/util.py
@@ -310,3 +310,103 @@ class cachedproperty(object):
 
     def __delete__(self, obj):
         raise AttributeError("can't delete attribute")
+
+# regexp matching signed floating point number (group 1) followed by
+# optional whitespace followed by time unit, e.g. day, hour (group 7)
+time_duration_re = re.compile(r'([-+]?((\d+)|(\d+\.\d+)|(\.\d+)|(\d+\.)))\s*([a-z]+)', re.IGNORECASE)
+
+# number of seconds in a time unit
+time_duration_units = {
+    'year'    : 365*24*60*60,
+    'years'   : 365*24*60*60,
+    'y'       : 365*24*60*60,
+    'month'   : 30*24*60*60,
+    'months'  : 30*24*60*60,
+    'week'    : 7*24*60*60,
+    'weeks'   : 7*24*60*60,
+    'w'       : 7*24*60*60,
+    'day'     : 24*60*60,
+    'days'    : 24*60*60,
+    'd'       : 24*60*60,
+    'hour'    : 60*60,
+    'hours'   : 60*60,
+    'h'       : 60*60,
+    'minute'  : 60,
+    'minutes' : 60,
+    'min'     : 60,
+    'second'  : 1,
+    'seconds' : 1,
+    'sec'     : 1,
+    's'       : 1,
+}
+
+def parse_time_duration(value):
+    '''
+
+    Given a time duration string, parse it and return the total number
+    of seconds represented as a floating point value. Negative values
+    are permitted.
+
+    The string should be composed of one or more numbers followed by a
+    time unit. Whitespace and punctuation is optional. The numbers may
+    be optionally signed.  The time units are case insenstive except
+    for the single character 'M' or 'm' which means month and minute
+    respectively.
+
+    Recognized time units are:
+
+        * year, years, y
+        * month, months, M
+        * week, weeks, w
+        * day, days, d
+        * hour, hours, h
+        * minute, minutes, min, m
+        * second, seconds, sec, s
+
+    Examples:
+        "1h"                    # 1 hour
+        "2 HOURS, 30 Minutes"   # 2.5 hours
+        "1week -1 day"          # 6 days
+        ".5day"                 # 12 hours
+        "2M"                    # 2 months
+        "1h:15m"                # 1.25 hours
+        "1h, -15min"            # 45 minutes
+        "30 seconds"            # .5 minute
+
+    Note: Despite the appearance you can perform arithmetic the
+    parsing is much simpler, the parser searches for signed values and
+    adds the signed value to a running total. Only + and - are permitted
+    and must appear prior to a digit.
+
+    :parameters:
+        value : string
+            A time duration string in the specified format
+    :returns:
+        total number of seconds as float (may be negative)
+    '''
+
+    matches = 0
+    duration = 0.0
+    for match in time_duration_re.finditer(value):
+        matches += 1
+        magnitude = match.group(1)
+        unit = match.group(7)
+
+        # Get the unit, only M and m are case sensitive
+        if unit == 'M':         # month
+            seconds_per_unit = 30*24*60*60
+        elif unit == 'm':       # minute
+            seconds_per_unit = 60
+        else:
+            unit = unit.lower()
+            seconds_per_unit = time_duration_units.get(unit)
+            if seconds_per_unit is None:
+                raise ValueError('unknown time duration unit "%s"' % unit)
+        magnitude = float(magnitude)
+        seconds = magnitude * seconds_per_unit
+        duration += seconds
+
+    if matches == 0:
+        raise ValueError('no time duration found in "%s"' % value)
+
+    return duration
diff --git a/ipaserver/plugins/xmlserver.py b/ipaserver/plugins/xmlserver.py
index 1771a93..03bca9a 100644
--- a/ipaserver/plugins/xmlserver.py
+++ b/ipaserver/plugins/xmlserver.py
@@ -25,7 +25,8 @@ Loads WSGI server plugins.
 from ipalib import api
 
 if 'in_server' in api.env and api.env.in_server is True:
-    from ipaserver.rpcserver import session, xmlserver, jsonserver
+    from ipaserver.rpcserver import session, xmlserver, jsonserver, krblogin
     api.register(session)
     api.register(xmlserver)
     api.register(jsonserver)
+    api.register(krblogin)
diff --git a/ipaserver/rpcserver.py b/ipaserver/rpcserver.py
index 26850db..a52ec1c 100644
--- a/ipaserver/rpcserver.py
+++ b/ipaserver/rpcserver.py
@@ -30,13 +30,17 @@ from ipalib.backend import Executioner
 from ipalib.errors import PublicError, InternalError, CommandError, JSONError, ConversionError, CCacheError, RefererError
 from ipalib.request import context, Connection, destroy_context
 from ipalib.rpc import xml_dumps, xml_loads
-from ipalib.util import make_repr
+from ipalib.util import make_repr, parse_time_duration
 from ipalib.compat import json
+from ipalib.session import session_mgr, read_krbccache_file, store_krbccache_file, delete_krbccache_file, fmt_time, default_max_session_lifetime
+from ipalib.backend import Backend
+from ipalib.krb_utils import krb5_parse_ccache, KRB5_CCache, krb5_format_tgt_principal_name, krb5_format_service_principal_name, krb_ticket_expiration_threshold
 from wsgiref.util import shift_path_info
 from ipapython.version import VERSION
 import base64
 import os
 import string
+import datetime
 _not_found_template = """<html>
 <head>
 <title>404 Not Found</title>
@@ -138,8 +142,8 @@ class session(Executioner):
         return key in self.__apps
 
     def __call__(self, environ, start_response):
+        self.debug('WSGI session.__call__:')
         try:
-            self.create_context(ccache=environ.get('KRB5CCNAME'))
             return self.route(environ, start_response)
         finally:
             destroy_context()
@@ -199,9 +203,7 @@ class WSGIExecutioner(Executioner):
         name = None
         args = ()
         options = {}
-        if not 'KRB5CCNAME' in environ:
-            return self.marshal(result, CCacheError(), _id)
-        self.debug('Request environment: %s' % environ)
+
         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:
@@ -262,15 +264,25 @@ class WSGIExecutioner(Executioner):
         """
         WSGI application for execution.
         """
+
+        self.debug('WSGI WSGIExecutioner.__call__:')
         try:
             status = '200 OK'
             response = self.wsgi_execute(environ)
             headers = [('Content-Type', self.content_type + '; charset=utf-8')]
         except StandardError, e:
-            self.exception('%s.__call__():', self.name)
+            self.exception('WSGI %s.__call__():', self.name)
             status = '500 Internal Server Error'
             response = status
             headers = [('Content-Type', 'text/plain')]
+
+        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
+            session_cookie = session_mgr.generate_cookie('/ipa', session_data['session_id'])
+            headers.append(('Set-Cookie', session_cookie))
+
         start_response(status, headers)
         return [response]
 
@@ -299,6 +311,18 @@ class xmlserver(WSGIExecutioner):
         }
         super(xmlserver, self)._on_finalize()
 
+    def __call__(self, environ, start_response):
+        '''
+        '''
+
+        self.debug('WSGI xmlserver.__call__:')
+        self.create_context(ccache=environ.get('KRB5CCNAME'))
+        try:
+            response = super(xmlserver, self).__call__(environ, start_response)
+        finally:
+            destroy_context()
+        return response
+
     def listMethods(self, *params):
         return tuple(name.decode('UTF-8') for name in self.Command)
 
@@ -458,6 +482,69 @@ class jsonserver(WSGIExecutioner):
     content_type = 'application/json'
     key = 'json'
 
+    def need_login(self, start_response):
+        status = '401 Unauthorized'
+        headers = []
+        response = ''
+
+        self.debug('jsonserver: %s', status)
+
+        start_response(status, headers)
+        return [response]
+
+    def __call__(self, environ, start_response):
+        '''
+        '''
+
+        self.debug('WSGI jsonserver.__call__:')
+
+        # Load the session data
+        session_data = session_mgr.load_session_data(environ.get('HTTP_COOKIE'))
+        session_id = session_data['session_id']
+
+        self.debug('jsonserver.__call__: session_id=%s start_timestamp=%s write_timestamp=%s expiration_timestamp=%s',
+                   session_id,
+                   fmt_time(session_data['session_start_timestamp']),
+                   fmt_time(session_data['session_write_timestamp']),
+                   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)
+
+        krbccache_pathname = store_krbccache_file(ccache_data)
+
+        # Redirect to login if Kerberos credentials are expired
+        cc = KRB5_CCache(krbccache_pathname)
+        ldap_principal = krb5_format_service_principal_name('ldap', self.api.env.host, self.api.env.realm)
+        tgt_principal = krb5_format_tgt_principal_name(self.api.env.realm)
+        if not (cc.credential_is_valid(ldap_principal) or cc.credential_is_valid(tgt_principal)):
+            self.debug('ccache expired, deleting session, need login')
+            session_mgr.delete_session_data(session_id)
+            delete_krbccache_file(krbccache_pathname)
+            return self.need_login(start_response)
+
+        # Store the session data in the per-thread context
+        setattr(context, 'session_data', session_data)
+
+        self.create_context(ccache=krbccache_pathname)
+
+        try:
+            response = super(jsonserver, self).__call__(environ, start_response)
+        finally:
+            # Kerberos may have updated the ccache data, refresh our copy of it
+            session_data['ccache_data'] = read_krbccache_file(krbccache_pathname)
+            # Delete the temporary ccache file we used
+            delete_krbccache_file(krbccache_pathname)
+            # Store the session data.
+            session_mgr.store_session_data(session_data)
+            destroy_context()
+
+        return response
+
     def marshal(self, result, error, _id=None):
         if error:
             assert isinstance(error, PublicError)
@@ -509,3 +596,78 @@ class jsonserver(WSGIExecutioner):
             )
         options = dict((str(k), v) for (k, v) in options.iteritems())
         return (method, args, options, _id)
+
+class krblogin(Backend):
+    key = 'login'
+
+    def __init__(self):
+        super(krblogin, self).__init__()
+
+    def _on_finalize(self):
+        super(krblogin, self)._on_finalize()
+        self.api.Backend.session.mount(self, self.key)
+
+        # 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))
+        except Exception, e:
+            self.session_auth_duration = default_max_session_lifetime
+            self.error('unable to parse session_auth_duration, defaulting to %d: %s',
+                       self.session_auth_duration, e)
+
+
+    def __call__(self, environ, start_response):
+        headers = []
+
+        self.debug('WSGI krblogin.__call__:')
+
+        # Get the ccache created by mod_auth_kerb
+        ccache=environ.get('KRB5CCNAME')
+        if ccache is None:
+            status = '500 Internal Error'
+            response = 'KRB5CCNAME not defined'
+            start_response(status, headers)
+            return [response]
+
+        ccache_scheme, ccache_location = krb5_parse_ccache(ccache)
+        assert ccache_scheme == 'FILE'
+
+        # Retrieve the session data (or newly create)
+        session_data = session_mgr.load_session_data(environ.get('HTTP_COOKIE'))
+        session_id = session_data['session_id']
+
+        # Copy the ccache file contents into the session data
+        session_data['ccache_data'] = read_krbccache_file(ccache_location)
+
+        # Compute when the session will expire
+        cc = KRB5_CCache(ccache)
+        tgt_principal = krb5_format_tgt_principal_name(self.api.env.realm)
+        authtime, starttime, endtime, renew_till = cc.get_credential_times(tgt_principal)
+
+        # Account for clock skew and/or give us some time leeway
+        krb_expiration = endtime - krb_ticket_expiration_threshold
+
+        # Set the session expiration time
+        session_mgr.set_session_expiration_time(session_data,
+                                                lifetime=self.session_auth_duration,
+                                                max_age=krb_expiration)
+
+        # Store the session data now that it's been updated with the ccache
+        session_mgr.store_session_data(session_data)
+
+        self.debug('krblogin: ccache="%s" session_id="%s" ccache="%s"',
+                   ccache, session_id, ccache)
+
+        # Return success and set session cookie
+        status = '200 Success'
+        response = ''
+
+        session_cookie = session_mgr.generate_cookie('/ipa', session_data['session_id'])
+        headers.append(('Set-Cookie', session_cookie))
+
+        start_response(status, headers)
+        return [response]
+
+
diff --git a/make-lint b/make-lint
index ef24149..d8a49f1 100755
--- a/make-lint
+++ b/make-lint
@@ -67,6 +67,10 @@ class IPATypeChecker(TypeChecker):
         'ipalib.parameters.Enum': ['values'],
         'ipalib.parameters.File': ['stdin_if_missing'],
         'urlparse.SplitResult': ['netloc'],
+        'ipalib.krb_utils.KRB5_CCache' : ['log', 'debug', 'info', 'warning', 'error', 'critical', 'exception'],
+        'ipalib.session.SessionManager' : ['log', 'debug', 'info', 'warning', 'error', 'critical', 'exception'],
+        'ipalib.session.SessionCCache' : ['log', 'debug', 'info', 'warning', 'error', 'critical', 'exception'],
+        'ipalib.session.MemcacheSessionManager' : ['log', 'debug', 'info', 'warning', 'error', 'critical', 'exception'],
     }
 
     def _related_classes(self, klass):
-- 
1.7.7.6


[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]