dbb531a6f20f74dccd6c5b1b8d2a5e5be0fb82a6
[cascardo/ipsilon.git] / ipsilon / login / authgssapi.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             principal = cherrypy.request.wsgi_environ.get('GSS_NAME', None)
46             if principal:
47                 userdata = {'krb_principal_name': principal}
48             else:
49                 userdata = {'krb_principal_name': self.user.name}
50             return self.lm.auth_successful(trans, self.user.name,
51                                            'krb', userdata)
52         else:
53             return self.lm.auth_failed(trans)
54
55
56 class KrbError(LoginPageBase):
57
58     def root(self, *args, **kwargs):
59         cherrypy.log.error('REQUEST: %s' % cherrypy.request.headers)
60         # If we have no negotiate header return whatever mod_auth_gssapi
61         # generated and wait for the next request
62
63         if 'WWW-Authenticate' not in cherrypy.request.headers:
64             cherrypy.response.status = 401
65
66             next_login = self.lm.next_login()
67             if next_login:
68                 return next_login.page.root(*args, **kwargs)
69
70             conturl = '%s/login' % self.basepath
71             return self._template('login/krb.html',
72                                   title='Kerberos Login',
73                                   cont=conturl)
74
75         # If we get here, negotiate failed
76         trans = self.get_valid_transaction('login', **kwargs)
77         return self.lm.auth_failed(trans)
78
79
80 class LoginManager(LoginManagerBase):
81
82     def __init__(self, *args, **kwargs):
83         super(LoginManager, self).__init__(*args, **kwargs)
84         self.name = 'krb'
85         self.path = 'krb/negotiate'
86         self.page = None
87         self.description = """
88 Kerberos Negotiate authentication plugin. Relies on the mod_auth_gssapi
89 apache plugin for actual authentication. """
90         self.new_config(self.name)
91
92     def get_tree(self, site):
93         self.page = Krb(site, self)
94         self.page.__dict__['negotiate'] = KrbAuth(site, self)
95         self.page.__dict__['unauthorized'] = KrbError(site, self)
96         self.page.__dict__['failed'] = KrbError(site, self)
97         return self.page
98
99
100 CONF_TEMPLATE = """
101
102 <Location /${instance}/login/krb/negotiate>
103   AuthType GSSAPI
104   AuthName "GSSAPI Single Sign On Login"
105   $keytab
106   GssapiSSLonly $gssapisslonly
107   GssapiLocalName on
108   Require valid-user
109
110   ErrorDocument 401 /${instance}/login/krb/unauthorized
111   ErrorDocument 500 /${instance}/login/krb/failed
112 </Location>
113 """
114
115
116 class Installer(LoginManagerInstaller):
117
118     def __init__(self, *pargs):
119         super(Installer, self).__init__()
120         self.name = 'krb'
121         self.pargs = pargs
122
123     def install_args(self, group):
124         group.add_argument('--krb', choices=['yes', 'no'], default='no',
125                            help='Configure Kerberos authentication')
126         group.add_argument('--krb-httpd-keytab',
127                            default='/etc/httpd/conf/http.keytab',
128                            help='Kerberos keytab location for HTTPD')
129
130     def configure(self, opts):
131         if opts['krb'] != 'yes':
132             return
133
134         confopts = {'instance': opts['instance']}
135
136         if os.path.exists(opts['krb_httpd_keytab']):
137             confopts['keytab'] = 'GssapiCredStore keytab:%s' % (
138                 opts['krb_httpd_keytab'])
139         else:
140             raise Exception('Keytab not found')
141
142         if opts['secure'] == 'no':
143             confopts['gssapisslonly'] = 'Off'
144         else:
145             confopts['gssapisslonly'] = 'On'
146
147         tmpl = Template(CONF_TEMPLATE)
148         hunk = tmpl.substitute(**confopts)  # pylint: disable=star-args
149         with open(opts['httpd_conf'], 'a') as httpd_conf:
150             httpd_conf.write(hunk)
151
152         # Add configuration data to database
153         po = PluginObject(*self.pargs)
154         po.name = 'krb'
155         po.wipe_data()
156
157         # Update global config, put 'krb' always first
158         ph = self.pargs[0]
159         ph.refresh_enabled()
160         if 'krb' not in ph.enabled:
161             enabled = []
162             enabled.extend(ph.enabled)
163             enabled.insert(0, 'krb')
164             ph.save_enabled(enabled)