分配给 window.location 的代码是否易受 XSS 攻击?

Is this code assigning to window.location vulnerable to XSS?

任何人都可以告诉我这段代码是否容易受到攻击?。如果是,请给出一些 XSS 示例,以便我理解。

代码页URL:

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>

如果这段代码是自动生成的,那么redirectUri的值是从页面URLhttps://myweb.com/auth?redirect_uri=...的查询参数redirect_uri中读取的如果没有编码或转义并且您的正则表达式保持原样 (即必须匹配 .com.ca),那么您可能容易受到 XSS 攻击。

这是一个威胁模型:

一个用户去https://myweb.com/auth?redirect_uri=javascript:alert(42)//.com

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

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。Copy/paste 和运行 自己进入控制台看看会发生什么。)

$('#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. {{{ }}} 小胡子符号让您退出 encoding/escaping。即您按原样消费价值。
  2. 由于您的正则表达式,您允许 JavaScript url。检查 必须以 httpshttp 开头。