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)
32 if (!saml_is_configured()) {
33 echo 'Please configure the SAML add-on via the admin interface.';
37 switch ($a->argv[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()
342 // If 'strict' is True, then the PHP Toolkit will reject unsigned
343 // or unencrypted messages if it expects them to be signed or encrypted.
344 // Also it will reject the messages if the SAML standard is not strictly
345 // followed: Destination, NameId, Conditions ... are validated too.
346 // Should never be set to anything else in production!
349 // Enable debug mode (to print errors).
352 // Set a BaseURL to be used instead of try to guess
353 // the BaseURL of the view that process the SAML Message.
354 // Ex http://sp.example.com/
355 // http://example.com/sp/
356 'baseurl' => DI::baseUrl() . '/saml',
358 // Service Provider Data that we are deploying.
360 // Identifier of the SP entity (must be a URI)
361 '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' => [
365 // URL Location where the <Response> from the IdP will be returned
366 'url' => DI::baseUrl() . '/saml/sso',
367 // SAML protocol binding to be used when returning the <Response>
368 // message. OneLogin Toolkit supports this endpoint for the
369 // HTTP-POST binding only.
370 'binding' => 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST',
372 // If you need to specify requested attributes, set a
373 // attributeConsumingService. nameFormat, attributeValue and
374 // friendlyName can be omitted
375 'attributeConsumingService'=> [
376 'serviceName' => 'Friendica SAML SSO and SLO Addon',
377 'serviceDescription' => 'SLO and SSO support for Friendica',
378 'requestedAttributes' => [
381 'isRequired' => false,
385 // Specifies info about where and how the <Logout Response> message MUST be
386 // returned to the requester, in this case our SP.
387 'singleLogoutService' => [
388 // URL Location where the <Response> from the IdP will be returned
389 'url' => DI::baseUrl() . '/saml/slo',
390 // SAML protocol binding to be used when returning the <Response>
391 // message. OneLogin Toolkit supports the HTTP-Redirect binding
392 // only for this endpoint.
393 'binding' => 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect',
395 // Specifies the constraints on the name identifier to be used to
396 // represent the requested subject.
397 // Take a look on lib/Saml2/Constants.php to see the NameIdFormat supported.
398 'NameIDFormat' => 'urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified',
399 // Usually x509cert and privateKey of the SP are provided by files placed at
400 // the certs folder. But we can also provide them with the following parameters
401 'x509cert' => DI::config()->get('saml', 'sp_cert'),
402 'privateKey' => DI::config()->get('saml', 'sp_key'),
405 // Identity Provider Data that we want connected with our SP.
407 // Identifier of the IdP entity (must be a URI)
408 'entityId' => DI::config()->get('saml', 'idp_id'),
409 // SSO endpoint info of the IdP. (Authentication Request protocol)
410 'singleSignOnService' => [
411 // URL Target of the IdP where the Authentication Request Message
413 'url' => DI::config()->get('saml', 'sso_url'),
414 // SAML protocol binding to be used when returning the <Response>
415 // message. OneLogin Toolkit supports the HTTP-Redirect binding
416 // only for this endpoint.
417 'binding' => 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect',
419 // SLO endpoint info of the IdP.
420 'singleLogoutService' => [
421 // URL Location of the IdP where SLO Request will be sent.
422 'url' => DI::config()->get('saml', 'slo_request_url'),
423 // URL location of the IdP where SLO Response will be sent (ResponseLocation)
424 // if not set, url for the SLO Request will be used
425 'responseUrl' => DI::config()->get('saml', 'slo_response_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',
431 // Public x509 certificate of the IdP
432 'x509cert' => DI::config()->get('saml', 'idp_cert'),
435 'wantXMLValidation' => false,
437 // Indicates whether the <samlp:AuthnRequest> messages sent by this SP
438 // will be signed. [Metadata of the SP will offer this info]
439 'authnRequestsSigned' => true,
441 // Indicates whether the <samlp:logoutRequest> messages sent by this SP
443 'logoutRequestSigned' => true,
445 // Indicates whether the <samlp:logoutResponse> messages sent by this SP
447 'logoutResponseSigned' => true,
450 'signMetadata' => true,