OpenFlyers SSO WordPress plugin 1.1.1

Import of the 1.1.0 archive plus a CLI guard on the two test scripts:
served over HTTP from wp-content/plugins they would delete the plugin
settings and create test accounts on the site.
This commit is contained in:
Lucas HENRY
2026-09-11 20:10:27 +02:00
commit 952607a112
8 changed files with 2826 additions and 0 deletions

View File

@@ -0,0 +1,596 @@
<?php
/**
* class-of-sso-admin.php
*
* Settings screen, member linking field and configuration diagnostics.
*
* @package OpenFlyers_SSO
*
* @link https://doc4-fr.openflyers.com/Plugin-WordPress Documentation publique
* @link https://work.openflyers.com/OF4-WordPress-SSO-plugin Fiche interne
*/
// Prevent direct access.
if (!defined('ABSPATH')) {
exit;
}
/**
* Class OF_SSO_Admin
*/
class OF_SSO_Admin
{
/**
* Register the admin hooks.
*
* @return void
*/
public static function init()
{
add_action('admin_menu', array(__CLASS__, 'addMenu'));
add_action('admin_init', array(__CLASS__, 'registerSettings'));
add_action('show_user_profile', array(__CLASS__, 'renderUserField'));
add_action('edit_user_profile', array(__CLASS__, 'renderUserField'));
add_action('personal_options_update', array(__CLASS__, 'saveUserField'));
add_action('edit_user_profile_update', array(__CLASS__, 'saveUserField'));
}
/**
* Add the settings page under the Settings menu.
*
* @return void
*/
public static function addMenu()
{
add_options_page(
__('OpenFlyers SSO', 'openflyers-sso'),
__('OpenFlyers SSO', 'openflyers-sso'),
'manage_options',
'openflyers-sso',
array(__CLASS__, 'renderPage')
);
}
/**
* Declare the option and its sanitize callback.
*
* @return void
*/
public static function registerSettings()
{
register_setting(
'of_sso_settings_group',
OF_SSO_OPTION,
array('sanitize_callback' => array(__CLASS__, 'sanitize'))
);
}
/**
* Sanitize the submitted settings.
*
* @param array $input Raw submitted values.
* @return array
*/
public static function sanitize($input)
{
$input = is_array($input) ? $input : array();
$current = of_sso_get_settings();
$output = array();
$textKeys = array('platform', 'client_id', 'default_role');
foreach ($textKeys as $key) {
$output[$key] = isset($input[$key]) ? sanitize_text_field($input[$key]) : '';
}
$urlKeys = array('base_url', 'redirect_uri', 'redirect_after_login');
foreach ($urlKeys as $key) {
$output[$key] = isset($input[$key]) ? esc_url_raw(trim($input[$key])) : '';
}
// Paths are kept as-is apart from trimming: they point outside the web root on purpose.
$pathKeys = array('cert_dir', 'auth_cert', 'auth_key', 'sign_cert', 'sign_key', 'ca_cert', 'server_sign_cert');
foreach ($pathKeys as $key) {
$output[$key] = isset($input[$key]) ? trim(wp_strip_all_tags($input[$key])) : '';
}
$boolKeys = array('send_x_ssl_cert', 'auto_create', 'show_login_button', 'debug');
foreach ($boolKeys as $key) {
$output[$key] = empty($input[$key]) ? 0 : 1;
}
// An empty secret field means "keep the stored value", so a secret is never wiped by accident.
foreach (array('client_secret', 'key_passphrase') as $key) {
$submitted = isset($input[$key]) ? trim($input[$key]) : '';
$output[$key] = ($submitted === '') ? $current[$key] : $submitted;
}
if (empty($output['base_url'])) {
$output['base_url'] = 'https://openflyers.com';
}
return $output;
}
/**
* Render the settings page.
*
* @return void
*/
public static function renderPage()
{
if (!current_user_can('manage_options')) {
return;
}
$settings = of_sso_get_settings();
$verdict = self::handleConnectionTest();
?>
<div class="wrap">
<h1><?php esc_html_e('OpenFlyers SSO', 'openflyers-sso'); ?></h1>
<p><?php esc_html_e('URL de redirection a declarer dans OpenFlyers (Administration > Configuration de l\'API) :', 'openflyers-sso'); ?></p>
<p><code><?php echo esc_html(of_sso_get_redirect_uri()); ?></code></p>
<?php self::renderConnectionTest($verdict); ?>
<form method="post" action="options.php">
<?php settings_fields('of_sso_settings_group'); ?>
<h2><?php esc_html_e('Plateforme et client', 'openflyers-sso'); ?></h2>
<table class="form-table" role="presentation">
<?php
self::textRow('platform', __('Code plateforme', 'openflyers-sso'), $settings['platform'], 'acat-lfcl');
self::descriptionRow(__('A laisser vide si la plateforme repond directement a la racine du domaine, ce qui est le cas des installations dediees.', 'openflyers-sso'));
self::textRow('base_url', __('URL de base OpenFlyers', 'openflyers-sso'), $settings['base_url'], 'https://openflyers.com');
self::textRow('client_id', __('client_id', 'openflyers-sso'), $settings['client_id'], '');
self::secretRow('client_secret', __('Passphrase (client_secret)', 'openflyers-sso'), $settings['client_secret']);
self::textRow('redirect_uri', __('URL de redirection (facultatif)', 'openflyers-sso'), $settings['redirect_uri'], of_sso_get_redirect_uri());
?>
</table>
<h2><?php esc_html_e('Certificats', 'openflyers-sso'); ?></h2>
<p class="description">
<?php esc_html_e('Indiquez le dossier ou vous avez depose les six fichiers fournis par OpenFlyers. Ce dossier doit etre hors de la racine web et lisible par PHP uniquement.', 'openflyers-sso'); ?>
</p>
<table class="form-table" role="presentation">
<?php
self::textRow('cert_dir', __('Dossier des certificats', 'openflyers-sso'), $settings['cert_dir'], '/home/site/of-certs');
self::secretRow('key_passphrase', __('Passphrase des cles privees (si protegees)', 'openflyers-sso'), $settings['key_passphrase']);
self::checkboxRow('send_x_ssl_cert', __('Envoyer l\'en-tete X-SSL-CERT', 'openflyers-sso'), $settings['send_x_ssl_cert'], __('A activer uniquement si OpenFlyers repond invalid_certificate alors que les certificats sont corrects.', 'openflyers-sso'));
?>
</table>
<p class="description">
<?php esc_html_e('Noms de fichiers attendus dans ce dossier :', 'openflyers-sso'); ?>
<code><?php echo implode('</code>, <code>', array_map('esc_html', of_sso_cert_file_names())); ?></code>
</p>
<details>
<summary style="cursor:pointer;margin:12px 0">
<?php esc_html_e('Chemins personnalises (avance)', 'openflyers-sso'); ?>
</summary>
<p class="description">
<?php esc_html_e('A remplir uniquement si un fichier porte un autre nom ou se trouve ailleurs. Un champ vide utilise le dossier ci-dessus.', 'openflyers-sso'); ?>
</p>
<table class="form-table" role="presentation">
<?php
$resolved = of_sso_resolve_cert_paths($settings);
self::textRow('auth_cert', __('Certificat TLS mutuel', 'openflyers-sso'), $settings['auth_cert'], $resolved['auth_cert']);
self::textRow('auth_key', __('Cle privee TLS mutuel', 'openflyers-sso'), $settings['auth_key'], $resolved['auth_key']);
self::textRow('sign_cert', __('Certificat de signature HTTP', 'openflyers-sso'), $settings['sign_cert'], $resolved['sign_cert']);
self::textRow('sign_key', __('Cle privee de signature HTTP', 'openflyers-sso'), $settings['sign_key'], $resolved['sign_key']);
self::textRow('ca_cert', __('Autorite de certification OpenFlyers', 'openflyers-sso'), $settings['ca_cert'], $resolved['ca_cert']);
self::textRow('server_sign_cert', __('Certificat de signature du serveur', 'openflyers-sso'), $settings['server_sign_cert'], $resolved['server_sign_cert']);
?>
</table>
</details>
<h2><?php esc_html_e('Comptes WordPress', 'openflyers-sso'); ?></h2>
<table class="form-table" role="presentation">
<?php
self::checkboxRow('auto_create', __('Creer automatiquement les comptes', 'openflyers-sso'), $settings['auto_create'], __('Si decoche, seuls les membres deja associes a un compte WordPress peuvent se connecter.', 'openflyers-sso'));
self::roleRow('default_role', __('Role des comptes crees', 'openflyers-sso'), $settings['default_role']);
self::textRow('redirect_after_login', __('Page apres connexion', 'openflyers-sso'), $settings['redirect_after_login'], home_url('/espace-membres/'));
self::checkboxRow('show_login_button', __('Bouton sur la page de connexion WordPress', 'openflyers-sso'), $settings['show_login_button'], '');
self::checkboxRow('debug', __('Journalisation', 'openflyers-sso'), $settings['debug'], __('Ecrit les erreurs dans le journal PHP (error_log).', 'openflyers-sso'));
?>
</table>
<?php submit_button(); ?>
</form>
<h2><?php esc_html_e('Diagnostic', 'openflyers-sso'); ?></h2>
<?php self::renderDiagnostics($settings); ?>
</div>
<?php
}
/**
* Run the connection test when its button was pressed.
*
* @return array|null Verdict returned by the client, or null when no test was requested.
*/
private static function handleConnectionTest()
{
if (empty($_POST['of_sso_test_connection']) or !current_user_can('manage_options')) {
return null;
}
if (!isset($_POST['of_sso_test_nonce'])
or !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['of_sso_test_nonce'])), 'of_sso_test_connection')
) {
return array('status' => 'unknown', 'detail' => __('Jeton de securite invalide, merci de recharger la page.', 'openflyers-sso'));
}
$client = of_sso_get_client();
if (!$client) {
return array('status' => 'unknown', 'detail' => __('Renseignez au moins le code plateforme et le client_id.', 'openflyers-sso'));
}
return $client->testConnection(of_sso_get_redirect_uri());
}
/**
* Render the connection test button and the verdict of the last run.
*
* @param array|null $verdict Verdict returned by handleConnectionTest().
* @return void
*/
private static function renderConnectionTest($verdict)
{
if (is_array($verdict)) {
// Every status but 'ok' names the exact link in the chain that refused the call.
$messages = array(
'ok' => array('success', __('Connexion a OpenFlyers reussie. Le certificat TLS, la signature et les identifiants du client sont acceptes : un membre peut se connecter.', 'openflyers-sso')),
'network' => array('error', __('Le serveur OpenFlyers n\'a pas pu etre contacte. Verifiez que l\'hebergeur autorise les connexions sortantes avec un certificat client, et que la cle privee est lisible par PHP.', 'openflyers-sso')),
'server_ca' => array('error', __('Le certificat du serveur OpenFlyers n\'a pas pu etre verifie avec le fichier ca.crt fourni. Ce fichier sert a valider le serveur, pas votre client : s\'il ne convient pas, retirez ca.crt du dossier des certificats pour utiliser le magasin d\'autorites du systeme.', 'openflyers-sso')),
'tls' => array('error', __('Le certificat TLS a ete refuse. Il ne correspond pas a celui enregistre dans OpenFlyers. Si les fichiers sont les bons, votre hebergeur termine sans doute le TLS sur un proxy : activez l\'option X-SSL-CERT.', 'openflyers-sso')),
'signature' => array('error', __('La signature HTTP a ete refusee. Verifiez la cle de signature, et surtout que l\'horloge du serveur est a l\'heure (NTP).', 'openflyers-sso')),
'client' => array('error', __('Le client_id ou la passphrase sont incorrects.', 'openflyers-sso')),
'grant_type' => array('error', __('Ce client n\'est pas declare avec le type d\'autorisation authorization_code dans OpenFlyers.', 'openflyers-sso')),
'unknown' => array('warning', __('Reponse inattendue d\'OpenFlyers.', 'openflyers-sso')),
);
$status = isset($messages[$verdict['status']]) ? $verdict['status'] : 'unknown';
list($noticeType, $text) = $messages[$status];
printf(
'<div class="notice notice-%s"><p><strong>%s</strong></p>%s</div>',
esc_attr($noticeType),
esc_html($text),
empty($verdict['detail'])
? ''
: '<p><code>' . esc_html($verdict['detail']) . '</code></p>'
);
}
?>
<form method="post">
<?php wp_nonce_field('of_sso_test_connection', 'of_sso_test_nonce'); ?>
<p>
<button type="submit" name="of_sso_test_connection" value="1" class="button button-secondary">
<?php esc_html_e('Tester la connexion a OpenFlyers', 'openflyers-sso'); ?>
</button>
<span class="description">
<?php esc_html_e('Verifie le certificat, la signature et les identifiants du client sans qu\'un membre ait a se connecter.', 'openflyers-sso'); ?>
</span>
</p>
</form>
<?php
}
/**
* Render the configuration checks.
*
* @param array $settings Current settings.
* @return void
*/
private static function renderDiagnostics(array $settings)
{
$checks = array();
$checks[] = array(
__('Extension cURL', 'openflyers-sso'),
function_exists('curl_init'),
__('Requise pour le TLS mutuel.', 'openflyers-sso'),
);
$checks[] = array(
__('Extension OpenSSL', 'openflyers-sso'),
function_exists('openssl_sign'),
__('Requise pour la signature HTTP.', 'openflyers-sso'),
);
$files = array(
'auth_cert' => __('Certificat TLS mutuel', 'openflyers-sso'),
'auth_key' => __('Cle privee TLS mutuel', 'openflyers-sso'),
'sign_cert' => __('Certificat de signature HTTP', 'openflyers-sso'),
'sign_key' => __('Cle privee de signature HTTP', 'openflyers-sso'),
'ca_cert' => __('Autorite de certification', 'openflyers-sso'),
'server_sign_cert' => __('Certificat de signature du serveur', 'openflyers-sso'),
);
// The folder setting and the per-file overrides both land here.
$paths = of_sso_resolve_cert_paths($settings);
foreach ($files as $key => $label) {
$path = $paths[$key];
$comment = '';
if (!empty($path) and is_readable($path) and substr($key, -4) === 'cert') {
$parsed = openssl_x509_parse((string) file_get_contents($path));
if (!empty($parsed['validTo_time_t'])) {
$comment = sprintf(
/* translators: %s: certificate expiry date. */
__('Expire le %s', 'openflyers-sso'),
date_i18n(get_option('date_format'), $parsed['validTo_time_t'])
);
}
}
// ca.crt only overrides the bundle used to validate the OpenFlyers server; without it
// the system store applies, which is what most hosts want.
if ($key === 'ca_cert' and empty($path)) {
$checks[] = array(
$label,
true,
__('Absent : le magasin d\'autorites du systeme sera utilise.', 'openflyers-sso'),
);
continue;
}
if (empty($path)) {
$comment = __('Aucun chemin : renseignez le dossier des certificats.', 'openflyers-sso');
} elseif (!is_readable($path)) {
$comment = sprintf(
/* translators: %s: expected file path. */
__('Introuvable ou illisible : %s', 'openflyers-sso'),
$path
);
}
$checks[] = array($label, !empty($path) && is_readable($path), $comment);
}
// A certificate paired with the wrong key fails at handshake time with an obscure error.
$pairs = array(
'auth' => array('auth_cert', 'auth_key', __('Le certificat TLS et sa cle correspondent', 'openflyers-sso')),
'sign' => array('sign_cert', 'sign_key', __('Le certificat de signature et sa cle correspondent', 'openflyers-sso')),
);
foreach ($pairs as $pair) {
list($certKey, $keyKey, $label) = $pair;
if (empty($paths[$certKey]) or empty($paths[$keyKey])
or !is_readable($paths[$certKey]) or !is_readable($paths[$keyKey])
) {
continue;
}
$privateKey = empty($settings['key_passphrase'])
? openssl_get_privatekey((string) file_get_contents($paths[$keyKey]))
: openssl_get_privatekey((string) file_get_contents($paths[$keyKey]), $settings['key_passphrase']);
$matches = $privateKey
? openssl_x509_check_private_key((string) file_get_contents($paths[$certKey]), $privateKey)
: false;
$checks[] = array(
$label,
$matches,
$matches ? '' : __('La cle ne correspond pas au certificat, ou la passphrase est incorrecte.', 'openflyers-sso'),
);
}
// A private key readable by anyone on a shared host is the main risk of this setup.
// Skipped on Windows, where fileperms() says nothing about the actual ACL.
foreach (array('auth_key', 'sign_key') as $key) {
if (DIRECTORY_SEPARATOR === '\\') {
break;
}
if (!empty($paths[$key]) and is_readable($paths[$key])) {
$perms = substr(sprintf('%o', fileperms($paths[$key])), -3);
$checks[] = array(
sprintf(
/* translators: %s: setting label. */
__('Permissions de %s', 'openflyers-sso'),
$key
),
in_array($perms, array('600', '400'), true),
sprintf(
/* translators: %s: octal file permissions. */
__('Actuellement %s, attendu 600.', 'openflyers-sso'),
$perms
),
);
}
}
echo '<table class="widefat striped" style="max-width:900px">';
foreach ($checks as $check) {
list($label, $ok, $comment) = $check;
printf(
'<tr><td style="width:320px">%s</td><td style="width:60px">%s</td><td>%s</td></tr>',
esc_html($label),
$ok ? '<span style="color:#00a32a">&#10003;</span>' : '<span style="color:#d63638">&#10007;</span>',
esc_html($comment)
);
}
echo '</table>';
}
/**
* Render a text input row.
*
* @param string $key Setting key.
* @param string $label Field label.
* @param string $value Current value.
* @param string $placeholder Placeholder text.
* @return void
*/
private static function textRow($key, $label, $value, $placeholder)
{
printf(
'<tr><th scope="row"><label for="of_sso_%1$s">%2$s</label></th>'
. '<td><input type="text" class="regular-text" id="of_sso_%1$s" name="%3$s[%1$s]" value="%4$s" placeholder="%5$s" /></td></tr>',
esc_attr($key),
esc_html($label),
esc_attr(OF_SSO_OPTION),
esc_attr($value),
esc_attr($placeholder)
);
}
/**
* Render a full-width note under the previous field.
*
* @param string $text Help text.
* @return void
*/
private static function descriptionRow($text)
{
printf('<tr><th scope="row"></th><td><p class="description">%s</p></td></tr>', esc_html($text));
}
/**
* Render a write-only secret row.
*
* @param string $key Setting key.
* @param string $label Field label.
* @param string $value Current value.
* @return void
*/
private static function secretRow($key, $label, $value)
{
printf(
'<tr><th scope="row"><label for="of_sso_%1$s">%2$s</label></th>'
. '<td><input type="password" class="regular-text" id="of_sso_%1$s" name="%3$s[%1$s]" value="" autocomplete="new-password" />'
. '<p class="description">%4$s</p></td></tr>',
esc_attr($key),
esc_html($label),
esc_attr(OF_SSO_OPTION),
empty($value)
? esc_html__('Non renseigne.', 'openflyers-sso')
: esc_html__('Deja enregistre. Laisser vide pour conserver la valeur actuelle.', 'openflyers-sso')
);
}
/**
* Render a checkbox row.
*
* @param string $key Setting key.
* @param string $label Field label.
* @param int $value Current value.
* @param string $description Help text.
* @return void
*/
private static function checkboxRow($key, $label, $value, $description)
{
printf(
'<tr><th scope="row">%2$s</th><td><label><input type="checkbox" id="of_sso_%1$s" name="%3$s[%1$s]" value="1" %4$s /> %2$s</label>'
. '<p class="description">%5$s</p></td></tr>',
esc_attr($key),
esc_html($label),
esc_attr(OF_SSO_OPTION),
checked(1, (int) $value, false),
esc_html($description)
);
}
/**
* Render the role selector.
*
* @param string $key Setting key.
* @param string $label Field label.
* @param string $value Current value.
* @return void
*/
private static function roleRow($key, $label, $value)
{
printf(
'<tr><th scope="row"><label for="of_sso_%1$s">%2$s</label></th><td><select id="of_sso_%1$s" name="%3$s[%1$s]">',
esc_attr($key),
esc_html($label),
esc_attr(OF_SSO_OPTION)
);
// wp_roles() is always available, unlike wp_dropdown_roles() which needs the admin includes.
foreach (wp_roles()->get_names() as $role => $name) {
printf(
'<option value="%s" %s>%s</option>',
esc_attr($role),
selected($role, $value, false),
esc_html(translate_user_role($name))
);
}
echo '</select></td></tr>';
}
/**
* Display the OpenFlyers identifier on the user profile screen.
*
* @param WP_User $user User being edited.
* @return void
*/
public static function renderUserField($user)
{
if (!current_user_can('edit_users') and get_current_user_id() !== $user->ID) {
return;
}
$value = get_user_meta($user->ID, OF_SSO_USER_META, true);
$editable = current_user_can('edit_users');
?>
<h2><?php esc_html_e('OpenFlyers', 'openflyers-sso'); ?></h2>
<table class="form-table" role="presentation">
<tr>
<th><label for="of_sso_user_id"><?php esc_html_e('Identifiant du membre', 'openflyers-sso'); ?></label></th>
<td>
<?php if ($editable) : ?>
<?php wp_nonce_field('of_sso_user_field', 'of_sso_user_nonce'); ?>
<input type="text" id="of_sso_user_id" name="of_sso_user_id" value="<?php echo esc_attr($value); ?>" class="regular-text" />
<p class="description"><?php esc_html_e('Identifiant OpenFlyers du membre. Necessaire pour associer ce compte WordPress a un compte OpenFlyers.', 'openflyers-sso'); ?></p>
<?php else : ?>
<code><?php echo esc_html($value ? $value : '-'); ?></code>
<?php endif; ?>
</td>
</tr>
</table>
<?php
}
/**
* Save the OpenFlyers identifier from the user profile screen.
*
* @param int $userId Edited user identifier.
* @return void
*/
public static function saveUserField($userId)
{
if (!current_user_can('edit_users')) {
return;
}
if (!isset($_POST['of_sso_user_nonce'])
or !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['of_sso_user_nonce'])), 'of_sso_user_field')
) {
return;
}
$value = isset($_POST['of_sso_user_id']) ? sanitize_text_field(wp_unslash($_POST['of_sso_user_id'])) : '';
if ($value === '') {
delete_user_meta($userId, OF_SSO_USER_META);
return;
}
update_user_meta($userId, OF_SSO_USER_META, (string) absint($value));
}
}

View File

@@ -0,0 +1,670 @@
<?php
/**
* class-of-sso-client.php
*
* OpenFlyers OAuth 2.0 protocol client.
*
* Ported from the official OpenFlyers demonstration client (oauth2-demo/ClientDemo.php).
* The OpenFlyers authorization server is stricter than a plain OAuth2/OIDC provider: every call to
* the token and resource endpoints must be sent over mutual TLS AND carry a Cavage HTTP Signature
* header, and the server signs its own responses (Digest + Signature) which the client must verify.
*
* @package OpenFlyers_SSO
*
* @link https://doc4-fr.openflyers.com/Plugin-WordPress Documentation publique
* @link https://work.openflyers.com/OF4-WordPress-SSO-plugin Fiche interne
*/
// Prevent direct access.
if (!defined('ABSPATH')) {
exit;
}
/**
* Class OF_SSO_Client
*/
class OF_SSO_Client
{
/**
* Configuration keys: client_id, client_secret, authorize_uri, token_uri, resource_uri,
* revoke_uri, auth_cert, auth_key, sign_cert, sign_key, ca_cert, server_sign_cert,
* key_passphrase, send_x_ssl_cert.
*
* @var array
*/
private $config;
/**
* Last error message, for display and logging.
*
* @var string
*/
private $lastError = '';
/**
* OAuth2 error code returned by the last failed call ('invalid_client', 'invalid_grant', ...).
*
* @var string
*/
private $lastErrorCode = '';
/**
* cURL error number of the last failed call, 0 when the failure happened above the transport.
*
* @var int
*/
private $lastCurlErrno = 0;
/**
* OF_SSO_Client constructor.
*
* @param array $config Client configuration.
*/
public function __construct(array $config)
{
$this->config = $config;
}
/**
* Return the last error raised by a request.
*
* @return string
*/
public function getLastError()
{
return $this->lastError;
}
/**
* Return the OAuth2 error code of the last failed call.
*
* @return string
*/
public function getLastErrorCode()
{
return $this->lastErrorCode;
}
/**
* Return the cURL error number of the last failed call.
*
* @return int
*/
public function getLastCurlErrno()
{
return $this->lastCurlErrno;
}
/**
* Generate a PKCE code_verifier.
*
* @param int $length Length of the generated string.
* @return string
*/
public static function generateCodeVerifier($length = 128)
{
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-._~';
$output = '';
for ($i = 0; $i < $length; $i++) {
$output .= $characters[random_int(0, strlen($characters) - 1)];
}
return $output;
}
/**
* Compute the PKCE code_challenge (S256) matching a code_verifier.
*
* @param string $codeVerifier The code_verifier.
* @return string
*/
public static function computeCodeChallenge($codeVerifier)
{
return strtr(rtrim(base64_encode(hash('sha256', $codeVerifier, true)), '='), '+/', '-_');
}
/**
* Build the URL the member's browser must be redirected to in order to log in on OpenFlyers.
*
* @param string $redirectUri Callback URL, must match the one registered in OpenFlyers.
* @param string $state Anti-CSRF opaque value.
* @param string $codeChallenge PKCE challenge.
* @param string $scope Requested scope, 'default.login' for authentication.
* @return string
*/
public function getAuthorizeUrl($redirectUri, $state, $codeChallenge, $scope = 'default.login')
{
$params = array(
'response_type' => 'code',
'client_id' => $this->config['client_id'],
'redirect_uri' => $redirectUri,
'scope' => $scope,
'state' => $state,
'code_challenge' => $codeChallenge,
'code_challenge_method' => 'S256',
);
return $this->config['authorize_uri'] . '?' . http_build_query($params);
}
/**
* Exchange an authorization code for an access token.
*
* @param string $code Authorization code returned by the authorization endpoint.
* @param string $codeVerifier PKCE verifier matching the challenge sent at authorize time.
* @param string $redirectUri Same callback URL as the one used to obtain the code.
* @return array|false Token array on success, false on failure.
*/
public function exchangeCode($code, $codeVerifier, $redirectUri)
{
return $this->apiRequest(
$this->config['token_uri'],
array(
'grant_type' => 'authorization_code',
'client_id' => $this->config['client_id'],
'client_secret' => empty($this->config['client_secret']) ? null : $this->config['client_secret'],
'redirect_uri' => $redirectUri,
'code' => $code,
'code_verifier' => $codeVerifier,
),
null,
true
);
}
/**
* Renew an access token from a refresh token.
*
* @param string $refreshToken The refresh token.
* @param string $scope Requested scope.
* @return array|false
*/
public function refreshToken($refreshToken, $scope = 'default.login')
{
return $this->apiRequest(
$this->config['token_uri'],
array(
'grant_type' => 'refresh_token',
'client_id' => $this->config['client_id'],
'client_secret' => empty($this->config['client_secret']) ? null : $this->config['client_secret'],
'refresh_token' => $refreshToken,
'scope' => $scope,
),
null,
true
);
}
/**
* Retrieve the OpenFlyers identifier of the member who authorized the token.
*
* The 'default.login' scope exposes the user identifier and nothing else.
*
* @param array $token Token array returned by exchangeCode().
* @return int|false OpenFlyers user id, or false on failure.
*/
public function getUserId(array $token)
{
$body = $this->apiRequest(
$this->config['resource_uri'],
array(
'resource_type' => 'user_information',
'client_id' => $this->config['client_id'],
),
$token,
false
);
if (!is_array($body) or !isset($body['user_id'])) {
$this->lastError = $this->lastError ? $this->lastError : 'No user_id in the resource server response';
return false;
}
return (int) $body['user_id'];
}
/**
* Retrieve a report from the resource server.
*
* Requires the 'reports.readonly' (custom report) or 'genericreports.readonly' (generic report)
* scope to have been granted to the token. Used when the member space needs more than the bare
* user identifier (name, e-mail, membership status, ...).
*
* @param array $token Token array returned by exchangeCode().
* @param int $reportId Identifier of the report in OpenFlyers.
* @param string $resourceType 'report' for a custom report, 'generic_report' otherwise.
* @param array $replacementList Report variables, as name => value.
* @return array|string|false Decoded JSON, raw CSV body, or false on failure.
*/
public function getReport(array $token, $reportId, $resourceType = 'report', array $replacementList = array())
{
$post = array(
'resource_type' => $resourceType,
'report_id' => (int) $reportId,
'client_id' => $this->config['client_id'],
);
if (!empty($replacementList)) {
$post['replacementList'] = $replacementList;
}
return $this->apiRequest($this->config['resource_uri'], $post, $token, false);
}
/**
* Revoke a token on the authorization server.
*
* @param array $token Token array holding the refresh token to revoke.
* @return bool
*/
public function revoke(array $token)
{
if (empty($this->config['revoke_uri']) or empty($token['refresh_token'])) {
return false;
}
$response = $this->apiRequest(
$this->config['revoke_uri'],
array(
'client_id' => $this->config['client_id'],
'token' => $token['refresh_token'],
'token_type_hint' => 'refresh_token',
),
$token,
false
);
return $response !== false;
}
/**
* Probe the token endpoint with a deliberately invalid authorization code.
*
* Everything guarding that endpoint is exercised on the way in: mutual TLS, HTTP signature and
* client credentials. Only the code itself cannot be valid. So a refusal that complains about
* the code, and nothing else, means the whole authentication chain is accepted. That is what
* has to be confirmed before a member ever tries to log in, and it needs no member and no
* browser.
*
* @param string $redirectUri The callback URL registered in OpenFlyers.
* @return array Verdict as array('status' => string, 'detail' => string), where status is one
* of 'ok', 'network', 'tls', 'signature', 'client', 'grant_type', 'unknown'.
*/
public function testConnection($redirectUri)
{
$this->exchangeCode('of-sso-connection-probe', self::generateCodeVerifier(), $redirectUri);
$code = $this->lastErrorCode;
$message = $this->lastError;
// CAINFO verifies the *server* certificate. A ca.crt that does not chain up to the one
// OpenFlyers serves stops the call here, which looks like a network failure but is not.
if (in_array($this->lastCurlErrno, array(60, 77), true)) {
return array('status' => 'server_ca', 'detail' => $message);
}
// Nothing reached the server: the failure is in the transport or in the key material.
if ($this->lastCurlErrno !== 0) {
return array('status' => 'network', 'detail' => $message);
}
// 'invalid_certificate' comes from the application, 'ssl_certificate_error' from the web
// server in front of it. Both mean the same thing to whoever has to fix it.
if ($code === 'invalid_certificate' or $code === 'ssl_certificate_error') {
return array('status' => 'tls', 'detail' => $message);
}
// A signature refusal also comes back as invalid_request, so the wording decides.
if (stripos($message, 'signature') !== false) {
return array('status' => 'signature', 'detail' => $message);
}
if ($code === 'invalid_client') {
return array('status' => 'client', 'detail' => $message);
}
if ($code === 'unsupported_grant_type') {
return array('status' => 'grant_type', 'detail' => $message);
}
// Anything else means the request was authenticated and only the fake code was rejected.
if ($code !== '') {
return array('status' => 'ok', 'detail' => $message);
}
return array('status' => 'unknown', 'detail' => $message);
}
/** Private methods */
/**
* Send a signed request over mutual TLS to the authorization or resource server.
*
* @param string $url Endpoint URL.
* @param array $post POST parameters.
* @param array|null $token Access token to send as a bearer, if any.
* @param bool $verifySignature Whether the response signature must be verified.
* @return array|string|false
*/
private function apiRequest($url, array $post, $token = null, $verifySignature = true)
{
$this->lastError = '';
$this->lastErrorCode = '';
$this->lastCurlErrno = 0;
// Every certificate and key must be readable before anything is sent over the wire.
if (!$this->checkFiles()) {
return false;
}
// Null values would be sent as empty strings and break client authentication.
$post = array_filter(
$post,
function ($value) {
return !is_null($value);
}
);
$postData = http_build_query($post);
// Headers covered by the HTTP signature. The order defines the signing string.
$headersToSign = array(
'Content-Type' => 'application/x-www-form-urlencoded',
'digest' => 'SHA-256=' . base64_encode(hash('sha256', $postData, true)),
'(request-target)' => 'post ' . parse_url($url, PHP_URL_PATH),
'Host' => parse_url($url, PHP_URL_HOST),
'Date' => gmdate('D, j M Y H:i:s T'),
);
$signKey = $this->readFile($this->config['sign_key']);
$keyId = openssl_x509_fingerprint($this->readFile($this->config['sign_cert']));
$headers = array();
$headers['Signature'] = $this->generateSignatureHeader($headersToSign, $keyId, $signKey);
$headers['Accept'] = 'application/json';
$headers['User-Agent'] = 'OpenFlyers-SSO-WordPress/' . OF_SSO_VERSION;
// Some hosting setups terminate TLS on a proxy that does not forward the client certificate
// to PHP. In that case OpenFlyers accepts the certificate fingerprint in X-SSL-CERT instead.
if (!empty($this->config['send_x_ssl_cert'])) {
$headers['X-SSL-CERT'] = openssl_x509_fingerprint($this->readFile($this->config['auth_cert']));
}
// '(request-target)' is a signing pseudo-header and must not be sent as a real header.
unset($headersToSign['(request-target)']);
$headers += $headersToSign;
if ($token and isset($token['access_token'])) {
$tokenType = isset($token['token_type']) ? $token['token_type'] : 'Bearer';
$headers['Authorization'] = $tokenType . ' ' . $token['access_token'];
}
$httpHeaders = array();
foreach ($headers as $key => $value) {
$httpHeaders[] = trim($key) . ': ' . trim($value);
}
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HEADER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $postData);
curl_setopt($curl, CURLOPT_HTTPHEADER, $httpHeaders);
curl_setopt($curl, CURLOPT_TIMEOUT, 30);
curl_setopt($curl, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2);
// Mutual TLS: client certificate and private key issued by the OpenFlyers PKI.
curl_setopt($curl, CURLOPT_SSLCERT, $this->config['auth_cert']);
curl_setopt($curl, CURLOPT_SSLKEY, $this->config['auth_key']);
if (!empty($this->config['key_passphrase'])) {
curl_setopt($curl, CURLOPT_KEYPASSWD, $this->config['key_passphrase']);
}
if (!empty($this->config['ca_cert'])) {
curl_setopt($curl, CURLOPT_CAINFO, $this->config['ca_cert']);
}
$response = curl_exec($curl);
$errno = curl_errno($curl);
$error = curl_error($curl);
curl_close($curl);
if ($response === false) {
$this->lastCurlErrno = $errno;
$this->lastError = sprintf('cURL error %d: %s', $errno, $error);
OF_SSO_Logger::log($this->lastError . ' (' . $url . ')');
return false;
}
return $this->parseResponse($response, $url, $verifySignature);
}
/**
* Check that every configured certificate and key can be read.
*
* @return bool
*/
private function checkFiles()
{
$required = array('auth_cert', 'auth_key', 'sign_cert', 'sign_key');
if (!empty($this->config['ca_cert'])) {
$required[] = 'ca_cert';
}
foreach ($required as $key) {
if (empty($this->config[$key]) or !is_readable($this->config[$key])) {
$this->lastError = sprintf('Unreadable or missing file for "%s"', $key);
OF_SSO_Logger::log($this->lastError);
return false;
}
}
return true;
}
/**
* Build the Cavage HTTP Signature header line.
*
* @param array $headersToSign Headers to cover, as name => value.
* @param string $keyId Fingerprint of the signing certificate.
* @param string $privateKey PEM encoded private key.
* @return string
*/
private function generateSignatureHeader(array $headersToSign, $keyId, $privateKey)
{
$headerList = '';
$signatureString = '';
foreach ($headersToSign as $key => $value) {
$normalizedKey = trim(strtolower($key));
$headerList .= $normalizedKey . ' ';
$signatureString .= $normalizedKey . ': ' . trim($value) . "\n";
}
$headerList = trim($headerList);
$signatureString = trim($signatureString);
$key = empty($this->config['key_passphrase'])
? openssl_get_privatekey($privateKey)
: openssl_get_privatekey($privateKey, $this->config['key_passphrase']);
$signature = '';
openssl_sign($signatureString, $signature, $key, 'RSA-SHA256');
return sprintf(
'keyId="%s",algorithm="rsa-sha256",headers="%s",signature="%s"',
$keyId,
$headerList,
base64_encode($signature)
);
}
/**
* Split the raw cURL response, check its status, verify Digest and Signature, decode the body.
*
* @param string $response Raw response including headers.
* @param string $url Endpoint that was called, for logging.
* @param bool $verifySignature Whether a valid response signature is mandatory.
* @return array|string|false
*/
private function parseResponse($response, $url, $verifySignature)
{
$parts = explode("\r\n\r\n", $response, 2);
if (count($parts) < 2) {
$this->lastError = 'Malformed response from the OpenFlyers server';
OF_SSO_Logger::log($this->lastError . ' (' . $url . ')');
return false;
}
list($rawHeaders, $body) = $parts;
// An informational block ('100 Continue') may precede the real response. Match it on the
// status line only: any "100" elsewhere in the headers, in a cookie or a content length,
// would otherwise split the body at the wrong place and lose the payload.
while (preg_match('#^HTTP/[0-9.]+\s+1\d\d#', $rawHeaders)) {
$split = explode("\r\n\r\n", $body, 2);
if (count($split) !== 2) {
break;
}
list($rawHeaders, $body) = $split;
}
$headerLines = explode("\r\n", $rawHeaders);
$statusLine = array_shift($headerLines);
$headers = array();
foreach ($headerLines as $line) {
if (strpos($line, ': ') === false) {
continue;
}
list($key, $value) = explode(': ', $line, 2);
$headers[strtolower(trim($key))] = trim($value);
}
if (!preg_match('#^HTTP/[0-9.]+ 200#', trim($statusLine))) {
// The interesting part of a refusal is in the body, not in the status line.
$error = json_decode($body, true);
$details = array();
if (is_array($error)) {
$this->lastErrorCode = isset($error['error']) ? (string) $error['error'] : '';
foreach (array('error', 'error_description', 'message', 'hint') as $field) {
if (!empty($error[$field]) and is_string($error[$field])) {
$details[] = $error[$field];
}
}
} elseif (preg_match('#<title>(.*?)</title>#is', $body, $title)) {
// A client certificate the server does not accept is rejected by the web server
// itself, which answers an HTML page long before PHP and its JSON errors run.
$details[] = trim($title[1]);
if (stripos($title[1], 'certificate') !== false) {
$this->lastErrorCode = 'ssl_certificate_error';
}
}
$this->lastError = 'OpenFlyers returned "' . trim($statusLine) . '"'
. (empty($details) ? '' : ' : ' . implode(' - ', array_unique($details)));
OF_SSO_Logger::log($this->lastError . ' (' . $url . ') body=' . substr($body, 0, 500));
return false;
}
// Response integrity: the server sends a Digest of the body and signs its own headers.
if (isset($headers['digest'])) {
list($algo, $expected) = array_pad(explode('=', $headers['digest'], 2), 2, '');
$computed = base64_encode(hash(strtolower(str_replace('-', '', $algo)), $body, true));
if (!hash_equals($expected, $computed)) {
$this->lastError = 'Digest mismatch, the response may have been tampered with';
OF_SSO_Logger::log($this->lastError . ' (' . $url . ')');
return false;
}
}
if ($verifySignature and !$this->verifyResponseSignature($headers, $url)) {
return false;
}
$decoded = json_decode($body, true);
return is_null($decoded) ? $body : $decoded;
}
/**
* Verify the Signature header sent back by the OpenFlyers server.
*
* @param array $headers Response headers, lowercased keys.
* @param string $url Endpoint that was called, for logging.
* @return bool
*/
private function verifyResponseSignature(array $headers, $url)
{
if (empty($this->config['server_sign_cert']) or !is_readable($this->config['server_sign_cert'])) {
$this->lastError = 'The OpenFlyers response signing certificate is missing';
OF_SSO_Logger::log($this->lastError);
return false;
}
if (empty($headers['signature'])) {
$this->lastError = 'No signature in the OpenFlyers response';
OF_SSO_Logger::log($this->lastError . ' (' . $url . ')');
return false;
}
$signature = array();
foreach (explode(',', $headers['signature']) as $chunk) {
if (strpos($chunk, '=') === false) {
continue;
}
list($key, $value) = explode('=', $chunk, 2);
$signature[trim($key)] = trim($value, '"');
}
if (empty($signature['headers']) or empty($signature['signature'])) {
$this->lastError = 'Unreadable signature in the OpenFlyers response';
OF_SSO_Logger::log($this->lastError . ' (' . $url . ')');
return false;
}
// Rebuild the signing string from the headers the server declared it had signed.
$signingString = '';
foreach (explode(' ', $signature['headers']) as $name) {
$name = trim($name);
if (!isset($headers[$name])) {
$this->lastError = 'Signed header "' . $name . '" missing from the response';
OF_SSO_Logger::log($this->lastError . ' (' . $url . ')');
return false;
}
$signingString .= $name . ': ' . trim($headers[$name]) . "\n";
}
$publicKey = openssl_get_publickey($this->readFile($this->config['server_sign_cert']));
$valid = openssl_verify(trim($signingString), base64_decode($signature['signature']), $publicKey, 'RSA-SHA256');
if ($valid !== 1) {
$this->lastError = 'Invalid signature on the OpenFlyers response';
OF_SSO_Logger::log($this->lastError . ' (' . $url . ')');
return false;
}
return true;
}
/**
* Read a local certificate or key file.
*
* @param string $path Absolute path.
* @return string
*/
private function readFile($path)
{
return is_readable($path) ? (string) file_get_contents($path) : '';
}
}