Thursday, June 25, 2020

How to fix for Fortify issue Open Redirect and Cross-Site Scripting: Poor Validation (URL_ENCODE)

Below are sample fixes for Fortify issue:
Open Redirect
Cross-Site Scripting: Poor Validation (URL_ENCODE)

Replace “Sink: Assignment to window.location”:
  window.location = theUrl;

with:
  var redirectUrl = window.urlUtil.getRedirectUrl(theUrl);
  if (redirectUrl) {
    window.location = redirectUrl;
  }

Add DOMPurify to _Layout.cshtml:
<script src="~/lib/dompurify/purify.min.js"></script>

Initialise trusted sites in e.g. _Layout.cshtml or site.js:
<script>
    "use strict";

    window.app.addTrustedSite('https://www.google.com');
    window.app.addTrustedSite('https://www.microsoft.com');
</script>

Add below js to a file e.g. site.js
"use strict";

(function () {

    var appService = {
        getPublicOrigin: getPublicOrigin,
        setPublicOrigin: setPublicOrigin,

        getTrustedSites: getTrustedSites,
        addTrustedSite: addTrustedSite,
    };

    window.app = appService;

    var publicOrigin = '/';
    var trustedSites = [];

    function getPublicOrigin() {
        return publicOrigin;
    }

    function setPublicOrigin(value) {
        publicOrigin = value;
    }

    function getTrustedSites() {
        return trustedSites;
    }

    function addTrustedSite(value) {
        if (value) {
            trustedSites.push(value);
        }
    }

})();

(function () {

    var urlService = {
        getRedirectUrl: getRedirectUrl,

        isRelative: isRelative,
        isWhitelisted: isWhitelisted,
    };

    window.urlUtil = urlService;

    function getRedirectUrl(url) {
        if (isRelative(url))
            return DOMPurify.sanitize(url);

        if (isWhitelisted(url))
            return DOMPurify.sanitize(url);

        return null;
    }

    function isRelative(url) {
        return url && url.match(/^\/[^\/\\]/);
    }

    function isWhitelisted(url) {
        url = url.toLowerCase();

        var whitelist = window.app.getTrustedSites();

        var i = whitelist.length;
        while (i--) {
            if (url.startsWith(whitelist[i])) {
                return true;
            }
        }
        return false;
    }

})();

No comments:

Post a Comment