1
0
mirror of https://git.teknik.io/Teknikode/Teknik.git synced 2023-08-02 14:16:22 +02:00

Added Server Maintainence program.

Fixed client side encrypted uploads that save the key from not being scanned.
This commit is contained in:
Uncled1023 2016-05-09 13:01:41 -07:00
parent 16099529d1
commit d5c85add89
9 changed files with 378 additions and 4 deletions

120
ServerMaint/Program.cs Normal file
View File

@ -0,0 +1,120 @@
using nClam;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using Teknik.Areas.Upload.Models;
using Teknik.Configuration;
using Teknik.Helpers;
using Teknik.Models;
namespace ServerMaint
{
public class Program
{
public static event Action<string> OutputEvent;
public static void Main(string[] args)
{
string currentPath = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
string parentPath = Directory.GetParent(currentPath).FullName;
string logFile = Path.Combine(currentPath, "virusLogs.txt");
string errorFile = Path.Combine(currentPath, "errorLogs.txt");
string configPath = Path.Combine(parentPath, "App_Data");
// Let's clean some stuff!!
try
{
Config config = Config.Load(configPath);
TeknikEntities db = new TeknikEntities();
// Scan all the uploads for viruses, and remove the bad ones
if (config.UploadConfig.VirusScanEnable)
{
List<Upload> uploads = db.Uploads.ToList();
int totalCount = uploads.Count();
int totalScans = 0;
int totalClean = 0;
int totalViruses = 0;
foreach (Upload upload in uploads)
{
totalScans++;
string subDir = upload.FileName[0].ToString();
string filePath = Path.Combine(config.UploadConfig.UploadDirectory, subDir, upload.FileName);
if (File.Exists(filePath))
{
// Read in the file
byte[] data = File.ReadAllBytes(filePath);
// If the IV is set, and Key is set, then decrypt it
if (!string.IsNullOrEmpty(upload.Key) && !string.IsNullOrEmpty(upload.IV))
{
// Decrypt the data
data = AES.Decrypt(data, upload.Key, upload.IV);
}
// We have the data, let's scan it
ClamClient clam = new ClamClient(config.UploadConfig.ClamServer, config.UploadConfig.ClamPort);
clam.MaxStreamSize = config.UploadConfig.MaxUploadSize;
ClamScanResult scanResult = clam.SendAndScanFile(data);
switch (scanResult.Result)
{
case ClamScanResults.Clean:
totalClean++;
string cleanMsg = string.Format("[{0}] Clean Scan: {1}/{2} Scanned | {3} - {4}", DateTime.Now, totalScans, totalCount, upload.Url, upload.FileName);
Output(cleanMsg);
break;
case ClamScanResults.VirusDetected:
totalViruses++;
string msg = string.Format("[{0}] Virus Detected: {1} - {2} - {3}", DateTime.Now, upload.Url, upload.FileName, scanResult.InfectedFiles.First().VirusName);
File.AppendAllLines(logFile, new List<string> { msg });
Output(msg);
//// Delete from the DB
//db.Uploads.Remove(upload);
//db.SaveChanges();
//// Delete the File
//if (File.Exists(filePath))
//{
// File.Delete(filePath);
//}
break;
case ClamScanResults.Error:
string errorMsg = string.Format("[{0}] Scan Error: {1}", DateTime.Now, scanResult.RawResult);
File.AppendAllLines(errorFile, new List<string> { errorMsg });
Output(errorMsg);
break;
case ClamScanResults.Unknown:
string unkMsg = string.Format("[{0}] Unknown Scan Result: {1}", DateTime.Now, scanResult.RawResult);
File.AppendAllLines(errorFile, new List<string> { unkMsg });
Output(unkMsg);
break;
}
}
}
Output(string.Format("Scanning Complete. {0} Scanned | {1} Viruses Found | {2} Total Files", totalScans, totalViruses, totalCount));
}
}
catch (Exception ex)
{
string msg = string.Format("[{0}] Exception: {1}", DateTime.Now, ex.Message);
File.AppendAllLines(errorFile, new List<string> { msg });
Output(msg);
}
}
public static void Output(string message)
{
Console.WriteLine(message);
if (OutputEvent != null)
{
OutputEvent(message);
}
}
}
}

View File

@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Teknik Server Maintainence")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Teknik")]
[assembly: AssemblyProduct("Teknik")]
[assembly: AssemblyCopyright("Copyright © 2015 - 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("e08975f9-1b84-41b0-875a-cec9778c4f9e")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

View File

@ -0,0 +1,137 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" 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>{E08975F9-1B84-41B0-875A-CEC9778C4F9E}</ProjectGuid>
<OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>ServerMaint</RootNamespace>
<AssemblyName>ServerMaint</AssemblyName>
<TargetFrameworkVersion>v4.5.2</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<TargetFrameworkProfile />
<NuGetPackageImportStamp>
</NuGetPackageImportStamp>
<PublishUrl>publish\</PublishUrl>
<Install>true</Install>
<InstallFrom>Disk</InstallFrom>
<UpdateEnabled>false</UpdateEnabled>
<UpdateMode>Foreground</UpdateMode>
<UpdateInterval>7</UpdateInterval>
<UpdateIntervalUnits>Days</UpdateIntervalUnits>
<UpdatePeriodically>false</UpdatePeriodically>
<UpdateRequired>false</UpdateRequired>
<MapFileExtensions>true</MapFileExtensions>
<ApplicationRevision>0</ApplicationRevision>
<ApplicationVersion>1.0.0.%2a</ApplicationVersion>
<IsWebBootstrapper>false</IsWebBootstrapper>
<UseApplicationTrust>false</UseApplicationTrust>
<BootstrapperEnabled>true</BootstrapperEnabled>
</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>
<Prefer32Bit>false</Prefer32Bit>
</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>
<Prefer32Bit>false</Prefer32Bit>
</PropertyGroup>
<ItemGroup>
<Reference Include="BouncyCastle.Crypto, Version=1.7.4137.9688, Culture=neutral, PublicKeyToken=a4292a325f69b123, processorArchitecture=MSIL">
<HintPath>..\packages\BouncyCastle.1.7.0\lib\Net40-Client\BouncyCastle.Crypto.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, processorArchitecture=MSIL">
<HintPath>..\packages\EntityFramework.6.1.3\lib\net45\EntityFramework.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="EntityFramework.SqlServer, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, processorArchitecture=MSIL">
<HintPath>..\packages\EntityFramework.6.1.3\lib\net45\EntityFramework.SqlServer.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Microsoft.AspNet.Identity.Core, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.AspNet.Identity.Core.2.2.1\lib\net45\Microsoft.AspNet.Identity.Core.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Microsoft.AspNet.Identity.EntityFramework, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.AspNet.Identity.EntityFramework.2.2.1\lib\net45\Microsoft.AspNet.Identity.EntityFramework.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="nClam, Version=2.0.6.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\packages\nClam.2.0.6.0\lib\net40-Client\nClam.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Newtonsoft.Json, Version=8.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<HintPath>..\packages\Newtonsoft.Json.8.0.2\lib\net45\Newtonsoft.Json.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="SecurityDriven.Inferno, Version=1.1.0.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\packages\Inferno.1.1.0\lib\net451\SecurityDriven.Inferno.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="System" />
<Reference Include="System.ComponentModel.DataAnnotations" />
<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.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Teknik\Teknik.csproj">
<Project>{b20317cd-76c6-4a7b-bce1-e4bef8e4f964}</Project>
<Name>Teknik</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<None Include="app.config" />
<None Include="packages.config" />
</ItemGroup>
<ItemGroup>
<BootstrapperPackage Include=".NETFramework,Version=v4.5.2">
<Visible>False</Visible>
<ProductName>Microsoft .NET Framework 4.5.2 %28x86 and x64%29</ProductName>
<Install>true</Install>
</BootstrapperPackage>
<BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">
<Visible>False</Visible>
<ProductName>.NET Framework 3.5 SP1</ProductName>
<Install>false</Install>
</BootstrapperPackage>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<Import Project="..\packages\GitVersionTask.3.4.1\build\dotnet\GitVersionTask.targets" Condition="Exists('..\packages\GitVersionTask.3.4.1\build\dotnet\GitVersionTask.targets')" />
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup>
<ErrorText>This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
</PropertyGroup>
<Error Condition="!Exists('..\packages\GitVersionTask.3.4.1\build\dotnet\GitVersionTask.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\GitVersionTask.3.4.1\build\dotnet\GitVersionTask.targets'))" />
</Target>
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

33
ServerMaint/app.config Normal file
View File

@ -0,0 +1,33 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<connectionStrings configSource="ConnectionStrings.config" />
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
</startup>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-1.6.5135.21930" newVersion="1.6.5135.21930" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Antlr3.Runtime" publicKeyToken="eb42632606e9261f" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-3.5.0.2" newVersion="3.5.0.2" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-8.0.0.0" newVersion="8.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>

View File

@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="BouncyCastle" version="1.7.0" targetFramework="net452" />
<package id="EntityFramework" version="6.1.3" targetFramework="net452" />
<package id="GitVersionTask" version="3.4.1" targetFramework="net452" developmentDependency="true" />
<package id="Inferno" version="1.1.0" targetFramework="net452" />
<package id="Microsoft.AspNet.Identity.Core" version="2.2.1" targetFramework="net452" />
<package id="Microsoft.AspNet.Identity.EntityFramework" version="2.2.1" targetFramework="net452" />
<package id="nClam" version="2.0.6.0" targetFramework="net452" />
<package id="Newtonsoft.Json" version="8.0.2" targetFramework="net452" />
</packages>

View File

@ -1,7 +1,7 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 14
VisualStudioVersion = 14.0.24720.0
VisualStudioVersion = 14.0.25123.0
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Teknik", "Teknik\Teknik.csproj", "{B20317CD-76C6-4A7B-BCE1-E4BEF8E4F964}"
EndProject
@ -11,6 +11,8 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution
README.md = README.md
EndProjectSection
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ServerMaint", "ServerMaint\ServerMaint.csproj", "{E08975F9-1B84-41B0-875A-CEC9778C4F9E}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@ -28,6 +30,14 @@ Global
{B20317CD-76C6-4A7B-BCE1-E4BEF8E4F964}.Release|Any CPU.Build.0 = Release|Any CPU
{B20317CD-76C6-4A7B-BCE1-E4BEF8E4F964}.Release|x64.ActiveCfg = Release|x64
{B20317CD-76C6-4A7B-BCE1-E4BEF8E4F964}.Release|x64.Build.0 = Release|x64
{E08975F9-1B84-41B0-875A-CEC9778C4F9E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{E08975F9-1B84-41B0-875A-CEC9778C4F9E}.Debug|Any CPU.Build.0 = Debug|Any CPU
{E08975F9-1B84-41B0-875A-CEC9778C4F9E}.Debug|x64.ActiveCfg = Debug|Any CPU
{E08975F9-1B84-41B0-875A-CEC9778C4F9E}.Debug|x64.Build.0 = Debug|Any CPU
{E08975F9-1B84-41B0-875A-CEC9778C4F9E}.Release|Any CPU.ActiveCfg = Release|Any CPU
{E08975F9-1B84-41B0-875A-CEC9778C4F9E}.Release|Any CPU.Build.0 = Release|Any CPU
{E08975F9-1B84-41B0-875A-CEC9778C4F9E}.Release|x64.ActiveCfg = Release|Any CPU
{E08975F9-1B84-41B0-875A-CEC9778C4F9E}.Release|x64.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE

View File

@ -50,9 +50,20 @@ namespace Teknik.Areas.API.Controllers
// Scan the file to detect a virus
if (Config.UploadConfig.VirusScanEnable)
{
byte[] scanData = fileData;
// If it was encrypted client side, decrypt it
if (!encrypt && key != null)
{
// If the IV is set, and Key is set, then decrypt it
if (!string.IsNullOrEmpty(key) && !string.IsNullOrEmpty(iv))
{
// Decrypt the data
scanData = AES.Decrypt(scanData, key, iv);
}
}
ClamClient clam = new ClamClient(Config.UploadConfig.ClamServer, Config.UploadConfig.ClamPort);
clam.MaxStreamSize = Config.UploadConfig.MaxUploadSize;
ClamScanResult scanResult = clam.SendAndScanFile(fileData);
ClamScanResult scanResult = clam.SendAndScanFile(scanData);
switch (scanResult.Result)
{

View File

@ -63,9 +63,20 @@ namespace Teknik.Areas.Upload.Controllers
// Scan the file to detect a virus
if (Config.UploadConfig.VirusScanEnable)
{
byte[] scanData = fileData;
// If it was encrypted client side, decrypt it
if (!encrypt && key != null)
{
// If the IV is set, and Key is set, then decrypt it
if (!string.IsNullOrEmpty(key) && !string.IsNullOrEmpty(iv))
{
// Decrypt the data
scanData = AES.Decrypt(scanData, key, iv);
}
}
ClamClient clam = new ClamClient(Config.UploadConfig.ClamServer, Config.UploadConfig.ClamPort);
clam.MaxStreamSize = Config.UploadConfig.MaxUploadSize;
ClamScanResult scanResult = clam.SendAndScanFile(fileData);
ClamScanResult scanResult = clam.SendAndScanFile(scanData);
switch (scanResult.Result)
{

View File

@ -137,8 +137,13 @@ namespace Teknik.Configuration
public static Config Load()
{
Config config = new Config();
string path = AppDomain.CurrentDomain.GetData("DataDirectory").ToString();
return Load(path);
}
public static Config Load(string path)
{
Config config = new Config();
if (!File.Exists(Path.Combine(path, "Config.json")))
{
Save(Path.Combine(path, "Config.json"), config);