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.
This commit is contained in:
John Dennis
2012-02-06 13:29:56 -05:00
committed by Endi S. Dewata
parent d1e0c1b606
commit bba4ccb3a0
12 changed files with 1843 additions and 31 deletions

View File

@@ -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

View File

@@ -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.
*
@@ -378,6 +404,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();
@@ -472,20 +531,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) {

View File

@@ -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

View File

@@ -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),

View File

@@ -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):

329
ipalib/krb_utils.py Normal file
View File

@@ -0,0 +1,329 @@
# 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

View File

@@ -49,14 +49,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):
"""

1098
ipalib/session.py Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -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

View File

@@ -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)

View File

@@ -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
from decimal import Decimal
_not_found_template = """<html>
<head>
@@ -139,8 +143,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()
@@ -200,9 +204,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:
@@ -263,15 +265,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]
@@ -300,6 +312,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)
@@ -461,6 +485,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)
@@ -512,3 +599,76 @@ 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]

View File

@@ -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):