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>
8 use Friendica\Content\Text\BBCode;
9 use Friendica\Core\Hook;
10 use Friendica\Core\Logger;
11 use Friendica\Core\Renderer;
12 use Friendica\Core\Session;
13 use Friendica\Database\DBA;
15 use Friendica\Model\User;
16 use Friendica\Util\Strings;
18 require_once(__DIR__ . '/vendor/autoload.php');
20 define('PW_LEN', 32); // number of characters to use for random passwords
22 function saml_module($a)
26 function saml_init($a)
28 if (DI::args()->getArgc() < 2) {
32 if (!saml_is_configured()) {
33 echo 'Please configure the SAML add-on via the admin interface.';
37 switch (DI::args()->get(1)) {
51 function saml_metadata()
54 $settings = new \OneLogin\Saml2\Settings(saml_settings());
55 $metadata = $settings->getSPMetadata();
56 $errors = $settings->validateMetadata($metadata);
59 header('Content-Type: text/xml');
62 throw new \OneLogin\Saml2\Error(
63 'Invalid SP metadata: '.implode(', ', $errors),
64 \OneLogin\Saml2\Error::METADATA_SP_INVALID
67 } catch (Exception $e) {
68 Logger::error($e->getMessage());
72 function saml_install()
74 Hook::register('login_hook', __FILE__, 'saml_sso_initiate');
75 Hook::register('logging_out', __FILE__, 'saml_slo_initiate');
76 Hook::register('head', __FILE__, 'saml_head');
77 Hook::register('footer', __FILE__, 'saml_footer');
80 function saml_head(&$a, &$b)
82 DI::page()->registerStylesheet(__DIR__ . '/saml.css');
85 function saml_footer(&$a, &$b)
87 $fragment = addslashes(BBCode::convert(DI::config()->get('saml', 'settings_statement')));
90 var target=$("#settings-nickname-desc");
91 if (target.length) { target.append("<p>$fragment</p>"); }
96 function saml_is_configured()
99 DI::config()->get('saml', 'idp_id') &&
100 DI::config()->get('saml', 'client_id') &&
101 DI::config()->get('saml', 'sso_url') &&
102 DI::config()->get('saml', 'slo_request_url') &&
103 DI::config()->get('saml', 'slo_response_url') &&
104 DI::config()->get('saml', 'sp_key') &&
105 DI::config()->get('saml', 'sp_cert') &&
106 DI::config()->get('saml', 'idp_cert');
109 function saml_sso_initiate(&$a, &$b)
111 if (!saml_is_configured()) {
112 Logger::warning('SAML SSO tried to trigger, but the SAML addon is not configured yet!');
116 $auth = new \OneLogin\Saml2\Auth(saml_settings());
117 $ssoBuiltUrl = $auth->login(null, [], false, false, true);
118 $_SESSION['AuthNRequestID'] = $auth->getLastRequestID();
119 header('Pragma: no-cache');
120 header('Cache-Control: no-cache, must-revalidate');
121 header('Location: ' . $ssoBuiltUrl);
125 function saml_sso_reply($a)
127 $auth = new \OneLogin\Saml2\Auth(saml_settings());
130 if (isset($_SESSION) && isset($_SESSION['AuthNRequestID'])) {
131 $requestID = $_SESSION['AuthNRequestID'];
134 $auth->processResponse($requestID);
135 unset($_SESSION['AuthNRequestID']);
137 $errors = $auth->getErrors();
139 if (!empty($errors)) {
140 echo 'Errors encountered.';
141 Logger::error(implode(', ', $errors));
145 if (!$auth->isAuthenticated()) {
146 echo 'Not authenticated';
150 $username = $auth->getNameId();
151 $email = $auth->getAttributeWithFriendlyName('email')[0];
152 $name = $auth->getAttributeWithFriendlyName('givenName')[0];
153 $last_name = $auth->getAttributeWithFriendlyName('surname')[0];
155 if (strlen($last_name)) {
156 $name .= " $last_name";
159 if (!DBA::exists('user', ['nickname' => $username])) {
160 $user = saml_create_user($username, $email, $name);
162 $user = User::getByNickname($username);
165 if (!empty($user['uid'])) {
166 DI::auth()->setForUser($a, $user);
169 if (isset($_POST['RelayState'])
170 && \OneLogin\Saml2\Utils::getSelfURL() != $_POST['RelayState']) {
171 $auth->redirectTo($_POST['RelayState']);
175 function saml_slo_initiate(&$a, &$b)
177 if (!saml_is_configured()) {
178 Logger::warning('SAML SLO tried to trigger, but the SAML addon is not configured yet!');
182 $auth = new \OneLogin\Saml2\Auth(saml_settings());
184 $sloBuiltUrl = $auth->logout();
185 $_SESSION['LogoutRequestID'] = $auth->getLastRequestID();
186 header('Pragma: no-cache');
187 header('Cache-Control: no-cache, must-revalidate');
188 header('Location: ' . $sloBuiltUrl);
192 function saml_slo_reply()
194 $auth = new \OneLogin\Saml2\Auth(saml_settings());
196 if (isset($_SESSION) && isset($_SESSION['LogoutRequestID'])) {
197 $requestID = $_SESSION['LogoutRequestID'];
202 $auth->processSLO(false, $requestID);
204 $errors = $auth->getErrors();
206 if (empty($errors)) {
207 $auth->redirectTo(DI::baseUrl());
209 Logger::error(implode(', ', $errors));
213 function saml_input($key, $label, $description)
219 DI::config()->get('saml', $key),
221 true, // all the fields are required
226 function saml_addon_admin(&$a, &$o)
230 'settings_statement',
231 DI::l10n()->t('Settings statement'),
232 DI::l10n()->t('A statement on the settings page explaining where the user should go to change '
233 . 'their e-mail and password. BBCode allowed.')
237 DI::l10n()->t('IdP ID'),
238 DI::l10n()->t('Identity provider (IdP) entity URI (e.g., https://example.com/auth/realms/user).')
242 DI::l10n()->t('Client ID'),
243 DI::l10n()->t('Identifier assigned to client by the identity provider (IdP).')
247 DI::l10n()->t('IdP SSO URL'),
248 DI::l10n()->t('The URL for your identity provider\'s SSO endpoint.')
252 DI::l10n()->t('IdP SLO request URL'),
253 DI::l10n()->t('The URL for your identity provider\'s SLO request endpoint.')
257 DI::l10n()->t('IdP SLO response URL'),
258 DI::l10n()->t('The URL for your identity provider\'s SLO response endpoint.')
262 DI::l10n()->t('SP private key'),
263 DI::l10n()->t('The private key the addon should use to authenticate.')
267 DI::l10n()->t('SP certificate'),
268 DI::l10n()->t('The certficate for the addon\'s private key.')
272 DI::l10n()->t('IdP certificate'),
273 DI::l10n()->t('The x509 certficate for your identity provider.')
276 '$submit' => DI::l10n()->t('Save Settings'),
278 $t = Renderer::getMarkupTemplate('admin.tpl', 'addon/saml/');
279 $o = Renderer::replaceMacros($t, $form);
282 function saml_addon_admin_post(&$a)
284 $set = function ($key) {
285 $val = (!empty($_POST[$key]) ? trim($_POST[$key]) : '');
286 DI::config()->set('saml', $key, $val);
291 $set('slo_request_url');
292 $set('slo_response_url');
296 $set('settings_statement');
299 function saml_create_user($username, $email, $name)
301 if (!strlen($email) || !strlen($name)) {
302 Logger::error('Could not create user: no email or username given.');
308 $bytes = openssl_random_pseudo_bytes(intval(ceil(PW_LEN * 0.75)), $strong);
311 throw new Exception('Strong algorithm not available for PRNG.');
314 $user = User::create([
316 'nickname' => $username,
318 'password' => base64_encode($bytes), // should be at least PW_LEN long
323 } catch (Exception $e) {
325 'Exception while creating user',
327 'username' => $username,
330 'exception' => $e->getMessage(),
331 'trace' => $e->getTraceAsString()
339 function saml_settings()
343 // If 'strict' is True, then the PHP Toolkit will reject unsigned
344 // or unencrypted messages if it expects them to be signed or encrypted.
345 // Also it will reject the messages if the SAML standard is not strictly
346 // followed: Destination, NameId, Conditions ... are validated too.
347 // Should never be set to anything else in production!
350 // Enable debug mode (to print errors).
353 // Set a BaseURL to be used instead of try to guess
354 // the BaseURL of the view that process the SAML Message.
355 // Ex http://sp.example.com/
356 // http://example.com/sp/
357 'baseurl' => DI::baseUrl() . '/saml',
359 // Service Provider Data that we are deploying.
362 // Identifier of the SP entity (must be a URI)
363 'entityId' => DI::config()->get('saml', 'client_id'),
365 // Specifies info about where and how the <AuthnResponse> message MUST be
366 // returned to the requester, in this case our SP.
367 'assertionConsumerService' => [
369 // URL Location where the <Response> from the IdP will be returned
370 'url' => DI::baseUrl() . '/saml/sso',
372 // SAML protocol binding to be used when returning the <Response>
373 // message. OneLogin Toolkit supports this endpoint for the
374 // HTTP-POST binding only.
375 'binding' => 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST',
378 // If you need to specify requested attributes, set a
379 // attributeConsumingService. nameFormat, attributeValue and
380 // friendlyName can be omitted
381 'attributeConsumingService'=> [
382 'serviceName' => 'Friendica SAML SSO and SLO Addon',
383 'serviceDescription' => 'SLO and SSO support for Friendica',
384 'requestedAttributes' => [
387 'isRequired' => false,
392 // Specifies info about where and how the <Logout Response> message MUST be
393 // returned to the requester, in this case our SP.
394 'singleLogoutService' => [
396 // URL Location where the <Response> from the IdP will be returned
397 'url' => DI::baseUrl() . '/saml/slo',
399 // SAML protocol binding to be used when returning the <Response>
400 // message. OneLogin Toolkit supports the HTTP-Redirect binding
401 // only for this endpoint.
402 'binding' => 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect',
405 // Specifies the constraints on the name identifier to be used to
406 // represent the requested subject.
407 // Take a look on lib/Saml2/Constants.php to see the NameIdFormat supported.
408 'NameIDFormat' => 'urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified',
410 // Usually x509cert and privateKey of the SP are provided by files placed at
411 // the certs folder. But we can also provide them with the following parameters
412 'x509cert' => DI::config()->get('saml', 'sp_cert'),
413 'privateKey' => DI::config()->get('saml', 'sp_key'),
416 // Identity Provider Data that we want connected with our SP.
419 // Identifier of the IdP entity (must be a URI)
420 'entityId' => DI::config()->get('saml', 'idp_id'),
422 // SSO endpoint info of the IdP. (Authentication Request protocol)
423 'singleSignOnService' => [
425 // URL Target of the IdP where the Authentication Request Message
427 'url' => DI::config()->get('saml', 'sso_url'),
429 // SAML protocol binding to be used when returning the <Response>
430 // message. OneLogin Toolkit supports the HTTP-Redirect binding
431 // only for this endpoint.
432 'binding' => 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect',
435 // SLO endpoint info of the IdP.
436 'singleLogoutService' => [
438 // URL Location of the IdP where SLO Request will be sent.
439 'url' => DI::config()->get('saml', 'slo_request_url'),
441 // URL location of the IdP where SLO Response will be sent (ResponseLocation)
442 // if not set, url for the SLO Request will be used
443 'responseUrl' => DI::config()->get('saml', 'slo_response_url'),
445 // SAML protocol binding to be used when returning the <Response>
446 // message. OneLogin Toolkit supports the HTTP-Redirect binding
447 // only for this endpoint.
448 'binding' => 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect',
451 // Public x509 certificate of the IdP
452 'x509cert' => DI::config()->get('saml', 'idp_cert'),
455 'wantXMLValidation' => false,
457 // Indicates whether the <samlp:AuthnRequest> messages sent by this SP
458 // will be signed. [Metadata of the SP will offer this info]
459 'authnRequestsSigned' => true,
461 // Indicates whether the <samlp:logoutRequest> messages sent by this SP
463 'logoutRequestSigned' => true,
465 // Indicates whether the <samlp:logoutResponse> messages sent by this SP
467 'logoutResponseSigned' => true,
470 'signMetadata' => true,