private static void Broadcast(string name, string message, NetConnection sender) { var connections = NetServer.Connections; if (sender != null) // Can set to null to send message to one that invoked broadcast method aswell. { connections.Remove(sender); } if (connections.Count > 0) { NetOutgoingMessage msg = NetServer.CreateMessage(); msg.Write(name); msg.Write(message); msg.Encrypt(new NetXtea("SuperSecretKey")); NetServer.SendMessage(msg, connections, NetDeliveryMethod.ReliableOrdered, 0); Console.WriteLine("Broadcasted message from " + name + ", containing the following message: " + message); } else { Console.WriteLine("No connections to send message to"); } }
/// <summary> /// TODO implement proper private/public key. is that even possible to do transperantly? /// </summary> /// <param name="recever"></param> /// <param name="message"></param> protected NetOutgoingMessage Encrypt(NetOutgoingMessage message) { NetEncryption algo = new NetXtea(NetPeerObject, "SharedKey45B635DF-649B-4C10-B110-439CE1784C59"); message.Encrypt(algo); return(message); }
public static NetOutgoingMessage Encrypt(string buffer) { NetOutgoingMessage om = Network.netClient.CreateMessage(buffer); om.Encrypt(Network.algo); return(om); }
public void Send(ProtoMessage message, bool encrypt = true) { NetOutgoingMessage msg = client.CreateMessage(); MemoryStream ms = new MemoryStream(); try { Serializer.SerializeWithLengthPrefix <ProtoMessage>(ms, message, ProtoBuf.PrefixStyle.Fixed32); msg.Write(ms.GetBuffer()); if (encryptionAlg != null && encrypt) { msg.Encrypt(encryptionAlg); } var result = client.SendMessage(msg, NetDeliveryMethod.ReliableOrdered); client.FlushSendQueue(); } catch (Exception e) { Debug.Log("Connected - remote hail message\n" + e.GetType() + "\n" + e.Message + "\n" + e.StackTrace); Exception inner; if (e.InnerException != null) { inner = e.InnerException; Debug.Log("Inner Exception:\n" + inner.GetType() + "\n" + inner.Message + "\n" + inner.StackTrace); } } }
private void SendMessage( NetOutgoingMessage message, LidgrenConnection connection, NetDeliveryMethod deliveryMethod, int sequenceChannel = 0 ) { if (message == null) { throw new ArgumentNullException(nameof(message)); } if (connection == null) { throw new ArgumentNullException(nameof(connection)); } if (connection.NetConnection == null) { throw new ArgumentNullException(nameof(connection.NetConnection)); } message.Encrypt(connection.Aes); connection.NetConnection.SendMessage(message, deliveryMethod, sequenceChannel); }
public void ResponseDiscovery(IPEndPoint recipient) { NetOutgoingMessage response = this._client.CreateMessage(); response.Write(NetworkSetting.ServerName); response.Encrypt(this._algo); this._client.SendDiscoveryResponse(response, recipient); }
public void SendMessage(byte[] msg, List <String> ipAddresses, bool reliable, bool inOrder) { // Test if any connections have been made to this machine, then send data if (clients.Count > 0) { // create new message to send to all clients NetOutgoingMessage om = netServer.CreateMessage(); om.Write(msg); if (enableEncryption) { om.Encrypt(xtea); } //Log.Write("Sending message: " + msg.ToString(), Log.LogLevel.Log); //Console.WriteLine("Sending message: " + ByteHelper.ConvertToString(msg)); NetDeliveryMethod deliverMethod = NetDeliveryMethod.Unreliable; int channel = sequenceChannel; if (reliable) { if (inOrder) { if (useSequencedInsteadOfOrdered) { deliverMethod = NetDeliveryMethod.ReliableSequenced; } else { deliverMethod = NetDeliveryMethod.ReliableOrdered; } } else { deliverMethod = NetDeliveryMethod.ReliableUnordered; channel = 0; } } else if (inOrder) { deliverMethod = NetDeliveryMethod.UnreliableSequenced; } List <NetConnection> recipients = new List <NetConnection>(); foreach (String ipAddress in ipAddresses) { if (clients.ContainsKey(ipAddress)) { recipients.Add(clients[ipAddress]); } } if (recipients.Count > 0) { netServer.SendMessage(om, recipients, deliverMethod, channel); } } }
public static void SendMessage(string msg, bool crypted) { NetOutgoingMessage om = netClient.CreateMessage(msg); if (crypted) { om.Encrypt(Network.algo); } netClient.SendMessage(om, NetDeliveryMethod.ReliableOrdered); netClient.FlushSendQueue(); CommonCode.historyCmd.Add("--> " + msg); }
public void SendMessage(NetOutgoingMessage msg, NetDeliveryMethod method) { msg.Encrypt(algo); if (IsTcp) { connection.SendBytes(msg.Data, msg.LengthBits, Hazel.SendOption.Reliable); GetClient().Recycle(msg); } else { GetClient().SendMessage(msg, method); } }
/// <summary> /// Send Message To Client /// </summary> /// <param name="msg">GameMessage</param> /// <param name="client">Client we want to send. Send to all connected client if it's null</param> public void SendMessage(GameMessage msg) { NetOutgoingMessage om = this._client.CreateMessage(); var b = SerializeTools.Serialize(msg); om.Write(b); om.Encrypt(this._algo); if (this._client.ConnectionStatus == NetConnectionStatus.Connected) { this._client.SendMessage(om, this._client.ServerConnection, NetDeliveryMethod.ReliableOrdered); } }
public static void SendViaProto(global::ProtoMessage.ProtoMessage m, NetConnection conn, bool isPCL, NetEncryption alg = null) { Contract.Requires(m != null && conn != null); NetOutgoingMessage msg = server.CreateMessage(); MemoryStream ms = new MemoryStream(); Serializer.SerializeWithLengthPrefix <global::ProtoMessage.ProtoMessage>(ms, m, PrefixStyle.Fixed32); msg.Write(ms.GetBuffer()); if (alg != null) { msg.Encrypt(alg); } server.SendMessage(msg, conn, NetDeliveryMethod.ReliableOrdered); server.FlushSendQueue(); }
public void SendMessage(byte[] msg, bool reliable, bool inOrder) { // subsequent input; send chat message to server // create a message NetOutgoingMessage om = netClient.CreateMessage(); om.Write(msg); if (enableEncryption) { om.Encrypt(xtea); } NetDeliveryMethod deliverMethod = NetDeliveryMethod.Unreliable; int channel = sequenceChannel; if (reliable) { if (inOrder) { if (useSequencedInsteadOfOrdered) { deliverMethod = NetDeliveryMethod.ReliableSequenced; } else { deliverMethod = NetDeliveryMethod.ReliableOrdered; } } else { deliverMethod = NetDeliveryMethod.ReliableUnordered; channel = 0; } } else if (inOrder) { deliverMethod = NetDeliveryMethod.UnreliableSequenced; } try { netClient.SendMessage(om, deliverMethod, sequenceChannel); } catch (SocketException se) { Log.Write("Socket exception is thrown in SendMessage: " + se.StackTrace); } }
/// <summary> /// Send Message To Client /// </summary> /// <param name="msg">GameMessage</param> /// <param name="client">Client we want to send. Send to all connected client if it's null</param> public void SendMessage(GameMessage msg, NetConnection client = null) { NetOutgoingMessage om = this._server.CreateMessage(); var b = SerializeTools.Serialize(msg); om.Write(b); om.Encrypt(this._algo); Console.ForegroundColor = ConsoleColor.Cyan; var clientId = client is null ? "All" : NetUtility.ToHexString(client.RemoteUniqueIdentifier); Console.WriteLine($" Send Message To {clientId}::MsgCode:{(Int32)msg.MsgCode},Content:{msg.Content}"); Console.ResetColor(); this._server.SendMessage(om, client, NetDeliveryMethod.ReliableOrdered); }
public void Send(ProtoMessage message, bool encrypt = true) { NetOutgoingMessage msg = client.CreateMessage(); MemoryStream ms = new MemoryStream(); try { Serializer.SerializeWithLengthPrefix <ProtoMessage>(ms, message, ProtoBuf.PrefixStyle.Fixed32); msg.Write(ms.GetBuffer()); if (alg != null && encrypt) { msg.Encrypt(alg); } var result = client.SendMessage(msg, NetDeliveryMethod.ReliableOrdered); client.FlushSendQueue(); } catch (Exception e) { } }
/// <summary> /// Sends a message by serializing with ProtoBufs /// </summary> /// <param name="m">Message to be sent</param> /// <param name="conn">Connection to send across</param> /// <param name="alg">Optional encryption algorithm</param> public static void SendViaProto(ProtoMessage m, NetConnection conn, NetEncryption alg = null) { Contract.Requires(m != null && conn != null); NetOutgoingMessage msg = server.CreateMessage(); MemoryStream ms = new MemoryStream(); Serializer.SerializeWithLengthPrefix <ProtoMessage>(ms, m, PrefixStyle.Fixed32); msg.Write(ms.GetBuffer()); if (alg != null) { msg.Encrypt(alg); } server.SendMessage(msg, conn, NetDeliveryMethod.ReliableOrdered); server.FlushSendQueue(); Globals_Server.logEvent("" + " Sending to: " + clientConnections[conn].username + " | ActionType = " + m.ActionType.ToString() + " | ResponseType = " + m.ResponseType.ToString() + " | " + conn.RemoteEndPoint.ToString() ); }
public void Send(ProtoMessage message, bool encrypt = true) { NetOutgoingMessage msg = client.CreateMessage(); MemoryStream ms = new MemoryStream(); try { //Serializer.SerializeWithLengthPrefix<ProtoMessage>(ms, message, ProtoBuf.PrefixStyle.Fixed32); Console.Write("Client: Sending"); msg.Write(ms.GetBuffer()); if (alg != null && encrypt) { Console.Write(" encrypted"); msg.Encrypt(alg); } var result = client.SendMessage(msg, NetDeliveryMethod.ReliableOrdered); Console.WriteLine(" message of type " + message.GetType() + " with Action: " + message.ActionType + " with result: " + result.ToString()); client.FlushSendQueue(); } catch (Exception e) { Console.WriteLine("CLIENT: Failed to serialise message!"); } }
public static void Run(NetPeer peer) { // // Test encryption // List <INetEncryption> algos = new List <INetEncryption>(); algos.Add(new NetXorEncryption("TopSecret")); algos.Add(new NetXtea("TopSecret")); algos.Add(new NetAESEncryption("TopSecret")); algos.Add(new NetRC2Encryption("TopSecret")); algos.Add(new NetDESEncryption("TopSecret")); algos.Add(new NetTripleDESEncryption("TopSecret")); foreach (var algo in algos) { NetOutgoingMessage om = peer.CreateMessage(); om.Write("Hallon"); om.Write(42); om.Write(5, 5); om.Write(true); om.Write("kokos"); int trueLen = om.LengthBits; om.Encrypt(algo); // convert to incoming message NetIncomingMessage im = Program.CreateIncomingMessage(om.PeekDataBuffer(), om.LengthBits); im.Decrypt(algo); if (im.LengthBits != trueLen) { throw new NetException("Length fail"); } if (im.ReadString() != "Hallon") { throw new NetException("fail"); } if (im.ReadInt32() != 42) { throw new NetException("fail"); } if (im.ReadInt32(5) != 5) { throw new NetException("fail"); } if (im.ReadBoolean() != true) { throw new NetException("fail"); } if (im.ReadString() != "kokos") { throw new NetException("fail"); } Console.WriteLine(algo.GetType().Name + " encryption verified"); } for (int i = 0; i < 100; i++) { byte[] salt = NetSRP.CreateRandomSalt(); byte[] x = NetSRP.ComputePrivateKey("user", "password", salt); byte[] v = NetSRP.ComputeServerVerifier(x); //Console.WriteLine("v = " + NetUtility.ToHexString(v)); byte[] a = NetSRP.CreateRandomEphemeral(); // NetUtility.ToByteArray("393ed364924a71ba7258633cc4854d655ca4ec4e8ba833eceaad2511e80db2b5"); byte[] A = NetSRP.ComputeClientEphemeral(a); //Console.WriteLine("A = " + NetUtility.ToHexString(A)); byte[] b = NetSRP.CreateRandomEphemeral(); // NetUtility.ToByteArray("cc4d87a90db91067d52e2778b802ca6f7d362490c4be294b21b4a57c71cf55a9"); byte[] B = NetSRP.ComputeServerEphemeral(b, v); //Console.WriteLine("B = " + NetUtility.ToHexString(B)); byte[] u = NetSRP.ComputeU(A, B); //Console.WriteLine("u = " + NetUtility.ToHexString(u)); byte[] Ss = NetSRP.ComputeServerSessionValue(A, v, u, b); //Console.WriteLine("Ss = " + NetUtility.ToHexString(Ss)); byte[] Sc = NetSRP.ComputeClientSessionValue(B, x, u, a); //Console.WriteLine("Sc = " + NetUtility.ToHexString(Sc)); if (Ss.Length != Sc.Length) { throw new NetException("SRP non matching lengths!"); } for (int j = 0; j < Ss.Length; j++) { if (Ss[j] != Sc[j]) { throw new NetException("SRP non matching session values!"); } } var test = NetSRP.CreateEncryption(Ss); } Console.WriteLine("Message encryption OK"); }
public void Listen() { while (server.Status == NetPeerStatus.Running && !ctSource.Token.IsCancellationRequested) { NetIncomingMessage im; WaitHandle.WaitAny(new WaitHandle[] { server.MessageReceivedEvent, ctSource.Token.WaitHandle }); while ((im = server.ReadMessage()) != null && !ctSource.Token.IsCancellationRequested) { if (im.SenderConnection != null) { Globals_Server.logEvent("Recieved: " + im.MessageType.ToString() + " | " + im.SenderConnection.RemoteEndPoint.ToString()); } else { Globals_Server.logEvent("Recieved: " + im.MessageType.ToString() + " | NULL"); } switch (im.MessageType) { case NetIncomingMessageType.DebugMessage: case NetIncomingMessageType.ErrorMessage: case NetIncomingMessageType.WarningMessage: Globals_Server.logError("Recieved warning message: " + im.ReadString()); break; case NetIncomingMessageType.VerboseDebugMessage: case NetIncomingMessageType.Data: { #if DEBUG //Console.WriteLine("SERVER: recieved data message"); #endif if (!clientConnections.ContainsKey(im.SenderConnection)) { //error im.SenderConnection.Disconnect("Not recognised"); return; } Client c = clientConnections[im.SenderConnection]; if (c.alg != null) { im.Decrypt(c.alg); } ProtoMessage m = null; using (MemoryStream ms = new MemoryStream(im.Data)) { try { m = Serializer.DeserializeWithLengthPrefix <ProtoMessage>(ms, PrefixStyle.Fixed32); } catch (Exception e) { NetOutgoingMessage errorMessage = server.CreateMessage( "Failed to deserialise message. The message may be incorrect, or the decryption may have failed."); if (c.alg != null) { errorMessage.Encrypt(c.alg); } server.SendMessage(errorMessage, im.SenderConnection, NetDeliveryMethod.ReliableOrdered); Globals_Server.logError("Failed to deserialize message for client: " + c.username); } } if (m == null) { string error = "Recieved null message from " + im.SenderEndPoint.ToString(); if (clientConnections.ContainsKey(im.SenderConnection)) { error += ", recognised client " + clientConnections[im.SenderConnection]; } else { error += ", unrecognised client (possible ping)"; } error += ". Data: " + im.ReadString(); Globals_Server.logError(error); break; } if (m.ActionType == Actions.LogIn) { ProtoLogIn login = m as ProtoLogIn; if (login == null) { im.SenderConnection.Disconnect("Received blank login message."); return; } lock (ServerLock) { if (LogInManager.VerifyUser(c.username, login.userSalt)) { if (LogInManager.ProcessLogIn(login, c)) { string log = c.username + " logs in from " + im.SenderEndPoint.ToString(); Globals_Server.logEvent(log); } } else { ProtoMessage reply = new ProtoMessage { ActionType = Actions.LogIn, ResponseType = DisplayMessages.LogInFail }; Server.SendViaProto(reply, c.conn, c.alg); //reply = new ProtoMessage { // ActionType = Actions.Update, // ResponseType = DisplayMessages.Error //}; //Server.SendViaProto(reply, c.conn, c.alg); im.SenderConnection.Disconnect("Authentication Fail"); Globals_Server.logEvent("Wrong Password, disconnecting user."); } } } // temp for testing, should validate connection first else if (clientConnections.ContainsKey(im.SenderConnection)) { if (Globals_Game.IsObserver(c)) { ProcessMessage(m, im.SenderConnection); ProtoClient clientDetails = new ProtoClient(c); clientDetails.ActionType = Actions.Update; clientDetails.ResponseType = DisplayMessages.Success; SendViaProto(clientDetails, im.SenderConnection, c.alg); } else { im.SenderConnection.Disconnect("Not logged in- Disconnecting"); } } } break; case NetIncomingMessageType.StatusChanged: byte stat = im.ReadByte(); NetConnectionStatus status = NetConnectionStatus.None; if (Enum.IsDefined(typeof(NetConnectionStatus), Convert.ToInt32(stat))) { status = (NetConnectionStatus)stat; } else { Globals_Server.logError("Failure to parse byte " + stat + " to NetConnectionStatus for endpoint " + im.ReadIPEndPoint()); } Globals_Server.logEvent("\tStatus is now: " + status); if (status == NetConnectionStatus.Disconnected) { string reason = im.ReadString(); if (reason == null) { reason = "Unknown"; } Globals_Server.logEvent(im.SenderConnection.RemoteEndPoint.ToString() + " has disconnected. Reason: " + reason); if (clientConnections.ContainsKey(im.SenderConnection)) { Disconnect(im.SenderConnection); } } break; case NetIncomingMessageType.ConnectionApproval: { string senderID = im.ReadString(); string text = im.ReadString(); Client client; Globals_Server.Clients.TryGetValue(senderID, out client); if (client != null) { ProtoLogIn logIn; //ProtoMessage logIn; if (!LogInManager.AcceptConnection(client, text, out logIn)) { im.SenderConnection.Deny("User not recognised."); } else { ProtoMessage temp = logIn; NetOutgoingMessage msg = server.CreateMessage(); MemoryStream ms = new MemoryStream(); // Include X509 certificate as bytes for client to validate //Serializer.SerializeWithLengthPrefix<ProtoLogIn>(ms, logIn, PrefixStyle.Fixed32); Serializer.SerializeWithLengthPrefix <ProtoMessage>(ms, temp, PrefixStyle.Fixed32); msg.Write(ms.GetBuffer()); clientConnections.Add(im.SenderConnection, client); client.conn = im.SenderConnection; im.SenderConnection.Approve(msg); //server.FlushSendQueue(); Globals_Server.logEvent("Accepted connection from " + client.username + " | " + senderID + " | " + text); } } else { im.SenderConnection.Deny("Username unrecognised."); } server.FlushSendQueue(); } break; case NetIncomingMessageType.ConnectionLatencyUpdated: Globals_Server.logEvent("LATENCY: Still getting these."); break; default: Globals_Server.logError("Received unrecognised incoming message type: " + im.MessageType); break; } server.Recycle(im); } } Globals_Server.logEvent("Server listening thread exits."); }
public void BroadcastMessage(byte[] msg, bool reliable, bool inOrder, bool excludeSender) { // Test if any connections have been made to this machine, then send data if (clients.Count > 0) { // create new message to send to all clients NetOutgoingMessage om = netServer.CreateMessage(); om.Write(msg); if (enableEncryption) { om.Encrypt(xtea); } //Log.Write("Sending message: " + msg.ToString(), Log.LogLevel.Log); //Console.WriteLine("Sending message: " + ByteHelper.ConvertToString(msg)); NetDeliveryMethod deliverMethod = NetDeliveryMethod.Unreliable; int channel = sequenceChannel; if (reliable) { if (inOrder) { if (useSequencedInsteadOfOrdered) { deliverMethod = NetDeliveryMethod.ReliableSequenced; } else { deliverMethod = NetDeliveryMethod.ReliableOrdered; } } else { deliverMethod = NetDeliveryMethod.ReliableUnordered; channel = 0; } } else if (inOrder) { deliverMethod = NetDeliveryMethod.UnreliableSequenced; } // broadcast the message in order if (excludeSender && (prevSender != null)) { // if there is only one connection, then the sender to be excluded is // the only connection the server has, so there is no point to broadcast if (clients.Count > 1) { List <NetConnection> recepients = new List <NetConnection>( clients.Values); recepients.Remove(prevSender); netServer.SendMessage(om, recepients, deliverMethod, channel); } } else { netServer.SendMessage(om, clientList, deliverMethod, channel); } } }
static void Update() { string serverStringBuffer = String.Empty; NetIncomingMessage msg; while ((msg = server.ReadMessage()) != null) { long senderUid = msg.SenderConnection == null ? 0 : msg.SenderConnection.RemoteUniqueIdentifier; string senderIpAddress = msg.SenderEndpoint.Address.ToString(); msg.Decrypt(algo); switch (msg.MessageType) { case NetIncomingMessageType.VerboseDebugMessage: case NetIncomingMessageType.DebugMessage: case NetIncomingMessageType.WarningMessage: case NetIncomingMessageType.ErrorMessage: Console.WriteLine(msg.ReadString()); break; case NetIncomingMessageType.Data: string dataString = msg.ReadString(); if (dataString.StartsWith("/")) { // Don't show this message to client, but still want it in console Console.WriteLine(uidNameMap[senderUid] + ": " + dataString); string[] commands = dataString.Remove(0, 1).Split(' '); serverStringBuffer += ProcessCommands(commands, msg.SenderConnection); } else { serverStringBuffer += uidNameMap[senderUid] + ": " + dataString + Environment.NewLine; } break; case NetIncomingMessageType.StatusChanged: serverStringBuffer += "User status changed: " + senderIpAddress + " " + (uidNameMap.ContainsKey(senderUid) ? uidNameMap[senderUid] + " " : "") + msg.SenderConnection.Status + Environment.NewLine; // If the status is connected, check the UID map if (msg.SenderConnection.Status == NetConnectionStatus.Connected && !uidNameMap.ContainsKey(senderUid)) { // add user uid to uidmap UpdateUIDMap(senderUid, senderUid.ToString()); NetOutgoingMessage nameSetMsg = server.CreateMessage(); nameSetMsg.Write(welcomeStr + Environment.NewLine); nameSetMsg.Encrypt(algo); server.SendMessage(nameSetMsg, msg.SenderConnection, NetDeliveryMethod.ReliableOrdered); } // If user is disconnecting, remove his uid in map if (msg.SenderConnection.Status == NetConnectionStatus.Disconnected) { uidNameMap.Remove(msg.SenderConnection.RemoteUniqueIdentifier); } break; default: Console.WriteLine("Unhandled type: " + msg.MessageType + "; Read string: " + msg.ReadString()); break; } server.Recycle(msg); // Display content of server string buffer on screen Console.Write(serverStringBuffer); // Send to all clients NetOutgoingMessage outMsg = server.CreateMessage(); outMsg.Write(serverStringBuffer); outMsg.Encrypt(algo); server.SendToAll(outMsg, NetDeliveryMethod.ReliableOrdered); } }
public static void Run(NetPeer peer) { // // Test XTEA // NetXtea xtea = new NetXtea("TopSecret"); byte[] original = new byte[16]; NetRandom.Instance.NextBytes(original); byte[] encrypted = new byte[original.Length]; xtea.EncryptBlock(original, 0, encrypted, 0); xtea.EncryptBlock(original, 8, encrypted, 8); byte[] decrypted = new byte[original.Length]; xtea.DecryptBlock(encrypted, 0, decrypted, 0); xtea.DecryptBlock(encrypted, 8, decrypted, 8); // compare! for (int i = 0; i < original.Length; i++) { if (original[i] != decrypted[i]) { throw new NetException("XTEA fail!"); } } Console.WriteLine("XTEA OK"); NetOutgoingMessage om = peer.CreateMessage(); om.Write("Hallon"); om.Write(42); om.Write(5, 5); om.Write(true); om.Write("kokos"); om.Encrypt(xtea); // convert to incoming message NetIncomingMessage im = Program.CreateIncomingMessage(om.PeekDataBuffer(), om.LengthBits); im.Decrypt(xtea); if (im.ReadString() != "Hallon") { throw new NetException("fail"); } if (im.ReadInt32() != 42) { throw new NetException("fail"); } if (im.ReadInt32(5) != 5) { throw new NetException("fail"); } if (im.ReadBoolean() != true) { throw new NetException("fail"); } if (im.ReadString() != "kokos") { throw new NetException("fail"); } for (int i = 0; i < 100; i++) { byte[] salt = NetSRP.CreateRandomSalt(); byte[] x = NetSRP.ComputePrivateKey("user", "password", salt); byte[] v = NetSRP.ComputeServerVerifier(x); //Console.WriteLine("v = " + NetUtility.ToHexString(v)); byte[] a = NetSRP.CreateRandomEphemeral(); // NetUtility.ToByteArray("393ed364924a71ba7258633cc4854d655ca4ec4e8ba833eceaad2511e80db2b5"); byte[] A = NetSRP.ComputeClientEphemeral(a); //Console.WriteLine("A = " + NetUtility.ToHexString(A)); byte[] b = NetSRP.CreateRandomEphemeral(); // NetUtility.ToByteArray("cc4d87a90db91067d52e2778b802ca6f7d362490c4be294b21b4a57c71cf55a9"); byte[] B = NetSRP.ComputeServerEphemeral(b, v); //Console.WriteLine("B = " + NetUtility.ToHexString(B)); byte[] u = NetSRP.ComputeU(A, B); //Console.WriteLine("u = " + NetUtility.ToHexString(u)); byte[] Ss = NetSRP.ComputeServerSessionValue(A, v, u, b); //Console.WriteLine("Ss = " + NetUtility.ToHexString(Ss)); byte[] Sc = NetSRP.ComputeClientSessionValue(B, x, u, a); //Console.WriteLine("Sc = " + NetUtility.ToHexString(Sc)); if (Ss.Length != Sc.Length) { throw new NetException("SRP non matching lengths!"); } for (int j = 0; j < Ss.Length; j++) { if (Ss[j] != Sc[j]) { throw new NetException("SRP non matching session values!"); } } var test = NetSRP.CreateEncryption(Ss); } Console.WriteLine("Message encryption OK"); }
static string ProcessCommands(string[] commands, NetConnection sender) { try { string stringBuffer = String.Empty; string messageToSender = String.Empty; NetOutgoingMessage outMsg = server.CreateMessage(); if (commands.Length > 1 && commands[0] == "nick") { string nickName = commands[1]; if (!String.IsNullOrWhiteSpace(nickName)) { UpdateUIDMap(sender.RemoteUniqueIdentifier, nickName); stringBuffer += sender.RemoteUniqueIdentifier + " (" + sender.RemoteEndpoint.Address + ")" + " has changed name to " + uidNameMap[sender.RemoteUniqueIdentifier] + Environment.NewLine; } } else if (commands.Length > 2 && commands[0] == "random") { int min, max; if (Int32.TryParse(commands[1], out min) && Int32.TryParse(commands[2], out max)) { stringBuffer += "Random number generated between " + min + " and " + max + ": " + rnd.Next(min, max) + Environment.NewLine; } } else if (commands.Length > 0 && commands[0] == "random") { stringBuffer += "Random number generated: " + rnd.Next() + Environment.NewLine; } else if (commands.Length > 2 && commands[0] == "kick") { // kicks a user with UID if (commands[2] == adminCode) { foreach (NetConnection connection in server.Connections) { if (connection.RemoteUniqueIdentifier.ToString() == commands[1]) { //connection.Deny("kicked"); connection.Disconnect("kicked"); stringBuffer += uidNameMap[connection.RemoteUniqueIdentifier] + " has been kicked by " + uidNameMap[sender.RemoteUniqueIdentifier] + Environment.NewLine; break; } } } } else if (commands.Length > 1 && commands[0] == "real") { foreach (NetConnection connection in server.Connections) { string nick = uidNameMap[connection.RemoteUniqueIdentifier]; if (nick == commands[1]) { messageToSender += "===== QUERY RESULT =====" + Environment.NewLine + "UID: " + connection.RemoteUniqueIdentifier + Environment.NewLine + "Nick: " + nick + Environment.NewLine + "IP: " + connection.RemoteEndpoint.Address + Environment.NewLine + "Port: " + connection.RemoteEndpoint.Port + Environment.NewLine + "===== END OF RESULT =====" + Environment.NewLine; } } } else if (commands.Length > 0 && commands[0] == "list") { messageToSender += "===== ONLINE USERS =====" + Environment.NewLine; foreach (NetConnection connection in server.Connections) { long uid = connection.RemoteUniqueIdentifier; messageToSender += uid + ": " + uidNameMap[uid] + Environment.NewLine; } messageToSender += "TOTAL: " + server.ConnectionsCount + Environment.NewLine + "===== END OF QUERY =====" + Environment.NewLine; } // send a message to sender, if messageToSender is not empty if (!String.IsNullOrEmpty(messageToSender)) { outMsg.Write(messageToSender); outMsg.Encrypt(algo); server.SendMessage(outMsg, sender, NetDeliveryMethod.ReliableOrdered); } return(stringBuffer); } catch (Exception exc) { Console.WriteLine("Error on command " + commands + " sent by " + sender.RemoteUniqueIdentifier + Environment.NewLine + exc.ToString()); return(String.Empty); } }
/// <summary> /// Sends a message /// </summary> /// <param name="msg">The message to send</param> /// <param name="method">The delivery method</param> /// <param name="sequenceChannel">The sequence channel</param> public void SendMessage(NetOutgoingMessage msg, NetDeliveryMethod method, Int32 sequenceChannel) { msg.Encrypt(_netEncryption); NetConnection.SendMessage(msg, method, sequenceChannel); }
public void Listen() { while (server.Status == NetPeerStatus.Running && !ctSource.Token.IsCancellationRequested) { NetIncomingMessage im; WaitHandle.WaitAny(new WaitHandle[] { server.MessageReceivedEvent, ctSource.Token.WaitHandle }); while ((im = server.ReadMessage()) != null && !ctSource.Token.IsCancellationRequested) { switch (im.MessageType) { case NetIncomingMessageType.DebugMessage: case NetIncomingMessageType.ErrorMessage: case NetIncomingMessageType.WarningMessage: Globals_Server.logError("Recieved warning message: " + im.ReadString()); break; case NetIncomingMessageType.VerboseDebugMessage: case NetIncomingMessageType.Data: { #if DEBUG Console.WriteLine("SERVER: recieved data message"); #endif if (!clientConnections.ContainsKey(im.SenderConnection)) { //error im.SenderConnection.Disconnect("Not recognised"); return; } Client c = clientConnections[im.SenderConnection]; if (c.alg != null) { im.Decrypt(c.alg); } ProtoMessage m = null; //global::ProtoMessage.ProtoMessage y = null; using (MemoryStream ms = new MemoryStream(im.Data)) { try { //y = Serializer.DeserializeWithLengthPrefix<global::ProtoMessage.ProtoMessage>(ms, //PrefixStyle.Fixed32); m = Serializer.DeserializeWithLengthPrefix <ProtoMessage>(ms, PrefixStyle.Fixed32); } catch (Exception e) { NetOutgoingMessage errorMessage = server.CreateMessage( "Failed to deserialise message. The message may be incorrect, or the decryption may have failed."); if (c.alg != null) { errorMessage.Encrypt(c.alg); } server.SendMessage(errorMessage, im.SenderConnection, NetDeliveryMethod.ReliableOrdered); Globals_Server.logError("Failed to deserialize message for client: " + c.username); } } if (m == null /*&& y == null*/) { string error = "Recieved null message from " + im.SenderEndPoint.ToString(); if (clientConnections.ContainsKey(im.SenderConnection)) { error += ", recognised client " + clientConnections[im.SenderConnection]; } else { error += ", unrecognised client (possible ping)"; } error += ". Data: " + im.ReadString(); Globals_Server.logError(error); break; } if (m.ActionType == Actions.LogIn) { ProtoLogIn login = m as ProtoLogIn; if (login == null) { im.SenderConnection.Disconnect("Not login"); return; } lock (ServerLock) { if (LogInManager.VerifyUser(c.username, login.userSalt)) { if (LogInManager.ProcessLogIn(login, c)) { string log = c.username + " logs in from " + im.SenderEndPoint.ToString(); Globals_Server.logEvent(log); } } else { ProtoMessage reply = new ProtoMessage { ActionType = Actions.LogIn, ResponseType = DisplayMessages.LogInFail }; im.SenderConnection.Disconnect("Authentication Fail"); } } } // temp for testing, should validate connection first else if (clientConnections.ContainsKey(im.SenderConnection)) { if (Globals_Game.IsObserver(c)) { ProcessMessage(m, im.SenderConnection); ProtoClient clientDetails = new ProtoClient(c); clientDetails.ActionType = Actions.Update; SendViaProto(clientDetails, im.SenderConnection, c.alg); } else { im.SenderConnection.Disconnect("Not logged in- Disconnecting"); } } /*//IF Y ACTION * if (y.ActionType == global::ProtoMessage.Actions.LogIn) * { * global::ProtoMessage.Client forCheck = new global::ProtoMessage.Client(c.username, c.myPlayerCharacter.playerID); * global::ProtoMessage.ProtoLogIn login = y as global::ProtoMessage.ProtoLogIn; * if (login == null) * { * im.SenderConnection.Disconnect("Not login"); * return; * } * lock (ServerLock) * { * if (LogInManager.VerifyUser(c.username, login.userSalt)) * { * if (LogInManager.ProcessLogIn(login, forCheck, true)) * { * string log = c.username + " logs in from " + im.SenderEndPoint.ToString(); * Globals_Server.logEvent(log); * } * } * else * { * ProtoMessage reply = new ProtoMessage * { * ActionType = Actions.LogIn, * ResponseType = DisplayMessages.LogInFail * }; * im.SenderConnection.Disconnect("Authentication Fail"); * } * } * } * // temp for testing, should validate connection first * else if (clientConnections.ContainsKey(im.SenderConnection)) * { * if (Globals_Game.IsObserver(c)) * { * ProcessMessage(y, im.SenderConnection); * ProtoClient clientDetails = new ProtoClient(c); * clientDetails.ActionType = Actions.Update; * SendViaProto(clientDetails, im.SenderConnection, c.alg); * } * else * { * im.SenderConnection.Disconnect("Not logged in- Disconnecting"); * } * }*/ } break; case NetIncomingMessageType.StatusChanged: byte stat = im.ReadByte(); NetConnectionStatus status = NetConnectionStatus.None; if (Enum.IsDefined(typeof(NetConnectionStatus), Convert.ToInt32(stat))) { status = (NetConnectionStatus)stat; } else { Globals_Server.logError("Failure to parse byte " + stat + " to NetConnectionStatus for endpoint " + im.ReadIPEndPoint()); } if (status == NetConnectionStatus.Disconnected) { if (clientConnections.ContainsKey(im.SenderConnection)) { Disconnect(im.SenderConnection); } } break; case NetIncomingMessageType.ConnectionApproval: { string senderID = im.ReadString(); string text = im.ReadString(); Client client; Globals_Server.Clients.TryGetValue(senderID, out client); if (client != null) { ProtoLogIn logIn; if (!LogInManager.AcceptConnection(client, text, out logIn)) { im.SenderConnection.Deny(); } else { NetOutgoingMessage msg = server.CreateMessage(); MemoryStream ms = new MemoryStream(); // Include X509 certificate as bytes for client to validate Serializer.SerializeWithLengthPrefix <ProtoLogIn>(ms, logIn, PrefixStyle.Fixed32); msg.Write(ms.GetBuffer()); clientConnections.Add(im.SenderConnection, client); client.conn = im.SenderConnection; im.SenderConnection.Approve(msg); server.FlushSendQueue(); Globals_Server.logEvent("Accepted connection from " + client.username); } } else { im.SenderConnection.Deny("unrecognised"); } } break; case NetIncomingMessageType.ConnectionLatencyUpdated: break; default: Globals_Server.logError("Received unrecognised incoming message type: " + im.MessageType); break; } server.Recycle(im); } } #if DEBUG Globals_Server.logEvent("Server listening thread exits"); #endif }
public static void TestEncryption(NetEncryption algo, bool printName = true) { NetOutgoingMessage om = algo.Peer.CreateMessage(); om.Write("Hallon"); om.Write(42); om.Write(5, 5); om.Write(true); om.Write("kokos"); int unencLen = om.BitLength; if (!om.Encrypt(algo)) { throw new LidgrenException("failed to encrypt"); } // convert to incoming message NetIncomingMessage im = Program.CreateIncomingMessage( om.GetBuffer().AsSpan(0, om.ByteLength).ToArray(), om.BitLength); if (im.GetBuffer().Length == 0) { throw new LidgrenException("bad im!"); } if (!im.Decrypt(algo)) { throw new LidgrenException("failed to decrypt"); } if (im.GetBuffer().Length == 0 || im.BitLength != unencLen) { throw new LidgrenException("Length fail"); } var str = im.ReadString(); if (str != "Hallon") { throw new LidgrenException("fail"); } if (im.ReadInt32() != 42) { throw new LidgrenException("fail"); } if (im.ReadInt32(5) != 5) { throw new LidgrenException("fail"); } if (im.ReadBool() != true) { throw new LidgrenException("fail"); } if (im.ReadString() != "kokos") { throw new LidgrenException("fail"); } if (printName) { Console.WriteLine(" - " + algo.GetType().Name + " OK"); } }