微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

将此代码分配给window.location容易受到XSS攻击吗?

如何解决将此代码分配给window.location容易受到XSS攻击吗?

谁能告诉我此代码是否易受攻击?如果可以,请提供一些XSS示例,以便我理解。

代码页网址:

https://myweb.com/auth?redirect_uri=https://otherurl.com/sdfdsf/sdfsdf

代码容易受到XSS攻击吗?


<a id="forgotPassword">forgotPassword</a>

<script>
//Jquery Code

$('#forgotPassword').click(function(){
 var redirectUri='https://otherurl.com/sdfdsf/sdfsdf',URLMatch=redirectUri.match(/^(.*?)(.com|.ca)/);
  if(URLMatch){
   window.location=URLMatch[0]+"/forgotPassword";
  }
});
</script>

解决方法

如果此代码是自动生成的,以便从页面URL redirectUri的查询参数redirect_uri中读取https://myweb.com/auth?redirect_uri=...的值,则不进行编码或转义,并且不使用正则表达式保持这种方式(即必须与.com.ca匹配),那么您很可能容易受到XSS攻击。

这是一种威胁模型:

用户转到https://myweb.com/auth?redirect_uri=javascript:alert(42)//.com

然后在https://myweb.com/auth处,脚本从URL中提取redirect_uri参数,并将其输入到不安全胡子模板中。例如

const  mustache = require("mustache");

const template = `
$('#forgotPassword').click(function(){
 var redirectUri='{{{url}}}',URLMatch=redirectUri.match(/^(.*?)(.com|.ca)/);
  if(URLMatch){
   window.location=URLMatch[0]+"/forgotPassword";
  }
});
`;

const jquery_code = mustache.render(template,{
  url: new URLSearchParams(window.location.search).get('redirect_uri')
});

这是jquery_code变量包含的内容:

$('#forgotPassword').click(function(){
 var redirectUri='javascript:alert(42)//.com',URLMatch=redirectUri.match(/^(.*?)(.com|.ca)/);
  if(URLMatch){
   window.location=URLMatch[0]+"/forgotPassword";
  }
});

让我们看看如果将其注入页面会发生什么:(我决定登录到控制台,脚本将分配给window.location。您自己复制/粘贴并运行到控制台中,以看看会发生什么。)

$('#forgotPassword').click(function(){
 var redirectUri='javascript:alert(42)//.com',URLMatch=redirectUri.match(/^(.*?)(.com|.ca)/);
  if(URLMatch){
   // window.location=URLMatch[0]+"/forgotPassword";
   console.log(
     `window.location="${URLMatch[0]+"/forgotPassword"}";`
   )
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<a id="forgotPassword">forgotPassword</a>


发生了什么事?

  1. {{{ }}}小胡子表示法使您退出编码/转义。即您按原样使用该值。
  2. 由于您的正则表达式,您已允许使用JavaScript网址。检查必须以httpshttp 开头。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。