friendica-addons/saml/saml.php

474 lines
13 KiB
PHP
Raw Normal View History

2021-05-17 03:56:37 +00:00
<?php
/*
* Name: SAML SSO and SLO
* Description: replace login and registration with a SAML identity provider.
2021-05-17 20:03:39 +00:00
* Version: 1.0
2021-05-17 03:56:37 +00:00
* Author: Ryan <https://friendica.verya.pe/profile/ryan>
*/
use Friendica\Content\Text\BBCode;
2021-05-17 03:56:37 +00:00
use Friendica\Core\Hook;
use Friendica\Core\Logger;
use Friendica\Core\Renderer;
use Friendica\Core\Session;
use Friendica\Database\DBA;
use Friendica\DI;
use Friendica\Model\User;
use Friendica\Util\Strings;
require_once(__DIR__ . '/vendor/autoload.php');
define('PW_LEN', 32); // number of characters to use for random passwords
2021-05-17 03:56:37 +00:00
function saml_module($a)
{
}
2021-05-17 03:56:37 +00:00
function saml_init($a)
{
if (DI::args()->getArgc() < 2) {
2021-05-17 17:55:15 +00:00
return;
}
2021-05-17 17:34:04 +00:00
if (!saml_is_configured()) {
echo 'Please configure the SAML add-on via the admin interface.';
return;
}
switch (DI::args()->get(1)) {
case 'metadata.xml':
2021-05-17 17:34:04 +00:00
saml_metadata();
break;
case 'sso':
2021-05-17 17:34:04 +00:00
saml_sso_reply($a);
break;
case 'slo':
2021-05-17 17:34:04 +00:00
saml_slo_reply();
break;
}
exit();
2021-05-17 03:56:37 +00:00
}
function saml_metadata()
{
2021-05-17 17:34:04 +00:00
try {
$settings = new \OneLogin\Saml2\Settings(saml_settings());
$metadata = $settings->getSPMetadata();
$errors = $settings->validateMetadata($metadata);
if (empty($errors)) {
header('Content-Type: text/xml');
echo $metadata;
} else {
throw new \OneLogin\Saml2\Error(
'Invalid SP metadata: '.implode(', ', $errors),
\OneLogin\Saml2\Error::METADATA_SP_INVALID
);
}
} catch (Exception $e) {
2021-05-17 17:55:15 +00:00
Logger::error($e->getMessage());
2021-05-17 17:34:04 +00:00
}
2021-05-17 03:56:37 +00:00
}
function saml_install()
{
2021-05-17 17:34:04 +00:00
Hook::register('login_hook', __FILE__, 'saml_sso_initiate');
Hook::register('logging_out', __FILE__, 'saml_slo_initiate');
Hook::register('head', __FILE__, 'saml_head');
Hook::register('footer', __FILE__, 'saml_footer');
2021-05-17 03:56:37 +00:00
}
function saml_head(&$a, &$b)
{
2021-05-17 17:34:04 +00:00
DI::page()->registerStylesheet(__DIR__ . '/saml.css');
2021-05-17 03:56:37 +00:00
}
function saml_footer(&$a, &$b)
{
2021-05-17 17:34:04 +00:00
$fragment = addslashes(BBCode::convert(DI::config()->get('saml', 'settings_statement')));
$b .= <<<EOL
2021-05-17 03:56:37 +00:00
<script>
var target=$("#settings-nickname-desc");
if (target.length) { target.append("<p>$fragment</p>"); }
2021-05-17 03:56:37 +00:00
</script>
EOL;
}
function saml_is_configured()
{
2021-05-17 17:34:04 +00:00
return
DI::config()->get('saml', 'idp_id') &&
DI::config()->get('saml', 'client_id') &&
DI::config()->get('saml', 'sso_url') &&
DI::config()->get('saml', 'slo_request_url') &&
DI::config()->get('saml', 'slo_response_url') &&
DI::config()->get('saml', 'sp_key') &&
DI::config()->get('saml', 'sp_cert') &&
DI::config()->get('saml', 'idp_cert');
2021-05-17 03:56:37 +00:00
}
function saml_sso_initiate(&$a, &$b)
{
2021-05-17 17:55:15 +00:00
if (!saml_is_configured()) {
Logger::warning('SAML SSO tried to trigger, but the SAML addon is not configured yet!');
2021-05-17 17:55:15 +00:00
return;
}
2021-05-17 17:34:04 +00:00
$auth = new \OneLogin\Saml2\Auth(saml_settings());
$ssoBuiltUrl = $auth->login(null, [], false, false, true);
2021-05-17 17:34:04 +00:00
$_SESSION['AuthNRequestID'] = $auth->getLastRequestID();
header('Pragma: no-cache');
header('Cache-Control: no-cache, must-revalidate');
header('Location: ' . $ssoBuiltUrl);
exit();
2021-05-17 03:56:37 +00:00
}
function saml_sso_reply($a)
{
2021-05-17 17:34:04 +00:00
$auth = new \OneLogin\Saml2\Auth(saml_settings());
$requestID = null;
2021-05-17 03:56:37 +00:00
2021-05-17 17:34:04 +00:00
if (isset($_SESSION) && isset($_SESSION['AuthNRequestID'])) {
$requestID = $_SESSION['AuthNRequestID'];
}
2021-05-17 03:56:37 +00:00
2021-05-17 17:34:04 +00:00
$auth->processResponse($requestID);
unset($_SESSION['AuthNRequestID']);
2021-05-17 03:56:37 +00:00
2021-05-17 17:34:04 +00:00
$errors = $auth->getErrors();
2021-05-17 03:56:37 +00:00
2021-05-17 17:34:04 +00:00
if (!empty($errors)) {
echo 'Errors encountered.';
2021-05-17 17:34:04 +00:00
Logger::error(implode(', ', $errors));
exit();
}
if (!$auth->isAuthenticated()) {
echo 'Not authenticated';
2021-05-17 17:34:04 +00:00
exit();
}
$username = $auth->getNameId();
$email = $auth->getAttributeWithFriendlyName('email')[0];
$name = $auth->getAttributeWithFriendlyName('givenName')[0];
$last_name = $auth->getAttributeWithFriendlyName('surname')[0];
if (strlen($last_name)) {
$name .= " $last_name";
}
if (!DBA::exists('user', ['nickname' => $username])) {
$user = saml_create_user($username, $email, $name);
} else {
$user = User::getByNickname($username);
}
if (!empty($user['uid'])) {
DI::auth()->setForUser($a, $user);
}
if (isset($_POST['RelayState'])
2021-05-17 17:55:15 +00:00
&& \OneLogin\Saml2\Utils::getSelfURL() != $_POST['RelayState']) {
2021-05-17 17:34:04 +00:00
$auth->redirectTo($_POST['RelayState']);
}
2021-05-17 03:56:37 +00:00
}
function saml_slo_initiate(&$a, &$b)
{
if (!saml_is_configured()) {
Logger::warning('SAML SLO tried to trigger, but the SAML addon is not configured yet!');
return;
}
2021-05-17 17:34:04 +00:00
$auth = new \OneLogin\Saml2\Auth(saml_settings());
$sloBuiltUrl = $auth->logout();
$_SESSION['LogoutRequestID'] = $auth->getLastRequestID();
header('Pragma: no-cache');
header('Cache-Control: no-cache, must-revalidate');
header('Location: ' . $sloBuiltUrl);
exit();
2021-05-17 03:56:37 +00:00
}
function saml_slo_reply()
{
2021-05-17 17:34:04 +00:00
$auth = new \OneLogin\Saml2\Auth(saml_settings());
2021-05-17 03:56:37 +00:00
2021-05-17 17:34:04 +00:00
if (isset($_SESSION) && isset($_SESSION['LogoutRequestID'])) {
$requestID = $_SESSION['LogoutRequestID'];
} else {
$requestID = null;
}
2021-05-17 03:56:37 +00:00
2021-05-17 17:34:04 +00:00
$auth->processSLO(false, $requestID);
2021-05-17 03:56:37 +00:00
2021-05-17 17:34:04 +00:00
$errors = $auth->getErrors();
2021-05-17 03:56:37 +00:00
2021-05-17 17:34:04 +00:00
if (empty($errors)) {
$auth->redirectTo(DI::baseUrl());
} else {
Logger::error(implode(', ', $errors));
}
2021-05-17 03:56:37 +00:00
}
function saml_input($key, $label, $description)
{
2021-05-17 17:34:04 +00:00
return [
'$' . $key => [
$key,
$label,
DI::config()->get('saml', $key),
$description,
2021-05-17 19:26:01 +00:00
true, // all the fields are required
2021-05-17 17:34:04 +00:00
]
];
2021-05-17 03:56:37 +00:00
}
2021-05-17 17:55:15 +00:00
function saml_addon_admin(&$a, &$o)
{
2021-05-17 17:55:15 +00:00
$form =
2021-05-17 17:34:04 +00:00
saml_input(
'settings_statement',
DI::l10n()->t('Settings statement'),
2021-05-17 17:59:03 +00:00
DI::l10n()->t('A statement on the settings page explaining where the user should go to change '
. 'their e-mail and password. BBCode allowed.')
2021-05-17 17:34:04 +00:00
) +
saml_input(
'idp_id',
DI::l10n()->t('IdP ID'),
DI::l10n()->t('Identity provider (IdP) entity URI (e.g., https://example.com/auth/realms/user).')
) +
saml_input(
'client_id',
DI::l10n()->t('Client ID'),
DI::l10n()->t('Identifier assigned to client by the identity provider (IdP).')
) +
saml_input(
'sso_url',
DI::l10n()->t('IdP SSO URL'),
DI::l10n()->t('The URL for your identity provider\'s SSO endpoint.')
) +
saml_input(
'slo_request_url',
DI::l10n()->t('IdP SLO request URL'),
DI::l10n()->t('The URL for your identity provider\'s SLO request endpoint.')
) +
saml_input(
'slo_response_url',
DI::l10n()->t('IdP SLO response URL'),
DI::l10n()->t('The URL for your identity provider\'s SLO response endpoint.')
) +
saml_input(
'sp_key',
DI::l10n()->t('SP private key'),
DI::l10n()->t('The private key the addon should use to authenticate.')
) +
saml_input(
'sp_cert',
DI::l10n()->t('SP certificate'),
DI::l10n()->t('The certficate for the addon\'s private key.')
) +
saml_input(
'idp_cert',
DI::l10n()->t('IdP certificate'),
DI::l10n()->t('The x509 certficate for your identity provider.')
) +
[
'$submit' => DI::l10n()->t('Save Settings'),
];
$t = Renderer::getMarkupTemplate('admin.tpl', 'addon/saml/');
2021-05-17 17:55:15 +00:00
$o = Renderer::replaceMacros($t, $form);
2021-05-17 03:56:37 +00:00
}
2021-05-17 17:55:15 +00:00
function saml_addon_admin_post(&$a)
{
$set = function ($key) {
$val = (!empty($_POST[$key]) ? trim($_POST[$key]) : '');
2021-05-17 17:34:04 +00:00
DI::config()->set('saml', $key, $val);
};
$set('idp_id');
$set('client_id');
$set('sso_url');
$set('slo_request_url');
$set('slo_response_url');
$set('sp_key');
$set('sp_cert');
$set('idp_cert');
$set('settings_statement');
2021-05-17 03:56:37 +00:00
}
function saml_create_user($username, $email, $name)
{
2021-05-17 17:34:04 +00:00
if (!strlen($email) || !strlen($name)) {
Logger::error('Could not create user: no email or username given.');
return false;
}
try {
$strong = false;
$bytes = openssl_random_pseudo_bytes(intval(ceil(PW_LEN * 0.75)), $strong);
if (!$strong) {
throw new Exception('Strong algorithm not available for PRNG.');
}
$user = User::create([
'username' => $name,
'nickname' => $username,
'email' => $email,
'password' => base64_encode($bytes), // should be at least PW_LEN long
2021-05-17 19:26:01 +00:00
'verified' => true
2021-05-17 17:34:04 +00:00
]);
2021-05-17 03:56:37 +00:00
2021-05-17 17:55:15 +00:00
return $user;
2021-05-17 17:34:04 +00:00
} catch (Exception $e) {
Logger::error(
'Exception while creating user',
[
'username' => $username,
'email' => $email,
'name' => $name,
'exception' => $e->getMessage(),
'trace' => $e->getTraceAsString()
2021-05-17 17:55:15 +00:00
]
);
2021-05-17 17:34:04 +00:00
return false;
}
2021-05-17 03:56:37 +00:00
}
function saml_settings()
{
return [
2021-05-17 17:34:04 +00:00
// If 'strict' is True, then the PHP Toolkit will reject unsigned
// or unencrypted messages if it expects them to be signed or encrypted.
// Also it will reject the messages if the SAML standard is not strictly
// followed: Destination, NameId, Conditions ... are validated too.
// Should never be set to anything else in production!
'strict' => true,
// Enable debug mode (to print errors).
'debug' => false,
// Set a BaseURL to be used instead of try to guess
// the BaseURL of the view that process the SAML Message.
// Ex http://sp.example.com/
// http://example.com/sp/
'baseurl' => DI::baseUrl() . '/saml',
2021-05-17 17:34:04 +00:00
// Service Provider Data that we are deploying.
'sp' => [
2021-05-17 17:34:04 +00:00
// Identifier of the SP entity (must be a URI)
2021-05-17 17:55:15 +00:00
'entityId' => DI::config()->get('saml', 'client_id'),
2021-05-17 17:34:04 +00:00
// Specifies info about where and how the <AuthnResponse> message MUST be
// returned to the requester, in this case our SP.
'assertionConsumerService' => [
2021-05-17 17:34:04 +00:00
// URL Location where the <Response> from the IdP will be returned
'url' => DI::baseUrl() . '/saml/sso',
2021-05-17 17:34:04 +00:00
// SAML protocol binding to be used when returning the <Response>
// message. OneLogin Toolkit supports this endpoint for the
// HTTP-POST binding only.
'binding' => 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST',
],
2021-05-17 17:34:04 +00:00
// If you need to specify requested attributes, set a
// attributeConsumingService. nameFormat, attributeValue and
// friendlyName can be omitted
'attributeConsumingService'=> [
'serviceName' => 'Friendica SAML SSO and SLO Addon',
'serviceDescription' => 'SLO and SSO support for Friendica',
'requestedAttributes' => [
[
2021-05-17 19:26:01 +00:00
'uid' => '',
'isRequired' => false,
]
]
],
2021-05-17 17:34:04 +00:00
// Specifies info about where and how the <Logout Response> message MUST be
// returned to the requester, in this case our SP.
'singleLogoutService' => [
2021-05-17 17:34:04 +00:00
// URL Location where the <Response> from the IdP will be returned
'url' => DI::baseUrl() . '/saml/slo',
2021-05-17 17:34:04 +00:00
// SAML protocol binding to be used when returning the <Response>
// message. OneLogin Toolkit supports the HTTP-Redirect binding
// only for this endpoint.
'binding' => 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect',
],
2021-05-17 17:34:04 +00:00
// Specifies the constraints on the name identifier to be used to
// represent the requested subject.
// Take a look on lib/Saml2/Constants.php to see the NameIdFormat supported.
'NameIDFormat' => 'urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified',
2021-05-17 17:34:04 +00:00
// Usually x509cert and privateKey of the SP are provided by files placed at
// the certs folder. But we can also provide them with the following parameters
2021-05-17 17:55:15 +00:00
'x509cert' => DI::config()->get('saml', 'sp_cert'),
'privateKey' => DI::config()->get('saml', 'sp_key'),
],
2021-05-17 17:34:04 +00:00
// Identity Provider Data that we want connected with our SP.
'idp' => [
2021-05-17 17:34:04 +00:00
// Identifier of the IdP entity (must be a URI)
2021-05-17 17:55:15 +00:00
'entityId' => DI::config()->get('saml', 'idp_id'),
2021-05-17 17:34:04 +00:00
// SSO endpoint info of the IdP. (Authentication Request protocol)
'singleSignOnService' => [
2021-05-17 17:34:04 +00:00
// URL Target of the IdP where the Authentication Request Message
// will be sent.
2021-05-17 17:55:15 +00:00
'url' => DI::config()->get('saml', 'sso_url'),
2021-05-17 17:34:04 +00:00
// SAML protocol binding to be used when returning the <Response>
// message. OneLogin Toolkit supports the HTTP-Redirect binding
// only for this endpoint.
'binding' => 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect',
],
2021-05-17 17:34:04 +00:00
// SLO endpoint info of the IdP.
'singleLogoutService' => [
2021-05-17 17:34:04 +00:00
// URL Location of the IdP where SLO Request will be sent.
2021-05-17 17:55:15 +00:00
'url' => DI::config()->get('saml', 'slo_request_url'),
2021-05-17 17:34:04 +00:00
// URL location of the IdP where SLO Response will be sent (ResponseLocation)
// if not set, url for the SLO Request will be used
2021-05-17 17:55:15 +00:00
'responseUrl' => DI::config()->get('saml', 'slo_response_url'),
2021-05-17 17:34:04 +00:00
// SAML protocol binding to be used when returning the <Response>
// message. OneLogin Toolkit supports the HTTP-Redirect binding
// only for this endpoint.
'binding' => 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect',
],
2021-05-17 19:26:01 +00:00
// Public x509 certificate of the IdP
'x509cert' => DI::config()->get('saml', 'idp_cert'),
],
'security' => [
2021-05-17 19:26:01 +00:00
'wantXMLValidation' => false,
// Indicates whether the <samlp:AuthnRequest> messages sent by this SP
// will be signed. [Metadata of the SP will offer this info]
'authnRequestsSigned' => true,
// Indicates whether the <samlp:logoutRequest> messages sent by this SP
// will be signed.
'logoutRequestSigned' => true,
// Indicates whether the <samlp:logoutResponse> messages sent by this SP
// will be signed.
'logoutResponseSigned' => true,
// Sign the Metadata
'signMetadata' => true,
]
];
2021-05-17 03:56:37 +00:00
}