3 * Name: SAML SSO and SLO
4 * Description: replace login and registration with a SAML identity provider.
6 * Author: Ryan <https://friendica.verya.pe/profile/ryan>
9 use Friendica\Content\Text\BBCode;
10 use Friendica\Core\Hook;
11 use Friendica\Core\Logger;
12 use Friendica\Core\Renderer;
13 use Friendica\Database\DBA;
15 use Friendica\Model\User;
16 use OneLogin\Saml2\Utils;
18 require_once(__DIR__ . '/vendor/autoload.php');
20 define('PW_LEN', 32); // number of characters to use for random passwords
22 function saml_module() {}
26 if (DI::args()->getArgc() < 2) {
30 if (!saml_is_configured()) {
31 echo 'Please configure the SAML add-on via the admin interface.';
35 switch (DI::args()->get(1)) {
49 function saml_metadata()
52 $settings = new \OneLogin\Saml2\Settings(saml_settings());
53 $metadata = $settings->getSPMetadata();
54 $errors = $settings->validateMetadata($metadata);
57 header('Content-Type: text/xml');
60 throw new \OneLogin\Saml2\Error(
61 'Invalid SP metadata: '.implode(', ', $errors),
62 \OneLogin\Saml2\Error::METADATA_SP_INVALID
65 } catch (Exception $e) {
66 Logger::error($e->getMessage());
70 function saml_install()
72 Hook::register('login_hook', __FILE__, 'saml_sso_initiate');
73 Hook::register('logging_out', __FILE__, 'saml_slo_initiate');
74 Hook::register('head', __FILE__, 'saml_head');
75 Hook::register('footer', __FILE__, 'saml_footer');
78 function saml_head(string &$body)
80 DI::page()->registerStylesheet(__DIR__ . '/saml.css');
83 function saml_footer(string &$body)
85 $fragment = addslashes(BBCode::convertForUriId(User::getSystemUriId(), DI::config()->get('saml', 'settings_statement')));
88 var target=$("#settings-nickname-desc");
89 if (target.length) { target.append("<p>$fragment</p>"); }
94 function saml_is_configured()
97 DI::config()->get('saml', 'idp_id') &&
98 DI::config()->get('saml', 'client_id') &&
99 DI::config()->get('saml', 'sso_url') &&
100 DI::config()->get('saml', 'slo_request_url') &&
101 DI::config()->get('saml', 'slo_response_url') &&
102 DI::config()->get('saml', 'sp_key') &&
103 DI::config()->get('saml', 'sp_cert') &&
104 DI::config()->get('saml', 'idp_cert');
107 function saml_sso_initiate(string &$body)
109 if (!saml_is_configured()) {
110 Logger::warning('SAML SSO tried to trigger, but the SAML addon is not configured yet!');
114 $auth = new \OneLogin\Saml2\Auth(saml_settings());
115 $ssoBuiltUrl = $auth->login(null, [], false, false, true);
116 DI::session()->set('AuthNRequestID', $auth->getLastRequestID());
117 header('Pragma: no-cache');
118 header('Cache-Control: no-cache, must-revalidate');
119 header('Location: ' . $ssoBuiltUrl);
123 function saml_sso_reply()
125 $auth = new \OneLogin\Saml2\Auth(saml_settings());
128 if (DI::session()->exists('AuthNRequestID')) {
129 $requestID = DI::session()->get('AuthNRequestID');
132 $auth->processResponse($requestID);
133 DI::session()->remove('AuthNRequestID');
135 $errors = $auth->getErrors();
137 if (!empty($errors)) {
138 echo 'Errors encountered.';
139 Logger::error(implode(', ', $errors));
143 if (!$auth->isAuthenticated()) {
144 echo 'Not authenticated';
148 $username = $auth->getNameId();
149 $email = $auth->getAttributeWithFriendlyName('email')[0];
150 $name = $auth->getAttributeWithFriendlyName('givenName')[0];
151 $last_name = $auth->getAttributeWithFriendlyName('surname')[0];
153 if (strlen($last_name)) {
154 $name .= " $last_name";
157 if (!DBA::exists('user', ['nickname' => $username])) {
158 $user = saml_create_user($username, $email, $name);
160 $user = User::getByNickname($username);
163 if (!empty($user['uid'])) {
164 DI::auth()->setForUser(DI::app(), $user);
167 if (isset($_POST['RelayState']) && Utils::getSelfURL() != $_POST['RelayState']) {
168 $auth->redirectTo($_POST['RelayState']);
172 function saml_slo_initiate()
174 if (!saml_is_configured()) {
175 Logger::warning('SAML SLO tried to trigger, but the SAML addon is not configured yet!');
179 $auth = new \OneLogin\Saml2\Auth(saml_settings());
181 $sloBuiltUrl = $auth->logout();
182 DI::session()->set('LogoutRequestID', $auth->getLastRequestID());
183 header('Pragma: no-cache');
184 header('Cache-Control: no-cache, must-revalidate');
185 header('Location: ' . $sloBuiltUrl);
189 function saml_slo_reply()
191 $auth = new \OneLogin\Saml2\Auth(saml_settings());
193 if (DI::session()->exists('LogoutRequestID')) {
194 $requestID = DI::session()->get('LogoutRequestID');
199 $auth->processSLO(false, $requestID);
201 $errors = $auth->getErrors();
203 if (empty($errors)) {
204 $auth->redirectTo(DI::baseUrl());
206 Logger::error(implode(', ', $errors));
210 function saml_input($key, $label, $description)
216 DI::config()->get('saml', $key),
218 true, // all the fields are required
223 function saml_addon_admin(string &$o)
227 'settings_statement',
228 DI::l10n()->t('Settings statement'),
229 DI::l10n()->t('A statement on the settings page explaining where the user should go to change '
230 . 'their e-mail and password. BBCode allowed.')
234 DI::l10n()->t('IdP ID'),
235 DI::l10n()->t('Identity provider (IdP) entity URI (e.g., https://example.com/auth/realms/user).')
239 DI::l10n()->t('Client ID'),
240 DI::l10n()->t('Identifier assigned to client by the identity provider (IdP).')
244 DI::l10n()->t('IdP SSO URL'),
245 DI::l10n()->t('The URL for your identity provider\'s SSO endpoint.')
249 DI::l10n()->t('IdP SLO request URL'),
250 DI::l10n()->t('The URL for your identity provider\'s SLO request endpoint.')
254 DI::l10n()->t('IdP SLO response URL'),
255 DI::l10n()->t('The URL for your identity provider\'s SLO response endpoint.')
259 DI::l10n()->t('SP private key'),
260 DI::l10n()->t('The private key the addon should use to authenticate.')
264 DI::l10n()->t('SP certificate'),
265 DI::l10n()->t('The certficate for the addon\'s private key.')
269 DI::l10n()->t('IdP certificate'),
270 DI::l10n()->t('The x509 certficate for your identity provider.')
273 '$submit' => DI::l10n()->t('Save Settings'),
275 $t = Renderer::getMarkupTemplate('admin.tpl', 'addon/saml/');
276 $o = Renderer::replaceMacros($t, $form);
279 function saml_addon_admin_post()
281 $set = function ($key) {
282 $val = (!empty($_POST[$key]) ? trim($_POST[$key]) : '');
283 DI::config()->set('saml', $key, $val);
288 $set('slo_request_url');
289 $set('slo_response_url');
293 $set('settings_statement');
296 function saml_create_user($username, $email, $name)
298 if (!strlen($email) || !strlen($name)) {
299 Logger::error('Could not create user: no email or username given.');
305 $bytes = openssl_random_pseudo_bytes(intval(ceil(PW_LEN * 0.75)), $strong);
308 throw new Exception('Strong algorithm not available for PRNG.');
311 $user = User::create([
313 'nickname' => $username,
315 'password' => base64_encode($bytes), // should be at least PW_LEN long
320 } catch (Exception $e) {
322 'Exception while creating user',
324 'username' => $username,
327 'exception' => $e->getMessage(),
328 'trace' => $e->getTraceAsString()
336 function saml_settings()
340 // If 'strict' is True, then the PHP Toolkit will reject unsigned
341 // or unencrypted messages if it expects them to be signed or encrypted.
342 // Also it will reject the messages if the SAML standard is not strictly
343 // followed: Destination, NameId, Conditions ... are validated too.
344 // Should never be set to anything else in production!
347 // Enable debug mode (to print errors).
350 // Set a BaseURL to be used instead of try to guess
351 // the BaseURL of the view that process the SAML Message.
352 // Ex http://sp.example.com/
353 // http://example.com/sp/
354 'baseurl' => DI::baseUrl() . '/saml',
356 // Service Provider Data that we are deploying.
359 // Identifier of the SP entity (must be a URI)
360 'entityId' => DI::config()->get('saml', 'client_id'),
362 // Specifies info about where and how the <AuthnResponse> message MUST be
363 // returned to the requester, in this case our SP.
364 'assertionConsumerService' => [
366 // URL Location where the <Response> from the IdP will be returned
367 'url' => DI::baseUrl() . '/saml/sso',
369 // SAML protocol binding to be used when returning the <Response>
370 // message. OneLogin Toolkit supports this endpoint for the
371 // HTTP-POST binding only.
372 'binding' => 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST',
375 // If you need to specify requested attributes, set a
376 // attributeConsumingService. nameFormat, attributeValue and
377 // friendlyName can be omitted
378 'attributeConsumingService'=> [
379 'serviceName' => 'Friendica SAML SSO and SLO Addon',
380 'serviceDescription' => 'SLO and SSO support for Friendica',
381 'requestedAttributes' => [
384 'isRequired' => false,
389 // Specifies info about where and how the <Logout Response> message MUST be
390 // returned to the requester, in this case our SP.
391 'singleLogoutService' => [
393 // URL Location where the <Response> from the IdP will be returned
394 'url' => DI::baseUrl() . '/saml/slo',
396 // SAML protocol binding to be used when returning the <Response>
397 // message. OneLogin Toolkit supports the HTTP-Redirect binding
398 // only for this endpoint.
399 'binding' => 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect',
402 // Specifies the constraints on the name identifier to be used to
403 // represent the requested subject.
404 // Take a look on lib/Saml2/Constants.php to see the NameIdFormat supported.
405 'NameIDFormat' => 'urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified',
407 // Usually x509cert and privateKey of the SP are provided by files placed at
408 // the certs folder. But we can also provide them with the following parameters
409 'x509cert' => DI::config()->get('saml', 'sp_cert'),
410 'privateKey' => DI::config()->get('saml', 'sp_key'),
413 // Identity Provider Data that we want connected with our SP.
416 // Identifier of the IdP entity (must be a URI)
417 'entityId' => DI::config()->get('saml', 'idp_id'),
419 // SSO endpoint info of the IdP. (Authentication Request protocol)
420 'singleSignOnService' => [
422 // URL Target of the IdP where the Authentication Request Message
424 'url' => DI::config()->get('saml', 'sso_url'),
426 // SAML protocol binding to be used when returning the <Response>
427 // message. OneLogin Toolkit supports the HTTP-Redirect binding
428 // only for this endpoint.
429 'binding' => 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect',
432 // SLO endpoint info of the IdP.
433 'singleLogoutService' => [
435 // URL Location of the IdP where SLO Request will be sent.
436 'url' => DI::config()->get('saml', 'slo_request_url'),
438 // URL location of the IdP where SLO Response will be sent (ResponseLocation)
439 // if not set, url for the SLO Request will be used
440 'responseUrl' => DI::config()->get('saml', 'slo_response_url'),
442 // SAML protocol binding to be used when returning the <Response>
443 // message. OneLogin Toolkit supports the HTTP-Redirect binding
444 // only for this endpoint.
445 'binding' => 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect',
448 // Public x509 certificate of the IdP
449 'x509cert' => DI::config()->get('saml', 'idp_cert'),
452 'wantXMLValidation' => false,
454 // Indicates whether the <samlp:AuthnRequest> messages sent by this SP
455 // will be signed. [Metadata of the SP will offer this info]
456 'authnRequestsSigned' => true,
458 // Indicates whether the <samlp:logoutRequest> messages sent by this SP
460 'logoutRequestSigned' => true,
462 // Indicates whether the <samlp:logoutResponse> messages sent by this SP
464 'logoutResponseSigned' => true,
467 'signMetadata' => true,