Basic support for OAuth2 user login and IMAP/SMTP authentication

- Add "Login with XXX" button to login screen if oauth is configured
- Perform OAuth login procedure and get an access token
- Implement XOAUTH2 authentication type for IAMP and SMTP

Requires a patched and not yet released version of Net_SMTP.
pull/7425/head
Thomas Bruederli 5 years ago
parent 1c76c8440f
commit 1e6a2f4f49

@ -19,7 +19,8 @@
"pear/net_sieve": "~1.4.3",
"roundcube/plugin-installer": "~0.1.6",
"masterminds/html5": "~2.5.0",
"endroid/qr-code": "~1.6.5"
"endroid/qr-code": "~1.6.5",
"guzzlehttp/guzzle": "^5.3.3"
},
"require-dev": {
"phpunit/phpunit": "^4.8.36 || ^5.7.21 || ^6 || ^7"

@ -318,6 +318,38 @@ $config['smtp_timeout'] = 0;
$config['smtp_conn_options'] = null;
// ----------------------------------
// OAuth
// ----------------------------------
// Enable OAuth2 by defining a provider. Use 'generic' here
$config['oauth_provider'] = null;
// Provider name to be displayed on the login buttin
$config['oauth_provider_name'] = 'Google';
// Mandatory: OAuth client ID for your Roundcube installation
$config['oauth_client_id'] = null;
// Mandatory: OAuth client secret
$config['oauth_client_secret'] = null;
// Mandatory: URI for OAuth user authentication (redirect)
$config['oauth_auth_uri'] = null;
// Mandatory: Endpoint for OAuth authentication requests (server-to-server)
$config['oauth_token_uri'] = null;
// Optional: Endpoint to query user identity if not provided in auth response
$config['oauth_identity_uri'] = null;
// Mandatory: OAuth scopes to request (space-separated string)
$config['oauth_scope'] = null;
// Optional: additional query parameters to send with login request (hash array)
$config['oauth_auth_parameters'] = [];
// ----------------------------------
// LDAP
// ----------------------------------

@ -188,6 +188,11 @@ if ($RCMAIL->task == 'login' && $RCMAIL->action == 'login') {
}
}
// handle oauth login requests
else if ($RCMAIL->task == 'login' && $RCMAIL->action == 'oauth') {
include INSTALL_PATH . 'program/steps/login/oauth.inc';
}
// end session
else if ($RCMAIL->task == 'logout' && isset($_SESSION['user_id'])) {
$RCMAIL->request_security_check(rcube_utils::INPUT_GET | rcube_utils::INPUT_POST);

@ -33,7 +33,7 @@ class rcmail extends rcube
*
* @var array
*/
static public $main_tasks = array('mail','settings','addressbook','login','logout','utils','dummy');
static public $main_tasks = array('mail','settings','addressbook','login','logout','utils','oauth','dummy');
/**
* Current task.
@ -140,6 +140,9 @@ class rcmail extends rcube
$GLOBALS['OUTPUT'] = $this->load_gui(!empty($_REQUEST['_framed']));
}
// load oauth manager
$this->oauth = rcmail_oauth::get_instance();
// run init method on all the plugins
$this->plugins->init($this, $this->task);
}

@ -0,0 +1,416 @@
<?php
/**
+-----------------------------------------------------------------------+
| This file is part of the Roundcube Webmail client |
| |
| Copyright (C) The Roundcube Dev Team |
| |
| Licensed under the GNU General Public License version 3 or |
| any later version with exceptions for skins & plugins. |
| See the README file for a full license statement. |
| |
| CONTENTS: |
| Roundcube OAuth2 utilities |
+-----------------------------------------------------------------------+
| Author: Thomas Bruederli <roundcube@gmail.com> |
+-----------------------------------------------------------------------+
*/
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
/**
* Roundcube OAuth2 utilities
*
* @package Webmail
* @subpackage Utils
*/
class rcmail_oauth
{
/** @var rcmail */
protected $rcmail;
/** @var array */
protected $options = array();
/** @var string */
protected $last_error = null;
/** @var rcmail_oauth */
static protected $instance;
/**
* Singleton factory
*
* @return rcmail_oauth The one and only instance
*/
static function get_instance($options = array())
{
if (!self::$instance) {
self::$instance = new rcmail_oauth($options);
self::$instance->init();
}
return self::$instance;
}
/**
* Object constructor
*
* @param array $options Config options:
*/
public function __construct($options = array())
{
$this->rcmail = rcmail::get_instance();
$this->options = (array) $options + array(
'provider' => $this->rcmail->config->get('oauth_provider'),
'auth_uri' => $this->rcmail->config->get('oauth_auth_uri'),
'token_uri' => $this->rcmail->config->get('oauth_token_uri'),
'client_id' => $this->rcmail->config->get('oauth_client_id'),
'client_secret' => $this->rcmail->config->get('oauth_client_secret'),
'identity_uri' => $this->rcmail->config->get('oauth_identity_uri'),
'scope' => $this->rcmail->config->get('oauth_scope'),
'auth_parameters' => $this->rcmail->config->get('oauth_auth_parameters', array()),
);
}
/**
* Initialize this instance
*
* @return void
*/
protected function init()
{
// subscrbe to storage and smtp init events
if ($this->is_enabled()) {
$this->rcmail->plugins->register_hook('storage_init', [$this, 'storage_init']);
$this->rcmail->plugins->register_hook('smtp_connect', [$this, 'smtp_connect']);
}
}
/**
* Check if OAuth is generally enabled in config
*
* @return boolean
*/
public function is_enabled()
{
return !empty($this->options['provider']) &&
!empty($this->options['token_uri']) &&
!empty($this->options['client_id']);
}
/**
* Compose a fully qualified redirect URI for auth requests
*
* @return string
*/
public function get_redirect_uri()
{
return $this->rcmail->url(['action' => 'oauth'], true, true);
}
/**
* Getter for the last error occured
*
* @return mixed
*/
public function get_last_error()
{
return $this->last_error;
}
/**
* Helper method to decode a JWT
*
* @param string $jwt
* @return array Hash array with decoded body
*/
public function jwt_decode($jwt)
{
list($headb64, $bodyb64, $cryptob64) = explode('.', $jwt);
$header = json_decode(base64_decode($headb64), true);
$body = json_decode(base64_decode($bodyb64), true);
if (!isset($body['azp']) || $body['azp'] !== $this->options['client_id']) {
throw new RuntimeException('Failed to validate JWT: invalid azp value');
}
return $body;
}
/**
* Login action: redirect to `oauth_auth_uri`
*
* @return void
*/
public function login_redirect()
{
if (!empty($this->options['auth_uri']) && !empty($this->options['client_id'])) {
// create a secret string
$_SESSION['oauth_state'] = rcube_utils::random_bytes(12);
// compose full oauth login uri
$delimiter = strpos($this->options['auth_uri'], '?') > 0 ? '&' : '?';
$query = http_build_query([
'response_type' => 'code',
'client_id' => $this->options['client_id'],
'scope' => $this->options['scope'],
'redirect_uri' => $this->get_redirect_uri(),
'state' => $_SESSION['oauth_state'],
] + (array)$this->options['auth_parameters']);
$this->rcmail->output->redirect($this->options['auth_uri'] . $delimiter . $query); // exit
} else {
// log error about missing config options
rcube::raise_error(array(
'message' => "Missing required OAuth config options 'oauth_auth_uri', 'oauth_client_id'",
'file' => __FILE__,
'line' => __LINE__,
), true, false);
}
}
/**
* Request access token with auth code returned from oauth login
*
* @param string $auth_code
* @param string $state
* @return array Authorization data as hash array with entries
* `username` as the authentication user name
* `authorization` as the oauth authorization string "<type> <access-token>"
* `token` as the complete oauth response to be stored in session
*/
public function request_access_token($auth_code, $state = null)
{
$oauth_token_uri = $this->options['token_uri'];
$oauth_client_id = $this->options['client_id'];
$oauth_client_secret = $this->options['client_secret'];
$oauth_identity_uri = $this->options['identity_uri'];
if (!empty($oauth_token_uri) && !empty($oauth_client_secret)) {
// validate state parameter against $_SESSION['oauth_state']
if (!empty($_SESSION['oauth_state']) && $_SESSION['oauth_state'] !== $state) {
throw new RuntimeException('Invalid state parameter');
}
// send token request to get a real access token for the given auth code
try {
$client = new Client([
'timeout' => 10.0,
]);
$response = $client->post($oauth_token_uri, array(
'body' => array(
'code' => $auth_code,
'client_id' => $oauth_client_id,
'client_secret' => $oauth_client_secret,
'redirect_uri' => $this->get_redirect_uri(),
'grant_type' => 'authorization_code',
),
));
$data = $response->json();
// auth success
if (!empty($data['access_token'])) {
$username = null;
$authorization = sprintf('%s %s', $data['token_type'], $data['access_token']);
// decode JWT id_token if provided
if (!empty($data['id_token'])) {
try {
$identity = $this->jwt_decode($data['id_token']);
$username = $identity['email'];
unset($data['id_token']);
} catch (\Exception $e) {
// ignore
}
}
// request user identity (email)
if (empty($username) && !empty($oauth_identity_uri)) {
$identity = $client->get($oauth_identity_uri, array(
'headers' => array(
'Authorization' => $authorization,
'Accept' => 'application/json',
),
))->json();
if (isset($identity['email'])) {
$username = $identity['email'];
}
}
$data['identity'] = $username;
self::mask_auth_data($data);
$this->rcmail->write_log('oauth2', 'Auth code success: ' . json_encode($data));
$this->rcmail->session->remove('oauth_state');
// return auth data
return array(
'username' => $username,
'authorization' => $authorization,
'token' => $data,
);
} else {
throw new Exception('Unexpected response from OAuth service');
}
} catch (RequestException $e) {
$this->last_error = "OAuth token request failed: " . $e->getMessage();
rcube::raise_error(array(
'message' => $this->last_error . '; ' . $e->getResponse(),
'file' => __FILE__,
'line' => __LINE__,
), true, false);
return false;
} catch (Exception $e) {
$this->last_error = "OAuth token request failed: " . $e->getMessage();
rcube::raise_error(array(
'message' => $this->last_error,
'file' => __FILE__,
'line' => __LINE__,
), true, false);
return false;
}
} else {
$this->last_error = "Missing required OAuth config options 'oauth_token_uri', 'oauth_client_id', 'oauth_client_secret'";
rcube::raise_error(array(
'message' => $this->last_error,
'file' => __FILE__,
'line' => __LINE__,
), true, false);
return false;
}
}
/**
* Obtain a new access token using the refresh_token grant type
*
* If successful, this will update the `oauth_token` entry in
* session data.
*
* @param array $token
* @return array Updated authorization data
*/
public function refresh_access_token(array $token)
{
// send token request to get a real access token for the given auth code
try {
$client = new Client([
'timeout' => 10.0,
]);
$response = $client->post($oauth_token_uri, array(
'body' => array(
'client_id' => $oauth_client_id,
'client_secret' => $oauth_client_secret,
'refresh_token' => $token['refresh_token'],
'grant_type' => 'refresh_token',
),
));
$data = $response->json();
// auth success
if (!empty($data['access_token'])) {
// update access token stored as password
$authorization = sprintf('%s %s', $data['token_type'], $data['access_token']);
$_SESSION['password'] = $this->rcmail->encrypt($authorization);
self::mask_auth_data($data);
// update session data
$_SESSION['oauth_token'] = array_merge($token, $data);
return [
'token' => $data,
'authorization' => $authorization,
];
}
} catch (RequestException $e) {
$this->last_error = "OAuth refresh token request failed: " . $e->getMessage();
rcube::raise_error(array(
'message' => $this->last_error . '; ' . $e->getResponse(),
'file' => __FILE__,
'line' => __LINE__,
), true, false);
return false;
} catch (Exception $e) {
$this->last_error = "OAuth refresh token request failed: " . $e->getMessage();
rcube::raise_error(array(
'message' => $this->last_error,
'file' => __FILE__,
'line' => __LINE__,
), true, false);
return false;
}
}
/**
* Modify some properties of the received auth response
*
* @param array $token
* @return void
*/
protected static function mask_auth_data(&$data)
{
// compute absolute token expiration date
$data['expires'] = time() + $data['expires_in'] - 600;
// mask access token before storing in session
$data['access_token'] = substr($data['access_token'], 0, 12) . str_repeat('*', strlen($data['access_token']) - 6);
}
/**
* Check the given access token data if still valid
*
* ... and attempt to refresh if possible.
*
* @param array $token
* @return void
*/
protected function check_token_validity($token)
{
if ($token['expires'] < time() && isset($token['refresh_token'])) {
$this->refresh_access_token($token);
}
}
/**
* Callback for 'storage_init' hook
*
* @param array $options
* @return array
*/
public function storage_init($options)
{
if (isset($_SESSION['oauth_token']) && $options['driver'] === 'imap') {
// check token validity
$this->check_token_validity($_SESSION['oauth_token']);
// enforce XOAUTH2 authorization type
$options['auth_type'] = 'XOAUTH2';
}
return $options;
}
/**
* Callback for 'smtp_connect' hook
*
* @param array $options
* @return array
*/
public function smtp_connect($options)
{
if (isset($_SESSION['oauth_token'])) {
// check token validity
$this->check_token_validity($_SESSION['oauth_token']);
// enforce XOAUTH2 authorization type
$options['smtp_user'] = '%u';
$options['smtp_pass'] = '%p';
$options['smtp_auth_type'] = 'XOAUTH2';
}
return $options;
}
}

@ -2235,6 +2235,12 @@ EOF;
$out .= html::p('formbuttons', html::tag('button', $button_attr, $this->app->gettext('login')));
}
// add oauth login button
if ($this->config->get('oauth_auth_uri') && $this->config->get('oauth_provider')) {
$link_attr = array('href' => $this->app->url(array('action' => 'oauth')), 'id' => 'rcmloginoauth', 'class' => 'button oauth ' . $this->config->get('oauth_provider'));
$out .= html::p('oauthlogin', html::a($link_attr, $this->app->gettext(array('name' => 'oauthlogin', 'vars' => array('provider' => $this->config->get('oauth_provider_name', 'OAuth'))))));
}
// surround html output with a form tag
if (empty($attrib['form'])) {
$out = $this->form_tag(array('name' => $form_name, 'method' => 'post'), $out);

@ -769,6 +769,20 @@ class rcube_imap_generic
$line = $this->readReply();
$result = $this->parseResult($line);
}
else if ($type == 'XOAUTH2') {
$auth = base64_encode("user=$user\1auth=$pass\1\1");
$this->putLine($this->nextTag() . " AUTHENTICATE XOAUTH2 $auth", true, true);
$line = trim($this->readReply());
if ($line[0] == '+') {
// send empty line
$this->putLine('', true, true);
$line = $this->readReply();
}
$result = $this->parseResult($line);
}
if ($result === self::ERROR_OK) {
// optional CAPABILITY response
@ -959,6 +973,7 @@ class rcube_imap_generic
case 'GSSAPI':
case 'PLAIN':
case 'LOGIN':
case 'XOAUTH2':
$result = $this->authenticate($user, $password, $auth_method);
break;

@ -22,6 +22,7 @@ $labels['username'] = 'Username';
$labels['password'] = 'Password';
$labels['server'] = 'Server';
$labels['login'] = 'Login';
$labels['oauthlogin'] = 'Login with $provider';
// taskbar
$labels['menu'] = 'Menu';

@ -224,3 +224,4 @@ $messages['listempty'] = 'The list is empty.';
$messages['listusebutton'] = 'Use the Create button to add a new record.';
$messages['keypaircreatesuccess'] = 'A new key pair has been successfully created for $identity.';
$messages['emptyattachment'] = 'This attachment appears to be empty.<br>Please, check with the person who sent this.';
$messages['oauthloginfailed'] = 'OAuth login failed. Please try again.';

@ -0,0 +1,86 @@
<?php
/**
+-----------------------------------------------------------------------+
| This file is part of the Roundcube Webmail client |
| |
| Copyright (C) The Roundcube Dev Team |
| |
| Licensed under the GNU General Public License version 3 or |
| any later version with exceptions for skins & plugins. |
| See the README file for a full license statement. |
| |
| PURPOSE: |
| Perform OAuth2 user login |
+-----------------------------------------------------------------------+
| Author: Thomas Bruederli <roundcube@gmail.com> |
+-----------------------------------------------------------------------+
*/
$rcmail = rcmail::get_instance();
$auth_code = rcube_utils::get_input_value('code', rcube_utils::INPUT_GET);
$auth_error = rcube_utils::get_input_value('error', rcube_utils::INPUT_GET);
// auth code return from oauth login
if (!empty($auth_code)) {
$auth = $rcmail->oauth->request_access_token($auth_code, rcube_utils::get_input_value('state', rcube_utils::INPUT_GET));
// oauth success
if ($auth && isset($auth['username'], $auth['authorization'], $auth['token'])) {
// enforce XOAUTH2 auth type
$rcmail->config->set('imap_auth_type', 'XOAUTH2');
// use access_token and user info for IMAP login
$storage_host = $rcmail->autoselect_host();
if ($rcmail->login($auth['username'], $auth['authorization'], $storage_host, true)) {
// replicate post-login tasks from index.php
$rcmail->session->remove('temp');
$rcmail->session->regenerate_id(false);
// send auth cookie if necessary
$rcmail->session->set_auth_cookie();
// save OAuth token in session
$_SESSION['oauth_token'] = $auth['token'];
// log successful login
$rcmail->log_login();
// allow plugins to control the redirect url after login success
$redir = $rcmail->plugins->exec_hook('login_after', array('_task' => 'mail'));
unset($redir['abort'], $redir['_err']);
// send redirect
$OUTPUT->redirect($redir, 0, true);
} else {
$OUTPUT->show_message('loginfailed', 'warning');
// log failed login
$error_code = $rcmail->login_error();
$rcmail->log_login($auth['username'], true, $error_code);
$rcmail->plugins->exec_hook('login_failed', array(
'code' => $error_code,
'host' => $storage_host,
'user' => $auth['username'],
));
$rcmail->kill_session();
// fall through -> login page
}
} else {
$OUTPUT->show_message('oauthloginfailed', 'warning');
}
}
// error return from oauth login
else if (!empty($auth_error)) {
$OUTPUT->show_message($auth_error, 'warning');
}
// login action: redirect to `oauth_auth_uri`
else if ($rcmail->task === 'login') {
// this will always exit() the process
$rcmail->oauth->login_redirect();
}

@ -1064,6 +1064,7 @@ function rcube_elastic_ui()
// Make logon form prettier
if (rcmail.env.task == 'login' && context == document) {
$('#rcmloginsubmit').addClass('btn-lg text-uppercase w-100');
$('#rcmloginoauth').addClass('btn btn-secondary btn-lg w-100');
$('#login-form table tr').each(function() {
var input = $('input,select', this),
label = $('label', this),

Loading…
Cancel
Save