From c22c843a56d6a3498eb9be2d0bbf6f4607b2e568 Mon Sep 17 00:00:00 2001 From: Jorge Miguel Lobo Escalona Date: Tue, 9 Sep 2025 16:09:02 +0200 Subject: [PATCH] F OpenNebula/one#6496 : SAML support (#3781) Including CLI, API and GUI Signed-off-by: Daniel --- install.sh | 6 + share/etc/oned.conf | 11 +- share/install_gems/AlmaLinux8/Gemfile.lock | 3 + share/install_gems/AlmaLinux9/Gemfile.lock | 3 + share/install_gems/Debian11/Gemfile.lock | 3 + share/install_gems/Debian12/Gemfile.lock | 3 + share/install_gems/Gemfile | 3 +- share/install_gems/RedHat8/Gemfile.lock | 3 + share/install_gems/RedHat9/Gemfile.lock | 3 + share/install_gems/Ubuntu2204/Gemfile.lock | 3 + share/install_gems/Ubuntu2404/Gemfile.lock | 3 + src/authm_mad/remotes/saml/authenticate | 154 ++++++++++++ src/authm_mad/remotes/saml/saml_auth.conf | 102 ++++++++ src/authm_mad/remotes/saml/saml_auth.rb | 237 ++++++++++++++++++ src/fireedge/package-lock.json | 39 +++ src/fireedge/package.json | 1 + .../User/CreateForm/Steps/General/schema.js | 16 +- .../Forms/User/CreateForm/Steps/index.js | 7 +- .../components/Tabs/User/Authentication.js | 1 + .../src/modules/constants/translates.js | 1 + src/fireedge/src/modules/constants/user.js | 1 + .../src/modules/containers/Login/Login.js | 4 +- .../containers/Login/Opennebula/Form.js | 39 ++- .../containers/Login/Opennebula/Opennebula.js | 43 +++- .../Settings/ChangePassword/ChangePassword.js | 3 +- src/fireedge/src/server/index.js | 3 + .../src/server/routes/api/auth/functions.js | 82 ++++++ .../src/server/routes/api/auth/index.js | 8 +- .../src/server/routes/api/auth/routes.js | 12 + src/fireedge/src/server/routes/api/index.js | 6 +- .../src/server/routes/entrypoints/App.js | 81 +++--- .../src/server/utils/constants/defaults.js | 7 +- src/fireedge/src/server/utils/errors.js | 11 + src/onecfg/share/etc/files.yaml | 7 + src/template/OpenNebulaTemplate.cc | 1 + src/um/User.cc | 1 + 36 files changed, 848 insertions(+), 63 deletions(-) create mode 100755 src/authm_mad/remotes/saml/authenticate create mode 100644 src/authm_mad/remotes/saml/saml_auth.conf create mode 100644 src/authm_mad/remotes/saml/saml_auth.rb diff --git a/install.sh b/install.sh index 9a5b9699d8..edbd95ffec 100755 --- a/install.sh +++ b/install.sh @@ -418,6 +418,7 @@ VAR_DIRS="$VAR_LOCATION/remotes \ $VAR_LOCATION/remotes/auth/ssh \ $VAR_LOCATION/remotes/auth/x509 \ $VAR_LOCATION/remotes/auth/ldap \ + $VAR_LOCATION/remotes/auth/saml \ $VAR_LOCATION/remotes/auth/server_x509 \ $VAR_LOCATION/remotes/auth/server_cipher \ $VAR_LOCATION/remotes/auth/dummy \ @@ -530,6 +531,7 @@ INSTALL_FILES=( AUTH_SSH_FILES:$VAR_LOCATION/remotes/auth/ssh AUTH_X509_FILES:$VAR_LOCATION/remotes/auth/x509 AUTH_LDAP_FILES:$VAR_LOCATION/remotes/auth/ldap + AUTH_SAML_FILES:$VAR_LOCATION/remotes/auth/saml AUTH_SERVER_X509_FILES:$VAR_LOCATION/remotes/auth/server_x509 AUTH_SERVER_CIPHER_FILES:$VAR_LOCATION/remotes/auth/server_cipher AUTH_DUMMY_FILES:$VAR_LOCATION/remotes/auth/dummy @@ -821,6 +823,7 @@ RUBY_AUTH_LIB_FILES="src/authm_mad/remotes/ssh/ssh_auth.rb \ src/authm_mad/remotes/server_x509/server_x509_auth.rb \ src/authm_mad/remotes/server_cipher/server_cipher_auth.rb \ src/authm_mad/remotes/ldap/ldap_auth.rb \ + src/authm_mad/remotes/saml/saml_auth.rb \ src/authm_mad/remotes/x509/x509_auth.rb" #----------------------------------------------------------------------------- @@ -1136,6 +1139,8 @@ AUTH_X509_FILES="src/authm_mad/remotes/x509/authenticate" AUTH_LDAP_FILES="src/authm_mad/remotes/ldap/authenticate" +AUTH_SAML_FILES="src/authm_mad/remotes/saml/authenticate" + AUTH_SSH_FILES="src/authm_mad/remotes/ssh/authenticate" AUTH_DUMMY_FILES="src/authm_mad/remotes/dummy/authenticate" @@ -1855,6 +1860,7 @@ HM_ETC_FILES="src/hm_mad/hmrc" AUTH_ETC_FILES="src/authm_mad/remotes/server_x509/server_x509_auth.conf \ src/authm_mad/remotes/ldap/ldap_auth.conf \ + src/authm_mad/remotes/saml/saml_auth.conf \ src/authm_mad/remotes/x509/x509_auth.conf" #------------------------------------------------------------------------------- diff --git a/share/etc/oned.conf b/share/etc/oned.conf index f18ff3b568..1ed8415ab5 100644 --- a/share/etc/oned.conf +++ b/share/etc/oned.conf @@ -726,7 +726,7 @@ HOOK_LOG_CONF = [ AUTH_MAD = [ EXECUTABLE = "one_auth_mad", - AUTHN = "ssh,x509,ldap,server_cipher,server_x509" + AUTHN = "ssh,x509,ldap,server_cipher,server_x509,saml" ] #DEFAULT_AUTH = "default" @@ -1353,6 +1353,15 @@ AUTH_MAD_CONF = [ MAX_TOKEN_TIME = "86400" ] +AUTH_MAD_CONF = [ + NAME = "saml", + PASSWORD_CHANGE = "YES", + PASSWORD_REQUIRED = "NO", + DRIVER_MANAGED_GROUPS = "YES", + DRIVER_MANAGED_GROUP_ADMIN = "YES", + MAX_TOKEN_TIME = "86400" +] + AUTH_MAD_CONF = [ NAME = "server_cipher", PASSWORD_CHANGE = "NO", diff --git a/share/install_gems/AlmaLinux8/Gemfile.lock b/share/install_gems/AlmaLinux8/Gemfile.lock index 198b249ecf..e2706b13ed 100644 --- a/share/install_gems/AlmaLinux8/Gemfile.lock +++ b/share/install_gems/AlmaLinux8/Gemfile.lock @@ -116,6 +116,8 @@ GEM optimist (~> 3.0) rchardet (1.8.0) rexml (3.4.3) + ruby-saml (1.14.0) + nokogiri (>= 1.10.5) ruby2_keywords (0.0.5) sequel (5.96.0) bigdecimal @@ -176,6 +178,7 @@ DEPENDENCIES rack rbvmomi2 rexml + ruby-saml sequel sinatra (< 4.0.0) sqlite3 (<= 1.6.9) diff --git a/share/install_gems/AlmaLinux9/Gemfile.lock b/share/install_gems/AlmaLinux9/Gemfile.lock index 0691ee3a74..5d2e089e40 100644 --- a/share/install_gems/AlmaLinux9/Gemfile.lock +++ b/share/install_gems/AlmaLinux9/Gemfile.lock @@ -128,6 +128,8 @@ GEM optimist (~> 3.0) rchardet (1.9.0) rexml (3.4.3) + ruby-saml (1.18.0) + nokogiri (>= 1.13.10) ruby2_keywords (0.0.5) sequel (5.96.0) bigdecimal @@ -186,6 +188,7 @@ DEPENDENCIES rackup rbvmomi2 rexml + ruby-saml sequel sinatra sqlite3 (<= 1.7.3) diff --git a/share/install_gems/Debian11/Gemfile.lock b/share/install_gems/Debian11/Gemfile.lock index 32ef13cfda..479bc10140 100644 --- a/share/install_gems/Debian11/Gemfile.lock +++ b/share/install_gems/Debian11/Gemfile.lock @@ -120,6 +120,8 @@ GEM rchardet (1.8.0) rexml (3.4.3) ruby2_keywords (0.0.5) + ruby-saml (1.18.0) + nokogiri (>= 1.13.10) sequel (5.96.0) bigdecimal sinatra (3.2.0) @@ -178,6 +180,7 @@ DEPENDENCIES rack rbvmomi2 rexml + ruby-saml sequel sinatra (< 4.0.0) sqlite3 (<= 1.6.9) diff --git a/share/install_gems/Debian12/Gemfile.lock b/share/install_gems/Debian12/Gemfile.lock index fd7063d930..0e809b3dce 100644 --- a/share/install_gems/Debian12/Gemfile.lock +++ b/share/install_gems/Debian12/Gemfile.lock @@ -142,6 +142,8 @@ GEM optimist (~> 3.0) rchardet (1.9.0) rexml (3.4.3) + ruby-saml (1.18.0) + nokogiri (>= 1.13.10) ruby2_keywords (0.0.5) sequel (5.96.0) bigdecimal @@ -212,6 +214,7 @@ DEPENDENCIES rackup rbvmomi2 rexml + ruby-saml sequel sinatra sqlite3 (<= 1.7.3) diff --git a/share/install_gems/Gemfile b/share/install_gems/Gemfile index ab8e0e6a77..1d13c4b113 100644 --- a/share/install_gems/Gemfile +++ b/share/install_gems/Gemfile @@ -81,6 +81,7 @@ gem 'public_suffix', ps gem 'rexml' gem 'aws-sdk-ec2', '>=1.151' gem 'aws-sdk-s3' +gem 'ruby-saml' group :cli do gem 'gnuplot' @@ -159,4 +160,4 @@ end group :oneswap do gem 'rbvmomi2' -end +end \ No newline at end of file diff --git a/share/install_gems/RedHat8/Gemfile.lock b/share/install_gems/RedHat8/Gemfile.lock index 198b249ecf..e2706b13ed 100644 --- a/share/install_gems/RedHat8/Gemfile.lock +++ b/share/install_gems/RedHat8/Gemfile.lock @@ -116,6 +116,8 @@ GEM optimist (~> 3.0) rchardet (1.8.0) rexml (3.4.3) + ruby-saml (1.14.0) + nokogiri (>= 1.10.5) ruby2_keywords (0.0.5) sequel (5.96.0) bigdecimal @@ -176,6 +178,7 @@ DEPENDENCIES rack rbvmomi2 rexml + ruby-saml sequel sinatra (< 4.0.0) sqlite3 (<= 1.6.9) diff --git a/share/install_gems/RedHat9/Gemfile.lock b/share/install_gems/RedHat9/Gemfile.lock index 0691ee3a74..5d2e089e40 100644 --- a/share/install_gems/RedHat9/Gemfile.lock +++ b/share/install_gems/RedHat9/Gemfile.lock @@ -128,6 +128,8 @@ GEM optimist (~> 3.0) rchardet (1.9.0) rexml (3.4.3) + ruby-saml (1.18.0) + nokogiri (>= 1.13.10) ruby2_keywords (0.0.5) sequel (5.96.0) bigdecimal @@ -186,6 +188,7 @@ DEPENDENCIES rackup rbvmomi2 rexml + ruby-saml sequel sinatra sqlite3 (<= 1.7.3) diff --git a/share/install_gems/Ubuntu2204/Gemfile.lock b/share/install_gems/Ubuntu2204/Gemfile.lock index 3216cadb65..9a23425ba9 100644 --- a/share/install_gems/Ubuntu2204/Gemfile.lock +++ b/share/install_gems/Ubuntu2204/Gemfile.lock @@ -128,6 +128,8 @@ GEM optimist (~> 3.0) rchardet (1.9.0) rexml (3.4.3) + ruby-saml (1.18.0) + nokogiri (>= 1.13.10) ruby2_keywords (0.0.5) sequel (5.96.0) bigdecimal @@ -186,6 +188,7 @@ DEPENDENCIES rackup rbvmomi2 rexml + ruby-saml sequel sinatra sqlite3 (<= 1.7.3) diff --git a/share/install_gems/Ubuntu2404/Gemfile.lock b/share/install_gems/Ubuntu2404/Gemfile.lock index 4e2d2fb1b6..6140bccebf 100644 --- a/share/install_gems/Ubuntu2404/Gemfile.lock +++ b/share/install_gems/Ubuntu2404/Gemfile.lock @@ -156,6 +156,8 @@ GEM optimist (~> 3.0) rchardet (1.9.0) rexml (3.4.3) + ruby-saml (1.18.0) + nokogiri (>= 1.13.10) ruby2_keywords (0.0.5) sequel (5.96.0) bigdecimal @@ -233,6 +235,7 @@ DEPENDENCIES rackup rbvmomi2 rexml + ruby-saml sequel sinatra sqlite3 diff --git a/src/authm_mad/remotes/saml/authenticate b/src/authm_mad/remotes/saml/authenticate new file mode 100755 index 0000000000..08907c24d6 --- /dev/null +++ b/src/authm_mad/remotes/saml/authenticate @@ -0,0 +1,154 @@ +#!/usr/bin/env ruby + +# ---------------------------------------------------------------------------- # +# Copyright 2002-2025, 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. # +# ---------------------------------------------------------------------------- # + +ONE_LOCATION = ENV['ONE_LOCATION'] + +if !ONE_LOCATION + RUBY_LIB_LOCATION = '/usr/lib/one/ruby' + GEMS_LOCATION = '/usr/share/one/gems' + ETC_LOCATION = '/etc/one/' +else + RUBY_LIB_LOCATION = ONE_LOCATION + '/lib/ruby' + GEMS_LOCATION = ONE_LOCATION + '/share/gems' + ETC_LOCATION = ONE_LOCATION + '/etc/' +end + +# %%RUBYGEMS_SETUP_BEGIN%% +require 'load_opennebula_paths' +# %%RUBYGEMS_SETUP_END%% + +$LOAD_PATH << RUBY_LIB_LOCATION + +require 'yaml' +require 'base64' +require 'opennebula/saml_auth' +require 'uri' +require 'timeout' +require 'rexml/document' +require 'opennebula/error' +require 'opennebula/xml_utils' +require 'onelogin/ruby-saml' + +DEV_DEBUG = false + +if defined?(URI::Parser) + URI_PARSER=URI::Parser.new +else + URI_PARSER=URI +end + +begin + xml = OpenNebula::XMLElement.new + xml.initialize_xml(STDIN.read, 'AUTHN') + + user = URI_PARSER.unescape(xml['/AUTHN/USERNAME']) + secret = URI_PARSER.unescape(xml['/AUTHN/SECRET']) +rescue StandardError + STDERR.puts 'Invalid XML input' + exit(-1) +end + +# Load SAML assertion and retrieve issuer +begin + assertion_text = Base64.decode64(secret) + assertion = Nokogiri::XML(assertion_text) + namespaces = { + 'saml' => 'urn:oasis:names:tc:SAML:2.0:assertion' + } + + issuer = assertion.at_xpath('//saml:Issuer', namespaces).text +rescue StandardError => e + STDERR.puts "Unable to parse SAML assertion: #{e.message}" + exit(-1) +end + +# Load configuration file +begin + options=YAML.load_file(ETC_LOCATION+'/auth/saml_auth.conf') +rescue StandardError => e + STDERR.puts 'Unable to load SAML configuration file.' + STDERR.puts 'Check that /etc/one/auth/saml_auth.conf exists and can be read by oneadmin.' + STDERR.puts "Error: #{e}" + exit(-1) +end + +# Check if the assertion is emitted by a trusted (configured) IDP +begin + provider = nil + options[:identity_providers].each do |_, idp_data| + if idp_data[:issuer] == issuer + provider = idp_data + break + end + end + + if provider.nil? + STDERR.puts 'SAML assertion not produced by a trusted Identity Provider.' + STDERR.puts 'Review the list of trusted Identity Providers in /etc/one/auth/saml_auth.conf' + exit(-1) + end +rescue StandardError => e + STDERR.puts 'Error checking if the assertion issuer is trusted.' + STDERR.puts "Error: #{e}" + exit(-1) +end + +puts('Identity Provider found! Loading provider config...') if DEV_DEBUG + +# Load provider config. Triggers mapping file autogenerate/refresh/load +begin + saml = OpenNebula::SamlAuth.new(provider, options) +rescue StandardError => e + STDERR.puts 'Error loading Identity Provider configuration or autogenerating mapping file.' + STDERR.puts "Error: #{e}" +end + +puts('Validating assertion...') if DEV_DEBUG +# Validate the assertion +begin + result = saml.validate_assertion(assertion_text) + if result.equal?(true) + puts('The SAML assertion is valid.') if DEV_DEBUG + else + STDERR.puts('SAML Assertion rejected. Reasons:') + result.each do |reason| + STDERR.puts('- ' + reason) + end + end +rescue StandardError => e + STDERR.puts 'Error validating SAML assertion.' + STDERR.puts "Error: #{e}" + exit(-1) +end + +# Group mapping logic +begin + xpath_request = "//saml:Attribute[@Name='#{provider[:group_field]}']/saml:AttributeValue" + idp_groups = assertion.xpath(xpath_request, namespaces).map(&:text) + puts("IDP reported group membership: #{idp_groups}") if DEV_DEBUG + saml.validate_required_group(idp_groups) + one_groups = saml.get_groups(idp_groups) + puts("Mapped OpenNebula groups: #{one_groups}") if DEV_DEBUG +rescue StandardError => e + STDERR.puts 'Error mapping received groups to OpenNebula groups.' + STDERR.puts "Error: #{e}" + exit(-1) +end + +# Using base64-encoded issuer URL as a password placeholder for new users +puts("saml #{user} #{Base64.strict_encode64(issuer)} #{one_groups}") diff --git a/src/authm_mad/remotes/saml/saml_auth.conf b/src/authm_mad/remotes/saml/saml_auth.conf new file mode 100644 index 0000000000..69829c91dd --- /dev/null +++ b/src/authm_mad/remotes/saml/saml_auth.conf @@ -0,0 +1,102 @@ +# -------------------------------------------------------------------------- # +# Global Service Provider (SP) Configuration # +# -------------------------------------------------------------------------- # +# The unique identifier for this OpenNebula instance as a Service Provider. +# This exact value must be configured in each Identity Provider (IdP) that +# you connect (e.g., as the Client ID in Keycloak or Audience URI in Okta). +# It is used to validate the 'Audience' in the SAML assertion. +:sp_entity_id: 'your-opennebula-sp-entity-id' + +# -------------------------------------------------------------------------- # +# Assertion Consumer Service (ACS) URL # +# -------------------------------------------------------------------------- # +# The endpoint where OpenNebula receives SAML assertions. +# This value must exactly match the 'Recipient' URL that the IdP +# includes in the SAML assertion, preventing SAML redirect attacks +:acs_url: 'https://your-opennebula-domain.com/fireedge/api/auth/acs' + +# -------------------------------------------------------------------------- # +# Identity Provider (IdP) Definitions # +# -------------------------------------------------------------------------- # +# A map containing the configuration for each trusted Identity Provider, +# where the key is the name of the provider. +:identity_providers: + :keycloak_idp: + # The 'issuer' is a unique identifier for the Identity Provider. + # This value from the SAML assertion's element is used + # to find the correct configuration block. + # Example: "https://your-keycloak-domain.com/realms/your-realm" + :issuer: 'https://your-keycloak-domain.com/realms/your-realm' + + # The X.509 public key certificate of the Identity Provider. + # This is used to verify the signature of the SAML assertion. + # The certificate should be in PEM format, without the -----BEGIN... + # and -----END... lines, and on a single line. + :idp_cert: 'MIID...your...IdP...cert...here...A==' + + # Field in the SAML assertion that contains the username. + # By default, the driver will use the content of the element. + :user_field: 'NameID' + + # Field in the SAML assertion that contains the group membership information. + # This should correspond to an with the Name specified here. + # Default is 'member'. + :group_field: 'member' + + # If set, SAML users must belong to this group in order to be allowed access to + # OpenNebula. If not set, any valid SAML user will be granted access. If that's + # the case and no group membership is reported, the ONE group ID defined in + # :mapping_default will be used. + # :group_required: 'one-users' + + # --- Group Mapping Configuration --- + + # If 'true', the driver will automatically generate a group mapping file + # from the information in the OpenNebula groups template. This is similar to the + # LDAP driver's functionality. + :mapping_generate: true + + # Key from the OpenNebula group template to map to a SAML group. + # Only relevant if mapping_generate is true + :mapping_key: 'SAML_GROUP' + + # Group mapping mode. Triggers IDP-dependant logic. + # Used to support specific IDP features (e.g. group nesting in Keycloak) + # Possible values: + # strict => strict mapping between the group names reported by the IdP and + # the ones in the mapping file. + # keycloak => handles Keycloak full group path syntax, supporting group nesting + # E.g. A user member of /group1/subgroup1 is considered both member + # of group1 and member of subgroup1. + :mapping_mode: 'keycloak' + + # Time in seconds that a mapping file will be considered valid before + # it is regenerated. Only relevant if mapping_generate is true + :mapping_timeout: 300 + + # The name of the group mapping file, which will be stored in + # OpenNebula's var directory ( /var/lib/one ). + # If mapping_generate is true, this file will be automatically created and + # populated. + :mapping_filename: 'keycloak_groups.yaml' + + # The default OpenNebula group ID to assign to a user if none of their SAML + # groups is found in the mapping file. + :mapping_default: 1 + + # Name of a group from the Identity Provider. If a user is a member of this group, + # they will be granted admin rights for ALL their mapped OpenNebula groups. + :group_admin_name: '/opennebula-admins' + :okta_idp: + :issuer: 'https://your-okta-domain.com/app/your-app-id/sso/saml' + :idp_cert: 'MIID...your...IdP...cert...here...A==' + :user_field: 'NameID' + :group_field: 'member' + # :group_required: 'opennebula-users' + :mapping_generate: true + :mapping_key: 'OKTA_GROUP' + :mapping_mode: 'strict' + :mapping_timeout: 300 + :mapping_filename: 'okta_groups.yaml' + :mapping_default: 1 + :group_admin_name: 'okta-opennebula-admins' \ No newline at end of file diff --git a/src/authm_mad/remotes/saml/saml_auth.rb b/src/authm_mad/remotes/saml/saml_auth.rb new file mode 100644 index 0000000000..cb249a75e8 --- /dev/null +++ b/src/authm_mad/remotes/saml/saml_auth.rb @@ -0,0 +1,237 @@ +# ---------------------------------------------------------------------------- # +# Copyright 2002-2024, 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 'rubygems' +require 'opennebula/xml_utils' +require 'opennebula/client' +require 'opennebula/group_pool' +require 'yaml' +require 'onelogin/ruby-saml' + +if !defined?(ONE_LOCATION) + ONE_LOCATION=ENV['ONE_LOCATION'] +end + +if !ONE_LOCATION + VAR_LOCATION='/var/lib/one/' +else + VAR_LOCATION=ONE_LOCATION+'/var/' +end + +# A top-level module for OpenNebula related classes. +module OpenNebula + + # This class handles SAML authentication responses and group mapping for OpenNebula. + class SamlAuth + + def initialize(provider, config) + @options={ + :issuer => nil, + :idp_cert => nil, + :user_field => 'NameID', + :group_field => 'memberOf', + :group_required => nil, + :mapping_generate => true, + :mapping_key => 'SAML_GROUP', + :mapping_mode => 'strict', + :mapping_timeout => 300, + :mapping_filename => 'saml_groups_1.yaml', + :mapping_default => 1, + :group_admin_name => 'cloud-admins' + }.merge(provider) + + @options[:mapping_file_path] = VAR_LOCATION + @options[:mapping_filename] + @options[:sp_entity_id] = config[:sp_entity_id] + @options[:acs_url] = config[:acs_url] + + if !options_ok? + STDERR.puts('Identity Provider configured options are not correct.') + STDERR.puts('Please, configure a valid Identity Provider certificate.') + exit(-1) + end + + generate_mapping if @options[:mapping_generate] + load_mapping + end + + def options_ok? + required_keys = [:issuer, :idp_cert, :sp_entity_id, :group_field] + return false unless required_keys.all? {|key| @options.key?(key) } + + # Avoid XPath injection towards the assertion + !@options[:group_field].include?("'") + end + + # Validates SAML assertion using the ruby-saml library. + # Returns true if the assertion is valid. + # If not valid, returns an array of errors with the failed validations. + # The following validations are performed: + # validations = [ + # :validate_version, # checks if SAML 2.0 is used + # :validate_id, # checks that the assertion contains an ID + # :validate_success_status, # validates the status of the assertion + # :validate_num_assertion, # validates that only a single assertion is contained + # :validate_signed_elements, # validates that only valid elements are signed + # :validate_structure, # validates the assertion against a specific schema + # :validate_no_duplicated_attributes, # checks for duplicated attributes + # :validate_in_response_to, # check if the provided request_id == inResponseTo + # :validate_one_conditions, # checks that saml:Conditions exist + # :validate_conditions, # validates that the assertion is not expired + # :validate_one_authnstatement, # checks that saml:AuthnStatement exists + # :validate_audience, # validates that Audience == sp_entity_id + # :validate_destination, # validates that destination == acs_url + # :validate_issuer, # validates if the assertion issuer matches the configured one + # :validate_session_expiration, # validates expiration (SessionNotOnOrAfter) + # :validate_subject_confirmation, # checks if subject confirmation is correct + # :validate_name_id, # checks that the NameID element is present + # :validate_signature # validates the assertion signature + # ] + + # Source: https://github.com/SAML-Toolkits/ruby-saml/blob/fbbedc978300deb9355a8e505849666974ef2e67/lib/onelogin/ruby-saml/response.rb#L399 + + def validate_assertion(assertion_text) + saml_settings = OneLogin::RubySaml::Settings.new + saml_settings.idp_cert = @options[:idp_cert] + saml_settings.issuer = @options[:issuer] + saml_settings.sp_entity_id = @options[:sp_entity_id] + saml_settings.assertion_consumer_service_url = @options[:acs_url] + assertion = OneLogin::RubySaml::Response.new(assertion_text, :settings => saml_settings) + return true if assertion.is_valid? + + return assertion.errors + end + + def generate_mapping + file=@options[:mapping_file_path] + generate = false + + if File.exist?(file) + stat = File.stat(file) + age = Time.now.to_i - stat.mtime.to_i + generate = true if age > @options[:mapping_timeout] + else + generate = true + end + + return unless generate + + client = OpenNebula::Client.new + group_pool = OpenNebula::GroupPool.new(client) + rc = group_pool.info + + if OpenNebula.is_error?(rc) + STDERR.puts 'Unable to retrieve OpenNebula groups. OpenNebula error.' + STDERR.puts "Error: #{rc.message}" + exit(-1) + end + + groups=[group_pool.get_hash['GROUP_POOL']['GROUP']].flatten + + yaml={} + + groups.each do |group| + if group['TEMPLATE'] && group['TEMPLATE'][@options[:mapping_key]] + yaml[group['TEMPLATE'][@options[:mapping_key]]] = group['ID'] + end + end + + File.open(file, 'w') do |f| + f.write(yaml.to_yaml) + end + end + + def load_mapping + file=@options[:mapping_file_path] + + @mapping = {} + + if File.exist?(file) + @mapping = YAML.safe_load(File.read(file)) + end + + @mapping = {} unless @mapping.class == Hash + end + + def validate_required_group(idp_groups) + required = @options[:group_required] + return if required.nil? + + return if idp_groups.include?(required) || idp_groups.include?("/#{required}") + + STDERR.puts('The user does not belong to the required group.') + STDERR.puts("Groups reported by the IdP: #{idp_groups}") + STDERR.puts("Configured required group: #{required} ( /#{required} if using Keycloak )") + exit(-1) + end + + def get_groups(idp_groups) + is_admin = false + case @options[:mapping_mode] + # Direct mapping of SAML group names to ONE group IDs + when 'strict' + valid_mappings = idp_groups.map {|group| @mapping[group] }.compact + g_admin = @options[:group_admin_name] + is_admin = g_admin && idp_groups.include?(g_admin) + # Keycloak-specific group syntax and group nesting support (e.g. /group1/subgroup1) + when 'keycloak' + valid_mappings = [] + idp_groups.each do |idp_group| + group_parts = idp_group.split('/') + # Remove empty strings from leading/trailing slashes + group_parts.reject!(&:empty?) + + # Build all possible parent group paths + (1..group_parts.length).each do |i| + # Create group path with leading slash (Keycloak format) + group_path = '/' + group_parts[0...i].join('/') + + is_admin = true if group_path == @options[:group_admin_name] + + # Check direct mapping first + if @mapping[group_path] + valid_mappings << @mapping[group_path] + elsif i == 1 + # Try without the leading slash for single group parts + # E.g. in the mapping file "/group1" should be the same as "group1" + group_path_no_slash = group_parts[0] + is_admin = true if group_path_no_slash == @options[:group_admin_name] + if @mapping[group_path_no_slash] + valid_mappings << @mapping[group_path_no_slash] + end + end + end + end + # Remove potential nil and duplicated values + valid_mappings.compact! + valid_mappings.uniq! + else + STDERR.puts("Unsupported group mapping mode: #{@options[:mapping_mode]}") + STDERR.puts('Supported modes are "strict" and "keycloak".') + exit(-1) + end + + # Return the default group if no mapping is found + valid_mappings = [@options[:mapping_default].to_s] if valid_mappings.empty? + + # Handle group admin case. Group admin can NOT be a nested group + valid_mappings = valid_mappings.map {|id| "*#{id}" } if is_admin + + return valid_mappings.join(' ') + end + + end + +end diff --git a/src/fireedge/package-lock.json b/src/fireedge/package-lock.json index 13641d2feb..4c6ec4730d 100644 --- a/src/fireedge/package-lock.json +++ b/src/fireedge/package-lock.json @@ -39,6 +39,7 @@ "btoa": "1.2.1", "clsx": "1.1.1", "compression": "1.7.4", + "cookie-parser": "1.4.7", "copy-webpack-plugin": "9.0.1", "core-js": "3.18.1", "cors": "2.8.5", @@ -5915,6 +5916,28 @@ "node": ">= 0.6" } }, + "node_modules/cookie-parser": { + "version": "1.4.7", + "resolved": "https://registry.npmjs.org/cookie-parser/-/cookie-parser-1.4.7.tgz", + "integrity": "sha512-nGUvgXnotP3BsjiLX2ypbQnWoGUPIIfHQNZkkC668ntrzGWEZVW70HDEB1qnNGMicPje6EttlIgzo51YSwNQGw==", + "license": "MIT", + "dependencies": { + "cookie": "0.7.2", + "cookie-signature": "1.0.6" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/cookie-parser/node_modules/cookie": { + "version": "0.7.2", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz", + "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, "node_modules/cookie-signature": { "version": "1.0.6", "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz", @@ -20957,6 +20980,22 @@ "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.4.0.tgz", "integrity": "sha512-+Hp8fLp57wnUSt0tY0tHEXh4voZRDnoIrZPqlo3DPiI4y9lwg/jqx+1Om94/W6ZaPDOUbnjOt/99w66zk+l1Xg==" }, + "cookie-parser": { + "version": "1.4.7", + "resolved": "https://registry.npmjs.org/cookie-parser/-/cookie-parser-1.4.7.tgz", + "integrity": "sha512-nGUvgXnotP3BsjiLX2ypbQnWoGUPIIfHQNZkkC668ntrzGWEZVW70HDEB1qnNGMicPje6EttlIgzo51YSwNQGw==", + "requires": { + "cookie": "0.7.2", + "cookie-signature": "1.0.6" + }, + "dependencies": { + "cookie": { + "version": "0.7.2", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz", + "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==" + } + } + }, "cookie-signature": { "version": "1.0.6", "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz", diff --git a/src/fireedge/package.json b/src/fireedge/package.json index e0d12f7889..5792718cb1 100644 --- a/src/fireedge/package.json +++ b/src/fireedge/package.json @@ -82,6 +82,7 @@ "btoa": "1.2.1", "clsx": "1.1.1", "compression": "1.7.4", + "cookie-parser": "1.4.7", "copy-webpack-plugin": "9.0.1", "core-js": "3.18.1", "cors": "2.8.5", diff --git a/src/fireedge/src/modules/components/Forms/User/CreateForm/Steps/General/schema.js b/src/fireedge/src/modules/components/Forms/User/CreateForm/Steps/General/schema.js index be5477e9f4..b26beb61a6 100644 --- a/src/fireedge/src/modules/components/Forms/User/CreateForm/Steps/General/schema.js +++ b/src/fireedge/src/modules/components/Forms/User/CreateForm/Steps/General/schema.js @@ -55,11 +55,15 @@ const PASSWORD_FIELD = { type: INPUT_TYPES.PASSWORD, dependOf: AUTH_TYPE_FIELD.name, htmlType: (authType) => - authType && authType === AUTH_DRIVER.LDAP && INPUT_TYPES.HIDDEN, + authType && + [AUTH_DRIVER.LDAP, AUTH_DRIVER.SAML].includes(authType) && + INPUT_TYPES.HIDDEN, validation: string() .trim() .when(AUTH_TYPE_FIELD.name, (authType, schema) => - authType === AUTH_DRIVER.LDAP ? schema.strip() : schema.required() + [AUTH_DRIVER.LDAP, AUTH_DRIVER.SAML].includes(authType) + ? schema.strip() + : schema.required() ) .default(() => undefined), grid: { md: 12 }, @@ -72,11 +76,15 @@ const CONFIRM_PASSWORD_FIELD = { type: INPUT_TYPES.PASSWORD, dependOf: AUTH_TYPE_FIELD.name, htmlType: (authType) => - authType && authType === AUTH_DRIVER.LDAP && INPUT_TYPES.HIDDEN, + authType && + [AUTH_DRIVER.LDAP, AUTH_DRIVER.SAML].includes(authType) && + INPUT_TYPES.HIDDEN, validation: string() .trim() .when(AUTH_TYPE_FIELD.name, (authType, schema) => - authType === AUTH_DRIVER.LDAP ? schema.strip() : schema.required() + [AUTH_DRIVER.LDAP, AUTH_DRIVER.SAML].includes(authType) + ? schema.strip() + : schema.required() ) .test('passwords-match', T.PasswordsMustMatch, function (value) { return this.parent.password === value diff --git a/src/fireedge/src/modules/components/Forms/User/CreateForm/Steps/index.js b/src/fireedge/src/modules/components/Forms/User/CreateForm/Steps/index.js index 3176ac773a..7dc48b37bf 100644 --- a/src/fireedge/src/modules/components/Forms/User/CreateForm/Steps/index.js +++ b/src/fireedge/src/modules/components/Forms/User/CreateForm/Steps/index.js @@ -33,11 +33,14 @@ const Steps = createSteps([General, PrimaryGroup, SecondaryGroups], { [SECONDARY_GROUPS_ID]: secondaryGroupsData, } = formData - // LDAP driver needs to set password to '-' + // LDAP and SAML drivers need to set password to '-' return { username: generalData.username, password: - generalData.authType === AUTH_DRIVER.LDAP ? '-' : generalData.password, + generalData.authType === AUTH_DRIVER.LDAP || + generalData.authType === AUTH_DRIVER.SAML + ? '-' + : generalData.password, driver: generalData.authType, group: [primaryGroupsData, ...secondaryGroupsData], } diff --git a/src/fireedge/src/modules/components/Tabs/User/Authentication.js b/src/fireedge/src/modules/components/Tabs/User/Authentication.js index 6a5d444c61..a1c98a7613 100644 --- a/src/fireedge/src/modules/components/Tabs/User/Authentication.js +++ b/src/fireedge/src/modules/components/Tabs/User/Authentication.js @@ -204,6 +204,7 @@ const AuthenticationInfo = ({ id }) => { 'ssh', 'x509', 'ldap', + 'saml', 'server_cipher', 'server_x509', 'custom', diff --git a/src/fireedge/src/modules/constants/translates.js b/src/fireedge/src/modules/constants/translates.js index 3af37019ef..258e482e29 100644 --- a/src/fireedge/src/modules/constants/translates.js +++ b/src/fireedge/src/modules/constants/translates.js @@ -243,6 +243,7 @@ module.exports = { ShowBelongingUser: 'Show all owned by the user', ShowBelongingUserAndGroups: 'Show all owned by the user or his groups', SignIn: 'Sign In Now', + SignInRemote: 'Sign In with SAML service', SignOut: 'Sign Out', SnapshotCreate: 'Snapshot create', SnapshotRevert: 'Snapshot revert', diff --git a/src/fireedge/src/modules/constants/user.js b/src/fireedge/src/modules/constants/user.js index abbf2d2db4..f1bb06cdcb 100644 --- a/src/fireedge/src/modules/constants/user.js +++ b/src/fireedge/src/modules/constants/user.js @@ -88,6 +88,7 @@ export const AUTH_DRIVER = { SSH: 'ssh', X509: 'x509', LDAP: 'ldap', + SAML: 'saml', SERVER_CIPHER: 'server_cipher', SERVER_X509: 'server_x509', CUSTOM: 'custom', diff --git a/src/fireedge/src/modules/containers/Login/Login.js b/src/fireedge/src/modules/containers/Login/Login.js index a6a0bebb4a..ca3a5cae17 100644 --- a/src/fireedge/src/modules/containers/Login/Login.js +++ b/src/fireedge/src/modules/containers/Login/Login.js @@ -14,10 +14,10 @@ * limitations under the License. * * ------------------------------------------------------------------------- */ +import { TranslateProvider } from '@ComponentsModule' import { OpenNebulaLogin } from '@modules/containers/Login/Opennebula' import { RemoteLogin } from '@modules/containers/Login/Remote' import { ReactElement } from 'react' -import { TranslateProvider } from '@ComponentsModule' /** * Displays the login form and handles the login process. @@ -29,7 +29,7 @@ export const Login = () => ( {window?.__REMOTE_AUTH__?.remote ? ( ) : ( - + )} ) diff --git a/src/fireedge/src/modules/containers/Login/Opennebula/Form.js b/src/fireedge/src/modules/containers/Login/Opennebula/Form.js index d8246bf6fe..a02aee1b1c 100644 --- a/src/fireedge/src/modules/containers/Login/Opennebula/Form.js +++ b/src/fireedge/src/modules/containers/Login/Opennebula/Form.js @@ -14,21 +14,22 @@ * limitations under the License. * * ------------------------------------------------------------------------- */ /* eslint-disable jsdoc/require-jsdoc */ -import { useEffect } from 'react' +import { ArrowTrSquare } from 'iconoir-react' import PropTypes from 'prop-types' +import { useEffect } from 'react' -import { Box, Slide, Stack } from '@mui/material' +import { Box, Divider, Link, Slide, Stack } from '@mui/material' -import { useForm, FormProvider } from 'react-hook-form' import { yupResolver } from '@hookform/resolvers/yup' +import { FormProvider, useForm } from 'react-hook-form' import { - TranslateProvider, - Translate, - SubmitButton, FormWithSchema, + SubmitButton, + Translate, + TranslateProvider, } from '@ComponentsModule' -import { T, STYLE_BUTTONS } from '@ConstantsModule' +import { STYLE_BUTTONS, T } from '@ConstantsModule' export const Form = ({ onBack, @@ -38,6 +39,7 @@ export const Form = ({ error, isLoading, transitionProps, + remoteRedirect, }) => { const { handleSubmit, setError, ...methods } = useForm({ reValidateMode: 'onSubmit', @@ -103,6 +105,28 @@ export const Form = ({ size={STYLE_BUTTONS.SIZE.LARGE} /> + {remoteRedirect && ( + <> + + + { + window.location.href = remoteRedirect + }} + data-cy="link-saml" + sx={{ + display: 'inline-flex', + gap: '0.4rem', + alignItems: 'center', + }} + > + + + + + )} @@ -123,6 +147,7 @@ Form.propTypes = { transitionProps: PropTypes.shape({ name: PropTypes.string, }), + remoteRedirect: PropTypes.string, } Form.defaultProps = { diff --git a/src/fireedge/src/modules/containers/Login/Opennebula/Opennebula.js b/src/fireedge/src/modules/containers/Login/Opennebula/Opennebula.js index 561d24e8ee..69a75cecd1 100644 --- a/src/fireedge/src/modules/containers/Login/Opennebula/Opennebula.js +++ b/src/fireedge/src/modules/containers/Login/Opennebula/Opennebula.js @@ -14,6 +14,11 @@ * limitations under the License. * * ------------------------------------------------------------------------- */ +import { OpenNebulaLogo, Tr } from '@ComponentsModule' +import { JWT_NAME, T } from '@ConstantsModule' +import { AuthAPI, AuthSlice, useAuth, useAuthApi } from '@FeaturesModule' +import { Form } from '@modules/containers/Login/Opennebula/Form' +import * as FORM_SCHEMA from '@modules/containers/Login/Opennebula/schema' import { Box, Container, @@ -22,17 +27,15 @@ import { useMediaQuery, useTheme, } from '@mui/material' -import { ReactElement, useState, useMemo } from 'react' - -import { useAuth, useAuthApi, AuthAPI } from '@FeaturesModule' - -import { Tr, OpenNebulaLogo } from '@ComponentsModule' -import { T } from '@ConstantsModule' -import { Form } from '@modules/containers/Login/Opennebula/Form' -import * as FORM_SCHEMA from '@modules/containers/Login/Opennebula/schema' +import { storage } from '@UtilsModule' +import PropTypes from 'prop-types' +import { ReactElement, useEffect, useMemo, useState } from 'react' +import { useDispatch } from 'react-redux' import { styles } from '@modules/containers/Login/styles' +const { actions: authActions } = AuthSlice + const STEPS = { USER_FORM: 0, FA2_FORM: 1, @@ -42,9 +45,21 @@ const STEPS = { /** * Displays the login form and handles the login process. * + * @param {object} props - Props + * @param {object} props.data - User Auth data * @returns {ReactElement} The login form. */ -export function OpenNebulaLoginHandler() { +export function OpenNebulaLoginHandler({ data = {} }) { + const dispatch = useDispatch() + const { remoteRedirect, jwt: userJWT } = data + + useEffect(() => { + if (userJWT) { + storage(JWT_NAME, userJWT) + dispatch(authActions.changeJwt(userJWT)) + } + }, []) + const isMobile = useMediaQuery((themeMobile) => themeMobile.breakpoints.only('xs') ) @@ -137,6 +152,7 @@ export function OpenNebulaLoginHandler() { fields={FORM_SCHEMA.FORM_USER_FIELDS} error={errorMessage} isLoading={isLoading} + remoteRedirect={remoteRedirect} /> )} {step === STEPS.FA2_FORM && ( @@ -173,4 +189,13 @@ export function OpenNebulaLoginHandler() { ) } +OpenNebulaLoginHandler.propTypes = { + data: PropTypes.shape({ + jwt: PropTypes.string, + id: PropTypes.string, + remoteRedirect: PropTypes.string, + }), +} +OpenNebulaLoginHandler.displayName = 'OpenNebula' + export default OpenNebulaLoginHandler diff --git a/src/fireedge/src/modules/containers/Settings/ChangePassword/ChangePassword.js b/src/fireedge/src/modules/containers/Settings/ChangePassword/ChangePassword.js index 96c6c88969..618ce0defd 100644 --- a/src/fireedge/src/modules/containers/Settings/ChangePassword/ChangePassword.js +++ b/src/fireedge/src/modules/containers/Settings/ChangePassword/ChangePassword.js @@ -98,7 +98,8 @@ const ChangePassword = () => { disabled={ user.ID === ONEADMIN_ID || user.ID === SERVERADMIN_ID || - user.AUTH_DRIVER === AUTH_DRIVER.LDAP + user.AUTH_DRIVER === AUTH_DRIVER.LDAP || + user.AUTH_DRIVER === AUTH_DRIVER.SAML } /> diff --git a/src/fireedge/src/server/index.js b/src/fireedge/src/server/index.js index 336488ebe5..90186cb130 100644 --- a/src/fireedge/src/server/index.js +++ b/src/fireedge/src/server/index.js @@ -38,6 +38,7 @@ import { import compression from 'compression' import cors from 'cors' import express from 'express' +import cookieParser from 'cookie-parser' import helmet from 'helmet' import http from 'http' import { resolve } from 'path' @@ -78,6 +79,8 @@ const port = appConfig.port || defaultPort app.use(helmet.xssFilter()) app.use(helmet.hidePoweredBy()) app.use(compression()) +app.use(cookieParser()) + app.use(`${basename}/client`, express.static(resolve(__dirname, frontPath))) app.use(`${basename}/client/*`, express.static(resolve(__dirname, frontPath))) diff --git a/src/fireedge/src/server/routes/api/auth/functions.js b/src/fireedge/src/server/routes/api/auth/functions.js index ea52c335c0..e2e2922af5 100644 --- a/src/fireedge/src/server/routes/api/auth/functions.js +++ b/src/fireedge/src/server/routes/api/auth/functions.js @@ -32,6 +32,7 @@ const { } = require('server/routes/api/auth/utils') const { defaults, httpCodes } = require('server/utils/constants') +const { xml2json } = require('server/utils/general') const { Actions } = require('server/utils/constants/commands/user') const { getFireedgeConfig } = require('server/utils/yml') const { @@ -39,6 +40,8 @@ const { } = require('server/utils/opennebula') const { writeInLogger } = require('server/utils/logger') +const { global } = require('window-or-global') +const atob = require('atob') const { internalServerError, unauthorized } = httpCodes @@ -172,6 +175,84 @@ const remoteAuth = ( } } +const getBasePath = (req = {}) => { + const originalUrl = req?.originalUrl || '' + const idx = originalUrl.indexOf('/api') + + return idx > 0 ? originalUrl.substring(0, idx) : '/' +} + +const samlErrorAndRedirect = (res, path = '/', err = '') => { + const error = new Error(err) + writeInLogger(error, { format: 'SAML authentication error: %s' }) + res.redirect(path) +} + +/** + * Saml authentication. for POST endpoint. + * + * @param {object} res - http response + * @param {Function} next - express stepper + * @param {object} params - params of http request + * @param {object} userData - user of http request + * @param {Function} oneConnection - function of xmlrpc + * @param {object} req - http request + */ +const samlAuth = ( + res = {}, + next = defaultEmptyFunction, + params = {}, + userData = {}, + oneConnection = defaultEmptyFunction, + req = {} +) => { + const basepath = getBasePath(req) + const { SAMLResponse } = params + + updaterResponse(new Map(internalServerError).toObject()) + + if (!SAMLResponse) { + samlErrorAndRedirect( + res, + basepath, + 'The SAMLResponse parameter is not found in the request.' + ) + + return + } + const xmlMessage = atob(SAMLResponse) + + xml2json(xmlMessage, (err, data) => { + if (err) { + samlErrorAndRedirect( + res, + basepath, + 'Error transforming SAML output into JSON' + ) + + return + } + + const samlUser = data?.Response?.Assertion?.Subject?.NameID?.['#text'] + if (samlUser) { + if (!global.saml) { + global.saml = {} + } + + global.saml[samlUser] = SAMLResponse + + res.cookie('saml_user', samlUser, { + path: '/', + httpOnly: true, + sameSite: 'lax', + maxAge: 5 * 60 * 1000, + }) + } + + res.redirect(basepath) + }) +} + /** * Fireedge select type auth. * (This is because the authentication methods have to be extended after that). @@ -203,4 +284,5 @@ const selectTypeAuth = ( module.exports = { selectTypeAuth, + samlAuth, } diff --git a/src/fireedge/src/server/routes/api/auth/index.js b/src/fireedge/src/server/routes/api/auth/index.js index 07458d7ed4..88981a608d 100644 --- a/src/fireedge/src/server/routes/api/auth/index.js +++ b/src/fireedge/src/server/routes/api/auth/index.js @@ -15,12 +15,16 @@ * ------------------------------------------------------------------------- */ const { Actions, Commands } = require('server/routes/api/auth/routes') -const { selectTypeAuth } = require('server/routes/api/auth/functions') -const { AUTHENTICATION } = Actions +const { selectTypeAuth, samlAuth } = require('server/routes/api/auth/functions') +const { AUTHENTICATION, SAML_AUTHENTICATION } = Actions module.exports = [ { ...Commands[AUTHENTICATION], action: selectTypeAuth, }, + { + ...Commands[SAML_AUTHENTICATION], + action: samlAuth, + }, ] diff --git a/src/fireedge/src/server/routes/api/auth/routes.js b/src/fireedge/src/server/routes/api/auth/routes.js index 78598b0515..d40ea88974 100644 --- a/src/fireedge/src/server/routes/api/auth/routes.js +++ b/src/fireedge/src/server/routes/api/auth/routes.js @@ -24,9 +24,11 @@ const { postBody } = fromData const basepath = '/auth' const AUTHENTICATION = 'authentication' +const SAML_AUTHENTICATION = 'authentication.saml' const Actions = { AUTHENTICATION, + SAML_AUTHENTICATION, } module.exports = { @@ -54,5 +56,15 @@ module.exports = { }, }, }, + [SAML_AUTHENTICATION]: { + path: `${basepath}/acs`, + httpMethod: POST, + auth: false, + params: { + SAMLResponse: { + from: postBody, + }, + }, + }, }, } diff --git a/src/fireedge/src/server/routes/api/index.js b/src/fireedge/src/server/routes/api/index.js index 73d753e761..06230e51c6 100644 --- a/src/fireedge/src/server/routes/api/index.js +++ b/src/fireedge/src/server/routes/api/index.js @@ -104,7 +104,8 @@ routes.forEach((file) => { next, getRequestParameters(params, serverDataSource), oneUser, - oneConnection + oneConnection, + req ) } @@ -128,7 +129,8 @@ routes.forEach((file) => { next, getRequestParameters(params, serverDataSource), oneUser, - oneConnection + oneConnection, + req ) }) } diff --git a/src/fireedge/src/server/routes/entrypoints/App.js b/src/fireedge/src/server/routes/entrypoints/App.js index c46bd0636a..a3f69be8e0 100644 --- a/src/fireedge/src/server/routes/entrypoints/App.js +++ b/src/fireedge/src/server/routes/entrypoints/App.js @@ -19,7 +19,10 @@ const { Router } = require('express') const { ServerStyleSheets } = require('@mui/styles') const { request: axios } = require('axios') const { writeInLogger } = require('server/utils/logger') -const { MissingHeaderError } = require('server/utils/errors') +const { + MissingHeaderError, + MissingSamlUserInfoError, +} = require('server/utils/errors') // server const { getSunstoneConfig, getFireedgeConfig } = require('server/utils/yml') @@ -39,6 +42,7 @@ const { defaultPort, httpMethod, } = require('server/utils/constants/defaults') +const { global } = require('window-or-global') const APP_NAMES = Object.keys(defaultApps) const APP_URL = '/fireedge' @@ -63,8 +67,6 @@ const defaultConfig = { const { POST } = httpMethod router.get('*', async (req, res) => { - const remoteJWT = {} - const APP_CONFIG = { [defaultApps.sunstone.name]: { @@ -81,52 +83,69 @@ router.get('*', async (req, res) => { const authType = appConfig?.auth const validAuthTypes = ['remote', 'x509'] - if (validAuthTypes.includes(authType)) { - remoteJWT.remote = true - remoteJWT.remoteRedirect = appConfig?.auth_redirect ?? '.' + const remoteJWT = { + remoteRedirect: appConfig?.auth_redirect ?? '', + } + const samlUser = req?.cookies?.saml_user + const samlUserData = global?.saml?.[samlUser] + const validateAuth = validAuthTypes.includes(authType) - const finderHeader = () => { - const headers = Object.keys(req.headers) + if (validateAuth || samlUserData) { + let remoteUser = { + user: samlUser, + token: samlUserData, + remember: false, + } + let findHeader = false - switch (authType) { - case validAuthTypes[1]: - return headers.find((header) => defaultHeaderx509.includes(header)) - default: - return headers.find((header) => defaultHeaderRemote.includes(header)) + if (validateAuth) { + remoteJWT.remote = true + const finderHeader = () => { + const headers = Object.keys(req.headers) + switch (authType) { + case validAuthTypes[1]: + return headers.find((header) => defaultHeaderx509.includes(header)) + default: + return headers.find((header) => + defaultHeaderRemote.includes(header) + ) + } + } + findHeader = finderHeader() + remoteUser = findHeader && { + user: req.get(findHeader), } } - const findHeader = finderHeader() try { - if (!findHeader) { - throw new MissingHeaderError(JSON.stringify(req.headers)) + if (samlUser) { + delete global.saml[req.cookies.saml_user] + res.clearCookie('saml_user', { + path: '/', + httpOnly: true, + sameSite: 'lax', + }) + } else { + if (validateAuth && !findHeader) { + throw new MissingHeaderError(JSON.stringify(req.headers)) + } else { + throw new MissingSamlUserInfoError(req?.cookies?.saml_user) + } } - const remoteUser = req.get(findHeader) - const paramsAxios = { method: POST, url: `${defaultProtocol}://${defaultIP}:${ appConfig.port || defaultPort }/${defaultAppName}/api/auth`, - data: { - user: remoteUser, - }, + data: remoteUser, validateStatus: (status) => status >= 200 && status <= 400, } const jwt = await axios(paramsAxios) - if (!global.remoteUsers) { - global.remoteUsers = {} - } - global.remoteUsers[remoteUser] = {} - - jwt?.data?.data?.token && - (global.remoteUsers[remoteUser].jwt = remoteJWT.jwt = - jwt.data.data.token) - jwt?.data?.data?.id && - (global.remoteUsers[remoteUser].id = remoteJWT.id = jwt.data.data.id) + jwt?.data?.data?.token && (remoteJWT.jwt = jwt.data.data.token) + jwt?.data?.data?.id && (remoteJWT.id = jwt.data.data.id) } catch (e) { writeInLogger(e) } diff --git a/src/fireedge/src/server/utils/constants/defaults.js b/src/fireedge/src/server/utils/constants/defaults.js index daade66e95..7d9172e3f4 100644 --- a/src/fireedge/src/server/utils/constants/defaults.js +++ b/src/fireedge/src/server/utils/constants/defaults.js @@ -50,7 +50,12 @@ const defaults = { defaultRegexpSplitLine: /\r|\n/, defaultSizeRotate: '100k', defaultAppName: appName, - defaultHeaderRemote: ['http_x_auth_username', 'x_auth_username'], + defaultHeaderRemote: [ + 'x-auth-username', + 'http-x-auth-username', + 'x_auth_username', + 'http_x_auth_username', + ], defaultHeaderx509: ['x-client-dn'], defaultConfigErrorMessage: { color: 'red', diff --git a/src/fireedge/src/server/utils/errors.js b/src/fireedge/src/server/utils/errors.js index 15475365a2..5765a1d0fa 100644 --- a/src/fireedge/src/server/utils/errors.js +++ b/src/fireedge/src/server/utils/errors.js @@ -45,6 +45,16 @@ class MissingHeaderError extends OpenNebulaError { } } +class MissingSamlUserInfoError extends OpenNebulaError { + /** + * @param {string} user - username. + */ + constructor(user = '') { + super(`Missing user Saml information: ${user}`) + this.name = 'MissingSamlUserInfoError' + } +} + class MissingFireEdgeKeyError extends OpenNebulaError { /** * @@ -70,5 +80,6 @@ module.exports = { MissingFireEdgeKeyError, OpenNebulaError, MissingHeaderError, + MissingSamlUserInfoError, InternalLoginError, } diff --git a/src/onecfg/share/etc/files.yaml b/src/onecfg/share/etc/files.yaml index 7a742391d5..93f6aadc04 100644 --- a/src/onecfg/share/etc/files.yaml +++ b/src/onecfg/share/etc/files.yaml @@ -58,6 +58,13 @@ mode: '0640' src: src/authm_mad/remotes/ldap/ldap_auth.conf +- name: /etc/one/auth/saml_auth.conf + class: Yaml::Strict + owner: root + group: oneadmin + mode: '0640' + src: src/authm_mad/remotes/saml/saml_auth.conf + - name: /etc/one/auth/server_x509_auth.conf class: Yaml owner: root diff --git a/src/template/OpenNebulaTemplate.cc b/src/template/OpenNebulaTemplate.cc index 56a1a34802..69a3c8fcd3 100644 --- a/src/template/OpenNebulaTemplate.cc +++ b/src/template/OpenNebulaTemplate.cc @@ -149,6 +149,7 @@ void OpenNebulaTemplate::set_multiple_conf_default() set_conf_auth("ssh", "YES", "NO", "NO", "-1"); set_conf_auth("x509", "NO", "NO", "NO", "-1"); set_conf_auth("ldap", "YES", "YES", "YES", "86400"); + set_conf_auth("saml", "YES", "YES", "YES", "86400"); set_conf_auth("server_cipher", "NO", "NO", "NO", "-1"); set_conf_auth("server_x509", "NO", "NO", "NO", "-1"); diff --git a/src/um/User.cc b/src/um/User.cc index ba7b3ef167..2c45eb790b 100644 --- a/src/um/User.cc +++ b/src/um/User.cc @@ -35,6 +35,7 @@ namespace {"ssh", 16 * 1024}, // SSH private key (16 KB) {"x509", 64 * 1024}, // X.509 certificate (64 KB) {"ldap", 256}, // LDAP password (256 characters) + {"saml", 12 * 1024}, // SAML issuer URL (12 KB) {"server_cipher", 4096}, // Encrypted key (4 KB) {"server_x509", 64 * 1024}, // Server X.509 certificate (64 KB) {"core", 256}, // Core authentication (256 characters)