Translated ['src/pentesting-web/hacking-with-cookies/README.md'] to zh

This commit is contained in:
Translator 2025-05-18 03:04:50 +00:00
parent 2a6ac43cf0
commit 3b18741082
2 changed files with 156 additions and 135 deletions

View File

@ -12,7 +12,7 @@ Cookie 的过期日期由 `Expires` 属性决定。相反,`Max-age` 属性定
### Domain ### Domain
接收 cookie 的主机由 `Domain` 属性指定。默认情况下,这设置为发出 cookie 的主机,不包括其子域。然而,当 `Domain` 属性被显式设置时,它也包括子域。这使得 `Domain` 属性的指定成为一个不那么严格的选项,适用于需要跨子域共享 cookie 的场景。例如,设置 `Domain=mozilla.org` 使得在其子域如 `developer.mozilla.org` 上可以访问 cookie 接收 cookie 的主机由 `Domain` 属性指定。默认情况下,这设置为发出 cookie 的主机,不包括其子域。然而,当 `Domain` 属性被显式设置时,它也包括子域。这使得 `Domain` 属性的指定成为一个不那么严格的选项,适用于需要跨子域共享 cookie 的场景。例如,设置 `Domain=mozilla.org` 使得其子域如 `developer.mozilla.org` 上的 cookie 可访问
### Path ### Path
@ -27,7 +27,7 @@ Cookie 的过期日期由 `Expires` 属性决定。相反,`Max-age` 属性定
### SameSite ### SameSite
- `SameSite` 属性决定 cookie 是否在来自第三方域的请求中发送。它提供三种设置: - `SameSite` 属性决定是否在来自第三方域的请求中发送 cookie。它提供三种设置:
- **Strict**:限制 cookie 在第三方请求中发送。 - **Strict**:限制 cookie 在第三方请求中发送。
- **Lax**:允许 cookie 与由第三方网站发起的 GET 请求一起发送。 - **Lax**:允许 cookie 与由第三方网站发起的 GET 请求一起发送。
- **None**:允许 cookie 从任何第三方域发送。 - **None**:允许 cookie 从任何第三方域发送。
@ -47,7 +47,7 @@ Cookie 的过期日期由 `Expires` 属性决定。相反,`Max-age` 属性定
表格来自 [Invicti](https://www.netsparker.com/blog/web-security/same-site-cookie-attribute-prevent-cross-site-request-forgery/) 并稍作修改。\ 表格来自 [Invicti](https://www.netsparker.com/blog/web-security/same-site-cookie-attribute-prevent-cross-site-request-forgery/) 并稍作修改。\
具有 _**SameSite**_ 属性的 cookie 将 **减轻 CSRF 攻击**,其中需要登录会话。 具有 _**SameSite**_ 属性的 cookie 将 **减轻 CSRF 攻击**,其中需要登录会话。
**\*请注意,从 Chrome802019年2月开始未设置 cookie samesite 属性的 cookie 的默认行为将 lax** ([https://www.troyhunt.com/promiscuous-cookies-and-their-impending-death-via-the-samesite-policy/](https://www.troyhunt.com/promiscuous-cookies-and-their-impending-death-via-the-samesite-policy/)).\ **\*请注意,从 Chrome802019年2月开始未设置 cookie samesite 属性的 cookie 的默认行为将 lax** ([https://www.troyhunt.com/promiscuous-cookies-and-their-impending-death-via-the-samesite-policy/](https://www.troyhunt.com/promiscuous-cookies-and-their-impending-death-via-the-samesite-policy/)).\
请注意临时情况下在应用此更改后Chrome 中 **没有 SameSite** **策略的 cookie 将在 **前 2 分钟内被 **视为 None**,然后在顶级跨站点 POST 请求中视为 Lax。** 请注意临时情况下在应用此更改后Chrome 中 **没有 SameSite** **策略的 cookie 将在 **前 2 分钟内被 **视为 None**,然后在顶级跨站点 POST 请求中视为 Lax。**
## Cookies Flags ## Cookies Flags
@ -58,7 +58,7 @@ Cookie 的过期日期由 `Expires` 属性决定。相反,`Max-age` 属性定
#### **Bypasses** #### **Bypasses**
- 如果页面 **将 cookie 作为请求的响应发送**(例如在 **PHPinfo** 页面中),可以利用 XSS 发送请求到此页面并 **窃取响应中的 cookie**(请查看 [https://hackcommander.github.io/posts/2022/11/12/bypass-httponly-via-php-info-page/](https://hackcommander.github.io/posts/2022/11/12/bypass-httponly-via-php-info-page/) 中的示例)。 - 如果页面 **作为请求的响应发送 cookie**(例如在 **PHPinfo** 页面中),可以利用 XSS 发送请求到此页面并 **窃取响应中的 cookie**(请查看 [https://blog.hackcommander.com/posts/2022/11/12/bypass-httponly-via-php-info-page/](https://blog.hackcommander.com/posts/2022/11/12/bypass-httponly-via-php-info-page/) 中的示例)。
- 这可以通过 **TRACE** **HTTP** 请求绕过,因为服务器的响应将反映发送的 cookie如果此 HTTP 方法可用)。此技术称为 **Cross-Site Tracking** - 这可以通过 **TRACE** **HTTP** 请求绕过,因为服务器的响应将反映发送的 cookie如果此 HTTP 方法可用)。此技术称为 **Cross-Site Tracking**
- 现代浏览器通过不允许从 JS 发送 TRACE 请求来避免此技术。然而,在特定软件中发现了一些绕过方法,例如向 IE6.0 SP2 发送 `\r\nTRACE` 而不是 `TRACE` - 现代浏览器通过不允许从 JS 发送 TRACE 请求来避免此技术。然而,在特定软件中发现了一些绕过方法,例如向 IE6.0 SP2 发送 `\r\nTRACE` 而不是 `TRACE`
- 另一种方法是利用浏览器的零日漏洞。 - 另一种方法是利用浏览器的零日漏洞。
@ -72,7 +72,7 @@ cookie-jar-overflow.md
### Secure ### Secure
请求将 **仅** 在通过安全通道(通常是 **HTTPS**)传输发送 cookie。 请求将 **仅** 在通过安全通道(通常是 **HTTPS**)传输的 HTTP 请求中发送 cookie。
## Cookies Prefixes ## Cookies Prefixes
@ -85,7 +85,7 @@ cookie-jar-overflow.md
- 禁止指定域,防止其传输到子域。 - 禁止指定域,防止其传输到子域。
- 这些 cookie 的路径必须设置为 `/` - 这些 cookie 的路径必须设置为 `/`
重要的是要注意,以 `__Host-` 开头的 cookie 不允许发送到超级域或子域。此限制有助于隔离应用程序 cookie。因此使用 `__Host-` 前缀为所有应用程序 cookie 被视为增强安全性和隔离的良好做法。 重要的是要注意,以 `__Host-` 开头的 cookie 不允许发送到超级域或子域。此限制有助于隔离应用程序 cookie。因此使用 `__Host-` 前缀为所有应用程序 cookie 被视为增强安全性和隔离的良好做法。
### Overwriting cookies ### Overwriting cookies
@ -93,7 +93,7 @@ cookie-jar-overflow.md
<figure><img src="../../images/image (6) (1) (1) (1) (1).png" alt=""><figcaption></figcaption></figure> <figure><img src="../../images/image (6) (1) (1) (1) (1).png" alt=""><figcaption></figcaption></figure>
或者在 PHP 中,可以在 cookie 名称的开头添加 **其他字符**,这些字符将被 **替换为下划线** 字符从而允许覆盖 `__HOST-` cookies 或者在 PHP 中,可以在 cookie 名称的开头添加 **其他字符**,这些字符将被 **替换为下划线**,允许覆盖 `__HOST-` cookies
<figure><img src="../../images/image (7) (1) (1) (1) (1).png" alt="" width="373"><figcaption></figcaption></figure> <figure><img src="../../images/image (7) (1) (1) (1) (1).png" alt="" width="373"><figcaption></figcaption></figure>
@ -133,7 +133,7 @@ cookie-tossing.md
点击上面的链接访问解释 JWT 可能存在缺陷的页面。 点击上面的链接访问解释 JWT 可能存在缺陷的页面。
用于 cookie 的 JSON Web Tokens (JWT) 也可能存在漏洞。有关潜在缺陷及其利用方式的深入信息,建议访问有关黑客 JWT 的链接文档。 用于 cookie 的 JSON Web Tokens (JWT) 也可能存在漏洞。有关潜在缺陷及其利用方式的详细信息,建议访问有关黑客 JWT 的链接文档。
### Cross-Site Request Forgery (CSRF) ### Cross-Site Request Forgery (CSRF)
@ -147,7 +147,7 @@ document.cookie = "a=v1"
document.cookie = "=test value;" // Setting an empty named cookie document.cookie = "=test value;" // Setting an empty named cookie
document.cookie = "b=v2" document.cookie = "b=v2"
``` ```
发送的 cookie 头中的结果是 `a=v1; test value; b=v2;`。有趣的是,如果设置了一个空名称的 cookie这允许对 cookies 进行操控,通过将空 cookie 设置为特定值,可能控制其他 cookies 发送的 cookie 头中的结果是 `a=v1; test value; b=v2;`。有趣的是,如果设置了一个空名称的 cookie这允许对 cookies 进行操控,通过将空 cookie 设置为特定值,可能控制其他 cookies
```js ```js
function setCookie(name, value) { function setCookie(name, value) {
document.cookie = `${name}=${value}` document.cookie = `${name}=${value}`
@ -167,7 +167,7 @@ document.cookie = "\ud800=meep"
#### 由于解析问题导致的 Cookie 走私 #### 由于解析问题导致的 Cookie 走私
(查看[原始研究](https://blog.ankursundara.com/cookie-bugs/)的更多细节) 一些网络服务器,包括 JavaJetty, TomCat, Undertow和 PythonZope, cherrypy, web.py, aiohttp, bottle, webob,由于对过时的 RFC2965 支持,错误处理 cookie 字符串。它们将双引号括起来的 cookie 值视为单个值,即使它包含分号,而分号通常应分隔键值对: (查看[原始研究](https://blog.ankursundara.com/cookie-bugs/)的更多细节)包括 JavaJetty、TomCat、Undertow和 PythonZope、cherrypy、web.py、aiohttp、bottle、webob在内的多个网络服务器,由于对过时的 RFC2965 支持,错误处理 cookie 字符串。它们将带有双引号的 cookie 值视为单个值,即使它包含分号,而分号通常应分隔键值对:
``` ```
RENDER_TEXT="hello world; JSESSIONID=13371337; ASDF=end"; RENDER_TEXT="hello world; JSESSIONID=13371337; ASDF=end";
``` ```
@ -179,7 +179,7 @@ RENDER_TEXT="hello world; JSESSIONID=13371337; ASDF=end";
- Zope 寻找逗号以开始解析下一个 cookie。 - Zope 寻找逗号以开始解析下一个 cookie。
- Python 的 cookie 类在空格字符上开始解析。 - Python 的 cookie 类在空格字符上开始解析。
这种漏洞在依赖基于 cookie 的 CSRF 保护的 web 应用程序中尤其危险,因为它允许攻击者注入伪造的 CSRF-token cookies可能绕过安全措施。这个问题因 Python 对重复 cookie 名称的处理而加剧,最后一个出现的名称会覆盖之前的名称。它还引发了对不安全上下文中 `__Secure-``__Host-` cookies 的担忧,并可能导致在将 cookies 传递给易受伪造影响的后端服务器时发生授权绕过。 这种漏洞在依赖基于 cookie 的 CSRF 保护的 web 应用程序中尤其危险,因为它允许攻击者注入伪造的 CSRF-token cookies可能绕过安全措施。这个问题因 Python 对重复 cookie 名称的处理而加剧,最后一个出现的名称会覆盖之前的名称。它还引发了对不安全上下文中 `__Secure-``__Host-` cookies 的担忧,并可能导致在将 cookies 传递给易受伪造影响的后端服务器时绕过授权
### Cookies $version ### Cookies $version
@ -189,16 +189,15 @@ RENDER_TEXT="hello world; JSESSIONID=13371337; ASDF=end";
#### Cookie Sandwich Attack #### Cookie Sandwich Attack
根据[**这篇博客**](https://portswigger.net/research/stealing-httponly-cookies-with-the-cookie-sandwich-technique),可以使用 cookie 三明治技术来窃取 HttpOnly cookies。以下是要求和步骤 根据[**这篇博客**](https://portswigger.net/research/stealing-httponly-cookies-with-the-cookie-sandwich-technique),可以使用 cookie sandwich 技术来窃取 HttpOnly cookies。以下是要求和步骤
- 找到一个明显无用的 **cookie 在响应中被反射** 的地方 - 找到一个明显无用的 **cookie 在响应中被反射的地方**
- **创建一个名为 `$Version`** 的 cookie值为 `1`(你可以在 JS 的 XSS 攻击中做到这一点),并使用更具体的路径以获取初始位置(一些框架如 Python 不需要这一步) - **创建一个名为 `$Version`** 的 cookie值为 `1`(你可以在 JS 的 XSS 攻击中做到这一点),并使用更具体的路径以获取初始位置(一些框架如 Python 不需要这一步)
- **创建被反射的 cookie**,其值留有 **开放的双引号**,并使用特定路径以便在 cookie 数据库中位于前一个 cookie (`$Version`) 之后 - **创建被反射的 cookie**,其值留有 **开放的双引号**,并使用特定路径以便在 cookie 数据库中位于前一个 cookie (`$Version`) 之后
- 然后,合法的 cookie 将按顺序排在后面 - 然后,合法的 cookie 将按顺序紧随其后
- **创建一个虚拟 cookie 来关闭双引号** 在其值 - **创建一个虚拟 cookie 来关闭双引号** 在其值
这样,受害者的 cookie 就会被困在新的 cookie 版本 1 中,并将在每次反射时被反射。 这样,受害者的 cookie 就会被困在新的 cookie 版本 1 中,并将在每次反射时被反射。
例如,来自帖子:
```javascript ```javascript
document.cookie = `$Version=1;`; document.cookie = `$Version=1;`;
document.cookie = `param1="start`; document.cookie = `param1="start`;
@ -213,7 +212,7 @@ document.cookie = `param2=end";`;
#### 使用引号字符串编码绕过值分析 #### 使用引号字符串编码绕过值分析
此解析指示在 cookies 内部取消转义已转义的值,因此 "\a" 变为 "a"。这对于绕过 WAFS 很有用,如: 此解析指示在 cookies 内部取消转义已转义的值,因此 "\a" 变为 "a"。这对于绕过 WAFS 很有用,如下所示
- `eval('test') => forbidden` - `eval('test') => forbidden`
- `"\e\v\a\l\(\'\t\e\s\t\'\)" => allowed` - `"\e\v\a\l\(\'\t\e\s\t\'\)" => allowed`
@ -238,7 +237,7 @@ Cookie: comment')
Resulting cookie: name=eval('test//, comment') => allowed Resulting cookie: name=eval('test//, comment') => allowed
``` ```
### 额外的易受攻击的 Cookie 检查 ### 额外脆弱的 Cookie 检查
#### **基本检查** #### **基本检查**
@ -247,15 +246,15 @@ Resulting cookie: name=eval('test//, comment') => allowed
- 尝试在 2 个设备(或浏览器)上使用相同的 cookie 登录同一账户。 - 尝试在 2 个设备(或浏览器)上使用相同的 cookie 登录同一账户。
- 检查 cookie 中是否有任何信息并尝试修改它。 - 检查 cookie 中是否有任何信息并尝试修改它。
- 尝试创建多个几乎相同用户名的账户,并检查是否可以看到相似之处。 - 尝试创建多个几乎相同用户名的账户,并检查是否可以看到相似之处。
- 检查是否存在 "**记住我**" 选项以查看其工作原理。如果存在且可能存在漏洞,请始终使用 "**记住我**" 的 cookie而不使用其他 cookie。 - 检查是否存在 "**记住我**" 选项以了解其工作原理。如果存在且可能存在漏洞,请始终使用 "**记住我**" 的 cookie而不使用其他 cookie。
- 检查即使在更改密码后,之前的 cookie 是否仍然有效。 - 检查即使在更改密码后,之前的 cookie 是否仍然有效。
#### **高级 cookie 攻击** #### **高级 cookie 攻击**
如果在登录时 cookie 保持不变(或几乎不变),这可能意味着该 cookie 与您账户的某个字段相关(可能是用户名)。然后您可以: 如果在登录时 cookie 保持不变(或几乎不变),这可能意味着该 cookie 与您账户的某个字段相关(可能是用户名)。然后您可以:
- 尝试创建许多非常 **相似** 的用户名**账户**,并尝试 **猜测** 算法的工作原理。 - 尝试创建许多用户名非常 **相似****账户**,并尝试 **猜测** 算法的工作原理。
- 尝试 **暴力破解用户名**。如果 cookie 仅作为您用户名的身份验证方法保存,那么您可以创建一个用户名为 "**Bmin**" 的账户,并 **暴力破解** 您的 cookie 的每一个 **位**,因为您尝试的其中一个 cookie 将是属于 "**admin**" 的。 - 尝试 **暴力破解用户名**。如果 cookie 仅作为您用户名的身份验证方法保存,那么您可以创建一个用户名为 "**Bmin**" 的账户,并 **暴力破解** 您的 cookie 的每一个 **位**,因为您尝试的其中一个 cookie 将是属于 "**admin**" 的那个
- 尝试 **Padding** **Oracle**(您可以解密 cookie 的内容)。使用 **padbuster** - 尝试 **Padding** **Oracle**(您可以解密 cookie 的内容)。使用 **padbuster**
**Padding Oracle - Padbuster 示例** **Padding Oracle - Padbuster 示例**
@ -268,7 +267,7 @@ padbuster http://web.com/index.php u7bvLewln6PJPSAbMb5pFfnCHSEd6olf 8 -cookies a
padBuster http://web.com/home.jsp?UID=7B216A634951170FF851D6CC68FC9537858795A28ED4AAC6 padBuster http://web.com/home.jsp?UID=7B216A634951170FF851D6CC68FC9537858795A28ED4AAC6
7B216A634951170FF851D6CC68FC9537858795A28ED4AAC6 8 -encoding 2 7B216A634951170FF851D6CC68FC9537858795A28ED4AAC6 8 -encoding 2
``` ```
Padbuster 将进行多次尝试,并会询问您哪个条件是错误条件(无效的条件)。 Padbuster 将进行多次尝试,并会询问您哪个条件是错误条件(无效的条件)。
然后它将开始解密 cookie可能需要几分钟 然后它将开始解密 cookie可能需要几分钟
@ -276,30 +275,30 @@ Padbuster 将进行多次尝试,并会询问您哪个条件是错误条件(
``` ```
padbuster http://web.com/index.php 1dMjA5hfXh0jenxJQ0iW6QXKkzAGIWsiDAKV3UwJPT2lBP+zAD0D0w== 8 -cookies thecookie=1dMjA5hfXh0jenxJQ0iW6QXKkzAGIWsiDAKV3UwJPT2lBP+zAD0D0w== -plaintext user=administrator padbuster http://web.com/index.php 1dMjA5hfXh0jenxJQ0iW6QXKkzAGIWsiDAKV3UwJPT2lBP+zAD0D0w== 8 -cookies thecookie=1dMjA5hfXh0jenxJQ0iW6QXKkzAGIWsiDAKV3UwJPT2lBP+zAD0D0w== -plaintext user=administrator
``` ```
此执行将正确加密和编码包含字符串 **user=administrator** 的 cookie 此执行将正确加密和编码 cookie并在其中包含字符串 **user=administrator**
**CBC-MAC** **CBC-MAC**
也许一个 cookie 可以有某个值,并可以使用 CBC 签名。然后,值的完整性是使用相同值的 CBC 创建的签名。由于建议使用空向量作为 IV这种完整性检查可能会受到攻击 也许一个 cookie 可以有某个值,并可以使用 CBC 签名。然后,值的完整性是通过使用相同值的 CBC 创建的签名。由于建议使用空向量作为 IV这种完整性检查可能会存在漏洞
**攻击** **攻击**
1. 获取用户名 **administ** 的签名 = **t** 1. 获取用户名 **administ** 的签名 = **t**
2. 获取用户名 **rator\x00\x00\x00 XOR t** 的签名 = **t'** 2. 获取用户名 **rator\x00\x00\x00 XOR t** 的签名 = **t'**
3. 在 cookie 中设置值 **administrator+t'** **t'** 将是 **(rator\x00\x00\x00 XOR t) XOR t** 的有效签名 = **rator\x00\x00\x00** 3. 在 cookie 中设置值 **administrator+t'** (**t'** 将是 **(rator\x00\x00\x00 XOR t) XOR t** 的有效签名 = **rator\x00\x00\x00**)
**ECB** **ECB**
如果 cookie 使用 ECB 加密,则可能会受到攻击。\ 如果 cookie 使用 ECB 加密,则可能会存在漏洞。\
当您登录时,您收到的 cookie 必须始终相同。 当您登录时,您收到的 cookie 必须始终相同。
**如何检测和攻击:** **如何检测和攻击:**
创建 2 个几乎相同数据的用户(用户名、密码、电子邮件等),并尝试发现给定 cookie 中的某些模式。 创建 2 个几乎相同数据的用户(用户名、密码、电子邮件等),并尝试发现给定 cookie 中的某些模式。
创建一个名为 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 的用户,并检查 cookie 中是否任何模式(由于 ECB 使用相同的密钥加密每个块,如果用户名被加密,则相同的加密字节可能会出现)。 创建一个名为 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 的用户,并检查 cookie 中是否存在任何模式(由于 ECB 使用相同的密钥加密每个块,如果用户名被加密,则相同的加密字节可能会出现)。
应该有一个模式(与使用的块的大小相同)。因此,知道一堆 "a" 是如何加密的,您可以创建一个用户名: "a"*(块的大小)+"admin"。然后,您可以从 cookie 中删除一个块的 "a" 的加密模式。您将拥有用户名 "admin" 的 cookie。 应该有一个模式(与使用的块的大小相同)。因此,知道一堆 "a" 是如何加密的,您可以创建一个用户名:"a"*(块的大小)+"admin"。然后,您可以从 cookie 中删除一个块的 "a" 的加密模式。您将拥有用户名 "admin" 的 cookie。
## 参考 ## 参考

View File

@ -1,27 +1,28 @@
/** /**
* HackTricks AI Chat Widget v1.15 Markdown rendering + sanitised * HackTricks AI Chat Widget v1.16 resizable sidebar
* ------------------------------------------------------------------------ * ---------------------------------------------------
* Replaces the static placeholder with a three-dot **bouncing** loader * Markdown rendering + sanitised (same as before)
* Renders assistant replies as Markdown while purging any unsafe HTML * NEW: dragtoresize panel, width persists via localStorage
* (XSS-safe via DOMPurify)
* ------------------------------------------------------------------------
*/ */
(function () { (function () {
const LOG = "[HackTricks-AI]"; const LOG = "[HackTricksAI]";
/* ---------------- Usertunable constants ---------------- */
/* ---------------- User-tunable constants ---------------- */ const MAX_CONTEXT = 3000; // highlightedtext char limit
const MAX_CONTEXT = 3000; // highlighted-text char limit const MAX_QUESTION = 500; // question char limit
const MAX_QUESTION = 500; // question char limit const MIN_W = 250; // ← resize limits →
const MAX_W = 600;
const DEF_W = 350; // default width (if nothing saved)
const TOOLTIP_TEXT = const TOOLTIP_TEXT =
"💡 Highlight any text on the page,\nthen click to ask HackTricks AI about it"; "💡 Highlight any text on the page,\nthen click to ask HackTricks AI about it";
const API_BASE = "https://www.hacktricks.ai/api/assistants/threads"; const API_BASE = "https://www.hacktricks.ai/api/assistants/threads";
const BRAND_RED = "#b31328"; // HackTricks brand const BRAND_RED = "#b31328";
/* ------------------------------ State ------------------------------ */ /* ------------------------------ State ------------------------------ */
let threadId = null; let threadId = null;
let isRunning = false; let isRunning = false;
/* ---------- helpers ---------- */
const $ = (sel, ctx = document) => ctx.querySelector(sel); const $ = (sel, ctx = document) => ctx.querySelector(sel);
if (document.getElementById("ht-ai-btn")) { if (document.getElementById("ht-ai-btn")) {
console.warn(`${LOG} Widget already injected.`); console.warn(`${LOG} Widget already injected.`);
@ -31,44 +32,37 @@
? document.addEventListener("DOMContentLoaded", init) ? document.addEventListener("DOMContentLoaded", init)
: init()); : init());
/* ==================================================================== */ /* =================================================================== */
/* 🔗 1. 3rd-party libs → Markdown & sanitiser */ /* 🔗 1. 3rdparty libs → Markdown & sanitiser */
/* ==================================================================== */ /* =================================================================== */
function loadScript(src) { function loadScript(src) {
return new Promise((resolve, reject) => { return new Promise((res, rej) => {
const s = document.createElement("script"); const s = document.createElement("script");
s.src = src; s.src = src;
s.onload = resolve; s.onload = res;
s.onerror = () => reject(new Error(`Failed to load ${src}`)); s.onerror = () => rej(new Error(`Failed to load ${src}`));
document.head.appendChild(s); document.head.appendChild(s);
}); });
} }
async function ensureDeps() { async function ensureDeps() {
const deps = []; const deps = [];
if (typeof marked === "undefined") { if (typeof marked === "undefined")
deps.push(loadScript("https://cdn.jsdelivr.net/npm/marked/marked.min.js")); deps.push(loadScript("https://cdn.jsdelivr.net/npm/marked/marked.min.js"));
} if (typeof DOMPurify === "undefined")
if (typeof DOMPurify === "undefined") {
deps.push( deps.push(
loadScript( loadScript(
"https://cdnjs.cloudflare.com/ajax/libs/dompurify/3.2.5/purify.min.js" "https://cdnjs.cloudflare.com/ajax/libs/dompurify/3.2.5/purify.min.js"
) )
); );
}
if (deps.length) await Promise.all(deps); if (deps.length) await Promise.all(deps);
} }
const mdToSafeHTML = (md) =>
DOMPurify.sanitize(marked.parse(md, { mangle: false, headerIds: false }), {
USE_PROFILES: { html: true }
});
function mdToSafeHTML(md) { /* =================================================================== */
// 1⃣ Markdown → raw HTML
const raw = marked.parse(md, { mangle: false, headerIds: false });
// 2⃣ Purify
return DOMPurify.sanitize(raw, { USE_PROFILES: { html: true } });
}
/* ==================================================================== */
async function init() { async function init() {
/* ----- make sure marked & DOMPurify are ready before anything else */
try { try {
await ensureDeps(); await ensureDeps();
} catch (e) { } catch (e) {
@ -76,14 +70,14 @@
return; return;
} }
console.log(`${LOG} Injecting widget… v1.15`); console.log(`${LOG} Injecting widget… v1.16`);
await ensureThreadId(); await ensureThreadId();
injectStyles(); injectStyles();
const btn = createFloatingButton(); const btn = createFloatingButton();
createTooltip(btn); createTooltip(btn);
const panel = createSidebar(); const panel = createSidebar(); // ← panel with resizer
const chatLog = $("#ht-ai-chat"); const chatLog = $("#ht-ai-chat");
const sendBtn = $("#ht-ai-send"); const sendBtn = $("#ht-ai-send");
const inputBox = $("#ht-ai-question"); const inputBox = $("#ht-ai-question");
@ -100,15 +94,8 @@
function addMsg(text, cls) { function addMsg(text, cls) {
const b = document.createElement("div"); const b = document.createElement("div");
b.className = `ht-msg ${cls}`; b.className = `ht-msg ${cls}`;
b[cls === "ht-ai" ? "innerHTML" : "textContent"] =
// ✨ assistant replies rendered as Markdown + sanitised cls === "ht-ai" ? mdToSafeHTML(text) : text;
if (cls === "ht-ai") {
b.innerHTML = mdToSafeHTML(text);
} else {
// user / context bubbles stay plain-text
b.textContent = text;
}
chatLog.appendChild(b); chatLog.appendChild(b);
chatLog.scrollTop = chatLog.scrollHeight; chatLog.scrollTop = chatLog.scrollHeight;
return b; return b;
@ -116,30 +103,28 @@
const LOADER_HTML = const LOADER_HTML =
'<span class="ht-loading"><span></span><span></span><span></span></span>'; '<span class="ht-loading"><span></span><span></span><span></span></span>';
function setInputDisabled(d) { const setInputDisabled = (d) => {
inputBox.disabled = d; inputBox.disabled = d;
sendBtn.disabled = d; sendBtn.disabled = d;
} };
function clearThreadCookie() { const clearThreadCookie = () => {
document.cookie = "threadId=; Path=/; Max-Age=0"; document.cookie = "threadId=; Path=/; Max-Age=0";
threadId = null; threadId = null;
} };
function resetConversation() { const resetConversation = () => {
chatLog.innerHTML = ""; chatLog.innerHTML = "";
clearThreadCookie(); clearThreadCookie();
panel.classList.remove("open"); panel.classList.remove("open");
} };
/* ------------------- Panel open / close ------------------- */ /* ------------------- Panel open / close ------------------- */
btn.addEventListener("click", () => { btn.addEventListener("click", () => {
if (!savedSelection) { if (!savedSelection) {
alert("Please highlight some text first to then ask HackTricks AI about it."); alert("Please highlight some text first.");
return; return;
} }
if (savedSelection.length > MAX_CONTEXT) { if (savedSelection.length > MAX_CONTEXT) {
alert( alert(`Highlighted text is too long. Max ${MAX_CONTEXT} chars.`);
`Highlighted text is too long (${savedSelection.length} chars). Max allowed: ${MAX_CONTEXT}.`
);
return; return;
} }
chatLog.innerHTML = ""; chatLog.innerHTML = "";
@ -157,11 +142,10 @@
addMsg("Please wait until the current operation completes.", "ht-ai"); addMsg("Please wait until the current operation completes.", "ht-ai");
return; return;
} }
isRunning = true; isRunning = true;
setInputDisabled(true); setInputDisabled(true);
const loadingBubble = addMsg("", "ht-ai"); const loading = addMsg("", "ht-ai");
loadingBubble.innerHTML = LOADER_HTML; loading.innerHTML = LOADER_HTML;
const content = context const content = context
? `### Context:\n${context}\n\n### Question to answer:\n${question}` ? `### Context:\n${context}\n\n### Question to answer:\n${question}`
@ -178,43 +162,39 @@
try { try {
const e = await res.json(); const e = await res.json();
if (e.error) err = `Error: ${e.error}`; if (e.error) err = `Error: ${e.error}`;
else if (res.status === 429) else if (res.status === 429) err = "Rate limit exceeded.";
err = "Rate limit exceeded. Please try again later.";
} catch (_) {} } catch (_) {}
loadingBubble.textContent = err; loading.textContent = err;
return; return;
} }
const data = await res.json(); const data = await res.json();
loadingBubble.remove(); loading.remove();
if (Array.isArray(data.response)) if (Array.isArray(data.response))
data.response.forEach((p) => { data.response.forEach((p) =>
addMsg( addMsg(
p.type === "text" && p.text && p.text.value p.type === "text" && p.text && p.text.value
? p.text.value ? p.text.value
: JSON.stringify(p), : JSON.stringify(p),
"ht-ai" "ht-ai"
); )
}); );
else if (typeof data.response === "string") else if (typeof data.response === "string")
addMsg(data.response, "ht-ai"); addMsg(data.response, "ht-ai");
else addMsg(JSON.stringify(data, null, 2), "ht-ai"); else addMsg(JSON.stringify(data, null, 2), "ht-ai");
} catch (e) { } catch (e) {
console.error("Error sending message:", e); console.error("Error sending message:", e);
loadingBubble.textContent = "An unexpected error occurred."; loading.textContent = "An unexpected error occurred.";
} finally { } finally {
isRunning = false; isRunning = false;
setInputDisabled(false); setInputDisabled(false);
chatLog.scrollTop = chatLog.scrollHeight; chatLog.scrollTop = chatLog.scrollHeight;
} }
} }
async function handleSend() { async function handleSend() {
const q = inputBox.value.trim(); const q = inputBox.value.trim();
if (!q) return; if (!q) return;
if (q.length > MAX_QUESTION) { if (q.length > MAX_QUESTION) {
alert( alert(`Question too long (${q.length}). Max ${MAX_QUESTION}.`);
`Your question is too long (${q.length} chars). Max allowed: ${MAX_QUESTION}.`
);
return; return;
} }
inputBox.value = ""; inputBox.value = "";
@ -228,9 +208,9 @@
handleSend(); handleSend();
} }
}); });
} } /* end init */
/* ==================================================================== */ /* =================================================================== */
async function ensureThreadId() { async function ensureThreadId() {
const m = document.cookie.match(/threadId=([^;]+)/); const m = document.cookie.match(/threadId=([^;]+)/);
if (m && m[1]) { if (m && m[1]) {
@ -241,62 +221,67 @@
const r = await fetch(API_BASE, { method: "POST", credentials: "include" }); const r = await fetch(API_BASE, { method: "POST", credentials: "include" });
const d = await r.json(); const d = await r.json();
if (!r.ok || !d.threadId) throw new Error(`${r.status} ${r.statusText}`); if (!r.ok || !d.threadId) throw new Error(`${r.status} ${r.statusText}`);
threadId = d.threadId; threadId = d.threadId;
document.cookie = document.cookie =
`threadId=${threadId}; Path=/; Secure; SameSite=Strict; Max-Age=7200`; `threadId=${threadId}; Path=/; Secure; SameSite=Strict; Max-Age=7200`;
} catch (e) { } catch (e) {
console.error("Error creating threadId:", e); console.error("Error creating threadId:", e);
alert("Failed to initialise the conversation. Please refresh and try again."); alert("Failed to initialise the conversation. Please refresh.");
throw e; throw e;
} }
} }
/* ==================================================================== */ /* =================================================================== */
function injectStyles() { function injectStyles() {
const css = ` const css = `
#ht-ai-btn{position:fixed;bottom:20px;left:50%;transform:translateX(-50%);width:60px;height:60px;border-radius:50%;background:#1e1e1e;color:#fff;font-size:28px;display:flex;align-items:center;justify-content:center;cursor:pointer;z-index:99999;box-shadow:0 2px 8px rgba(0,0,0,.4);transition:opacity .2s} #ht-ai-btn{position:fixed;bottom:20px;left:50%;transform:translateX(-50%);min-width:60px;height:60px;border-radius:30px;background:linear-gradient(45deg, #b31328, #d42d3f, #2d5db4, #3470e4);background-size:300% 300%;animation:gradientShift 8s ease infinite;color:#fff;font-size:18px;display:flex;align-items:center;justify-content:center;cursor:pointer;z-index:99999;box-shadow:0 2px 8px rgba(0,0,0,.4);transition:opacity .2s;padding:0 20px}
#ht-ai-btn:hover{opacity:.85} #ht-ai-btn span{margin-left:8px;font-weight:bold}
@media(max-width:768px){#ht-ai-btn{display:none}} @keyframes gradientShift{0%{background-position:0% 50%}50%{background-position:100% 50%}100%{background-position:0% 50%}}
#ht-ai-tooltip{position:fixed;padding:6px 8px;background:#111;color:#fff;border-radius:4px;font-size:13px;white-space:pre-wrap;pointer-events:none;opacity:0;transform:translate(-50%,-8px);transition:opacity .15s ease,transform .15s ease;z-index:100000} #ht-ai-btn:hover{opacity:.85}
#ht-ai-tooltip.show{opacity:1;transform:translate(-50%,-12px)} @media(max-width:768px){#ht-ai-btn{display:none}}
#ht-ai-panel{position:fixed;top:0;right:0;height:100%;width:350px;max-width:90vw;background:#000;color:#fff;display:flex;flex-direction:column;transform:translateX(100%);transition:transform .3s ease;z-index:100000;font-family:system-ui,-apple-system,Segoe UI,Roboto,"Helvetica Neue",Arial,sans-serif} #ht-ai-tooltip{position:fixed;padding:6px 8px;background:#111;color:#fff;border-radius:4px;font-size:13px;white-space:pre-wrap;pointer-events:none;opacity:0;transform:translate(-50%,-8px);transition:opacity .15s ease,transform .15s ease;z-index:100000}
#ht-ai-panel.open{transform:translateX(0)} #ht-ai-tooltip.show{opacity:1;transform:translate(-50%,-12px)}
@media(max-width:768px){#ht-ai-panel{display:none}} #ht-ai-panel{position:fixed;top:0;right:0;height:100%;max-width:90vw;background:#000;color:#fff;display:flex;flex-direction:column;transform:translateX(100%);transition:transform .3s ease;z-index:100000;font-family:system-ui,-apple-system,Segoe UI,Roboto,"Helvetica Neue",Arial,sans-serif}
#ht-ai-header{display:flex;justify-content:space-between;align-items:center;padding:12px 16px;border-bottom:1px solid #333} #ht-ai-panel.open{transform:translateX(0)}
#ht-ai-header .ht-actions{display:flex;gap:8px;align-items:center} @media(max-width:768px){#ht-ai-panel{display:none}}
#ht-ai-close,#ht-ai-reset{cursor:pointer;font-size:18px;background:none;border:none;color:#fff;padding:0} #ht-ai-header{display:flex;justify-content:space-between;align-items:center;padding:12px 16px;border-bottom:1px solid #333}
#ht-ai-close:hover,#ht-ai-reset:hover{opacity:.7} #ht-ai-header .ht-actions{display:flex;gap:8px;align-items:center}
#ht-ai-chat{flex:1;overflow-y:auto;padding:16px;display:flex;flex-direction:column;gap:12px;font-size:14px} #ht-ai-close,#ht-ai-reset{cursor:pointer;font-size:18px;background:none;border:none;color:#fff;padding:0}
.ht-msg{max-width:90%;line-height:1.4;padding:10px 12px;border-radius:8px;white-space:pre-wrap;word-wrap:break-word} #ht-ai-close:hover,#ht-ai-reset:hover{opacity:.7}
.ht-user{align-self:flex-end;background:${BRAND_RED}} #ht-ai-chat{flex:1;overflow-y:auto;padding:16px;display:flex;flex-direction:column;gap:12px;font-size:14px}
.ht-ai{align-self:flex-start;background:#222} .ht-msg{max-width:90%;line-height:1.4;padding:10px 12px;border-radius:8px;white-space:pre-wrap;word-wrap:break-word}
.ht-context{align-self:flex-start;background:#444;font-style:italic;font-size:13px} .ht-user{align-self:flex-end;background:${BRAND_RED}}
#ht-ai-input{display:flex;gap:8px;padding:12px 16px;border-top:1px solid #333} .ht-ai{align-self:flex-start;background:#222}
#ht-ai-question{flex:1;min-height:40px;max-height:120px;resize:vertical;padding:8px;border-radius:6px;border:none;font-size:14px} .ht-context{align-self:flex-start;background:#444;font-style:italic;font-size:13px}
#ht-ai-send{padding:0 18px;border:none;border-radius:6px;background:${BRAND_RED};color:#fff;font-size:14px;cursor:pointer} #ht-ai-input{display:flex;gap:8px;padding:12px 16px;border-top:1px solid #333}
#ht-ai-send:disabled{opacity:.5;cursor:not-allowed} #ht-ai-question{flex:1;min-height:40px;max-height:120px;resize:vertical;padding:8px;border-radius:6px;border:none;font-size:14px}
/* Loader animation */ #ht-ai-send{padding:0 18px;border:none;border-radius:6px;background:${BRAND_RED};color:#fff;font-size:14px;cursor:pointer}
.ht-loading{display:inline-flex;align-items:center;gap:4px} #ht-ai-send:disabled{opacity:.5;cursor:not-allowed}
.ht-loading span{width:6px;height:6px;border-radius:50%;background:#888;animation:ht-bounce 1.2s infinite ease-in-out} /* Loader */
.ht-loading span:nth-child(2){animation-delay:0.2s} .ht-loading{display:inline-flex;align-items:center;gap:4px}
.ht-loading span:nth-child(3){animation-delay:0.4s} .ht-loading span{width:6px;height:6px;border-radius:50%;background:#888;animation:ht-bounce 1.2s infinite ease-in-out}
@keyframes ht-bounce{0%,80%,100%{transform:scale(0);}40%{transform:scale(1);} } .ht-loading span:nth-child(2){animation-delay:0.2s}
::selection{background:#ffeb3b;color:#000} .ht-loading span:nth-child(3){animation-delay:0.4s}
::-moz-selection{background:#ffeb3b;color:#000}`; @keyframes ht-bounce{0%,80%,100%{transform:scale(0);}40%{transform:scale(1);} }
::selection{background:#ffeb3b;color:#000}
::-moz-selection{background:#ffeb3b;color:#000}
/* NEW: resizer handle */
#ht-ai-resizer{position:absolute;left:0;top:0;width:6px;height:100%;cursor:ew-resize;background:transparent}
#ht-ai-resizer:hover{background:rgba(255,255,255,.05)}`;
const s = document.createElement("style"); const s = document.createElement("style");
s.id = "ht-ai-style"; s.id = "ht-ai-style";
s.textContent = css; s.textContent = css;
document.head.appendChild(s); document.head.appendChild(s);
} }
/* =================================================================== */
function createFloatingButton() { function createFloatingButton() {
const d = document.createElement("div"); const d = document.createElement("div");
d.id = "ht-ai-btn"; d.id = "ht-ai-btn";
d.textContent = "🤖"; d.innerHTML = "🤖<span>HackTricksAI</span>";
document.body.appendChild(d); document.body.appendChild(d);
return d; return d;
} }
function createTooltip(btn) { function createTooltip(btn) {
const t = document.createElement("div"); const t = document.createElement("div");
t.id = "ht-ai-tooltip"; t.id = "ht-ai-tooltip";
@ -311,11 +296,16 @@
btn.addEventListener("mouseleave", () => t.classList.remove("show")); btn.addEventListener("mouseleave", () => t.classList.remove("show"));
} }
/* =================================================================== */
function createSidebar() { function createSidebar() {
const saved = parseInt(localStorage.getItem("htAiWidth") || DEF_W, 10);
const width = Math.min(Math.max(saved, MIN_W), MAX_W);
const p = document.createElement("div"); const p = document.createElement("div");
p.id = "ht-ai-panel"; p.id = "ht-ai-panel";
p.style.width = width + "px"; // ← applied width
p.innerHTML = ` p.innerHTML = `
<div id="ht-ai-header"><strong>HackTricks AI Chat</strong> <div id="ht-ai-header"><strong>HackTricks AI Chat</strong>
<div class="ht-actions"> <div class="ht-actions">
<button id="ht-ai-reset" title="Reset"></button> <button id="ht-ai-reset" title="Reset"></button>
<span id="ht-ai-close" title="Close"></span> <span id="ht-ai-close" title="Close"></span>
@ -326,7 +316,39 @@
<textarea id="ht-ai-question" placeholder="Type your question…"></textarea> <textarea id="ht-ai-question" placeholder="Type your question…"></textarea>
<button id="ht-ai-send">Send</button> <button id="ht-ai-send">Send</button>
</div>`; </div>`;
/* NEW: resizer strip */
const resizer = document.createElement("div");
resizer.id = "ht-ai-resizer";
p.appendChild(resizer);
document.body.appendChild(p); document.body.appendChild(p);
addResizeLogic(resizer, p);
return p; return p;
} }
/* ---------------- resize behaviour ---------------- */
function addResizeLogic(handle, panel) {
let startX, startW, dragging = false;
const onMove = (e) => {
if (!dragging) return;
const dx = startX - e.clientX; // dragging leftwards ⇒ +dx
let newW = startW + dx;
newW = Math.min(Math.max(newW, MIN_W), MAX_W);
panel.style.width = newW + "px";
};
const onUp = () => {
if (!dragging) return;
dragging = false;
localStorage.setItem("htAiWidth", parseInt(panel.style.width, 10));
document.removeEventListener("mousemove", onMove);
document.removeEventListener("mouseup", onUp);
};
handle.addEventListener("mousedown", (e) => {
dragging = true;
startX = e.clientX;
startW = parseInt(window.getComputedStyle(panel).width, 10);
document.addEventListener("mousemove", onMove);
document.addEventListener("mouseup", onUp);
});
}
})(); })();