简体   繁体   中英

How to make javascript cookie secure. I have tried the regex for securing the url and cookie value but no one is working

This is my cookie code.

var campaignId ="someCookieValue";
var d = new Date();
d.setTime(d.getTime() + (365*24*60*60*1000));   // SET COOKIE EXPIRY TO 365 days.
var expires = "expires="+ d.toUTCString();
document.cookie = 'campaignId='+ campaignId + "; Domain="+ document.domain + "; path=/; " + expires;
document.cookie = 'sourceUrl='+ window.location.href + ";" + expires;

Tried this for validating

var campaignId ="someCookieValue";  
var d = new Date();
d.setTime(d.getTime() + (365*24*60*60*1000));   // SET COOKIE EXPIRY TO 365 days.
var expires = "expires="+ d.toUTCString();
var value = new RegExp(/^[a-zA-Z0-9\-_\.:]*$/);
if(value.test(campaignId))
    document.cookie = 'campaignId='+ campaignId + "; Domain="+ document.domain + "; path=/; " + expires;
var expression =/[-a-zA-Z0-9@:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9@:%_\+.~#?&//=]*)?/gi;
var pattern = new RegExp(expression);
var cookieValue = window.location.href;
if(cookieValue){
    if(value.test(cookieValue)) {
        cookieValue = encodeURIComponent(cookieValue);
        document.cookie = 'sourceUrl='+ cookieValue + ";" + expires;
    }
}

I'm getting issue in fortify scan on document.cookie like the method lambda() in main.js includes unvalidated data in an HTTP cookie on line 486. This enables Cookie manipulation attacks and can lead to other HTTP Response header manipulation attacks like: cache-poisoning , cross-site scripting , cross-user defacement , page hijacking or open redirect .

Found the solution. I encripted my cookie values by an external cryptoJs and fortify scan issue resolved.

var campaignId ="someCookieValue";
    var mySecret ="mysecret";
    var d = new Date();
            d.setTime(d.getTime() + (365*24*60*60*1000));   // SET COOKIE EXPIRY TO 365 days.
            var expires = "expires="+ d.toUTCString();
            var mySecret ="mysecret";
            var cookieValue = window.location.href;
            //Here I added encryption
            campaignId = CryptoJS.AES.encrypt(campaignId, mySecret);
            cookieValue = CryptoJS.AES.encrypt(cookieValue, mySecret); //end
            document.cookie = 'campaignId='+ campaignId + "; Domain="+ document.domain + "; path=/; " + expires;
            document.cookie = 'sourceUrl='+ cookieValue + ";" + expires;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM