diff --git a/share/install_gems/Gemfile b/share/install_gems/Gemfile
index c6be1dac90..5e99e0befa 100644
--- a/share/install_gems/Gemfile
+++ b/share/install_gems/Gemfile
@@ -36,6 +36,7 @@ end
if RUBY_VERSION >= '2.4.0'
gem 'xmlrpc'
+ gem 'webauthn' # sunstone
end
if RUBY_VERSION < '2.1'
diff --git a/src/sunstone/etc/sunstone-server.conf b/src/sunstone/etc/sunstone-server.conf
index f86b1b64e9..53ce93ec2e 100644
--- a/src/sunstone/etc/sunstone-server.conf
+++ b/src/sunstone/etc/sunstone-server.conf
@@ -97,6 +97,40 @@
# Two Factor Authentication Issuer Label
:two_factor_auth_issuer: opennebula
+################################################################################
+# WebAuthn
+################################################################################
+
+# This value needs to match `window.location.origin` evaluated by the User Agent
+# during registration and authentication ceremonies. Remember that WebAuthn
+# requires TLS on anything else than localhost.
+:webauthn_origin: http://localhost:9869
+
+# Relying Party name for display purposes
+:webauthn_rpname: 'OpenNebula Cloud'
+
+# Optional client timeout hint, in milliseconds. Specifies how long the browser
+# should wait for any interaction with the user.
+:webauthn_timeout: 60000
+
+# Optional differing Relying Party ID
+# See https://www.w3.org/TR/webauthn/#relying-party-identifier
+# :webauthn_rpid: example.com
+
+# Supported cryptographic algorithms
+# See https://www.iana.org/assignments/jose/jose.xhtml
+# Possible is any list of
+# ES256 | ES384 | ES512 | PS256 | PS384 | PS512 | RS256 | RS384 | RS512 | RS1
+# :webauthn_algorithms: [ES256, PS256, RS256]
+
+################################################################################
+# Check Upgrades
+################################################################################
+
+# To check for the latest release. Comment this value if you don't want to check
+# this.
+:remote_version: http://downloads.opennebula.org/latest
+
################################################################################
# UI Settings
################################################################################
diff --git a/src/sunstone/models/OpenNebula2FA/SunstoneWebAuthn.rb b/src/sunstone/models/OpenNebula2FA/SunstoneWebAuthn.rb
new file mode 100644
index 0000000000..5fd9b6e048
--- /dev/null
+++ b/src/sunstone/models/OpenNebula2FA/SunstoneWebAuthn.rb
@@ -0,0 +1,155 @@
+# -------------------------------------------------------------------------- #
+# Copyright 2002-2019, OpenNebula Project, OpenNebula Systems #
+# #
+# Licensed under the Apache License, Version 2.0 (the "License"); you may #
+# not use this file except in compliance with the License. You may obtain #
+# a copy of the License at #
+# #
+# http://www.apache.org/licenses/LICENSE-2.0 #
+# #
+# Unless required by applicable law or agreed to in writing, software #
+# distributed under the License is distributed on an "AS IS" BASIS, #
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #
+# See the License for the specific language governing permissions and #
+# limitations under the License. #
+#--------------------------------------------------------------------------- #
+
+require 'json'
+require 'webauthn'
+
+# WebAuthn authentication
+module SunstoneWebAuthn
+
+ def self.configure(conf)
+ @client = OpenNebula::Client.new
+ @challenges = Hash.new
+ WebAuthn.configure do |config|
+ if !conf.include?(:webauthn_origin) || conf[:webauthn_origin] == ''
+ raise StandardError.new("Configuration of ':webauthn_origin' is missing")
+ end
+ config.origin = conf[:webauthn_origin]
+
+ if !conf.include?(:webauthn_rpname) || conf[:webauthn_rpname] == ''
+ raise StandardError.new("Configuration of ':webauthn_rpname' is missing")
+ end
+ config.rp_name = conf[:webauthn_rpname]
+
+ conf[:webauthn_timeout] ||= 60000
+ config.credential_options_timeout = conf[:webauthn_timeout]
+
+ if conf.include?(:webauthn_rpid) && conf[:webauthn_rpid] != ''
+ config.rp_id = conf[:webauthn_rpid]
+ end
+
+ conf[:webauthn_algorithms] ||= ["ES256", "PS256", "RS256"]
+ config.algorithms = conf[:webauthn_algorithms]
+ end
+ end
+
+ def self.getOptionsForCreate(user_id, user_name)
+ known_credentials = getCredentialIDsForUser(user_id)
+ options = WebAuthn::Credential.options_for_create(
+ user: { id: Base64.urlsafe_encode64(user_id, padding: false), name: user_name },
+ authenticator_selection: { user_verification: 'discouraged' },
+ exclude: known_credentials
+ )
+ @challenges[user_id] = options.challenge
+ return renderJSON(options.as_json)
+ end
+
+ def self.getOptionsForGet(user_id)
+ known_credentials = getCredentialIDsForUser(user_id)
+ unless known_credentials.length == 0
+ options = WebAuthn::Credential.options_for_get(
+ user_verification: 'discouraged',
+ allow: known_credentials
+ )
+ @challenges[user_id] = options.challenge
+ return renderJSON(options.as_json)
+ end
+ end
+
+ def self.getCredentialsForUser(user_id)
+ user = User.new_with_id(user_id, @client)
+ rc = user.info
+
+ if OpenNebula.is_error?(rc)
+ $cloud_auth.logger.error {"user.info error: #{rc.message}"}
+ return nil
+ end
+
+ credentials = []
+ json_str = user['TEMPLATE/SUNSTONE/WEBAUTHN_CREDENTIALS']
+ if json_str.nil?
+ return credentials
+ end
+ begin
+ credentials = JSON.parse(json_str.gsub("'", '"'))['cs']
+ rescue Exception => e
+ return OpenNebula::Error.new(e.message)
+ end
+ return credentials
+ end
+
+ def self.getCredentialIDsForUser(user_id)
+ return getCredentialsForUser(user_id).map { |hash| hash['id'] }
+ end
+
+ def self.verifyCredentialFromRegistration(user_id, publicKeyCredential)
+ credential_with_attestation = WebAuthn::Credential.from_create(publicKeyCredential)
+ challenge = @challenges.delete(user_id.to_s)
+ begin
+ credential_with_attestation.verify(challenge)
+ return credential_with_attestation
+ rescue WebAuthn::Error => e
+ return OpenNebula::Error.new(e.message)
+ end
+ end
+
+ def self.authenticate(user_id, publicKeyCredential_s)
+ begin
+ publicKeyCredential = JSON.parse(publicKeyCredential_s)
+ received_credential = WebAuthn::Credential.from_get(publicKeyCredential)
+ rescue Exception => e
+ return false
+ end
+ credentials = getCredentialsForUser(user_id)
+ stored_credential = credentials.find { |hash| hash['id'] == publicKeyCredential['id'] }
+ challenge = @challenges.delete(user_id.to_s)
+ begin
+ received_credential.verify(challenge, public_key: stored_credential['pk'], sign_count: Integer(stored_credential['cnt']))
+ stored_credential['cnt'] = received_credential.sign_count
+ updateCredentials(user_id, credentials)
+ return true
+ rescue WebAuthn::SignCountVerificationError => e
+ # Cryptographic verification of the authenticator data succeeded, but the signature counter was less then or equal
+ # to the stored value. This can have several reasons and depending on risk tolerance an implementation can choose to fail or
+ # pass authentication. For more information see https://www.w3.org/TR/webauthn/#sign-counter. Here, we fail authentication.
+ return false
+ rescue WebAuthn::Error => e
+ return false
+ end
+ return false
+ end
+
+ def self.updateCredentials(user_id, credentials)
+ user = User.new_with_id(user_id, @client)
+ rc = user.info
+
+ if OpenNebula.is_error?(rc)
+ $cloud_auth.logger.error {"user.info error: #{rc.message}"}
+ return nil
+ end
+
+ credentialsJSON = JSON.generate({ "cs" => credentials}).gsub('"', "'")
+ # This does not work; breaks the template (guess the replace function is buggy)
+ # user.replace({'WEBAUTHN_CREDENTIALS' => credentialsJSON}, 'TEMPLATE/SUNSTONE')
+ user.retrieve_xmlelements('TEMPLATE/SUNSTONE/WEBAUTHN_CREDENTIALS')[0].set_content(credentialsJSON)
+ user.update(user.template_like_str('TEMPLATE'))
+ end
+
+ def self.renderJSON(hash)
+ return JSON.generate(hash)
+ end
+
+end
diff --git a/src/sunstone/models/OpenNebulaJSON/UserJSON.rb b/src/sunstone/models/OpenNebulaJSON/UserJSON.rb
index 7eec7d2731..d61cfe0e4f 100644
--- a/src/sunstone/models/OpenNebulaJSON/UserJSON.rb
+++ b/src/sunstone/models/OpenNebulaJSON/UserJSON.rb
@@ -14,9 +14,15 @@
# limitations under the License. #
#--------------------------------------------------------------------------- #
+require 'json'
require 'OpenNebulaJSON/JSONUtils'
require 'sunstone_2f_auth'
+begin
+ require "SunstoneWebAuthn"
+rescue LoadError
+end
+
module OpenNebulaJSON
class UserJSON < OpenNebula::User
include JSONUtils
@@ -46,6 +52,8 @@ module OpenNebulaJSON
when "update" then self.update(action_hash['params'])
when "enable_two_factor_auth" then self.enable_two_factor_auth(action_hash['params'])
when "disable_two_factor_auth" then self.disable_two_factor_auth(action_hash['params'])
+ when "enable_security_key" then self.enable_security_key(action_hash['params'])
+ when "disable_security_key" then self.disable_security_key(action_hash['params'])
when "set_quota" then self.set_quota(action_hash['params'])
when "addgroup" then self.addgroup(action_hash['params'])
when "delgroup" then self.delgroup(action_hash['params'])
@@ -93,6 +101,46 @@ module OpenNebulaJSON
def disable_two_factor_auth(params=Hash.new)
sunstone_setting = params["current_sunstone_setting"]
sunstone_setting.delete("TWO_FACTOR_AUTH_SECRET")
+ if !params['delete_all'].nil? && params['delete_all'] == true
+ sunstone_setting.delete("WEBAUTHN_CREDENTIALS")
+ end
+ sunstone_setting = { "sunstone" => sunstone_setting }
+ template_raw = template_to_str_sunstone_with_explicite_empty_value(sunstone_setting)
+ update_params = { "template_raw" => template_raw, "append" => true }
+ update(update_params)
+ end
+
+ def enable_security_key(params=Hash.new)
+ if !$conf[:webauthn_avail]
+ return OpenNebula::Error.new("WebAuthn not available.")
+ end
+ sunstone_setting = params["current_sunstone_setting"]
+ webauthn_credential = SunstoneWebAuthn.verifyCredentialFromRegistration(@pe_id, params['publicKeyCredential'])
+ template_credentials = self['TEMPLATE/SUNSTONE/WEBAUTHN_CREDENTIALS'] || "{'cs':[]}"
+ credentials = parse_json(template_credentials.gsub("'", '"'), 'cs')
+ credentials.append({
+ 'id' => webauthn_credential.id,
+ 'pk' => webauthn_credential.public_key,
+ 'cnt' => webauthn_credential.sign_count,
+ 'name' => params['nickname']
+ })
+ sunstone_setting["WEBAUTHN_CREDENTIALS"] = JSON.generate({ "cs" => credentials}).gsub('"', "'")
+ sunstone_setting = { "sunstone" => sunstone_setting }
+ template_raw = template_to_str_sunstone_with_explicite_empty_value(sunstone_setting)
+ update_params = { "template_raw" => template_raw, "append" => true }
+ update(update_params)
+ end
+
+ def disable_security_key(params=Hash.new)
+ sunstone_setting = params["current_sunstone_setting"]
+ credentials = parse_json(sunstone_setting["WEBAUTHN_CREDENTIALS"].gsub("'", '"'), 'cs')
+ for i in 0..credentials.length() do
+ if credentials[i]["pk"] == params["tokenid_to_remove"]
+ credentials.delete_at(i)
+ break
+ end
+ end
+ sunstone_setting["WEBAUTHN_CREDENTIALS"] = JSON.generate({ "cs" => credentials}).gsub('"', "'")
sunstone_setting = { "sunstone" => sunstone_setting }
template_raw = template_to_str_sunstone_with_explicite_empty_value(sunstone_setting)
update_params = { "template_raw" => template_raw, "append" => true }
diff --git a/src/sunstone/public/app/login.js b/src/sunstone/public/app/login.js
index 771124b3ee..949a2fa248 100644
--- a/src/sunstone/public/app/login.js
+++ b/src/sunstone/public/app/login.js
@@ -17,11 +17,15 @@
define(function(require) {
require('../bower_components/jquery/dist/jquery.min');
var OpenNebulaAuth = require('opennebula/auth');
+ var WebAuthnJSON = require('../bower_components/webauthn-json/dist/index');
+
var showErrorAuth = false;
+ var uid;
+
var textOpenNebulaNotRunning = "OpenNebula is not running or there was a server exception. Please check the server logs.";
var textInvalidUserorPassword = "Invalid username or password";
var textNoAnswerFromServer = "No answer from server. Is it running?";
- var textTwoFactorTokenInvalid = "Two factor Token Invalid";
+ var textTwoFactorTokenInvalid = "Invalid second factor authentication";
var idElementTwoFactor = "#two_factor_auth_token";
function auth_success(req, response) {
@@ -29,6 +33,9 @@ define(function(require) {
$("#login_form").hide();
$("#login_spinner").hide();
$("#two_factor_auth").fadeIn("slow");
+ $("#two_factor_auth_token").focus();
+ $("#login_btn")[0].type = "button";
+ $("#two_factor_auth_login_btn")[0].type = "submit";
if(!showErrorAuth){
showErrorAuth = true;
} else {
@@ -36,19 +43,57 @@ define(function(require) {
$("#error_box").fadeIn("slow");
$("#login_spinner").hide();
}
+ uid = response.uid;
+ prepareWebAuthn(uid);
} else {
showErrorAuth = false;
window.location.href = ".";
}
}
+ function prepareWebAuthn(uid) {
+ $("#webauthn_login_btn").unbind();
+ $.ajax({
+ url: "webauthn_options_for_get?uid=" + uid,
+ type: "GET",
+ dataType: "json",
+ success: function (response) {
+ if (!response) {
+ return
+ }
+ if (!navigator.credentials) {
+ $("#webauthn_login_div").hide();
+ console.warn('WebAuthn functionality unavailable. Ask your cloud administrator to enable TLS.');
+ }
+ $("#webauthn_login_btn").click(function () {
+ WebAuthnJSON.get({ "publicKey": response }).then(authenticate)
+ .catch((e) => {
+ $("#error_message").text(e.message);
+ $("#error_box").fadeIn("slow");
+ $("#login_spinner").hide();
+ });
+ });
+ },
+ error: function (response) {
+ if (response.status == 501) {
+ $("#webauthn_login_div").hide();
+ console.warn('WebAuthn functionality unavailable. Ask your cloud administrator to upgrade the Ruby version.');
+ }
+ }
+ });
+ }
+
function auth_error(req, error) {
var status = error.error.http_status;
switch (status){
case 401:
- $("#error_message").text(textInvalidUserorPassword);
+ if (showErrorAuth) {
+ $("#error_message").text(textTwoFactorTokenInvalid);
+ } else {
+ $("#error_message").text(textInvalidUserorPassword);
+ }
break;
case 500:
$("#error_message").text(textOpenNebulaNotRunning);
@@ -63,11 +108,22 @@ define(function(require) {
$("#login_spinner").hide();
}
- function authenticate() {
+ function authenticate(publicKeyCredential) {
var username = $("#username").val();
var password = $("#password").val();
var remember = $("#check_remember").is(":checked");
- var two_factor_auth_token = $("#two_factor_auth_token").val();
+ var two_factor_auth_token;
+ var error_callback;
+ if (publicKeyCredential == undefined) {
+ two_factor_auth_token = $("#two_factor_auth_token").val();
+ error_callback = auth_error
+ } else {
+ two_factor_auth_token = JSON.stringify(publicKeyCredential);
+ error_callback = (req, error) => {
+ auth_error(req, error);
+ prepareWebAuthn(uid);
+ }
+ }
$("#error_box").fadeOut("slow");
$("#login_spinner").show();
@@ -80,7 +136,7 @@ define(function(require) {
remember: remember,
success: auth_success,
two_factor_auth_token: two_factor_auth_token,
- error: auth_error
+ error: error_callback
});
}
@@ -130,7 +186,7 @@ define(function(require) {
return false;
});
- $("#two_factor_auth_login").click(function() {
+ $("#two_factor_auth_login_btn").click(function() {
if($(idElementTwoFactor) && $(idElementTwoFactor).val().length){
authenticate();
}
diff --git a/src/sunstone/public/app/opennebula/user.js b/src/sunstone/public/app/opennebula/user.js
index cd408d4f32..9e82456e7c 100644
--- a/src/sunstone/public/app/opennebula/user.js
+++ b/src/sunstone/public/app/opennebula/user.js
@@ -108,6 +108,14 @@ define(function(require) {
var action_obj = params.data.extra_param;
OpenNebulaAction.simple_action(params, RESOURCE, "disable_two_factor_auth", action_obj);
},
+ "enable_sunstone_security_key": function(params) {
+ var action_obj = params.data.extra_param;
+ OpenNebulaAction.simple_action(params, RESOURCE, "enable_security_key", action_obj);
+ },
+ "disable_sunstone_security_key": function(params) {
+ var action_obj = params.data.extra_param;
+ OpenNebulaAction.simple_action(params, RESOURCE, "disable_security_key", action_obj);
+ },
"accounting" : function(params) {
OpenNebulaAction.monitor(params, RESOURCE, false);
},
diff --git a/src/sunstone/public/app/tabs/settings-tab/panels/user-config.js b/src/sunstone/public/app/tabs/settings-tab/panels/user-config.js
index 48f6fb119f..69028862fc 100644
--- a/src/sunstone/public/app/tabs/settings-tab/panels/user-config.js
+++ b/src/sunstone/public/app/tabs/settings-tab/panels/user-config.js
@@ -98,11 +98,7 @@ define(function(require) {
$("#provision_user_views_select option[value=\"" + config["user_config"]["default_view"] + "\"]", context).attr("selected", "selected");
- if (that.element.TEMPLATE.SUNSTONE && that.element.TEMPLATE.SUNSTONE.TWO_FACTOR_AUTH_SECRET) {
- $(".provision_two_factor_auth_button", context).html(Locale.tr("Disable"));
- } else {
- $(".provision_two_factor_auth_button", context).html(Locale.tr("Manage two factor authentication"));
- }
+ $(".provision_two_factor_auth_button", context).html(Locale.tr("Manage two factor authentication"));
// Login token button
context.off("click", ".provision_login_token_button");
@@ -116,23 +112,14 @@ define(function(require) {
context.off("click", ".provision_two_factor_auth_button");
context.on("click", ".provision_two_factor_auth_button", function(){
var sunstone_setting = that.element.TEMPLATE.SUNSTONE || {};
- if (sunstone_setting.TWO_FACTOR_AUTH_SECRET) {
- Sunstone.runAction(
- "User.disable_sunstone_two_factor_auth",
- that.element.ID,
- {current_sunstone_setting: sunstone_setting}
- );
- } else {
- Sunstone.getDialog(TWO_FACTOR_AUTH_DIALOG_ID).setParams({
- element: that.element,
- sunstone_setting: sunstone_setting
- });
- Sunstone.getDialog(TWO_FACTOR_AUTH_DIALOG_ID).reset();
- Sunstone.getDialog(TWO_FACTOR_AUTH_DIALOG_ID).show();
- }
+ Sunstone.getDialog(TWO_FACTOR_AUTH_DIALOG_ID).setParams({
+ element: that.element,
+ sunstone_setting: sunstone_setting
+ });
+ Sunstone.getDialog(TWO_FACTOR_AUTH_DIALOG_ID).reset();
+ Sunstone.getDialog(TWO_FACTOR_AUTH_DIALOG_ID).show();
});
-
$("#provision_change_password_form").submit(function() {
var pw = $("#provision_new_password", this).val();
var confirm_password = $("#provision_new_confirm_password", this).val();
diff --git a/src/sunstone/public/app/tabs/settings-tab/panels/user-config/html.hbs b/src/sunstone/public/app/tabs/settings-tab/panels/user-config/html.hbs
index 167e288b27..fdbb74ba40 100644
--- a/src/sunstone/public/app/tabs/settings-tab/panels/user-config/html.hbs
+++ b/src/sunstone/public/app/tabs/settings-tab/panels/user-config/html.hbs
@@ -239,7 +239,7 @@
- {{tr "Two factor authentication can be enabled for loging into Sunestone UI."}}
+ {{tr "Two factor authentication can be enabled for logging into Sunestone UI."}}
- {{tr "Two factor authentication can be enabled for loging into Sunestone UI."}}
+ {{tr "Two factor authentication can be enabled for logging into Sunstone UI."}}