3 # Copyright (C) 2014 Ipsilon project Contributors, for license see COPYING
5 from ipsilon.tools.saml2metadata import Metadata
6 from ipsilon.tools.saml2metadata import SAML2_NAMEID_MAP
7 from ipsilon.tools.saml2metadata import SAML2_SERVICE_MAP
8 from ipsilon.tools.certs import Certificate
9 from ipsilon.tools import files
10 from urllib import urlencode
25 HTTPDCONFD = '/etc/httpd/conf.d'
26 SAML2_TEMPLATE = '/usr/share/ipsilon/templates/install/saml2/sp.conf'
27 SAML2_CONFFILE = '/etc/httpd/conf.d/ipsilon-saml.conf'
28 SAML2_HTTPDIR = '/etc/httpd/saml2'
29 SAML2_PROTECTED = '/saml2protected'
31 #Installation arguments
35 logger = logging.getLogger()
39 global logger # pylint: disable=W0603
40 logger = logging.getLogger()
41 lh = logging.StreamHandler(sys.stderr)
46 logger.info('Installing SAML2 Service Provider')
48 if args['saml_idp_metadata'] is None:
49 #TODO: detect via SRV records ?
50 if args['saml_idp_url']:
51 args['saml_idp_metadata'] = ('%s/saml2/metadata' %
52 args['saml_idp_url'].rstrip('/'))
54 raise ValueError('An IDP URL or metadata file/URL is required.')
59 if os.path.exists(args['saml_idp_metadata']):
60 with open(args['saml_idp_metadata']) as f:
62 elif args['saml_idp_metadata'].startswith('file://'):
63 with open(args['saml_idp_metadata'][7:]) as f:
66 r = requests.get(args['saml_idp_metadata'])
69 except Exception, e: # pylint: disable=broad-except
70 logger.error("Failed to retrieve IDP Metadata file!\n" +
71 "Error: [%s]" % repr(e))
75 if not args['saml_no_httpd']:
76 path = os.path.join(SAML2_HTTPDIR, args['hostname'])
77 if os.path.exists(path):
78 raise Exception('Service Provider is already configured')
79 os.makedirs(path, 0750)
84 if not args['saml_secure_setup']:
89 port_str = ':%s' % args['port']
91 url = '%s://%s%s' % (proto, args['hostname'], port_str)
92 url_sp = url + args['saml_sp']
93 url_logout = url + args['saml_sp_logout']
94 url_post = url + args['saml_sp_post']
95 url_paos = url + args['saml_sp_paos']
100 c.generate('certificate', args['hostname'])
101 m.set_entity_id(url_sp)
103 m.add_service(SAML2_SERVICE_MAP['logout-redirect'], url_logout)
104 if not args['no_saml_soap_logout']:
105 m.add_service(SAML2_SERVICE_MAP['slo-soap'], url_logout)
106 m.add_service(SAML2_SERVICE_MAP['response-post'], url_post,
107 index="0", isDefault="true")
108 m.add_service(SAML2_SERVICE_MAP['response-paos'], url_paos,
110 m.add_allowed_name_format(SAML2_NAMEID_MAP[args['saml_nameid']])
111 sp_metafile = os.path.join(path, 'metadata.xml')
112 m.output(sp_metafile)
114 # Register with the IDP if the IDP URL was provided
115 if args['saml_idp_url']:
116 if args['admin_password']:
117 if args['admin_password'] == '-':
118 admin_password = sys.stdin.readline().rstrip('\n')
121 with open(args['admin_password']) as f:
122 admin_password = f.read().rstrip('\n')
123 except Exception as e: # pylint: disable=broad-except
124 logger.error("Failed to read password file!\n" +
127 elif ('IPSILON_ADMIN_PASSWORD' in os.environ) and \
128 (os.environ['IPSILON_ADMIN_PASSWORD']):
129 admin_password = os.environ['IPSILON_ADMIN_PASSWORD']
131 admin_password = getpass.getpass('%s password: ' %
137 with open(sp_metafile) as f:
139 sp_metadata += line.strip()
140 except Exception as e: # pylint: disable=broad-except
141 logger.error("Failed to read SP Metadata file!\n" +
146 if args['saml_sp_image']:
149 with open(args['saml_sp_image']) as f:
151 sp_image = base64.b64encode(sp_image)
152 except Exception as e: # pylint: disable=broad-except
153 logger.error("Failed to read SP Image file!\n" +
156 sp_link = 'https://%s%s' % (args['hostname'], args['saml_auth'])
160 saml2_register_sp(args['saml_idp_url'], args['admin_user'],
161 admin_password, args['saml_sp_name'],
162 sp_metadata, args['saml_sp_description'],
163 args['saml_sp_visible'], sp_image, sp_link)
164 except Exception as e: # pylint: disable=broad-except
165 logger.error("Failed to register SP with IDP!\n" +
169 if not args['saml_no_httpd']:
170 idp_metafile = os.path.join(path, 'idp-metadata.xml')
171 with open(idp_metafile, 'w+') as f:
174 saml_protect = 'auth'
176 if args['saml_base'] != args['saml_auth']:
177 saml_protect = 'info'
178 saml_auth = '<Location %s>\n' \
179 ' MellonEnable "auth"\n' \
180 ' Header append Cache-Control "no-cache"\n' \
181 '</Location>\n' % args['saml_auth']
184 if args['saml_auth'] == SAML2_PROTECTED:
185 # default location, enable the default page
192 ssl_port = args['port']
196 if args['saml_secure_setup']:
201 samlopts = {'saml_base': args['saml_base'],
202 'saml_protect': saml_protect,
203 'saml_sp_key': c.key,
204 'saml_sp_cert': c.cert,
205 'saml_sp_meta': sp_metafile,
206 'saml_idp_meta': idp_metafile,
207 'saml_sp': args['saml_sp'],
208 'saml_secure_on': saml_secure,
209 'saml_auth': saml_auth,
210 'ssl_require': ssl_require,
211 'ssl_rewrite': ssl_rewrite,
212 'ssl_port': ssl_port,
213 'sp_hostname': args['hostname'],
216 files.write_from_template(SAML2_CONFFILE, SAML2_TEMPLATE, samlopts)
218 files.fix_user_dirs(SAML2_HTTPDIR, args['httpd_user'])
220 logger.info('SAML Service Provider configured.')
221 logger.info('You should be able to restart the HTTPD server and' +
222 ' then access it at %s%s' % (url, args['saml_auth']))
224 logger.info('SAML Service Provider configuration ready.')
225 logger.info('Use the certificate, key and metadata.xml files to' +
226 ' configure your Service Provider')
229 def saml2_register_sp(url, user, password, sp_name, sp_metadata,
230 sp_description, sp_visible, sp_image, sp_link):
231 s = requests.Session()
233 # Authenticate to the IdP
234 form_auth_url = '%s/login/form' % url.rstrip('/')
235 test_auth_url = '%s/login/testauth' % url.rstrip('/')
236 auth_data = {'login_name': user,
237 'login_password': password}
239 r = s.post(form_auth_url, data=auth_data)
240 if r.status_code == 404:
241 r = s.post(test_auth_url, data=auth_data)
243 if r.status_code != 200:
244 raise Exception('Unable to authenticate to IdP (%d)' % r.status_code)
247 sp_url = '%s/rest/providers/saml2/SPS/%s' % (url.rstrip('/'), sp_name)
248 sp_headers = {'Content-type': 'application/x-www-form-urlencoded',
250 sp_data = {'metadata': sp_metadata}
252 sp_data['description'] = sp_description
254 sp_data['visible'] = sp_visible
257 sp_data['imagefile'] = sp_image
258 sp_data['splink'] = sp_link
259 sp_data = urlencode(sp_data)
261 r = s.post(sp_url, headers=sp_headers, data=sp_data)
262 if r.status_code != 201:
263 message = json.loads(r.text)['message']
264 raise Exception('%s' % message)
272 def saml2_uninstall():
273 path = os.path.join(SAML2_HTTPDIR, args['hostname'])
274 if os.path.exists(path):
277 except Exception, e: # pylint: disable=broad-except
280 if os.path.exists(SAML2_CONFFILE):
282 os.remove(SAML2_CONFFILE)
283 except Exception, e: # pylint: disable=broad-except
288 logger.info('Uninstalling Service Provider')
289 #FXIME: ask confirmation
291 logger.info('Uninstalled SAML2 data')
294 def log_exception(e):
295 if 'debug' in args and args['debug']:
301 def parse_config_profile(args):
302 config = ConfigParser.ConfigParser()
303 files = config.read(args['config_profile'])
305 raise ConfigurationError('Config Profile file %s not found!' %
306 args['config_profile'])
308 if 'globals' in config.sections():
309 G = config.options('globals')
311 val = config.get('globals', g)
320 if k.lower() == g.lower():
324 if 'arguments' in config.sections():
325 A = config.options('arguments')
327 val = config.get('arguments', a)
340 fc = argparse.ArgumentDefaultsHelpFormatter
341 parser = argparse.ArgumentParser(description='Client Install Options',
343 parser.add_argument('--version',
344 action='version', version='%(prog)s 0.1')
345 parser.add_argument('--hostname', default=socket.getfqdn(),
346 help="Machine's fully qualified host name")
347 parser.add_argument('--port', default=None,
348 help="Port number that SP listens on")
349 parser.add_argument('--admin-user', default='admin',
350 help="Account allowed to create a SP")
351 parser.add_argument('--admin-password', default=None,
352 help="File containing the password for the account " +
353 "used to create a SP (- to read from stdin)")
354 parser.add_argument('--httpd-user', default='apache',
355 help="Web server account used to read certs")
356 parser.add_argument('--saml', action='store_true', default=True,
357 help="Whether to install a saml2 SP")
358 parser.add_argument('--saml-idp-url', default=None,
359 help="A URL of the IDP to register the SP with")
360 parser.add_argument('--saml-idp-metadata', default=None,
361 help="A URL pointing at the IDP Metadata (FILE or HTTP)")
362 parser.add_argument('--saml-no-httpd', action='store_true', default=False,
363 help="Do not configure httpd")
364 parser.add_argument('--saml-base', default='/',
365 help="Where saml2 authdata is available")
366 parser.add_argument('--saml-auth', default=SAML2_PROTECTED,
367 help="Where saml2 authentication is enforced")
368 parser.add_argument('--saml-sp', default='/saml2',
369 help="Where saml communication happens")
370 parser.add_argument('--saml-sp-logout', default=None,
371 help="Single Logout URL")
372 parser.add_argument('--saml-sp-post', default=None,
373 help="Post response URL")
374 parser.add_argument('--saml-sp-paos', default=None,
375 help="PAOS response URL, used for ECP")
376 parser.add_argument('--no-saml-soap-logout', action='store_true',
378 help="Disable Single Logout over SOAP")
379 parser.add_argument('--saml-secure-setup', action='store_true',
380 default=True, help="Turn on all security checks")
381 parser.add_argument('--saml-nameid', default='unspecified',
382 choices=SAML2_NAMEID_MAP.keys(),
383 help="SAML NameID format to use")
384 parser.add_argument('--saml-sp-name', default=None,
385 help="The SP name to register with the IdP")
386 parser.add_argument('--saml-sp-description', default=None,
387 help="The description of the SP to display on the " +
389 parser.add_argument('--saml-sp-visible', action='store_false',
391 help="The SP is visible in the portal")
392 parser.add_argument('--saml-sp-image', default=None,
393 help="Image to display for this SP on the portal")
394 parser.add_argument('--debug', action='store_true', default=False,
395 help="Turn on script debugging")
396 parser.add_argument('--config-profile', default=None,
397 help=argparse.SUPPRESS)
398 parser.add_argument('--uninstall', action='store_true',
399 help="Uninstall the server and all data")
401 args = vars(parser.parse_args())
403 if args['config_profile']:
404 args = parse_config_profile(args)
406 if len(args['hostname'].split('.')) < 2:
407 raise ValueError('Hostname: %s is not a FQDN.' % args['hostname'])
409 if args['port'] and not args['port'].isdigit():
410 raise ValueError('Port number: %s is not an integer.' % args['port'])
412 # Validate that all path options begin with '/'
413 path_args = ['saml_base', 'saml_auth', 'saml_sp', 'saml_sp_logout',
414 'saml_sp_post', 'saml_sp_paos']
415 for path_arg in path_args:
416 if args[path_arg] is not None and not args[path_arg].startswith('/'):
417 raise ValueError('--%s must begin with a / character.' %
418 path_arg.replace('_', '-'))
420 # The saml_sp setting must be a subpath of saml_base since it is
421 # used as the MellonEndpointPath.
422 if not args['saml_sp'].startswith(args['saml_base']):
423 raise ValueError('--saml-sp must be a subpath of --saml-base.')
425 # The samle_auth setting must be a subpath of saml_base otherwise
426 # the IdP cannot be identified by mod_auth_mellon.
427 if not args['saml_auth'].startswith(args['saml_base']):
428 raise ValueError('--saml-auth must be a subpath of --saml-base.')
430 # The saml_sp_logout, saml_sp_post and saml_sp_paos settings must
431 # be subpaths of saml_sp (the mellon endpoint).
432 path_args = {'saml_sp_logout': 'logout',
433 'saml_sp_post': 'postResponse',
434 'saml_sp_paos': 'paosResponse'}
435 for path_arg, default_path in path_args.items():
436 if args[path_arg] is None:
437 args[path_arg] = '%s/%s' % (args['saml_sp'].rstrip('/'),
440 elif not args[path_arg].startswith(args['saml_sp']):
441 raise ValueError('--%s must be a subpath of --saml-sp' %
442 path_arg.replace('_', '-'))
444 # If saml_idp_url if being used, we require saml_sp_name to
445 # use when registering the SP.
446 if args['saml_idp_url'] and not args['saml_sp_name']:
447 raise ValueError('--saml-sp-name must be specified when using' +
450 # At least one on this list needs to be specified or we do nothing
456 if not present and not args['uninstall']:
457 raise ValueError('Nothing to install, please select a Service type.')
460 if __name__ == '__main__':
466 if 'uninstall' in args and args['uninstall'] is True:
470 except Exception, e: # pylint: disable=broad-except
472 if 'uninstall' in args and args['uninstall'] is True:
473 logging.info('Uninstallation aborted.')
475 logging.info('Installation aborted.')
479 if 'uninstall' in args and args['uninstall'] is True:
480 logging.info('Uninstallation complete.')
482 logging.info('Installation complete.')