From 112345328ceedcbe4b8f5f670808db792717fc00 Mon Sep 17 00:00:00 2001 From: Avril Date: Sun, 1 Dec 2019 16:01:24 +0000 Subject: [PATCH] Initial commit --- .gitignore | 350 +++++++++++++++++++++++++++ libstenet.sln | 31 +++ libstenet/AES.cs | 129 ++++++++++ libstenet/EncryptedNetwork.cs | 436 ++++++++++++++++++++++++++++++++++ libstenet/Internal.cs | 192 +++++++++++++++ libstenet/RSA.cs | 117 +++++++++ libstenet/libstenet.csproj | 23 ++ test/Program.cs | 112 +++++++++ test/test.csproj | 12 + 9 files changed, 1402 insertions(+) create mode 100644 .gitignore create mode 100644 libstenet.sln create mode 100644 libstenet/AES.cs create mode 100644 libstenet/EncryptedNetwork.cs create mode 100644 libstenet/Internal.cs create mode 100644 libstenet/RSA.cs create mode 100644 libstenet/libstenet.csproj create mode 100644 test/Program.cs create mode 100644 test/test.csproj diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..fcb95d4 --- /dev/null +++ b/.gitignore @@ -0,0 +1,350 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ \ No newline at end of file diff --git a/libstenet.sln b/libstenet.sln new file mode 100644 index 0000000..585dddb --- /dev/null +++ b/libstenet.sln @@ -0,0 +1,31 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.29519.87 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "libstenet", "libstenet\libstenet.csproj", "{80064396-C3F3-4D92-9FCF-7C44B52DBC6E}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "test", "test\test.csproj", "{0C90F432-198A-45FD-A1A8-A14DFB47FE6B}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {80064396-C3F3-4D92-9FCF-7C44B52DBC6E}.Debug|Any CPU.ActiveCfg = Release|Any CPU + {80064396-C3F3-4D92-9FCF-7C44B52DBC6E}.Debug|Any CPU.Build.0 = Release|Any CPU + {80064396-C3F3-4D92-9FCF-7C44B52DBC6E}.Release|Any CPU.ActiveCfg = Release|Any CPU + {80064396-C3F3-4D92-9FCF-7C44B52DBC6E}.Release|Any CPU.Build.0 = Release|Any CPU + {0C90F432-198A-45FD-A1A8-A14DFB47FE6B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {0C90F432-198A-45FD-A1A8-A14DFB47FE6B}.Debug|Any CPU.Build.0 = Debug|Any CPU + {0C90F432-198A-45FD-A1A8-A14DFB47FE6B}.Release|Any CPU.ActiveCfg = Release|Any CPU + {0C90F432-198A-45FD-A1A8-A14DFB47FE6B}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {4BF5692D-8290-4789-A4FB-DDAE5062B36A} + EndGlobalSection +EndGlobal diff --git a/libstenet/AES.cs b/libstenet/AES.cs new file mode 100644 index 0000000..cc4e2c5 --- /dev/null +++ b/libstenet/AES.cs @@ -0,0 +1,129 @@ +using System; +using System.Collections.Generic; +using System.Runtime.InteropServices; +using System.Security.Cryptography; +using System.Text; + +namespace EncryptedNetwork +{ + public unsafe struct AESKey + { + public const int KeySize = 32; + public const int IVSize = 16; + + internal fixed byte key[KeySize]; + internal fixed byte iv[IVSize]; + + /// + /// The Key (256 bit) + /// + public byte[] Key + { + get + { + byte[] bytes = new byte[KeySize]; + fixed (byte* k = key) + { + Marshal.Copy((IntPtr)k, bytes, 0, KeySize); + } + return bytes; + } + set + { + if (value.Length != KeySize) throw new ArgumentException(nameof(value) + " must be exaclty " + KeySize + " bytes (not " + value.Length + ")"); + fixed (byte* k = key) + { + Marshal.Copy(value, 0, (IntPtr)k, KeySize); + } + } + } + + /// + /// The IV (128 bits) + /// + public byte[] IV + { + get + { + byte[] bytes = new byte[IVSize]; + fixed (byte* k = iv) + { + Marshal.Copy((IntPtr)k, bytes, 0, IVSize); + } + return bytes; + } + set + { + if (value.Length != IVSize) throw new ArgumentException(nameof(value) + " must be exaclty " + IVSize + " bytes (not " + value.Length + ")"); + fixed (byte* k = iv) + { + Marshal.Copy(value, 0, (IntPtr)k, IVSize); + } + } + } + + + /// + /// Binary serialisation of this key + /// + public byte[] BinaryData + { + get + { + return this.ToByteArrayUnmanaged(); + } + set + { + if (value.Length < sizeof(AESKey)) throw new ArgumentException(nameof(value) + " must be at least " + sizeof(AESKey) + " bytes (not " + value.Length + ")"); + fixed (AESKey* k = &this) + { + Marshal.Copy(value, 0, (IntPtr)k, sizeof(AESKey)); + } + } + } + + /// + /// Create a new key + /// + /// The new AES Key + public static AESKey NewKey() + { + RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider(); + byte[] buffer = new byte[sizeof(AESKey)]; + rng.GetBytes(buffer); + rng.Dispose(); + return buffer.ToStructureUnmanaged(); + } + + /// + /// Set the key and iv to an AesCryptoServiceProvider + /// + /// The CSP + public void ToCSP(AesCryptoServiceProvider r) + { + r.KeySize = 256; + r.BlockSize = 128; + + r.Key = Key; + r.IV = IV; + } + + /// + /// Get the key and iv from and AESCryptoServiceProvider + /// + /// The CSP + public void FromCSP(AesCryptoServiceProvider r) + { + Key = r.Key; + IV = r.IV; + } + /// + /// Initialise a new AESKey from an AESCryptoServiceProvider + /// + /// The AES key + public AESKey(AesCryptoServiceProvider aes) + { + FromCSP(aes); + } + } +} diff --git a/libstenet/EncryptedNetwork.cs b/libstenet/EncryptedNetwork.cs new file mode 100644 index 0000000..303efdb --- /dev/null +++ b/libstenet/EncryptedNetwork.cs @@ -0,0 +1,436 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.IO; +using System.Security.Cryptography; +using System.Net; +using System.Net.Sockets; +using System.Threading.Tasks; +using System.Threading; + +namespace EncryptedNetwork +{ + internal interface IEncryptedContainer + { + EncryptedNetworkStream Parent { get; } + + EncryptedNetworkStreamBlock WriteBlock(); + EncryptedNetworkStreamBlock ReadBlock(); + EncryptedNetworkStreamBlock ReadBlock(int msTimeout); + Task ReadBlockAsync(CancellationToken cancel); + Task ReadBlockAsync(); + } + /// + /// An encrypted block container for an . + /// + public abstract class EncryptedNetworkStreamBlock : BackedStream, IEncryptedContainer + { + internal EncryptedNetworkStreamBlock(Stream back) : base(back) { } + + /// + /// The EncryptedNetworkStream that owns this block. + /// + public abstract EncryptedNetworkStream Parent { get; } + + /// + /// Start a Read block synchronously with a milisecond timeout. + /// + /// The timeout + /// The new Read block. + public abstract EncryptedNetworkStreamBlock ReadBlock(int msTimeout); + /// + /// Start a Read block synchronously. + /// + /// The new Read block. + public abstract EncryptedNetworkStreamBlock ReadBlock(); + /// + /// Start a Write block. + /// + /// + public abstract EncryptedNetworkStreamBlock WriteBlock(); + + /// + /// Start a Read block asynchronously. + /// + /// Token for cancellation. + /// Awaitable Task for new Read block. + public async virtual Task ReadBlockAsync(CancellationToken cancel) + { + return await Task.Run(ReadBlock); + } + /// + /// Start a Read block asynchronously. + /// + /// Awaitable Task for new Read block. + public virtual Task ReadBlockAsync() => ReadBlockAsync(CancellationToken.None); + } + /// + /// Proveides RSA & AES cryptography wrapper over a . + /// + public class EncryptedNetworkStream : BackedStream, IEncryptedContainer + { + private class EncryptedReadBlock : EncryptedNetworkStreamBlock + { + private AesCryptoServiceProvider aes = null; + EncryptedNetworkStream ens; + public EncryptedReadBlock(BackedStream ens, IEncryptedContainer container) + : base(ens) + { + KeepBackingStreamAlive = true; + this.ens = container.Parent; + } + public override bool KeepBackingStreamAlive { get => true; set { if (!value) throw new NotSupportedException("Cannot set ReadBlock to dispose of its parent."); } } + + public override EncryptedNetworkStream Parent => ens; + + public async Task Initialise(CancellationToken cancel) + { + ens.ThrowIfNotExchanged(); + + aes = new AesCryptoServiceProvider(); + try + { + var len = (await backing.BlockingReadValueUnmanagedAsync(cancel)).NetOrd(); + if (len <= 0) + throw new ArgumentException("Invalid length read. ("+len+")"); + + byte[] by = new byte[len]; + await backing.BlockingReadAsync(by, 0, len, cancel); + + var decrypted = ens.you.Decrypt(by, false); + + var key = decrypted.ToStructureUnmanaged(); + key.ToCSP(aes); + } + catch(Exception ex) + { + aes.Dispose(); + aes = null; + throw ex; + } + } + + public override int Read(byte[] buffer, int offset, int count) + => ReadAsync(buffer, offset, count, CancellationToken.None).Sync(); + public override async Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) + { + static int roundUp(int numToRound, int multiple) + { + if (multiple == 0) + return numToRound; + + int remainder = Math.Abs(numToRound) % multiple; + if (remainder == 0) + return numToRound; + if (numToRound < 0) + return -(Math.Abs(numToRound) - remainder); + return numToRound + multiple - remainder; + } + + if (aes == null) + return await backing.ReadAsync(buffer, offset, count, cancellationToken); + else + { + byte[] byr = new byte[count % 16 == 0 ? count + 16 : roundUp(count, 16)]; + await backing.BlockingReadAsync(byr, 0, byr.Length, cancellationToken); + using (var dec = aes.CreateDecryptor()) + { + Array.Copy(dec.TransformFinalBlock(byr, 0, byr.Length), 0, buffer, offset, count); + return count; + } + } + + } + + public override void Write(byte[] buffer, int offset, int count) + => backing.Write(buffer, offset, count); + + public override EncryptedNetworkStreamBlock WriteBlock() + { + var w = new EncryptedWriteBlock(this, this); + w.Initialise(); + return w; + } + + public override EncryptedNetworkStreamBlock ReadBlock() + { + var r = new EncryptedReadBlock(this, this); + r.Initialise(CancellationToken.None).Sync(); + return r; + } + public override EncryptedNetworkStreamBlock ReadBlock(int msTimeout) + { + var r = new EncryptedReadBlock(this, this); + r.Initialise(CancellationToken.None).Sync(msTimeout); + return r; + } + public async override Task ReadBlockAsync(CancellationToken cancel) + { + var r = new EncryptedReadBlock(this, this); + await r.Initialise(cancel); + return r; + } + ~EncryptedReadBlock() { Dispose(false); aes = null; } + } + private class EncryptedWriteBlock : EncryptedNetworkStreamBlock + { + private AesCryptoServiceProvider aes = null; + EncryptedNetworkStream ens; + + public override EncryptedNetworkStream Parent => ens; + public override bool KeepBackingStreamAlive { get => true; set { if (!value) throw new NotSupportedException("Cannot set WriteBlock to dispose of its parent."); } } + + public EncryptedWriteBlock(BackedStream ens, IEncryptedContainer container) + : base(ens) + { + KeepBackingStreamAlive = true; + this.ens = container.Parent; + } + + public void Initialise() + { + ens.ThrowIfNotExchanged(); + + aes = new AesCryptoServiceProvider(); + + try + { + var key = AESKey.NewKey(); + key.ToCSP(aes); + + var encrypted = ens.them.Encrypt(key.ToByteArrayUnmanaged(), false); + var size = encrypted.Length.NetOrd(); + + backing.WriteValueUnmanaged(size); + backing.Write(encrypted, 0, encrypted.Length); + } + catch(Exception ex) + { + aes.Dispose(); + aes = null; + throw ex; + } + } + + protected override void Dispose(bool disposing) + { + base.Dispose(disposing); + aes.Dispose(); + } + + public override int Read(byte[] buffer, int offset, int count) + => backing.Read(buffer, offset, count); + + + public override void Write(byte[] buffer, int offset, int count) + { + if (aes == null) + backing.Write(buffer, offset, count); + else + { + using(var enc = aes.CreateEncryptor()) + { + var ebuf = enc.TransformFinalBlock(buffer, offset, count); + backing.Write(ebuf, 0, ebuf.Length); + } + } + } + + public override EncryptedNetworkStreamBlock WriteBlock() + { + var w = new EncryptedWriteBlock(this, this); + w.Initialise(); + return w; + } + + public override EncryptedNetworkStreamBlock ReadBlock() + { + var r = new EncryptedReadBlock(this, this); + r.Initialise(CancellationToken.None).Sync(); + return r; + } + public override EncryptedNetworkStreamBlock ReadBlock(int msTimeout) + { + var r = new EncryptedReadBlock(this, this); + r.Initialise(CancellationToken.None).Sync(msTimeout); + return r; + } + public async override Task ReadBlockAsync(CancellationToken cancel) + { + var r = new EncryptedReadBlock(this, this); + await r.Initialise(cancel); + return r; + } + ~EncryptedWriteBlock() { Dispose(false); aes = null; } + } + + private readonly RSACryptoServiceProvider you; + private RSACryptoServiceProvider them; + + /// + /// Your local RSA CSP (with both public and private keys.) + /// + public RSACryptoServiceProvider PrivateCSP => you; + /// + /// Your local RSA public key. + /// + public RSAPublicKey LocalPublicKey => RSAPublicKey.FromCSP(you); + /// + /// Remote endpoint's RSA public key. + /// + /// Thrown if RSA public keys have not been exchanged yet. + public RSAPublicKey RemotePublicKey => them == null ? throw ThrowNotYetExchangedException() : RSAPublicKey.FromCSP(them); + + private static ArgumentException ThrowNotYetExchangedException() => throw new ArgumentException("Keys not yet exchanged."); + private void ThrowIfNotExchanged() { if (!Exchanged) ThrowNotYetExchangedException(); } + + /// + /// Have RSA public keys been exchanged yet? + /// + public bool Exchanged => them != null; + + EncryptedNetworkStream IEncryptedContainer.Parent => this; + + /// + /// Initialise a new from a + /// + /// The Stream to set backing for. + /// Your local RSA CSP to use for private a public keys. + public EncryptedNetworkStream(NetworkStream stream, RSACryptoServiceProvider key) + :base(stream) + { + you = key; + } + /// + /// Initialise a new from a + /// + /// The Stream to set backing for. + public EncryptedNetworkStream(NetworkStream stream) : this(stream, new RSACryptoServiceProvider()) { } + /// + /// Initialise a new from a + /// + /// The Socket to set backing for. (NOTE: Closes the socket on dispose) + /// Your local RSA CSP to use for private a public keys. + public EncryptedNetworkStream(Socket sock, RSACryptoServiceProvider key) + : this(new NetworkStream(sock, true), key) { } + /// + /// Initialise a new from a + /// + /// The Socket to set backing for. (NOTE: Closes the socket on dispose) + public EncryptedNetworkStream(Socket sock) + : this(sock, new RSACryptoServiceProvider()) { } + + /// + /// Exchange the RSA public keys asynchronously. + /// + /// Awaitable Task that completes when the operation is successful. + public Task ExchangeAsync() => ExchangeAsync(CancellationToken.None); + /// + /// Exchange the RSA public keys asynchronously. + /// + /// Cancellation token. + /// Awaitable Task that completes when the operation is successful. + public async Task ExchangeAsync(CancellationToken cancel) + { + backing.WriteValueUnmanaged(LocalPublicKey); + + try + { + var pub = await backing.BlockingReadValueUnmanagedAsync(cancel); + + them??= new RSACryptoServiceProvider(); + pub.ToCSP(them); + } + catch (Exception ex) + { + them?.Dispose(); + them = null; + throw ex; + } + } + /// + /// Exchange RSA public keys synchronously with a milisecond timeout. + /// + /// The timout. + public void Exchange(int msTimeout) + => ExchangeAsync().Sync(msTimeout); + /// + /// Exchange RSA public keys synchronously. + /// + public void Exchange() + => ExchangeAsync().Sync(); + + protected override void Dispose(bool disposing) + { + base.Dispose(disposing); + } + + /// + /// Read unencrypted data from the backing stream. + /// + /// Buffer to read into. + /// Offset of buffer. + /// Number of bytes to read into buffer. + /// The number of bytes successfully read. + public override int Read(byte[] buffer, int offset, int count) + => backing.Read(buffer, offset, count); + /// + /// Write unencrypted data to the backing stream. + /// + /// Buffer to write from. + /// Offset of buffer. + /// Number of bytes to write from buffer. + public override void Write(byte[] buffer, int offset, int count) + => backing.Write(buffer, offset, count); + + /// + /// Create a new encrypted write block for this stream. + /// + /// The new WriteBlock. + public EncryptedNetworkStreamBlock WriteBlock() + { + var w = new EncryptedWriteBlock(this, this); + w.Initialise(); + return w; + } + + /// + /// Create a new encrypted read block for this stream synchronously. + /// + /// The new ReadBlock. + public EncryptedNetworkStreamBlock ReadBlock() + { + var r = new EncryptedReadBlock(this, this); + r.Initialise(CancellationToken.None).Sync(); + return r; + } + /// + /// Create a new encrypted read block for this stream synchronously with a milisecond timeout. + /// + /// The timeout. + /// The new ReadBlock. + public EncryptedNetworkStreamBlock ReadBlock(int msTimeout) + { + var r = new EncryptedReadBlock(this, this); + r.Initialise(CancellationToken.None).Sync(msTimeout); + return r; + } + + /// + /// Create a new encrypted read block for this stream asynchronously. + /// + /// Cancellation token. + /// Awaitable Task that completes and returns the new ReadBlock. + public async Task ReadBlockAsync(CancellationToken cancel) + { + var r = new EncryptedReadBlock(this, this); + await r.Initialise(cancel); + return r; + } + /// + /// Create a new encrypted read block for this stream asynchronously. + /// + /// Awaitable Task that completes and returns the new ReadBlock. + public Task ReadBlockAsync() => ReadBlockAsync(CancellationToken.None); + } +} diff --git a/libstenet/Internal.cs b/libstenet/Internal.cs new file mode 100644 index 0000000..61b7bd9 --- /dev/null +++ b/libstenet/Internal.cs @@ -0,0 +1,192 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Runtime.CompilerServices; +using System.Text; +using System.Threading.Tasks; + +namespace EncryptedNetwork +{ + /// + /// Provides a wrapper to override methods of a Stream + /// + public abstract class BackedStream : Stream + { + protected Stream backing; + /// + /// The Stream used as the backing + /// + public Stream Backing { get { return backing; } } + /// + /// Keep the backing stream alive after the class is disposed (default false) + /// + public virtual bool KeepBackingStreamAlive { get; set; } = false; + /// + /// Initialise an instance of the BackedStream class + /// + /// The initial Stream + public BackedStream(Stream s) + { + backing = s; + } + + protected override void Dispose(bool disposing) + { + if (disposing) + { + if (!KeepBackingStreamAlive) backing.Dispose(); + } + } + + #region Stream Overrides + public override bool CanRead + { + get { return Backing.CanRead; } + } + public override bool CanSeek + { + get { return Backing.CanSeek; } + } + public override bool CanWrite + { + get { return Backing.CanWrite; } + } + public override void Flush() + { + Backing.Flush(); + } + public override long Length + { + get { return Backing.Length; } + } + public override long Position + { + get + { + return Backing.Position; + } + set + { + Backing.Position = value; + } + } + public override long Seek(long offset, SeekOrigin origin) + { + return Backing.Seek(offset, origin); + } + public override void SetLength(long value) + { + Backing.SetLength(value); + } + #endregion + } + internal static class Extensions + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static unsafe void WriteValueUnmanaged(this Stream s, T t) where T : unmanaged + { + byte[] buffer = new byte[sizeof(T)]; + fixed (byte* ptr = buffer) + { + *(T*)ptr = t; + } + s.Write(buffer, 0, buffer.Length); + } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static unsafe T ReadValueUnmanaged(this Stream s) where T : unmanaged + { + T output; + byte[] buffer = new byte[sizeof(T)]; + s.Read(buffer, 0, buffer.Length); + + fixed (byte* ptr = buffer) + { + output = *(T*)ptr; + } + + return output; + } + + public static unsafe T SwapByteOrder(this T v) where T: unmanaged + { + Span b = new Span(&v, sizeof(T)); + b.Reverse(); + return v; + } + + /*public static unsafe T Little(this T v) where T : unmanaged + { + if (BitConverter.IsLittleEndian) return v; + else return v.SwapByteOrder(); + }*/ + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static unsafe T NetOrd(this T v) where T : unmanaged + { + if (!BitConverter.IsLittleEndian) return v; + else return v.SwapByteOrder(); + } + + public static T Sync(this Task task, int timeout) + { + task.Wait(timeout); + if (task.IsFaulted) + throw task.Exception; + return task.Result; + } + public static T Sync(this Task task) + { + task.Wait(); + if (task.IsFaulted) + throw task.Exception; + return task.Result; + } + public static void Sync(this Task task) + { + task.Wait(); + if (task.IsFaulted) + throw task.Exception; + } + public static void Sync(this Task task, int msTimeout) + { + task.Wait(msTimeout); + if (task.IsFaulted) + throw task.Exception; + } + + public static async Task BlockingReadValueUnmanagedAsync(this Stream s, System.Threading.CancellationToken? cancel) where T : unmanaged + { + int size; + unsafe + { + size = sizeof(T); + } + byte[] buffer = new byte[size]; + await s.BlockingReadAsync(buffer, 0, size, cancel); + + return buffer.ToStructureUnmanaged(); + } + public static async Task BlockingReadAsync(this Stream s, byte[] to, int offset, int length, System.Threading.CancellationToken? cancel) + { + int read = 0; + while ((read += await (cancel == null ? s.ReadAsync(to, offset + read, length - read) : s.ReadAsync(to, offset + read, length - read, cancel.Value))) < length) cancel?.ThrowIfCancellationRequested(); + } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static unsafe T ToStructureUnmanaged(this byte[] bytes) where T : unmanaged + { + fixed (byte* ptr = bytes) + { + return *(T*)ptr; + } + } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static unsafe byte[] ToByteArrayUnmanaged(this T t) where T : unmanaged + { + byte[] o = new byte[sizeof(T)]; + fixed (byte* ptr = o) + { + *(T*)ptr = t; + } + return o; + } + } +} diff --git a/libstenet/RSA.cs b/libstenet/RSA.cs new file mode 100644 index 0000000..dc8723a --- /dev/null +++ b/libstenet/RSA.cs @@ -0,0 +1,117 @@ +using System; +using System.Collections.Generic; +using System.Runtime.InteropServices; +using System.Security.Cryptography; +using System.Text; + +namespace EncryptedNetwork +{ + public unsafe struct RSAPublicKey + { + public const int ModulusSize = 128; + public const int ExponentSize = 3; + + internal fixed byte mod[ModulusSize]; + internal fixed byte exp[ExponentSize]; + + /// + /// The modulus of this key + /// + public byte[] Modulus + { + get + { + byte[] bytes = new byte[ModulusSize]; + fixed (byte* m = mod) + { + Marshal.Copy((IntPtr)m, bytes, 0, ModulusSize); + } + return bytes; + } + set + { + if (value.Length != ModulusSize) throw new ArgumentException(nameof(value) + " must be exaclty " + ModulusSize + " bytes (not " + value.Length + ")"); + fixed (byte* m = mod) + { + Marshal.Copy(value, 0, (IntPtr)m, ModulusSize); + } + } + } + /// + /// The public exponent of this key + /// + public byte[] Exponent + { + get + { + byte[] bytes = new byte[ExponentSize]; + fixed (byte* m = exp) + { + Marshal.Copy((IntPtr)m, bytes, 0, ExponentSize); + } + return bytes; + } + set + { + if (value.Length != ExponentSize) throw new ArgumentException(nameof(value) + " must be exaclty " + ExponentSize + " bytes (not " + value.Length + ")"); + fixed (byte* m = exp) + { + Marshal.Copy(value, 0, (IntPtr)m, ExponentSize); + } + } + } + + /// + /// Binary serialisation of this key + /// + public byte[] BinaryData + { + get + { + return this.ToByteArrayUnmanaged(); + } + set + { + if (value.Length < sizeof(RSAPublicKey)) throw new ArgumentException(nameof(value) + " must be at least " + sizeof(RSAPublicKey) + " bytes (not " + value.Length + ")"); + fixed (RSAPublicKey* k = &this) + { + Marshal.Copy(value, 0, (IntPtr)k, sizeof(RSAPublicKey)); + } + } + } + + /// + /// Set the public key to a RSACryptoServiceProvider + /// + /// The CSP to set the key to + public void ToCSP(RSACryptoServiceProvider csp) + { + var p = csp.ExportParameters(false); + p.Modulus = Modulus; + p.Exponent = Exponent; + csp.ImportParameters(p); + } + /// + /// Get the public key information from an RSACryptoServiceProvider and return it in an RSAPublicKey struct + /// + /// The CSP + /// A new RSAPublicKey struct + public static RSAPublicKey FromCSP(RSACryptoServiceProvider csp) + { + RSAPublicKey rp = new RSAPublicKey(); + var p = csp.ExportParameters(false); + rp.Modulus = p.Modulus; + rp.Exponent = p.Exponent; + return rp; + } + + public static implicit operator byte[](RSAPublicKey rp) + { + return rp.ToByteArrayUnmanaged(); + } + public static explicit operator RSAPublicKey(byte[] byt) + { + return byt.ToStructureUnmanaged(); + } + } +} diff --git a/libstenet/libstenet.csproj b/libstenet/libstenet.csproj new file mode 100644 index 0000000..324ae39 --- /dev/null +++ b/libstenet/libstenet.csproj @@ -0,0 +1,23 @@ + + + + netstandard2.1 + EncryptedNetwork + false + false + 3.0.0 + Avril + + Simple RSA & AES wrapper around NetworkStream + + + + true + true + + + + true + + + diff --git a/test/Program.cs b/test/Program.cs new file mode 100644 index 0000000..9c8a213 --- /dev/null +++ b/test/Program.cs @@ -0,0 +1,112 @@ +using System; +using EncryptedNetwork; +using System.Threading.Tasks; +using System.Net; +using System.Net.Sockets; +using System.IO; + +namespace test +{ + class Program + { + static async Task client() + { + try + { + Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); + await sock.ConnectAsync(new IPEndPoint(IPAddress.Loopback, 24444)); + + using (var ens = new EncryptedNetworkStream(sock)) + { + await ens.ExchangeAsync(); + + using(var read = await ens.ReadBlockAsync()) + { + Console.WriteLine(await read.ReadStringAsync()); + + + using (var write = read.WriteBlock()) + { + write.WriteString("World."); + } + } + } + } + catch(Exception ex) + { + Console.WriteLine("CLIENT: " + ex.Message); + } + } + static Task server() + { + return Task.Run(async () => + { + TcpListener listen = new TcpListener(24444); + listen.Start(); + + Task c = client(); + + while(true) + { + var sock = await listen.AcceptSocketAsync(); + + using(var ens = new EncryptedNetworkStream(sock)) + { + await ens.ExchangeAsync(); + + using(var write = ens.WriteBlock()) + { + write.WriteString("Hello"); + using (var read = await write.ReadBlockAsync()) + { + Console.WriteLine(await read.ReadStringAsync()); + } + } + } + + break; + } + listen.Stop(); + + await c; + }); + } + static void Main(string[] args) + { + var serv = server(); + serv.Wait(); + if (serv.IsFaulted) + Console.WriteLine("SERVER FAILED: " + serv.Exception.Message); + Console.ReadKey(); + } + } + + static class Extensions + { + public static void WriteString(this Stream stream, string str) + { + byte[] buf = System.Text.Encoding.UTF8.GetBytes(str); + + var l = buf.Length; + var num = BitConverter.GetBytes(l); + + stream.Write(num, 0, sizeof(int)); + stream.Write(buf, 0, buf.Length); + } + + public static async Task ReadStringAsync(this Stream stream) + { + byte[] num = new byte[sizeof(int)]; + + await stream.ReadAsync(num, 0, sizeof(int)); + + int l = BitConverter.ToInt32(num, 0); + if (l <= 0) throw new ArgumentException(l + " not valid length for string."); + + byte[] buf = new byte[l]; + await stream.ReadAsync(buf, 0, l); + + return System.Text.Encoding.UTF8.GetString(buf); + } + } +} diff --git a/test/test.csproj b/test/test.csproj new file mode 100644 index 0000000..76f602a --- /dev/null +++ b/test/test.csproj @@ -0,0 +1,12 @@ + + + + Exe + netcoreapp3.0 + + + + + + +