push init

main
jeffrey 2025-03-29 08:54:15 +01:00
parent 27d649e279
commit 8b0f909a10
8 changed files with 487 additions and 0 deletions

6
App.config Normal file
View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
</startup>
</configuration>

3
FodyWeavers.xml Normal file
View File

@ -0,0 +1,3 @@
<Weavers xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="FodyWeavers.xsd">
<Costura />
</Weavers>

299
Program.cs Normal file
View File

@ -0,0 +1,299 @@
using CommandLine;
using System;
using System.CodeDom;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace SharpScan
{
public class Options
{
[Option('h', "hosts", Required = true, Separator = ',', HelpText = "Hosts to scan, coma separated. CIDR accepted")]
public IEnumerable<string> Hosts { get; set; }
[Option('p', "ports", Required = false, Separator = ',', HelpText = "TCP port to scan, coma separated")]
public IEnumerable<int> Ports { get; set; }
[Option('t', "timeout", Required = false, Default = 500, HelpText = "Timeout in milliseconds to check a port")]
public int Timeout { get; set; }
[Option('d', "delay", Required = false, Default = 0, HelpText = "Delay in milliseconds between 2 scan request")]
public int Delay { get; set; }
[Option('j', "jittler", Required = false, Default = 0, HelpText = "Jittler to apply to delay, in percent, new evalutation for each request")]
public int Jittler { get; set; }
[Option('r', "randomize", Required = false, Default = false, HelpText = "Randomize hosts/ports scan order. Results will be printed in normal order")]
public bool Randomize { get; set; }
[Option('f', "top-ports", Required = false, Default = 0, HelpText = "Equivalent of nmap --top-ports option")]
public int TopPorts { get; set; }
}
class Program
{
public static List<string> GetIpsFromCidr(string cidr)
{
var ipList = new List<string>();
// Séparer l'adresse IP et le masque
var parts = cidr.Split('/');
var ipAddress = parts[0];
var subnetMask = int.Parse(parts[1]);
// Convertir l'adresse IP en un format numérique
var ip = IPAddress.Parse(ipAddress);
var ipBytes = ip.GetAddressBytes();
uint ipNumeric = BitConverter.ToUInt32(ipBytes.Reverse().ToArray(), 0);
// Calculer le nombre total d'adresses IP dans le réseau
uint totalAddresses = (uint)Math.Pow(2, 32 - subnetMask);
// Calculer l'adresse de broadcast en ajoutant le nombre total d'adresses moins un
uint broadcastIpNumeric = ipNumeric + totalAddresses - 1;
// Générer les adresses IP en excluant l'adresse du réseau et de broadcast
for (uint i = 1; i < totalAddresses - 1; i++)
{
uint currentIp = ipNumeric + i;
byte[] bytes = BitConverter.GetBytes(currentIp);
Array.Reverse(bytes); // Revertir l'ordre des octets pour obtenir une IP valide
ipList.Add(new IPAddress(bytes).ToString());
}
return ipList;
}
public static void Shuffle<T>(List<T> list)
{
Random rand = new Random();
int n = list.Count;
while (n > 1)
{
n--;
int k = rand.Next(n + 1); // Choisir un index aléatoire entre 0 et n
T value = list[k];
list[k] = list[n];
list[n] = value;
}
}
public static bool IsPortOpen(string hostname, int port, int timeoutMilliseconds)
{
using (var client = new TcpClient(AddressFamily.InterNetwork))
{
var connectDone = new ManualResetEvent(false);
bool connected = false;
Exception connectException = null;
Thread connectThread = new Thread(() =>
{
try
{
client.Connect(hostname, port);
connected = true;
}
catch (SocketException ex)
{
connectException = ex;
connected = false;
}
finally
{
connectDone.Set();
}
});
connectThread.Start();
if (!connectDone.WaitOne(timeoutMilliseconds))
{
// Timeout
connectThread.Abort(); // On tente d'interrompre le thread de connexion.
return false;
}
if (connectException != null)
{
// La connexion a échoué.
return false;
}
return connected;
}
}
static void Main(string[] args)
{
List<(string address, int port)> cibles = new List<(string address, int port)>();
List<string> addresses = new List<string>();
List<(string address, int port)> results = new List<(string address, int port)>();
List<int> ports = new List<int>();
int timeout = 0;
bool randomize = false;
int delay = 0;
int jittler = 0;
int top_port = 0;
Parser.Default.ParseArguments<Options>(args).WithParsed<Options>(o => {
// Gestion des hosts
foreach (string host in o.Hosts)
{
if (host.Contains('/'))
{
addresses.AddRange(GetIpsFromCidr(host));
}
else
{
addresses.Add(host);
}
}
// Gestion des ports
if (o.Ports.Count() > 0)
{
if (o.Ports.Count() == 1 && o.Ports.First() == -1)
{
foreach (int port in Enumerable.Range(0, 65536))
{
ports.Add(port);
}
}
else
{
foreach (int port in o.Ports)
{
ports.Add(port);
}
}
}
else
{
if (o.TopPorts > 0)
{
if (o.TopPorts <= Utils.top_ports_list.Count())
{
ports = Utils.top_ports_list.GetRange(0, o.TopPorts);
}
else
{
ports = Utils.top_ports_list;
}
}
else
{
ports = Utils.top_ports_list.GetRange(0, 12);
}
}
timeout = o.Timeout;
randomize = o.Randomize;
delay = o.Delay;
jittler = o.Jittler;
top_port = o.TopPorts;
});
// Construction des cibles
foreach (string address in addresses)
{
foreach (int port in ports)
{
cibles.Add((address, port));
}
}
if (randomize)
{
Shuffle(cibles);
}
// Check wich ports are available
Random r;
int sleep_value;
Console.WriteLine($"There is {cibles.Count} requests to send !!!");
int cpt = 1;
Stopwatch chronometre = new Stopwatch();
chronometre.Start();
int fraction = cibles.Count / 10;
int cpt_fraction = 0;
// Estimation de la durée du scan
int total = 0;
total += ((delay + (jittler * delay / 100)) * cibles.Count) / 1000;
total += (timeout * cibles.Count) / 1000;
total += (2 * 100) / total; // On rajoute un chouilla pour le temps de traitement.
TimeSpan temps = TimeSpan.FromSeconds(total);
string total_formatee = temps.ToString(@"hh\:mm\:ss");
Console.WriteLine($"Duree estimée: {total_formatee}");
foreach ((string address, int port) in cibles)
{
if( cpt % fraction == 0)
{
cpt_fraction += 10;
Console.WriteLine($"Request {cpt}/{cibles.Count} ({cpt_fraction})%");
}
if (IsPortOpen(address, port, timeout))
{
results.Add((address, port));
}
// Sleep delay value
r = new Random();
sleep_value = r.Next(delay, delay + (jittler * delay / 100));
Thread.Sleep(sleep_value);
cpt += 1;
}
chronometre.Stop();
TimeSpan duree = chronometre.Elapsed;
string dureeFormatee = duree.ToString(@"hh\:mm\:ss"); // Format : heures:minutes
Console.WriteLine($"Durée (heures:minutes) : {dureeFormatee}");
// Affichage des résultats
results = results.OrderBy(tuple => IPAddress.Parse(tuple.address).GetAddressBytes().Select(b => (int)b).Aggregate(0, (acc, b) => acc * 256 + b)).ThenBy(tuple => tuple.port).ToList();
string current_host = "";
Console.WriteLine("\n ===[ SCAN RESULTS ]===");
foreach ((string address, int port) in results)
{
if (!(address == current_host))
{
Console.WriteLine($"\n{address}");
current_host = address;
}
Console.WriteLine($" {port} opened ({Utils.GetDesc(port)})");
}
}
}
}

View File

@ -0,0 +1,33 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Les informations générales relatives à un assembly dépendent de
// l'ensemble d'attributs suivant. Changez les valeurs de ces attributs pour modifier les informations
// associées à un assembly.
[assembly: AssemblyTitle("SharpScan")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("SharpScan")]
[assembly: AssemblyCopyright("Copyright © 2025")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// L'affectation de la valeur false à ComVisible rend les types invisibles dans cet assembly
// aux composants COM. Si vous devez accéder à un type dans cet assembly à partir de
// COM, affectez la valeur true à l'attribut ComVisible sur ce type.
[assembly: ComVisible(false)]
// Le GUID suivant est pour l'ID de la typelib si ce projet est exposé à COM
[assembly: Guid("d49e443b-710e-4561-8c38-97204dc7444f")]
// Les informations de version pour un assembly se composent des quatre valeurs suivantes :
//
// Version principale
// Version secondaire
// Numéro de build
// Révision
//
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

94
SharpScan.csproj Normal file
View File

@ -0,0 +1,94 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="packages\Costura.Fody.6.0.0\build\Costura.Fody.props" Condition="Exists('packages\Costura.Fody.6.0.0\build\Costura.Fody.props')" />
<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>{D49E443B-710E-4561-8C38-97204DC7444F}</ProjectGuid>
<OutputType>Exe</OutputType>
<RootNamespace>SharpScan</RootNamespace>
<AssemblyName>SharpScan</AssemblyName>
<TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<Deterministic>true</Deterministic>
<NuGetPackageImportStamp>
</NuGetPackageImportStamp>
</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>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x64'">
<DebugSymbols>true</DebugSymbols>
<OutputPath>bin\x64\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<DebugType>full</DebugType>
<PlatformTarget>x64</PlatformTarget>
<LangVersion>7.3</LangVersion>
<ErrorReport>prompt</ErrorReport>
<Prefer32Bit>true</Prefer32Bit>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x64'">
<OutputPath>bin\x64\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<Optimize>true</Optimize>
<DebugType>pdbonly</DebugType>
<PlatformTarget>x64</PlatformTarget>
<LangVersion>7.3</LangVersion>
<ErrorReport>prompt</ErrorReport>
<Prefer32Bit>true</Prefer32Bit>
</PropertyGroup>
<ItemGroup>
<Reference Include="CommandLine, Version=2.9.1.0, Culture=neutral, PublicKeyToken=5a870481e358d379, processorArchitecture=MSIL">
<HintPath>packages\CommandLineParser.2.9.1\lib\net461\CommandLine.dll</HintPath>
</Reference>
<Reference Include="Costura, Version=6.0.0.0, Culture=neutral, PublicKeyToken=9919ef960d84173d, processorArchitecture=MSIL">
<HintPath>packages\Costura.Fody.6.0.0\lib\netstandard2.0\Costura.dll</HintPath>
</Reference>
<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="Utils.cs" />
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
<None Include="packages.config" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup>
<ErrorText>Ce projet fait référence à des packages NuGet qui sont manquants sur cet ordinateur. Utilisez l'option de restauration des packages NuGet pour les télécharger. Pour plus d'informations, consultez http://go.microsoft.com/fwlink/?LinkID=322105. Le fichier manquant est : {0}.</ErrorText>
</PropertyGroup>
<Error Condition="!Exists('packages\Costura.Fody.6.0.0\build\Costura.Fody.props')" Text="$([System.String]::Format('$(ErrorText)', 'packages\Costura.Fody.6.0.0\build\Costura.Fody.props'))" />
<Error Condition="!Exists('packages\Costura.Fody.6.0.0\build\Costura.Fody.targets')" Text="$([System.String]::Format('$(ErrorText)', 'packages\Costura.Fody.6.0.0\build\Costura.Fody.targets'))" />
<Error Condition="!Exists('packages\Fody.6.9.2\build\Fody.targets')" Text="$([System.String]::Format('$(ErrorText)', 'packages\Fody.6.9.2\build\Fody.targets'))" />
</Target>
<Import Project="packages\Costura.Fody.6.0.0\build\Costura.Fody.targets" Condition="Exists('packages\Costura.Fody.6.0.0\build\Costura.Fody.targets')" />
<Import Project="packages\Fody.6.9.2\build\Fody.targets" Condition="Exists('packages\Fody.6.9.2\build\Fody.targets')" />
</Project>

28
SharpScan.sln Normal file
View File

@ -0,0 +1,28 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.12.35527.113 d17.12
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SharpScan", "SharpScan.csproj", "{D49E443B-710E-4561-8C38-97204DC7444F}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Debug|x64 = Debug|x64
Release|Any CPU = Release|Any CPU
Release|x64 = Release|x64
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{D49E443B-710E-4561-8C38-97204DC7444F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{D49E443B-710E-4561-8C38-97204DC7444F}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D49E443B-710E-4561-8C38-97204DC7444F}.Debug|x64.ActiveCfg = Release|x64
{D49E443B-710E-4561-8C38-97204DC7444F}.Debug|x64.Build.0 = Release|x64
{D49E443B-710E-4561-8C38-97204DC7444F}.Release|Any CPU.ActiveCfg = Release|Any CPU
{D49E443B-710E-4561-8C38-97204DC7444F}.Release|Any CPU.Build.0 = Release|Any CPU
{D49E443B-710E-4561-8C38-97204DC7444F}.Release|x64.ActiveCfg = Release|x64
{D49E443B-710E-4561-8C38-97204DC7444F}.Release|x64.Build.0 = Release|x64
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

18
Utils.cs Normal file

File diff suppressed because one or more lines are too long

6
packages.config Normal file
View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="CommandLineParser" version="2.9.1" targetFramework="net472" />
<package id="Costura.Fody" version="6.0.0" targetFramework="net472" developmentDependency="true" />
<package id="Fody" version="6.9.2" targetFramework="net472" developmentDependency="true" />
</packages>