简体   繁体   English

我可以通过使用会话来阻止XSS攻击吗?

[英]Can i prevent an XSS attack by using a session?

Can we prevent a XSS attack by using a session every time the user has loaded the page? 我们可以在每次用户加载页面时使用会话来防止XSS攻击吗?

This is my PHP code. 这是我的PHP代码。

session_start();

if (isset($_GET["content"]) && isset($_GET["session"] && isset($_SESSION["code"])) {
    if ($_SESSION["code"] == $_GET["session"]) {
        echo $_GET["content"];
    }
}

$code = rand(1000, 9000);

$_SESSION["code"] = $code;

echo(str_replace("{CODE}", $code, $html);

For example, this is the URL 例如,这是URL

http://example.com/index.php?content=xxxxx&session=GENERATED_SESSION

Where GENERATED_SESSION is the code added by my JavaScript code. 其中GENERATED_SESSION是我的JavaScript代码添加的代码。

This is a page that will be loaded more times by a iframe, that code can prevent a XSS? 这是一个由iframe加载更多次的页面,该代码可以阻止XSS?

I think your attempting to prevent CSRF (Cross site request forgery) rather than XSS (Cross site scripting). 我认为您试图阻止CSRF(跨站点请求伪造)而不是XSS(跨站点脚本)。

XSS is preventing people injecting malicious code into you're application eg if you have a blog with a comment form, someone could enter a JS <script></script> tag into your comment box, so that when their comment is loaded on your blog, the JS is executed. XSS阻止人们将恶意代码注入您的应用程序中,例如,如果您有一个带有评论表单的博客,有人可以在您的评论框中输入JS <script></script>标记,以便当他们的评论加载到您的评论框中时博客,JS被执行了。

Your approach is a common approach to prevent CSRF (Although I'm not sure where JS comes into it). 您的方法是防止CSRF的常用方法(虽然我不确定JS在哪里进入)。

An 'un-guessable' token is generated and stored in the session, the value of this token is rendered in a hidden form element within your form, and when someone submits your form, you should check that the value in the hidden field matches the value in the session, exactly as you are doing (Without the syntax errors :) ). 生成并存储在会话中的“不可猜测”令牌,此令牌的值在表单中的隐藏表单元素中呈现,当有人提交表单时,您应检查隐藏字段中的值是否与会话中的值,与您正在做的完全一样(没有语法错误:))。

I would personally use a better mechanism for generating the token though, as the random number you are generating could potentially be "fluked". 我个人会使用一种更好的机制来生成令牌,因为你生成的随机数可能会“侥幸”。

On a side note, you should generally only use the GET method for a search/read request, so the CSRF protection wouldn't really protect anything, and you also need to consider what happens when the user refreshes the search. 另外,您通常只应使用GET方法进行搜索/读取请求,因此CSRF保护不会真正保护任何内容,您还需要考虑用户刷新搜索时会发生什么。

Whenever you are changing something (ie create, update or delete) it's good practice to use the POST form method, but the same CSRF principle applies. 每当您更改某些内容(即创建,更新或删除)时,最好使用POST表单方法,但适用相同的CSRF原则。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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