From 292932bb75b7639f48cc0ee2dd6aeaa9e6a0e99f Mon Sep 17 00:00:00 2001 From: texpert Date: Mon, 20 Jan 2025 00:53:34 +0200 Subject: [PATCH 01/10] Sanitize user fields and posts comments against XSS attacks --- app/models/camaleon_cms/post_comment.rb | 18 ++++++++++++++ app/models/camaleon_cms/term_taxonomy.rb | 6 ----- app/models/camaleon_record.rb | 6 +++++ .../concerns/camaleon_cms/user_methods.rb | 24 +++++++++++++++++-- spec/models/post_comment_spec.rb | 7 ++++++ spec/models/term_taxonomy_spec.rb | 1 - spec/models/user_spec.rb | 4 +++- 7 files changed, 56 insertions(+), 10 deletions(-) create mode 100644 spec/models/post_comment_spec.rb diff --git a/app/models/camaleon_cms/post_comment.rb b/app/models/camaleon_cms/post_comment.rb index 079bfb35..06df778c 100644 --- a/app/models/camaleon_cms/post_comment.rb +++ b/app/models/camaleon_cms/post_comment.rb @@ -21,6 +21,24 @@ class PostComment < CamaleonRecord scope :comment_parent, -> { where(comment_parent: 'is not null') } scope :approveds, -> { where(approved: 'approved') } + # TODO: Remove the 1st branch when support will be dropped of Rails < 7.1 + if ::Rails::VERSION::STRING < '7.1.0' + before_validation(on: %i[create update]) do + %i[content].each do |attr| + next unless new_record? || attribute_changed?(attr) + + self[attr] = ActionController::Base.helpers.sanitize( + __send__(attr)&.gsub(TRANSLATION_TAG_HIDE_REGEX, TRANSLATION_TAG_HIDE_MAP) + )&.gsub(TRANSLATION_TAG_RESTORE_REGEX, TRANSLATION_TAG_RESTORE_MAP) + end + end + else + normalizes :content, with: lambda { |field| + ActionController::Base.helpers.sanitize(field.gsub(TRANSLATION_TAG_HIDE_REGEX, TRANSLATION_TAG_HIDE_MAP)) + .gsub(TRANSLATION_TAG_RESTORE_REGEX, TRANSLATION_TAG_RESTORE_MAP) + } + end + validates :content, presence: true validates_presence_of :author, :author_email, if: proc { |c| c.is_anonymous.present? } after_create :update_counter diff --git a/app/models/camaleon_cms/term_taxonomy.rb b/app/models/camaleon_cms/term_taxonomy.rb index abe88f86..57a549f3 100644 --- a/app/models/camaleon_cms/term_taxonomy.rb +++ b/app/models/camaleon_cms/term_taxonomy.rb @@ -3,12 +3,6 @@ class TermTaxonomy < CamaleonRecord include CamaleonCms::Metas include CamaleonCms::CustomFieldsRead - TRANSLATION_TAG_HIDE_MAP = { '' => '--!' }.freeze - TRANSLATION_TAG_HIDE_REGEX = Regexp.new(TRANSLATION_TAG_HIDE_MAP.keys.map { |x| Regexp.escape(x) }.join('|')).freeze - TRANSLATION_TAG_RESTORE_MAP = { '--!' => '-->', '!--' => '' => '--!' }.freeze + TRANSLATION_TAG_HIDE_REGEX = Regexp.new(TRANSLATION_TAG_HIDE_MAP.keys.map { |x| Regexp.escape(x) }.join('|')).freeze + TRANSLATION_TAG_RESTORE_MAP = { '--!' => '-->', '!--' => '