CVE-2022-0243 (published 2022-01-19T20:15Z)

Cross-site Scripting (XSS) - Stored in NuGet OrchardCore.Application.Cms.Targets prior to 1.2.2.

Severity: LOW
CVSS v2 base score: 3.5 (AV:N/AC:M/Au:S/C:N/I:P/A:N)
CVSS v3 base score: 5.4, MEDIUM (CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N)

Weakness information:
cwe_id: CWE-79
cwe_name: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
description: The product does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.
extended_description: 
            Cross-site scripting (XSS) vulnerabilities occur when:
            
               Untrusted data enters a web application, typically from a web request.
               The web application dynamically generates a web page that contains this untrusted data.
               During page generation, the application does not prevent the data from containing content that is executable by a web browser, such as JavaScript, HTML tags, HTML attributes, mouse events, Flash, ActiveX, etc.
               A victim visits the generated web page through a web browser, which contains malicious script that was injected using the untrusted data.
               Since the script comes from a web page that was sent by the web server, the victim's web browser executes the malicious script in the context of the web server's domain.
               This effectively violates the intention of the web browser's same-origin policy, which states that scripts in one domain should not be able to access resources or run code in a different domain.
            
            There are three main kinds of XSS:
            
               
                  Type 1: Reflected XSS (or Non-Persistent) - 
         			The server reads data directly from the HTTP request and reflects it back in the HTTP response. Reflected XSS exploits occur when an attacker causes a victim to supply dangerous content to a vulnerable web application, which is then reflected back to the victim and executed by the web browser. The most common mechanism for delivering malicious content is to include it as a parameter in a URL that is posted publicly or e-mailed directly to the victim. URLs constructed in this manner constitute the core of many phishing schemes, whereby an attacker convinces a victim to visit a URL that refers to a vulnerable site. After the site reflects the attacker's content back to the victim, the content is executed by the victim's browser.
               
                  Type 2: Stored XSS (or Persistent) - 
               The application stores dangerous data in a database, message forum, visitor log, or other trusted data store. At a later time, the dangerous data is subsequently read back into the application and included in dynamic content. From an attacker's perspective, the optimal place to inject malicious content is in an area that is displayed to either many users or particularly interesting users. Interesting users typically have elevated privileges in the application or interact with sensitive data that is valuable to the attacker. If one of these users executes malicious content, the attacker may be able to perform privileged operations on behalf of the user or gain access to sensitive data belonging to the user. For example, the attacker might inject XSS into a log message, which might not be handled properly when an administrator views the logs.
            
               
                  Type 0: DOM-Based XSS - 
               In DOM-based XSS, the client performs the injection of XSS into the page; in the other types, the server performs the injection. DOM-based XSS generally involves server-controlled, trusted script that is sent to the client, such as Javascript that performs sanity checks on a form before the user submits it. If the server-supplied script processes user-supplied data and then injects it back into the web page (such as with dynamic HTML), then DOM-based XSS is possible.
            
            
            Once the malicious script is injected, the attacker can perform a variety of malicious activities. The attacker could transfer private information, such as cookies that may include session information, from the victim's machine to the attacker. The attacker could send malicious requests to a web site on behalf of the victim, which could be especially dangerous to the site if the victim has administrator privileges to manage that site. Phishing attacks could be used to emulate trusted web sites and trick the victim into entering a password, allowing the attacker to compromise the victim's account on that web site. Finally, the script could exploit a vulnerability in the web browser itself possibly taking over the victim's machine, sometimes referred to as "drive-by hacking."
            In many cases, the attack can be launched without the victim even being aware of it. Even with careful users, attackers frequently use a variety of methods to encode the malicious portion of the attack, such as URL encoding or Unicode, so the request looks less suspicious.
         
         

Fix information:
repo_url: https://github.com/orchardcms/orchardcore
commit_details: repo_url: https://github.com/orchardcms/orchardcore
author: Sébastien Ros
author_date: 2022-01-18 11:03:05-08:00
msg: Fix localization and sanitization usages (#11034)
repository: repo_url: https://github.com/orchardcms/orchardcore
repo_name: OrchardCMS/OrchardCore
description: Orchard Core is an open-source modular and multi-tenant application framework built with ASP.NET Core, and a content management system (CMS) built on top of that framework.
repo_language: C#
owner: orchardcms
file_changes: filename: LinkFieldDisplayDriver.cs
change_type: ModificationType.MODIFY
diff: @@ -1,4 +1,5 @@
 using System;
+using System.Text.Encodings.Web;
 using System.Threading.Tasks;
 using Microsoft.AspNetCore.Mvc.Infrastructure;
 using Microsoft.AspNetCore.Mvc.Routing;
@@ -11,6 +12,7 @@ using OrchardCore.ContentManagement.Display.Models;
 using OrchardCore.ContentManagement.Metadata.Models;
 using OrchardCore.DisplayManagement.ModelBinding;
 using OrchardCore.DisplayManagement.Views;
+using OrchardCore.Infrastructure.Html;
 using OrchardCore.Mvc.ModelBinding;
 
 namespace OrchardCore.ContentFields.Drivers
@@ -20,15 +22,21 @@ namespace OrchardCore.ContentFields.Drivers
         private readonly IUrlHelperFactory _urlHelperFactory;
         private readonly IActionContextAccessor _actionContextAccessor;
         private readonly IStringLocalizer S;
+        private readonly IHtmlSanitizerService _htmlSanitizerService;
+        private readonly HtmlEncoder _htmlencoder;
 
         public LinkFieldDisplayDriver(
             IUrlHelperFactory urlHelperFactory,
             IActionContextAccessor actionContextAccessor,
-            IStringLocalizer<LinkFieldDisplayDriver> localizer)
+            IStringLocalizer<LinkFieldDisplayDriver> localizer,
+            IHtmlSanitizerService htmlSanitizerService,
+            HtmlEncoder htmlencoder)
         {
             _urlHelperFactory = urlHelperFactory;
             _actionContextAccessor = actionContextAccessor;
             S = localizer;
+            _htmlSanitizerService = htmlSanitizerService;
+            _htmlencoder = htmlencoder;
         }
 
         public override IDisplayResult Display(LinkField field, BuildFieldDisplayContext context)
@@ -91,6 +99,15 @@ namespace OrchardCore.ContentFields.Drivers
                 {
                     updater.ModelState.AddModelError(Prefix, nameof(field.Url), S["{0} is an invalid url.", field.Url]);
                 }
+                else
+                {
+                    var link = $"<a href=\"{_htmlencoder.Encode(urlToValidate)}\"></a>";
+
+                    if (!String.Equals(link, _htmlSanitizerService.Sanitize(link), StringComparison.OrdinalIgnoreCase))
+                    {
+                        updater.ModelState.AddModelError(Prefix, nameof(field.Url), S["{0} is an invalid url.", field.Url]);
+                    }
+                }
 
                 // Validate Text
                 if (settings.LinkTextMode == LinkTextMode.Required && String.IsNullOrWhiteSpace(field.Text))
@@ -101,9 +118,6 @@ namespace OrchardCore.ContentFields.Drivers
                 {
                     updater.ModelState.AddModelError(Prefix, nameof(field.Text), S["The text default value is required for {0}.", context.PartFieldDefinition.DisplayName()]);
                 }
-
-                // Run this through a sanitizer in case someone puts html in it.
-                // No settings.
             }
 
             return Edit(field, context);

programming_language: C#
filename: AuditTrailContentController.cs
change_type: ModificationType.MODIFY
diff: @@ -111,12 +111,15 @@ namespace OrchardCore.Contents.AuditTrail.Controllers
             }
 
             var result = await _contentManager.RestoreAsync(contentItem);
+
             if (!result.Succeeded)
             {
                 await _notifier.WarningAsync(H["'{0}' was not restored, the version is not valid.", contentItem.DisplayText]);
+
                 foreach (var error in result.Errors)
                 {
-                    await _notifier.WarningAsync(new LocalizedHtmlString(error.ErrorMessage, error.ErrorMessage));
+                    // Pass ErrorMessage as an argument to ensure it is encoded
+                    await _notifier.WarningAsync(new LocalizedHtmlString(nameof(AuditTrailContentController.Restore), "{0}", false, error.ErrorMessage));
                 }
 
                 return RedirectToAction("Index", "Admin", new { area = "OrchardCore.AuditTrail" });

programming_language: C#
filename: HtmlMenuItemPartDisplayDriver.cs
change_type: ModificationType.MODIFY
diff: @@ -1,4 +1,9 @@
+using System;
+using System.Text.Encodings.Web;
 using System.Threading.Tasks;
+using Microsoft.AspNetCore.Mvc.Infrastructure;
+using Microsoft.AspNetCore.Mvc.Routing;
+using Microsoft.Extensions.Localization;
 using OrchardCore.ContentManagement.Display.ContentDisplay;
 using OrchardCore.ContentManagement.Display.Models;
 using OrchardCore.DisplayManagement.ModelBinding;
@@ -12,11 +17,25 @@ namespace OrchardCore.Menu.Drivers
 {
     public class HtmlMenuItemPartDisplayDriver : ContentPartDisplayDriver<HtmlMenuItemPart>
     {
+        private readonly IUrlHelperFactory _urlHelperFactory;
+        private readonly IActionContextAccessor _actionContextAccessor;
         private readonly IHtmlSanitizerService _htmlSanitizerService;
+        private readonly HtmlEncoder _htmlencoder;
+        private readonly IStringLocalizer S;
 
-        public HtmlMenuItemPartDisplayDriver(IHtmlSanitizerService htmlSanitizerService)
+        public HtmlMenuItemPartDisplayDriver(
+            IUrlHelperFactory urlHelperFactory,
+            IActionContextAccessor actionContextAccessor,
+            IStringLocalizer<HtmlMenuItemPartDisplayDriver> localizer,
+            IHtmlSanitizerService htmlSanitizerService,
+            HtmlEncoder htmlencoder
+            )
         {
+            _urlHelperFactory = urlHelperFactory;
+            _actionContextAccessor = actionContextAccessor;
             _htmlSanitizerService = htmlSanitizerService;
+            _htmlencoder = htmlencoder;
+            S = localizer;
         }
 
         public override IDisplayResult Display(HtmlMenuItemPart part, BuildPartDisplayContext context)
@@ -62,6 +81,35 @@ namespace OrchardCore.Menu.Drivers
                 part.ContentItem.DisplayText = model.Name;
                 part.Html = settings.SanitizeHtml ? _htmlSanitizerService.Sanitize(model.Html) : model.Html;
                 part.Url = model.Url;
+
+                var urlToValidate = part.Url;
+
+                if (!String.IsNullOrEmpty(urlToValidate))
+                {
+                    urlToValidate = urlToValidate.Split('#', 2)[0];
+
+                    if (urlToValidate.StartsWith("~/", StringComparison.Ordinal))
+                    {
+                        var urlHelper = _urlHelperFactory.GetUrlHelper(_actionContextAccessor.ActionContext);
+                        urlToValidate = urlHelper.Content(urlToValidate);
+                    }
+
+                    urlToValidate = urlToValidate.ToUriComponents();
+
+                    if (!Uri.IsWellFormedUriString(urlToValidate, UriKind.RelativeOrAbsolute))
+                    {
+                        updater.ModelState.AddModelError(nameof(part.Url), S["{0} is an invalid url.", part.Url]);
+                    }
+                    else
+                    {
+                        var link = $"<a href=\"{_htmlencoder.Encode(urlToValidate)}\"></a>";
+
+                        if (!String.Equals(link, _htmlSanitizerService.Sanitize(link), StringComparison.OrdinalIgnoreCase))
+                        {
+                            updater.ModelState.AddModelError(nameof(part.Url), S["{0} is an invalid url.", part.Url]);
+                        }
+                    }
+                }
             }
 
             return Edit(part, context);

programming_language: C#
filename: LinkMenuItemPartDisplayDriver.cs
change_type: ModificationType.MODIFY
diff: @@ -1,8 +1,14 @@
+using System;
+using System.Text.Encodings.Web;
 using System.Threading.Tasks;
+using Microsoft.AspNetCore.Mvc.Infrastructure;
+using Microsoft.AspNetCore.Mvc.Routing;
+using Microsoft.Extensions.Localization;
 using OrchardCore.ContentManagement.Display.ContentDisplay;
 using OrchardCore.ContentManagement.Display.Models;
 using OrchardCore.DisplayManagement.ModelBinding;
 using OrchardCore.DisplayManagement.Views;
+using OrchardCore.Infrastructure.Html;
 using OrchardCore.Menu.Models;
 using OrchardCore.Menu.ViewModels;
 
@@ -10,6 +16,26 @@ namespace OrchardCore.Menu.Drivers
 {
     public class LinkMenuItemPartDisplayDriver : ContentPartDisplayDriver<LinkMenuItemPart>
     {
+        private readonly IUrlHelperFactory _urlHelperFactory;
+        private readonly IActionContextAccessor _actionContextAccessor;
+        private readonly IHtmlSanitizerService _htmlSanitizerService;
+        private readonly HtmlEncoder _htmlencoder;
+        private readonly IStringLocalizer S;
+
+        public LinkMenuItemPartDisplayDriver(
+            IUrlHelperFactory urlHelperFactory,
+            IActionContextAccessor actionContextAccessor,
+            IStringLocalizer<LinkMenuItemPartDisplayDriver> localizer,
+            IHtmlSanitizerService htmlSanitizerService,
+            HtmlEncoder htmlencoder
+            )
+        {
+            _urlHelperFactory = urlHelperFactory;
+            _actionContextAccessor = actionContextAccessor; 
+            _htmlSanitizerService = htmlSanitizerService;
+            _htmlencoder = htmlencoder;
+            S = localizer;
+        }
 
         public override IDisplayResult Display(LinkMenuItemPart part, BuildPartDisplayContext context)
         {
@@ -45,11 +71,42 @@ namespace OrchardCore.Menu.Drivers
             {
                 part.Url = model.Url;
                 part.ContentItem.DisplayText = model.Name;
+
                 // This code can be removed in a later release.
 #pragma warning disable 0618
                 part.Name = model.Name;
 #pragma warning restore 0618
+
+                var urlToValidate = part.Url;
+
+                if (!String.IsNullOrEmpty(urlToValidate))
+                {
+                    urlToValidate = urlToValidate.Split('#', 2)[0];
+
+                    if (urlToValidate.StartsWith("~/", StringComparison.Ordinal))
+                    {
+                        var urlHelper = _urlHelperFactory.GetUrlHelper(_actionContextAccessor.ActionContext);
+                        urlToValidate = urlHelper.Content(urlToValidate);
+                    }
+
+                    urlToValidate = urlToValidate.ToUriComponents();
+
+                    if (!Uri.IsWellFormedUriString(urlToValidate, UriKind.RelativeOrAbsolute))
+                    {
+                        updater.ModelState.AddModelError(nameof(part.Url), S["{0} is an invalid url.", part.Url]);
+                    }
+                    else
+                    {
+                        var link = $"<a href=\"{_htmlencoder.Encode(urlToValidate)}\"></a>";
+
+                        if (!String.Equals(link, _htmlSanitizerService.Sanitize(link), StringComparison.OrdinalIgnoreCase))
+                        {
+                            updater.ModelState.AddModelError(nameof(part.Url), S["{0} is an invalid url.", part.Url]);
+                        }
+                    }
+                }
             }
+
             return Edit(part);
         }
     }

programming_language: C#
filename: RegisterUserTask.cs
change_type: ModificationType.MODIFY
diff: @@ -134,15 +134,14 @@ namespace OrchardCore.Users.Workflows.Activities
                     workflowContext.Properties["EmailConfirmationUrl"] = uri;
 
                     var subject = await _expressionEvaluator.EvaluateAsync(ConfirmationEmailSubject, workflowContext, null);
-                    var localizedSubject = new LocalizedString(nameof(RegisterUserTask), subject);
 
                     var body = await _expressionEvaluator.EvaluateAsync(ConfirmationEmailTemplate, workflowContext, _htmlEncoder);
-                    var localizedBody = new LocalizedHtmlString(nameof(RegisterUserTask), body);
+
                     var message = new MailMessage()
                     {
                         To = email,
-                        Subject = localizedSubject.ResourceNotFound ? subject : localizedSubject.Value,
-                        Body = localizedBody.IsResourceNotFound ? body : localizedBody.Value,
+                        Subject = subject,
+                        Body = body,
                         IsBodyHtml = true
                     };
                     var smtpService = _httpContextAccessor.HttpContext.RequestServices.GetService<ISmtpService>();

programming_language: C#
filename: NotifyTask.cs
change_type: ModificationType.MODIFY
diff: @@ -55,6 +55,8 @@ namespace OrchardCore.Workflows.Activities
         public override async Task<ActivityExecutionResult> ExecuteAsync(WorkflowExecutionContext workflowContext, ActivityContext activityContext)
         {
             var message = await _expressionEvaluator.EvaluateAsync(Message, workflowContext, _htmlEncoder);
+
+            // The notification message can contain HTML by design
             await _notifier.AddAsync(NotificationType, new LocalizedHtmlString(nameof(NotifyTask), message));
 
             return Outcomes("Done");

programming_language: C#
filename: UserTaskEvent.Fields.Design.cshtml
change_type: ModificationType.MODIFY
diff: @@ -8,7 +8,7 @@
 @if (Model.Activity.Actions.Any())
 {
     <span>@T["Request any user action of <em>{0}</em>", string.Join(", ", Model.Activity.Actions)]</span><br />
-    <span>@T["Required roles: <em>{0}</em>", Model.Activity.Roles.Any() ? new LocalizedHtmlString("RequiredRoles", string.Join(", ", Model.Activity.Roles)) : T["Any"]]</span>
+    <span>@T["Required roles: <em>{0}</em>", Model.Activity.Roles.Any() ? Html.Raw(Html.Encode(string.Join(", ", Model.Activity.Roles))) : T["Any"]]</span>
 }
 else
 {

programming_language: C#
filename: Details.cshtml
change_type: ModificationType.MODIFY
diff: @@ -44,7 +44,7 @@
                     </div>
                     <div class="col">
                         <label>@T["Status"]</label>
-                        <span>@Model.Workflow.Status.GetLocalizedStatus(T)</span>
+                        <span>@T.GetLocalizedStatus(Model.Workflow.Status)</span>
                     </div>
                     @if (Model.Workflow.Status == WorkflowStatus.Faulted)
                     {

programming_language: HTML
filename: Index.cshtml
change_type: ModificationType.MODIFY
diff: @@ -104,7 +104,7 @@
                                 <span class="hint">@T["Created {0}", (object)(await DisplayAsync(await New.TimeSpan(Utc: entry.Workflow.CreatedUtc)))]</span>
                                 <div class="info">
                                     <span class="badge badge-@statusCss">
-                                        @entry.Workflow.Status.GetLocalizedStatus(T)
+                                        @T.GetLocalizedStatus(entry.Workflow.Status)
                                     </span>
                                 </div>
                             </div>

programming_language: HTML
filename: ActivityExtensions.cs
change_type: ModificationType.MODIFY
diff: @@ -8,8 +8,6 @@ namespace OrchardCore.Workflows.Helpers
 {
     public static class ActivityExtensions
     {
-        private static IHtmlLocalizer H;
-
         public static bool IsEvent(this IActivity activity)
         {
             return activity is IEvent;
@@ -18,14 +16,16 @@ namespace OrchardCore.Workflows.Helpers
         public static LocalizedHtmlString GetTitleOrDefault(this IActivity activity, Func<LocalizedHtmlString> defaultTitle)
         {
             var title = activity.As<ActivityMetadata>().Title;
-            return !string.IsNullOrEmpty(title) ? new LocalizedHtmlString(title, title) : defaultTitle();
+
+            // A string used in LocalizedHtmlString won't be encoded so it needs to be pre-encoded.
+            // Passing the title as an argument so it uses the HtmlEncoder when rendered
+            // Another options would be to use new LocalizedHtmlString(Html.Encode(title)) but it's not available in the current context
+
+            return !string.IsNullOrEmpty(title) ? new LocalizedHtmlString(nameof(ActivityExtensions.GetTitleOrDefault), "{0}", false, title) : defaultTitle();
         }
 
-        public static LocalizedHtmlString GetLocalizedStatus(this WorkflowStatus status, IHtmlLocalizer localizer)
+        public static LocalizedHtmlString GetLocalizedStatus(this IHtmlLocalizer H, WorkflowStatus status)
         {
-            // Field for PoExtractor compatibility
-            H = localizer;
-
             return status switch
             {
                 WorkflowStatus.Aborted => H["Aborted"],
@@ -36,7 +36,7 @@ namespace OrchardCore.Workflows.Helpers
                 WorkflowStatus.Idle => H["Idle"],
                 WorkflowStatus.Resuming => H["Resuming"],
                 WorkflowStatus.Starting => H["Starting"],
-                _ => new LocalizedHtmlString(status.ToString(), status.ToString()),
+                _ => throw new NotSupportedException(),
             };
         }
     }

programming_language: C#