did some more progress
This commit is contained in:
parent
9a0482fd56
commit
edf4f91fa9
5 changed files with 242 additions and 53 deletions
|
@ -1,3 +1,4 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Security.Cryptography;
|
||||
|
||||
|
@ -8,20 +9,36 @@ public class Data
|
|||
public Dictionary<string, RSA> Keys { set; get; } = [];
|
||||
public Dictionary<string, Queue<byte[]>> Messages { set; get; } = [];
|
||||
|
||||
public RSA? GetKey(string Phone) {
|
||||
public RSA? GetKey(string Phone)
|
||||
{
|
||||
return Keys.TryGetValue(Phone, out RSA? value) ? value : null;
|
||||
}
|
||||
|
||||
public Queue<byte[]>? GetMessages(string Phone) {
|
||||
public List<byte[]>? GetMessages(string Phone, int limit = -1)
|
||||
{
|
||||
// Check we have a RSA key for the phone and get the messages
|
||||
if(!Keys.ContainsKey(Phone)) { return null; }
|
||||
if(Messages.TryGetValue(Phone, out Queue<byte[]>? value)) {
|
||||
return value;
|
||||
if (!Keys.ContainsKey(Phone)) { return null; }
|
||||
if (Messages.TryGetValue(Phone, out Queue<byte[]>? value))
|
||||
{
|
||||
List<byte[]> msgs = new(limit == -1 ? value.Count : Math.Min(value.Count, limit));
|
||||
int count = 0;
|
||||
while (count != limit && value.TryDequeue(out byte[]? m))
|
||||
{
|
||||
count += 1;
|
||||
msgs.Add(m);
|
||||
}
|
||||
return msgs;
|
||||
}
|
||||
else {
|
||||
else
|
||||
{
|
||||
// generate a new queue because one doesnt already exists
|
||||
Messages[Phone] = new Queue<byte[]>();
|
||||
return Messages[Phone];
|
||||
return []; // no messages were in the list so no reason to attempt to send any message
|
||||
}
|
||||
}
|
||||
|
||||
public bool PeekMessages(string Phone)
|
||||
{
|
||||
return Messages.TryGetValue(Phone, out Queue<byte[]>? value) && value.TryPeek(out var _);
|
||||
}
|
||||
}
|
|
@ -1,4 +1,6 @@
|
|||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
|
@ -37,7 +39,18 @@ public class Program
|
|||
{
|
||||
// Currently, every time it gets a block, it will simply send it back but ToUpper
|
||||
TcpClient client = await server.AcceptTcpClientAsync();
|
||||
_ = Task.Run(async () => await HandleClient(client, connectionCounter));
|
||||
_ = Task.Run(async () =>
|
||||
{
|
||||
try
|
||||
{
|
||||
await HandleClient(client, connectionCounter, key);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine($"Client crashed: {ex.Message}");
|
||||
Console.WriteLine(ex.StackTrace);
|
||||
}
|
||||
});
|
||||
connectionCounter += 1;
|
||||
}
|
||||
}
|
||||
|
@ -52,21 +65,30 @@ public class Program
|
|||
}
|
||||
}
|
||||
|
||||
static async Task HandleClient(TcpClient client, int id)
|
||||
static async Task HandleClient(TcpClient client, int id, RSA pubKey)
|
||||
{
|
||||
Write(id, "Got a new client");
|
||||
string clientPhone = "";
|
||||
NetworkStream stream = client.GetStream();
|
||||
byte[] buffer = new byte[1024];
|
||||
byte counter = 0;
|
||||
// Get AES session key
|
||||
int len = await stream.ReadAsync(buffer);
|
||||
Write(id, $"Got {len} bytes");
|
||||
byte[] skBytes = pubKey.Decrypt(buffer[..len], RSAEncryptionPadding.OaepSHA256);
|
||||
Aes sk = Aes.Create();
|
||||
sk.Key = buffer[..32]; // just to make sure no one sends a too big to be true key
|
||||
sk.IV = buffer[32..len];
|
||||
Write(id, "key + iv: " + len.ToString());
|
||||
sk.Key = skBytes[..32]; // just to make sure no one sends a too big to be true key
|
||||
sk.IV = skBytes[32..];
|
||||
Write(id, $"key: {string.Join(' ', sk.Key)}");
|
||||
Write(id, $"IV: {string.Join(' ', sk.IV)}");
|
||||
await stream.WriteAsync(new byte[] { 0 });
|
||||
|
||||
// Get first message (should be either login or )
|
||||
// Get first message (should be either login or register)
|
||||
len = await stream.ReadAsync(buffer);
|
||||
byte[] msg = sk.DecryptCfb(buffer[..MSG_LEN], sk.IV, PaddingMode.PKCS7);
|
||||
Write(id, $"Got {len} bytes");
|
||||
byte[] msgDec = sk.DecryptCfb(buffer[..len], sk.IV, PaddingMode.PKCS7);
|
||||
byte[] msg = msgDec[..MSG_LEN];
|
||||
Write(id, Request.RequestToString(msg));
|
||||
if (msg[0] != 0)
|
||||
{
|
||||
Write(id, "Invalid session id!");
|
||||
|
@ -80,10 +102,12 @@ public class Program
|
|||
// get phone number
|
||||
string phone = Utils.BytesToNumber(msg[3..11]);
|
||||
Write(id, $"Client wants to register as {phone}");
|
||||
clientPhone = phone;
|
||||
int keyLen = BitConverter.ToInt32(msg, 11);
|
||||
RSA pub = RSA.Create();
|
||||
pub.ImportRSAPublicKey(buffer.AsSpan()[MSG_LEN..], out int bytesRead);
|
||||
pub.ImportRSAPublicKey(msgDec.AsSpan()[MSG_LEN..], out int bytesRead);
|
||||
Write(id, $"Imported key len: {bytesRead} while client claims it is {keyLen}");
|
||||
Write(id, $"Imported key is: \n {pub.ExportRSAPublicKeyPem()}\n");
|
||||
// generate the 6 digit code and send it
|
||||
byte[] code = [
|
||||
(byte)Rnd.Next(10),
|
||||
|
@ -101,7 +125,8 @@ public class Program
|
|||
tries -= 1;
|
||||
len = await stream.ReadAsync(buffer);
|
||||
Write(id, $"Got 6 digit code with sig, len: {len}");
|
||||
msg = sk.DecryptCfb(buffer[..MSG_LEN], sk.IV, PaddingMode.PKCS7);
|
||||
msg = sk.DecryptCfb(buffer[..MSG_LEN], sk.IV, PaddingMode.None);
|
||||
Write(id, Request.RequestToString(msg));
|
||||
byte[] sig = buffer[MSG_LEN..len];
|
||||
if (msg[0] != 0 || msg[1] != (byte)RequestType.ConfirmRegister || msg[2] != counter)
|
||||
{
|
||||
|
@ -145,6 +170,7 @@ public class Program
|
|||
else if (msg[1] == (byte)RequestType.Login)
|
||||
{
|
||||
// verify login
|
||||
// TODO: Login
|
||||
}
|
||||
else
|
||||
{
|
||||
|
@ -162,6 +188,7 @@ public class Program
|
|||
// either by getting new messages for other ppl, or sending back keys/pending messages
|
||||
len = await stream.ReadAsync(buffer);
|
||||
msg = sk.DecryptCfb(buffer[..MSG_LEN], sk.IV, PaddingMode.None);
|
||||
Write(id, Request.RequestToString(msg));
|
||||
// verify that the counter message is correct
|
||||
if (msg[0] != 0 || msg[2] != counter)
|
||||
{
|
||||
|
@ -173,22 +200,47 @@ public class Program
|
|||
switch ((RequestType)msg[1])
|
||||
{
|
||||
case RequestType.GetMessages:
|
||||
byte[] msgsLens = new byte[16]; // 128 bits
|
||||
// get 15 messages, last byte will indicate if there are more
|
||||
List<byte[]> msgs = Data.GetMessages(clientPhone, 15) ?? [];
|
||||
byte[] msgsBytes = new byte[msgs.Select(m => m.Length).Sum()];
|
||||
int msgsbytesIndex = 0;
|
||||
for (int i = 0; i < msgsLens.Length - 1; i += 1)
|
||||
{
|
||||
// it is expected that all messages will be less than 255 bytes, hence a single byte to
|
||||
// denote length is sufficient, but a simple update to the protocol can allow up to 7 messages
|
||||
// per request (instead of 15), and use an ushort (u16) instead
|
||||
msgsLens[i] = (byte)(msgs.Count > i ? msgs[i].Length : 0);
|
||||
if (i < msgs.Count)
|
||||
{
|
||||
// copy the message to the msgsBytes array
|
||||
Array.Copy(msgs[i], 0, msgsBytes, msgsbytesIndex, msgs[i].Length);
|
||||
}
|
||||
}
|
||||
msgsLens[15] = Data.PeekMessages(clientPhone) ? (byte)1 : (byte)0;
|
||||
// only need to encrypt the lengths of the messages, as the messages themselves are encrypted
|
||||
msgsLens = sk.EncryptCfb(msgsLens, sk.IV, PaddingMode.None);
|
||||
byte[] finalPayload = [.. msgsLens, .. msgsBytes];
|
||||
await stream.WriteAsync(finalPayload);
|
||||
break;
|
||||
case RequestType.GetUserKey:
|
||||
string phone = Utils.BytesToNumber(msg[3..11]);
|
||||
RSA? key = Data.GetKey(phone);
|
||||
if (key != null)
|
||||
{
|
||||
msg = sk.EncryptCfb(key.ExportRSAPublicKey(), sk.IV, PaddingMode.PKCS7);
|
||||
msg = [0, .. key.ExportRSAPublicKey()];
|
||||
msg = sk.EncryptCfb(msg, sk.IV, PaddingMode.PKCS7);
|
||||
await stream.WriteAsync(msg);
|
||||
}
|
||||
else
|
||||
{
|
||||
msg = sk.EncryptCfb(Encoding.UTF8.GetBytes("USER DOES NOT EXIST"), sk.IV, PaddingMode.PKCS7);
|
||||
msg = [1, .. Encoding.UTF8.GetBytes("USER DOES NOT EXIST")];
|
||||
msg = sk.EncryptCfb(msg, sk.IV, PaddingMode.PKCS7);
|
||||
await stream.WriteAsync(msg);
|
||||
}
|
||||
break;
|
||||
case RequestType.SendMessage:
|
||||
|
||||
break;
|
||||
default:
|
||||
msg = sk.EncryptCfb(Encoding.UTF8.GetBytes("INVALID REQUEST"), sk.IV, PaddingMode.PKCS7);
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue