1fac5ed8133a6f28b687312c5d0549bcf30da847
[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 import logging
26
27
28 class GSSAPI(LoginPageBase):
29
30     def root(self, *args, **kwargs):
31         # Someone typed manually or a robot is walking th tree.
32         # Redirect to default page
33         return self.lm.redirect_to_path(self.lm.path)
34
35
36 class GSSAPIAuth(LoginPageBase):
37
38     def root(self, *args, **kwargs):
39         trans = self.get_valid_transaction('login', **kwargs)
40         # If we can get here, we must be authenticated and remote_user
41         # was set. Check the session has a user set already or error.
42         us = UserSession()
43         us.remote_login()
44         self.user = us.get_user()
45         if not self.user.is_anonymous:
46             principal = cherrypy.request.wsgi_environ.get('GSS_NAME', None)
47             if principal:
48                 userdata = {'gssapi_principal_name': principal}
49             else:
50                 userdata = {'gssapi_principal_name': self.user.name}
51             return self.lm.auth_successful(trans, self.user.name,
52                                            'gssapi', userdata)
53         else:
54             return self.lm.auth_failed(trans)
55
56
57 class GSSAPIError(LoginPageBase):
58
59     def root(self, *args, **kwargs):
60         cherrypy.log.error('REQUEST: %s' % cherrypy.request.headers,
61                            severity=logging.DEBUG)
62         # If we have no negotiate header return whatever mod_auth_gssapi
63         # generated and wait for the next request
64
65         if 'WWW-Authenticate' not in cherrypy.request.headers:
66             cherrypy.response.status = 401
67
68             next_login = self.lm.next_login()
69             if next_login:
70                 return next_login.page.root(*args, **kwargs)
71
72             conturl = '%s/login' % self.basepath
73             return self._template('login/gssapi.html',
74                                   title='GSSAPI Login',
75                                   cont=conturl)
76
77         # If we get here, negotiate failed
78         trans = self.get_valid_transaction('login', **kwargs)
79         return self.lm.auth_failed(trans)
80
81
82 class LoginManager(LoginManagerBase):
83
84     def __init__(self, *args, **kwargs):
85         super(LoginManager, self).__init__(*args, **kwargs)
86         self.name = 'gssapi'
87         self.path = 'gssapi/negotiate'
88         self.page = None
89         self.description = """
90 GSSAPI Negotiate authentication plugin. Relies on the mod_auth_gssapi
91 apache plugin for actual authentication. """
92         self.new_config(self.name)
93
94     def get_tree(self, site):
95         self.page = GSSAPI(site, self)
96         self.page.__dict__['negotiate'] = GSSAPIAuth(site, self)
97         self.page.__dict__['unauthorized'] = GSSAPIError(site, self)
98         self.page.__dict__['failed'] = GSSAPIError(site, self)
99         return self.page
100
101
102 CONF_TEMPLATE = """
103
104 <Location /${instance}/login/gssapi/negotiate>
105   AuthType GSSAPI
106   AuthName "GSSAPI Single Sign On Login"
107   $keytab
108   GssapiSSLonly $gssapisslonly
109   GssapiLocalName on
110   Require valid-user
111
112   ErrorDocument 401 /${instance}/login/gssapi/unauthorized
113   ErrorDocument 500 /${instance}/login/gssapi/failed
114 </Location>
115 """
116
117
118 class Installer(LoginManagerInstaller):
119
120     def __init__(self, *pargs):
121         super(Installer, self).__init__()
122         self.name = 'gssapi'
123         self.pargs = pargs
124
125     def install_args(self, group):
126         group.add_argument('--gssapi', choices=['yes', 'no'], default='no',
127                            help='Configure GSSAPI authentication')
128         group.add_argument('--gssapi-httpd-keytab',
129                            default='/etc/httpd/conf/http.keytab',
130                            help='Kerberos keytab location for HTTPD')
131
132     def configure(self, opts):
133         if opts['gssapi'] != 'yes':
134             return
135
136         confopts = {'instance': opts['instance']}
137
138         if os.path.exists(opts['gssapi_httpd_keytab']):
139             confopts['keytab'] = 'GssapiCredStore keytab:%s' % (
140                 opts['gssapi_httpd_keytab'])
141         else:
142             raise Exception('Keytab not found')
143
144         if opts['secure'] == 'no':
145             confopts['gssapisslonly'] = 'Off'
146         else:
147             confopts['gssapisslonly'] = 'On'
148
149         tmpl = Template(CONF_TEMPLATE)
150         hunk = tmpl.substitute(**confopts)
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 = 'gssapi'
157         po.wipe_data()
158
159         # Update global config, put 'gssapi' always first
160         ph = self.pargs[0]
161         ph.refresh_enabled()
162         if 'gssapi' not in ph.enabled:
163             enabled = []
164             enabled.extend(ph.enabled)
165             enabled.insert(0, 'gssapi')
166             ph.save_enabled(enabled)