Ejemplo n.º 1
0
        public void Serialize()
        {
            var crypto = new RSACryptoServiceProvider();

            var p = new RSAAsymmetricKey(crypto.ExportCspBlob(true));

            byte[] buffer = new byte[20480];
            var    writer = new BufferValueWriter(buffer);

            p.Serialize(null, writer);
            int len = writer.Length;

            writer.Flush();

            var reader = new BufferValueReader(buffer);
            var key    = new RSAAsymmetricKey(null, reader);

            Assert.AreEqual(len, reader.Position);

            Assert.IsNull(key.D);
            Assert.IsNull(key.DP);
            Assert.IsNull(key.DQ);
            AssertArrayMatches(p.Exponent, key.Exponent);
            Assert.IsNull(key.InverseQ);
            AssertArrayMatches(p.Modulus, key.Modulus);
            Assert.IsNull(key.P);
            Assert.IsNull(key.Q);

            Assert.IsNotNull(key.PublicSignature);
        }
Ejemplo n.º 2
0
        public void ConnectedWithKey()
        {
            this.provider.Start(MessageTypes);

            RSAAsymmetricKey key = null;

            var test = new AsyncTest(e =>
            {
                var ce = (ConnectionMadeEventArgs)e;

                Assert.IsNotNull(ce.ClientPublicKey);
                Assert.AreEqual(key, ce.ClientPublicKey);
            });

            this.provider.ConnectionMade += test.PassHandler;

            var c = GetNewClientConnection(out key);

            if (key == null)
            {
                Assert.Ignore();
            }

            c.ConnectAsync(Target, MessageTypes);

            test.Assert(10000);
        }
Ejemplo n.º 3
0
        static void Main(string[] args)
        {
            Console.WriteLine("Getting server key...");

            RSAAsymmetricKey key = GetKey("server.key");

            Console.WriteLine("Got it.");

            var provider = new NetworkConnectionProvider(
                new[] { SocialProtocol.Instance },
                new Target(Target.AnyIP, 42912),
                10000,
                key);

            SocialServer server = new SocialServer(new MemoryWatchListProvider(), IdentityProvider);

            server.ConnectionMade += OnConnectionMade;
            server.AddConnectionProvider(provider);
            server.Start();

            Console.WriteLine("Server ready.");

            while (true)
            {
                Thread.Sleep(1000);
            }
        }
Ejemplo n.º 4
0
        public UdpConnectionProvider(int port, Protocol protocol, RSAAsymmetricKey authKey)
            : base(new[] { protocol }, port)
        {
            if (protocol == null)
            {
                throw new ArgumentNullException("protocol");
            }
            if (authKey == null)
            {
                throw new ArgumentNullException("authKey");
            }
            if (port <= 0)
            {
                throw new ArgumentOutOfRangeException("port");
            }

            this.crypto = new RSACrypto();
            this.crypto.ImportKey(authKey);

            this.pkEncryption = new RSACrypto();
            this.pkEncryption.ImportKey(authKey);

            this.authKey = authKey;

            ValidateProtocols(this.protocols.Values);
        }
Ejemplo n.º 5
0
        protected NetworkConnection(IEnumerable <Protocol> protocols, RSAAsymmetricKey authKey, bool generateKey)
        {
            if (protocols == null)
            {
                throw new ArgumentNullException("protocols");
            }

            this.authenticationKey = authKey;
            this.requiresHandshake = protocols.Any(p => p.id != 1 && p.RequiresHandshake);
            if (this.requiresHandshake)
            {
                ThreadPool.QueueUserWorkItem(s =>
                {
                    this.pkAuthentication = new RSACrypto();

                    if (this.authenticationKey == null)
                    {
                        if (generateKey)
                        {
                            this.publicAuthenticationKey = this.pkAuthentication.ExportKey(false);
                            this.authenticationKey       = this.pkAuthentication.ExportKey(true);
                        }
                    }
                    else
                    {
                        this.pkAuthentication.ImportKey(authKey);
                        this.publicAuthenticationKey = this.pkAuthentication.ExportKey(false);
                    }

                    this.authReady = true;
                });
            }

            this.protocols = new Dictionary <byte, Protocol>();
            foreach (Protocol p in protocols)
            {
                if (p == null)
                {
                    throw new ArgumentNullException("protocols", "protocols contains a null protocol");
                }
                if (this.protocols.ContainsKey(p.id))
                {
                    throw new ArgumentException("Only one version of a protocol may be specified");
                }

                this.protocols.Add(p.id, p);
            }

            this.protocols[1] = TempestMessage.InternalProtocol;

            //this.sendArgs.SetBuffer (new byte[1024], 0, 1024);
            //this.sendArgs.Completed += ReliableSendCompleted;

                        #if TRACE
            this.connectionId = Interlocked.Increment(ref nextConnectionId);
            this.typeName     = GetType().Name;
            Trace.WriteLineIf(NTrace.TraceVerbose, String.Empty, this.typeName + ":" + this.connectionId + " Ctor");
                        #endif
        }
Ejemplo n.º 6
0
 public UdpClientConnection(Protocol protocol, RSAAsymmetricKey key)
     : this(new[] { protocol }, key)
 {
     if (protocol == null)
     {
         throw new ArgumentNullException("protocol");
     }
 }
Ejemplo n.º 7
0
 internal UdpConnection(IEnumerable <Protocol> protocols, RSACrypto remoteCrypto, RSACrypto localCrypto, RSAAsymmetricKey localKey)
     : this(protocols)
 {
     this.remoteCrypto = remoteCrypto;
     this.localCrypto  = localCrypto;
     this.localCrypto.ImportKey(localKey);
     LocalKey = localKey;
 }
Ejemplo n.º 8
0
        static UdpConnectionProviderTests()
        {
            var crypto = new RSACrypto();
            serverKey = crypto.ExportKey (true);

            crypto = new RSACrypto();
            localKey = crypto.ExportKey (true);
        }
Ejemplo n.º 9
0
        protected override IClientConnection SetupClientConnection(out RSAAsymmetricKey k)
        {
            var c = new NetworkClientConnection(p);

            k = (RSAAsymmetricKey)c.LocalKey;

            return(c);
        }
Ejemplo n.º 10
0
        public GablarskiClient(RSAAsymmetricKey key)
        {
            if (key == null)
            {
                throw new ArgumentNullException("key");
            }

            Setup(new UdpClientConnection(GablarskiProtocol.Instance, key), null, null, null, null);
        }
        static UdpConnectionProviderTests()
        {
            var crypto = new RSACrypto();

            serverKey = crypto.ExportKey(true);

            crypto   = new RSACrypto();
            localKey = crypto.ExportKey(true);
        }
Ejemplo n.º 12
0
        public NetworkClientConnection(IEnumerable<Protocol> protocols, RSAAsymmetricKey authKey)
            : base(protocols, authKey, false)
        {
            if (NetworkConnection.AutoSizeSendBufferLimit)
                Interlocked.Add (ref sendBufferLimit, AutoSizeFactor);

            if (authKey == null)
                throw new ArgumentNullException ("authKey");
        }
Ejemplo n.º 13
0
        protected IClientConnection GetNewClientConnection(out RSAAsymmetricKey key)
        {
            var c = SetupClientConnection(out key);

            lock (this.connections)
                this.connections.Add(c);

            return(c);
        }
Ejemplo n.º 14
0
		public UdpClientConnection (IEnumerable<Protocol> protocols, RSAAsymmetricKey key)
			: base (protocols, new RSACrypto(), new RSACrypto(), key)
		{
			if (protocols == null)
				throw new ArgumentNullException ("protocols");
			if (key == null)
				throw new ArgumentNullException ("key");

			this.serializer = new ClientMessageSerializer (this, protocols);
		}
Ejemplo n.º 15
0
        public GablarskiSocialClient(Person person, RSAAsymmetricKey key)
            : base(new NetworkClientConnection(new [] { SocialProtocol.Instance, GablarskiProtocol.Instance }, key), person)
        {
            if (key == null)
            {
                throw new ArgumentNullException("key");
            }

            this.RegisterMessageHandler <JoinVoiceMessage> (OnJoinVoiceMessage);

            InvitedToGroup += (sender, args) => args.AcceptInvite = true;
        }
Ejemplo n.º 16
0
        public NetworkClientConnection(IEnumerable <Protocol> protocols, RSAAsymmetricKey authKey)
            : base(protocols, authKey, false)
        {
            if (NetworkConnection.AutoSizeSendBufferLimit)
            {
                Interlocked.Add(ref sendBufferLimit, AutoSizeFactor);
            }

            if (authKey == null)
            {
                throw new ArgumentNullException("authKey");
            }
        }
Ejemplo n.º 17
0
        protected override void Recycle()
        {
            if (AutoSizeSendBufferLimit)
            {
                Interlocked.Add(ref sendBufferLimit, AutoSizeFactor * -1);
            }

            this.serverEncryption        = null;
            this.serverEncryptionKey     = null;
            this.serverAuthenticationKey = null;

            base.Recycle();
        }
Ejemplo n.º 18
0
		internal UdpServerConnection (int connectionId, EndPoint remoteEndpoint, UdpConnectionProvider provider, RSACrypto remoteCrypto, RSACrypto localCrypto, RSAAsymmetricKey key)
			: base (provider.protocols.Values)
		{
			this.remoteCrypto = remoteCrypto;
			this.localCrypto = localCrypto;
			LocalKey = key;

			ConnectionId = connectionId;
			IPEndPoint = (IPEndPoint)remoteEndpoint;
			RemoteTarget = remoteEndpoint.ToTarget();
			this.provider = provider;

			this.socket = this.provider.GetSocket (remoteEndpoint);
		}
Ejemplo n.º 19
0
        public UdpClientConnection(IEnumerable <Protocol> protocols, RSAAsymmetricKey key)
            : base(protocols, new RSACrypto(), new RSACrypto(), key)
        {
            if (protocols == null)
            {
                throw new ArgumentNullException("protocols");
            }
            if (key == null)
            {
                throw new ArgumentNullException("key");
            }

            this.serializer = new ClientMessageSerializer(this, protocols);
        }
Ejemplo n.º 20
0
        internal UdpServerConnection(int connectionId, EndPoint remoteEndpoint, UdpConnectionProvider provider, RSACrypto remoteCrypto, RSACrypto localCrypto, RSAAsymmetricKey key)
            : base(provider.protocols.Values)
        {
            this.remoteCrypto = remoteCrypto;
            this.localCrypto = localCrypto;
            LocalKey = key;

            ConnectionId = connectionId;
            IPEndPoint = (IPEndPoint)remoteEndpoint;
            RemoteTarget = remoteEndpoint.ToTarget();
            this.provider = provider;

            this.socket = this.provider.GetSocket (remoteEndpoint);
        }
Ejemplo n.º 21
0
        static async Task SetupAsync()
        {
            var app = (AppDelegate)UIApplication.SharedApplication.Delegate;

            RSAAsymmetricKey key = await app.key.ConfigureAwait(false);

            string id     = key.PublicSignature.Aggregate(String.Empty, (s, b) => s + b.ToString("X2"));
            var    person = new Person(id)
            {
                Nickname = Settings.Nickname,
                Avatar   = Settings.Avatar,
                Status   = Status.Online
            };

            SocialClient = new GablarskiSocialClient(person, key);
            SocialClient.SetTarget(new Target("192.168.1.6", SocialProtocol.DefaultPort));
        }
Ejemplo n.º 22
0
        public void ImportPrivateCspBlob()
        {
            var           crypto = new RSACryptoServiceProvider();
            RSAParameters p      = crypto.ExportParameters(true);

            byte[] csp = crypto.ExportCspBlob(true);

            var key = new RSAAsymmetricKey(csp);

            AssertArrayMatches(p.D, key.D);
            AssertArrayMatches(p.DP, key.DP);
            AssertArrayMatches(p.DQ, key.DQ);
            AssertArrayMatches(p.Exponent, key.Exponent);
            AssertArrayMatches(p.InverseQ, key.InverseQ);
            AssertArrayMatches(p.Modulus, key.Modulus);
            AssertArrayMatches(p.P, key.P);
            AssertArrayMatches(p.Q, key.Q);

            Assert.IsNotNull(key.PublicSignature);
        }
Ejemplo n.º 23
0
        public UdpConnectionProvider(int port, Protocol protocol, RSAAsymmetricKey authKey)
            : base(new[] { protocol }, port)
        {
            if (protocol == null)
                throw new ArgumentNullException ("protocol");
            if (authKey == null)
                throw new ArgumentNullException ("authKey");
            if (port <= 0)
                throw new ArgumentOutOfRangeException ("port");

            this.crypto = new RSACrypto();
            this.crypto.ImportKey (authKey);

            this.pkEncryption = new RSACrypto();
            this.pkEncryption.ImportKey (authKey);

            this.authKey = authKey;

            ValidateProtocols (this.protocols.Values);
        }
Ejemplo n.º 24
0
        public static async Task <QueryResults> QueryAsync(RSAAsymmetricKey key, Target target, TimeSpan timeout)
        {
            if (key == null)
            {
                throw new ArgumentNullException("key");
            }
            if (target == null)
            {
                throw new ArgumentNullException("target");
            }

            var tcs = new TaskCompletionSource <QueryResults>();

            var connection = new UdpClientConnection(GablarskiProtocol.Instance, key);

            connection.Start(MessageTypes.Unreliable);

            var cancelSources = new CancellationTokenSource(timeout);

            cancelSources.Token.Register(() => {
                tcs.TrySetCanceled();
                connection.Dispose();
            });

            connection.ConnectionlessMessageReceived += (sender, args) => {
                var results = args.Message as QueryServerResultMessage;
                if (results == null)
                {
                    return;
                }

                tcs.TrySetResult(new QueryResults(results.ServerInfo, results.Channels, results.Users));

                connection.Dispose();
            };

            await connection.SendConnectionlessMessageAsync(new QueryServerMessage(), target).ConfigureAwait(false);

            return(await tcs.Task.ConfigureAwait(false));
        }
Ejemplo n.º 25
0
        protected override bool VerifyMessage(string hashAlg, Message message, byte[] signature, byte[] data, int moffset, int length)
        {
            if (HMAC == null)
            {
                var msg = (FinalConnectMessage)message;

                byte[] resized = new byte[length];
                Buffer.BlockCopy(data, moffset, resized, 0, length);

                RSAAsymmetricKey key = (RSAAsymmetricKey)Activator.CreateInstance(msg.PublicAuthenticationKeyType);
                key.Deserialize(new BufferValueReader(msg.PublicAuthenticationKey), this.connection.Encryption);

                this.connection.RemoteKey = key;
                this.connection.RemoteCrypto.ImportKey(key);

                return(this.connection.RemoteCrypto.VerifySignedHash(hashAlg, resized, signature));
            }
            else
            {
                return(base.VerifyMessage(hashAlg, message, signature, data, moffset, length));
            }
        }
Ejemplo n.º 26
0
        public UdpConnectionProvider(int port, IEnumerable <Protocol> protocols, RSAAsymmetricKey authKey)
            : base(protocols, port)
        {
            if (protocols == null)
            {
                throw new ArgumentNullException("protocols");
            }
            if (authKey == null)
            {
                throw new ArgumentNullException("authKey");
            }
            if (port <= 0)
            {
                throw new ArgumentOutOfRangeException("port");
            }

            this.crypto = new RSACrypto();
            this.crypto.ImportKey(authKey);
            this.authKey = authKey;

            ValidateProtocols(this.protocols.Values);
        }
Ejemplo n.º 27
0
        private static RSAAsymmetricKey GetKey(string keypath)
        {
            if (!File.Exists(keypath))
            {
                var           rsa        = new RSACrypto();
                RSAParameters parameters = rsa.ExportKey(true);

                using (var stream = File.OpenWrite(keypath)) {
                    var writer = new StreamValueWriter(stream);
                    RSAParametersSerializer.Serialize(writer, parameters);
                }
            }

            RSAAsymmetricKey key;

            using (var stream = File.OpenRead(keypath)) {
                var           reader     = new StreamValueReader(stream);
                RSAParameters parameters = RSAParametersSerializer.Deserialize(reader);
                key = new RSAAsymmetricKey(parameters);
            }

            return(key);
        }
Ejemplo n.º 28
0
        public static Task <RSAAsymmetricKey> GetCryptoKeyAsync(CancellationToken cancelToken = default(CancellationToken))
        {
            return(Task.Run(() => {
                RSAAsymmetricKey key = null;
                if (KeyFile.Exists)
                {
                    try {
                        using (var stream = File.OpenRead(KeyFile.FullName)) {
                            var reader = new StreamValueReader(stream);
                            RSAParameters parameters = RSAParametersSerializer.Deserialize(reader);
                            key = new RSAAsymmetricKey(parameters);
                        }
                    } catch (Exception ex) {
                        Trace.TraceWarning("Failed to read key: {0}", ex);
                        KeyFile.Delete();
                    }
                }

                cancelToken.ThrowIfCancellationRequested();

                if (!KeyFile.Exists)
                {
                    var rsa = new RSACrypto();
                    RSAParameters parameters = rsa.ExportKey(true);
                    key = new RSAAsymmetricKey(parameters);

                    cancelToken.ThrowIfCancellationRequested();

                    using (var stream = File.OpenWrite(KeyFile.FullName)) {
                        var writer = new StreamValueWriter(stream);
                        RSAParametersSerializer.Serialize(writer, parameters);
                    }
                }

                return key;
            }, cancelToken));
        }
Ejemplo n.º 29
0
        protected override IClientConnection SetupClientConnection(out RSAAsymmetricKey k)
        {
            var c = new NetworkClientConnection (p);
            k = (RSAAsymmetricKey) c.LocalKey;

            return c;
        }
Ejemplo n.º 30
0
        protected override void Recycle()
        {
            if (AutoSizeSendBufferLimit)
                Interlocked.Add (ref sendBufferLimit, AutoSizeFactor * -1);

            this.serverEncryption = null;
            this.serverEncryptionKey = null;
            this.serverAuthenticationKey = null;

            base.Recycle();
        }
Ejemplo n.º 31
0
        public NetworkConnectionProvider(IEnumerable<Protocol> protocols, Target target, int maxConnections, RSAAsymmetricKey authKey, IEnumerable<string> enabledHashAlgorithms = null)
            : this(protocols, target, maxConnections, enabledHashAlgorithms)
        {
            if (authKey == null)
                throw new ArgumentNullException ("authKey");

            this.authenticationKey = authKey;
        }
Ejemplo n.º 32
0
 protected override IClientConnection SetupClientConnection(out RSAAsymmetricKey key)
 {
     key = localKey;
     return SetupClientConnection();
 }
Ejemplo n.º 33
0
        protected override void OnTempestMessageReceived(MessageEventArgs e)
        {
            switch (e.Message.MessageType)
            {
                case (ushort)TempestMessageType.Ping:
                    var ping = (PingMessage)e.Message;
                    if (PingFrequency == 0 || this.activityTimer == null)
                    {
                        if (this.activityTimer != null)
                            this.activityTimer.Dispose();

                        if (ping.Interval != 0)
                        {
                            this.activityTimer = new Tempest.Timer (100);
                            this.activityTimer.TimesUp += OnActivityTimer;
                            this.activityTimer.Start();
                        }
                    }
                    else if (ping.Interval != PingFrequency)
                        this.activityTimer.Interval = ping.Interval;

                    base.OnTempestMessageReceived (e);
                    break;

                case (ushort)TempestMessageType.AcknowledgeConnect:
                    var msg = (AcknowledgeConnectMessage)e.Message;

                    this.protocols = this.protocols.Values.Intersect (msg.EnabledProtocols).ToDictionary (pr => pr.id);
                    ConnectionId = msg.ConnectionId;

                    this.serverEncryption = new RSACrypto();
                    this.serverEncryption.ImportKey (msg.PublicEncryptionKey);
                    this.serverEncryptionKey = msg.PublicEncryptionKey;

                    var encryption = new AesManaged { KeySize = 256 };
                    encryption.GenerateKey();

                    BufferValueWriter authKeyWriter = new BufferValueWriter (new byte[1600]);
                    this.publicAuthenticationKey.Serialize (authKeyWriter, this.serverEncryption);

                    this.serializer.AES = encryption;
                    this.serializer.HMAC = new HMACSHA256 (encryption.Key);

                    SendAsync (new FinalConnectMessage
                    {
                        AESKey = this.serverEncryption.Encrypt (encryption.Key),
                        PublicAuthenticationKeyType = this.publicAuthenticationKey.GetType(),
                        PublicAuthenticationKey = authKeyWriter.ToArray()
                    });

                    break;

                case (ushort)TempestMessageType.Connected:
                    var connected = (ConnectedMessage) e.Message;
                    ConnectionId = connected.ConnectionId;

                    OnConnected (new ClientConnectionEventArgs (this));

                    var tcs = Interlocked.Exchange (ref this.connectCompletion, null);
                    if (tcs != null)
                        tcs.TrySetResult (new ClientConnectionResult (ConnectionResult.Success, this.serverAuthenticationKey));

                    break;

                default:
                    base.OnTempestMessageReceived(e);
                    break;
            }
        }
Ejemplo n.º 34
0
 public static Task StartAsync(RSAAsymmetricKey key)
 {
     return(Task.Factory.StartNew(Start, key, TaskCreationOptions.HideScheduler));
 }
Ejemplo n.º 35
0
        protected override void OnTempestMessageReceived(MessageEventArgs e)
        {
            switch (e.Message.MessageType)
            {
            case (ushort)TempestMessageType.Ping:
                var ping = (PingMessage)e.Message;
                if (PingFrequency == 0 || this.activityTimer == null)
                {
                    if (this.activityTimer != null)
                    {
                        this.activityTimer.Dispose();
                    }

                    if (ping.Interval != 0)
                    {
                        this.activityTimer          = new Tempest.Timer(100);
                        this.activityTimer.TimesUp += OnActivityTimer;
                        this.activityTimer.Start();
                    }
                }
                else if (ping.Interval != PingFrequency)
                {
                    this.activityTimer.Interval = ping.Interval;
                }

                base.OnTempestMessageReceived(e);
                break;

            case (ushort)TempestMessageType.AcknowledgeConnect:
                var msg = (AcknowledgeConnectMessage)e.Message;

                this.protocols = this.protocols.Values.Intersect(msg.EnabledProtocols).ToDictionary(pr => pr.id);
                ConnectionId   = msg.ConnectionId;

                this.serverEncryption = new RSACrypto();
                this.serverEncryption.ImportKey((RSAAsymmetricKey)msg.PublicEncryptionKey);
                this.serverEncryptionKey = (RSAAsymmetricKey)msg.PublicEncryptionKey;

                var encryption = new AesManaged {
                    KeySize = 256
                };
                encryption.GenerateKey();

                BufferValueWriter authKeyWriter = new BufferValueWriter(new byte[1600]);
                this.publicAuthenticationKey.Serialize(this.serializer.SerializationContext, authKeyWriter, this.serverEncryption);

                this.serializer.AES  = encryption;
                this.serializer.HMAC = new HMACSHA256(encryption.Key);

                SendAsync(new FinalConnectMessage
                {
                    AESKey = this.serverEncryption.Encrypt(encryption.Key),
                    PublicAuthenticationKeyType = this.publicAuthenticationKey.GetType(),
                    PublicAuthenticationKey     = authKeyWriter.ToArray()
                });

                break;

            case (ushort)TempestMessageType.Connected:
                var connected = (ConnectedMessage)e.Message;
                ConnectionId = connected.ConnectionId;

                OnConnected(new ClientConnectionEventArgs(this));

                var tcs = Interlocked.Exchange(ref this.connectCompletion, null);
                if (tcs != null)
                {
                    tcs.SetResult(new ClientConnectionResult(ConnectionResult.Success, this.serverAuthenticationKey));
                }

                break;

            default:
                base.OnTempestMessageReceived(e);
                break;
            }
        }
Ejemplo n.º 36
0
		public UdpClientConnection (Protocol protocol, RSAAsymmetricKey key)
			: this (new[] { protocol }, key)
		{
			if (protocol == null)
				throw new ArgumentNullException ("protocol");
		}
 protected override IClientConnection SetupClientConnection(out RSAAsymmetricKey key)
 {
     key = localKey;
     return(SetupClientConnection());
 }
Ejemplo n.º 38
0
 static NetworkProviderTests()
 {
     var rsa = new RSACrypto();
     key = rsa.ExportKey (true);
 }
Ejemplo n.º 39
0
        public UdpConnectionProvider(int port, IEnumerable<Protocol> protocols, RSAAsymmetricKey authKey)
            : base(protocols, port)
        {
            if (protocols == null)
                throw new ArgumentNullException ("protocols");
            if (authKey == null)
                throw new ArgumentNullException ("authKey");
            if (port <= 0)
                throw new ArgumentOutOfRangeException ("port");

            this.crypto = new RSACrypto();
            this.crypto.ImportKey (authKey);
            this.authKey = authKey;

            ValidateProtocols (this.protocols.Values);
        }
Ejemplo n.º 40
0
        public static void Main()
        {
            Trace.Listeners.Add(new ConsoleTraceListener());

            log4net.Config.XmlConfigurator.Configure();

            var serverConfig = (BarrelConfiguration)ConfigurationManager.GetSection("barrel");

            if (serverConfig == null)
            {
                LogManager.GetLogger("Barrel").Fatal("Section 'barrel' not found in configuration.");
                return;
            }

            var log = LogManager.GetLogger(serverConfig.Name.Remove(" "));

            log.Info("Checking configuration");
            if (!serverConfig.CheckConfiguration(log))
            {
                log.Fatal("Errors found in configuration, shutting down.");
                return;
            }

            ServerProviders providers = serverConfig.GetProviders(log);

            if (providers == null)
            {
                log.Fatal("Errors loading server configuration, shutting down.");
                return;
            }

            log.Info("Setting up");

            GablarskiServer server = new GablarskiServer(new ServerSettings
            {
                Name           = serverConfig.Name,
                Description    = serverConfig.Description,
                ServerPassword = serverConfig.Password,
                ServerLogo     = serverConfig.LogoURL
            }, providers.Users, providers.Permissions, providers.Channels);

            if (serverConfig.Network)
            {
                var keyFile          = new FileInfo("server.key");
                RSAAsymmetricKey key = null;
                if (keyFile.Exists)
                {
                    try {
                        using (var stream = File.OpenRead(keyFile.FullName)) {
                            var           reader     = new StreamValueReader(stream);
                            RSAParameters parameters = RSAParametersSerializer.Deserialize(reader);
                            key = new RSAAsymmetricKey(parameters);
                        }
                    } catch (Exception ex) {
                        Trace.TraceWarning("Failed to read key: {0}", ex);
                        keyFile.Delete();
                    }
                }

                if (!keyFile.Exists)
                {
                    var           rsa        = new RSACrypto();
                    RSAParameters parameters = rsa.ExportKey(true);
                    key = new RSAAsymmetricKey(parameters);

                    using (var stream = File.OpenWrite(keyFile.FullName)) {
                        var writer = new StreamValueWriter(stream);
                        RSAParametersSerializer.Serialize(writer, parameters);
                    }
                }

                server.AddConnectionProvider(new UdpConnectionProvider(serverConfig.Port, GablarskiProtocol.Instance, key), ExecutionMode.GlobalOrder);
            }

            foreach (IConnectionProvider provider in providers.ConnectionProviders)
            {
                server.AddConnectionProvider(provider, ExecutionMode.GlobalOrder);
            }

            server.Start();

            log.Info("Server started");

            while (true)
            {
                Console.ReadKey();
            }
        }
Ejemplo n.º 41
0
        /// <summary>
        /// Initializes a new instance of the <see cref="NetworkConnectionProvider" /> class.
        /// </summary>
        /// <param name="target">The target to listen to.</param>
        /// <param name="maxConnections">Maximum number of connections to allow.</param>
        /// <param name="protocols">The protocols to accept.</param>
        /// <param name="enabledHashAlgs">
        /// The signature hash algorithms (in order of preference) to enable.
        /// <c>null</c> or an empty collection will enable all of the signature hash algorithms.
        /// </param>
        /// <exception cref="ArgumentNullException"><paramref name="target"/> or <paramref name="protocols" /> is <c>null</c>.</exception>
        /// <exception cref="ArgumentOutOfRangeException"><paramref name="maxConnections"/> is &lt;= 0</exception>
        public NetworkConnectionProvider(IEnumerable<Protocol> protocols, Target target, int maxConnections, IEnumerable<string> enabledHashAlgs = null)
        {
            if (protocols == null)
                throw new ArgumentNullException ("protocols");
            if (target == null)
                throw new ArgumentNullException ("target");
            if (maxConnections <= 0)
                throw new ArgumentOutOfRangeException ("maxConnections");

            this.protocols = protocols;
            this.target = target;
            MaxConnections = maxConnections;
            this.serverConnections = new List<NetworkServerConnection> (maxConnections);

            if (protocols.Any (p => p != null && p.RequiresHandshake))
            {
                ThreadPool.QueueUserWorkItem (s =>
                {
                    Task encryptKeyGen = Task.Factory.StartNew (() =>
                    {
                        this.pkEncryption = new RSACrypto();
                        this.publicEncryptionKey = this.pkEncryption.ExportKey (false);
                    });

                    Task authKeyGen = Task.Factory.StartNew (() =>
                    {
                        this.authentication = new RSACrypto();
                        if (this.authenticationKey == null)
                            this.authenticationKey = this.authentication.ExportKey (true);
                        else
                            this.authentication.ImportKey (this.authenticationKey);

                        this.publicAuthenticationKey = this.authentication.ExportKey (false);

                        if (enabledHashAlgs == null || !enabledHashAlgs.Any())
                            this.enabledHashAlgorithms.AddRange (this.authentication.SupportedHashAlgs);
                        else // Need to maintain preference order
                            this.enabledHashAlgorithms.AddRange (enabledHashAlgs.Where (a => this.authentication.SupportedHashAlgs.Contains (a)));
                    });

                    authKeyGen.Wait();
                    encryptKeyGen.Wait();

                    this.keyWait.Set();
                });
            }
            else
                this.keyWait.Set();
        }
Ejemplo n.º 42
0
 protected virtual IClientConnection SetupClientConnection(out RSAAsymmetricKey key)
 {
     key = null;
     return(SetupClientConnection());
 }
Ejemplo n.º 43
0
        public NetworkConnectionProvider(IEnumerable <Protocol> protocols, Target target, int maxConnections, RSAAsymmetricKey authKey, IEnumerable <string> enabledHashAlgorithms = null)
            : this(protocols, target, maxConnections, enabledHashAlgorithms)
        {
            if (authKey == null)
            {
                throw new ArgumentNullException("authKey");
            }

            this.authenticationKey = authKey;
        }
Ejemplo n.º 44
0
        static NetworkProviderTests()
        {
            var rsa = new RSACrypto();

            key = rsa.ExportKey(true);
        }