60eeb6b14df1758648916e4bb2f3337bd9484f90
[cascardo/ipsilon.git] / ipsilon / login / authkrb.py
1 # Copyright (C) 2014  Simo Sorce <simo@redhat.com>
2 #
3 # see file 'COPYING' for use and warranty information
4 #
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation, either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
17
18 from ipsilon.login.common import LoginPageBase, LoginManagerBase, \
19     LoginManagerInstaller
20 from ipsilon.util.plugin import PluginObject
21 from ipsilon.util.user import UserSession
22 from string import Template
23 import cherrypy
24 import os
25
26
27 class Krb(LoginPageBase):
28
29     def root(self, *args, **kwargs):
30         # Someone typed manually or a robot is walking th tree.
31         # Redirect to default page
32         return self.lm.redirect_to_path(self.lm.path)
33
34
35 class KrbAuth(LoginPageBase):
36
37     def root(self, *args, **kwargs):
38         trans = self.get_valid_transaction('login', **kwargs)
39         # If we can get here, we must be authenticated and remote_user
40         # was set. Check the session has a user set already or error.
41         us = UserSession()
42         us.remote_login()
43         self.user = us.get_user()
44         if not self.user.is_anonymous:
45             userdata = {'krb_principal_name': self.user.name}
46             return self.lm.auth_successful(trans, self.user.name,
47                                            'krb', userdata)
48         else:
49             return self.lm.auth_failed(trans)
50
51
52 class KrbError(LoginPageBase):
53
54     def root(self, *args, **kwargs):
55         cherrypy.log.error('REQUEST: %s' % cherrypy.request.headers)
56         # If we have no negotiate header return whatever mod_auth_kerb
57         # generated and wait for the next request
58
59         if 'WWW-Authenticate' not in cherrypy.request.headers:
60             cherrypy.response.status = 401
61
62             next_login = self.lm.next_login()
63             if next_login:
64                 return next_login.page.root(*args, **kwargs)
65
66             conturl = '%s/login' % self.basepath
67             return self._template('login/krb.html',
68                                   title='Kerberos Login',
69                                   cont=conturl)
70
71         # If we get here, negotiate failed
72         trans = self.get_valid_transaction('login', **kwargs)
73         return self.lm.auth_failed(trans)
74
75
76 class LoginManager(LoginManagerBase):
77
78     def __init__(self, *args, **kwargs):
79         super(LoginManager, self).__init__(*args, **kwargs)
80         self.name = 'krb'
81         self.path = 'krb/negotiate'
82         self.page = None
83         self.description = """
84 Kereros Negotiate authentication plugin. Relies on the mod_auth_kerb apache
85 plugin for actual authentication. """
86         self.new_config(self.name)
87
88     def get_tree(self, site):
89         self.page = Krb(site, self)
90         self.page.__dict__['negotiate'] = KrbAuth(site, self)
91         self.page.__dict__['unauthorized'] = KrbError(site, self)
92         self.page.__dict__['failed'] = KrbError(site, self)
93         return self.page
94
95
96 CONF_TEMPLATE = """
97
98 <Location /${instance}/login/krb/negotiate>
99   AuthType Kerberos
100   AuthName "Kerberos Login"
101   KrbMethodNegotiate on
102   KrbMethodK5Passwd off
103   KrbServiceName HTTP
104   $realms
105   $keytab
106   KrbSaveCredentials off
107   KrbConstrainedDelegation off
108   # KrbLocalUserMapping On
109   Require valid-user
110
111   ErrorDocument 401 /${instance}/login/krb/unauthorized
112   ErrorDocument 500 /${instance}/login/krb/failed
113 </Location>
114 """
115
116
117 class Installer(LoginManagerInstaller):
118
119     def __init__(self, *pargs):
120         super(Installer, self).__init__()
121         self.name = 'krb'
122         self.pargs = pargs
123
124     def install_args(self, group):
125         group.add_argument('--krb', choices=['yes', 'no'], default='no',
126                            help='Configure Kerberos authentication')
127         group.add_argument('--krb-realms',
128                            help='Allowed Kerberos Auth Realms')
129         group.add_argument('--krb-httpd-keytab',
130                            default='/etc/httpd/conf/http.keytab',
131                            help='Kerberos keytab location for HTTPD')
132
133     def configure(self, opts):
134         if opts['krb'] != 'yes':
135             return
136
137         confopts = {'instance': opts['instance']}
138
139         if os.path.exists(opts['krb_httpd_keytab']):
140             confopts['keytab'] = '  Krb5KeyTab %s' % opts['krb_httpd_keytab']
141         else:
142             raise Exception('Keytab not found')
143
144         if opts['krb_realms'] is None:
145             confopts['realms'] = '  # KrbAuthRealms - Any realm is allowed'
146         else:
147             confopts['realms'] = '  KrbAuthRealms %s' % opts['krb_realms']
148
149         tmpl = Template(CONF_TEMPLATE)
150         hunk = tmpl.substitute(**confopts)  # pylint: disable=star-args
151         with open(opts['httpd_conf'], 'a') as httpd_conf:
152             httpd_conf.write(hunk)
153
154         # Add configuration data to database
155         po = PluginObject(*self.pargs)
156         po.name = 'krb'
157         po.wipe_data()
158
159         # Update global config, put 'krb' always first
160         ph = self.pargs[0]
161         ph.refresh_enabled()
162         if 'krb' not in ph.enabled:
163             enabled = []
164             enabled.extend(ph.enabled)
165             enabled.insert(0, 'krb')
166             ph.save_enabled(enabled)