Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
Injector committed May 27, 2022
0 parents commit e12a10d
Show file tree
Hide file tree
Showing 8 changed files with 364 additions and 0 deletions.
25 changes: 25 additions & 0 deletions Server - C#/TcpServer/TcpServer.sln
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.32413.511
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TcpServer", "TcpServer\TcpServer.csproj", "{E82A6974-DF0B-4AD8-97DE-E561ADFF9F94}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{E82A6974-DF0B-4AD8-97DE-E561ADFF9F94}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{E82A6974-DF0B-4AD8-97DE-E561ADFF9F94}.Debug|Any CPU.Build.0 = Debug|Any CPU
{E82A6974-DF0B-4AD8-97DE-E561ADFF9F94}.Release|Any CPU.ActiveCfg = Release|Any CPU
{E82A6974-DF0B-4AD8-97DE-E561ADFF9F94}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {D557D5DD-8BC6-41C8-BC9D-AEDE37BB46F4}
EndGlobalSection
EndGlobal
6 changes: 6 additions & 0 deletions Server - C#/TcpServer/TcpServer/App.config
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8" />
</startup>
</configuration>
16 changes: 16 additions & 0 deletions Server - C#/TcpServer/TcpServer/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TcpServer
{
public class Program
{
public static void Main()
{
Server.Initialize();
}
}
}
36 changes: 36 additions & 0 deletions Server - C#/TcpServer/TcpServer/Properties/AssemblyInfo.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

// Общие сведения об этой сборке предоставляются следующим набором
// набора атрибутов. Измените значения этих атрибутов для изменения сведений,
// связанные с этой сборкой.
[assembly: AssemblyTitle("TCP Server")]
[assembly: AssemblyDescription("TCP C# Server for listening php clients")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Xleb Factory")]
[assembly: AssemblyProduct("TCP Server")]
[assembly: AssemblyCopyright("© Bloomstorm, 2021-2022")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Установка значения False для параметра ComVisible делает типы в этой сборке невидимыми
// для компонентов COM. Если необходимо обратиться к типу в этой сборке через
// из модели COM задайте для атрибута ComVisible этого типа значение true.
[assembly: ComVisible(false)]

// Следующий GUID представляет идентификатор typelib, если этот проект доступен из модели COM
[assembly: Guid("e82a6974-df0b-4ad8-97de-e561adff9f94")]

// Сведения о версии сборки состоят из указанных ниже четырех значений:
//
// Основной номер версии
// Дополнительный номер версии
// Номер сборки
// Номер редакции
//
// Можно задать все значения или принять номера сборки и редакции по умолчанию
// используя "*", как показано ниже:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
171 changes: 171 additions & 0 deletions Server - C#/TcpServer/TcpServer/Server.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,171 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Xml;
using System.Xml.Serialization;

namespace TcpServer
{
public class Server
{
public const string SERVER_CONFIG_FILE = "ServerConfig.xml";
public static string RconPassword { get; private set; }
public static int ListMode { get; private set; }
public static string[] IPList { get; private set; }
private static TcpListener _TcpListener;
private static bool _initialized;

public static void Initialize()
{
if (_initialized) return;
_initialized = true;
var xmlConfig = new XmlServerConfig();
if (File.Exists(SERVER_CONFIG_FILE))
{
xmlConfig = XmlParser.Parse<XmlServerConfig>(File.ReadAllText(SERVER_CONFIG_FILE));
}
TcpListener server = null;
var ipAddress = IPAddress.Parse(xmlConfig.Ip);

RconPassword = xmlConfig.Rcon;
ListMode = xmlConfig.ListMode;
IPList = xmlConfig.Ips.Select(xmlIp => xmlIp.Ip).ToArray();

server = new TcpListener(ipAddress, xmlConfig.Port);
server.Start();
_TcpListener = server;
Console.WriteLine($"Server is running with IP {xmlConfig.Ip} port {xmlConfig.Port}");

while (true)
{
var socket = server.AcceptSocket();
Console.WriteLine($"Connection accepted from {socket.RemoteEndPoint}");
if (ListMode == 1)
{
var clientAddress = socket.RemoteEndPoint.ToString().Split(':')[0];
var found = false;
for (int i = 0; i < IPList.Length; i++)
{
if (IPList[i] == clientAddress)
found = true;
}
if (!found)
{
socket.Close();
Console.WriteLine($"List Mode = 1, non white listed IP. Connection closed.");
return;
}
}
if (ListMode == 2)
{
var clientAddress = socket.RemoteEndPoint.ToString().Split(':')[0];
var found = false;
for (int i = 0; i < IPList.Length; i++)
{
if (IPList[i] == clientAddress)
found = true;
}
if (found)
{
socket.Close();
Console.WriteLine($"List Mode = 2, black listed IP. Connection closed.");
return;
}
}
var buffer = new byte[256];
var receivedMessage = ReceiveString(socket, 1, buffer);
Console.WriteLine($"Received: {receivedMessage}");
var args = receivedMessage.Split('|');
if (args.Length > 0)
{
if (args[0] != RconPassword)
{
Console.Write("Invalid RCON password");
SendString(socket, 1, "Invalid RCON Password");
socket.Close();
}
else
{
if (args.Length > 1)
{
switch (args[1])
{
case "1":
Console.Write("Sending Pong");
SendString(socket, 1, "Pong");
break;
}
}
}
}
socket.Close();
}
}

public static void Stop()
{
_TcpListener.Stop();
_initialized = false;
RconPassword = string.Empty;
ListMode = 0;
IPList = null;
}

public static void SendString(Socket socket, int encodingType, string message)
{
switch (encodingType)
{
case 0:
var ascii = new ASCIIEncoding();
socket.Send(ascii.GetBytes(message));
break;
case 1:
var utf = new UTF8Encoding();
socket.Send(utf.GetBytes(message));
break;
}
}

public static string ReceiveString(Socket socket, int encodingType, byte[] buffer)
{
switch (encodingType)
{
case 0:
var asciiK = socket.Receive(buffer);
return Encoding.ASCII.GetString(buffer.Take(asciiK).ToArray());
case 1:
var utf8K = socket.Receive(buffer);
return Encoding.UTF8.GetString(buffer.Take(utf8K).ToArray());
}
return string.Empty;
}

[Serializable]
[XmlRoot(ElementName = "config")]
public class XmlServerConfig
{
[XmlElement("ip")]
public string Ip = "127.0.0.1";
[XmlElement("port")]
public int Port = 27015;
[XmlElement("rcon")]
public string Rcon = string.Empty;
[XmlElement("listmode")]
public int ListMode = 0;
[XmlArray("ips"), XmlArrayItem("ip")]
public List<XmlIp> Ips = new List<XmlIp>();
}

[XmlRoot("ip")]
public class XmlIp
{
[XmlAttribute("ip")]
public string Ip = "127.0.0.1";
}
}
}
55 changes: 55 additions & 0 deletions Server - C#/TcpServer/TcpServer/TcpServer.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{E82A6974-DF0B-4AD8-97DE-E561ADFF9F94}</ProjectGuid>
<OutputType>Exe</OutputType>
<RootNamespace>TcpServer</RootNamespace>
<AssemblyName>TcpServer</AssemblyName>
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<Deterministic>true</Deterministic>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Server.cs" />
<Compile Include="XmlParser.cs" />
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>
15 changes: 15 additions & 0 deletions Server - C#/TcpServer/TcpServer/XmlParser.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
using System.Xml.Serialization;
using System.IO;

namespace TcpServer
{
public static class XmlParser
{
public static T Parse<T>(string xml)
{
var xmlSerializer = new XmlSerializer(typeof(T));
using (var stringReader = new StringReader(xml))
return (T)xmlSerializer.Deserialize(stringReader);
}
}
}
40 changes: 40 additions & 0 deletions Web - php/tcp_rcon.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
<?php
$address = "0.0.0.0";
$port = 27015;
$rcon = "RconPass1234";
$cmdId = "1";
$cmdArguments = ""; // formation: arg1|arg2|arg3

$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket === false)
{
echo "Socket creation failed: " . socket_strerror(socket_last_error()) . "\n";
return;
}
echo "Connecting...\n";

$result = socket_connect($socket, $address, $port);
if ($result === false)
{
echo "Socket connection failed: $result " . socket_strerror(socket_last_error($socket)) . "\n";
return;
}
else
{
echo "Connected\n";
}

$in = strlen($cmdArguments) > 0 ? "$rcon|$cmdId|$cmdArguments" : "$rcon|$cmdId";
$out = "";

echo "Sending cmd...\n";
socket_write($socket, $in, strlen($in));
echo "Sent cmd\n";
echo "Reading response\n";

while ($out = socket_read($socket, 2048))
{
echo $out;
}
socket_close($socket);
?>

0 comments on commit e12a10d

Please sign in to comment.