online_security_project/client/Program.cs

414 lines
18 KiB
C#

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
using client;
using lib;
namespace Client;
public class Program
{
static string User = "";
static readonly Random Rand = new((int)DateTime.Now.Ticks);
static byte Counter = (byte)Rand.Next();
static async Task Main(string[] args)
{
// Load some info stuff
User = args
.SkipWhile(a => !new[] { "-p", "--phone" }.Contains(a)) // search for the option
.Skip(1) // skip the `-u/--user` itself to get the value
.FirstOrDefault() ?? "0000"; // get the value or deafult if it doesnt exist
// On boot, check if a key is available
RSA? serverKey = LoadRSAFromFile("server_key.pem");
if (serverKey == null)
{
Log.System("Could not find server key, please run server before clients!");
return;
}
// Attempt to load the user's keys,
RSA pubKey = LoadRSAFromFile($"pubkey_{User}.pem") ?? RSA.Create(1024);
RSA privKey = LoadRSAFromFile($"privkey_{User}.pem") ?? pubKey;
SaveRSAKeys(User, pubKey, privKey);
// if pubKey and privKey is the same object then we created the keys just now, otherwise we can use the below flags to force a registration
bool needsRegister = pubKey == privKey || args.Any(a => new[] { "-fr", "--force-register" }.Contains(a));
// Connect to the server
using TcpClient client = new("127.0.0.1", 12345);
var stream = client.GetStream();
// Establish secure connection
Aes sk = Aes.Create(); // creates an AES-256 key
Log.Decrypted($"Session key + IV", [.. sk.Key, .. sk.IV]);
byte[] skEnc = serverKey.Encrypt([.. sk.Key, .. sk.IV], RSAEncryptionPadding.OaepSHA256);
Log.Encrypted("Session key + IV", skEnc);
await stream.WriteAsync(skEnc);
// wait for the server to confirm it recieved the keys, supposedly we would want to read exactly what we need then
// send as much as we can in 1 go (and maybe use buffered streams), but i didnt do that and im fine with that
await stream.ReadExactlyAsync(new byte[1]);
if (needsRegister)
{
try
{
await RegisterClient(User, pubKey, privKey, sk, stream);
}
catch (Exception ex)
{
Log.System("Failed registration process");
Log.System("Exception: " + ex.Message);
Log.System("Stack: " + ex.StackTrace);
return;
}
}
else
{
// start login process
byte[] msg = Request.CreateRequest(RequestType.Login, ref Counter, Utils.NumberToBytes(User));
Log.Decrypted("Login", msg);
msg = sk.EncryptCfb(msg, sk.IV, PaddingMode.PKCS7);
Log.Encrypted("Login", msg);
await stream.WriteAsync(msg);
byte[] toSign = new byte[16];
await stream.ReadExactlyAsync(toSign, 0, 16);
Log.Encrypted("Challenge", toSign);
toSign = sk.DecryptCfb(toSign, sk.IV, PaddingMode.None);
Log.Decrypted("Challenge", toSign);
byte[] signed = privKey.SignData(toSign, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
Log.Decrypted("Signed", signed);
msg = Request.CreateRequest(RequestType.ConfirmLogin, ref Counter, BitConverter.GetBytes(signed.Length));
Log.Decrypted("Challenge message", msg);
msg = sk.EncryptCfb(msg, sk.IV, PaddingMode.None);
Log.Encrypted("Challenge message", msg);
msg = [.. msg, .. signed];
Log.Encrypted("Challenge final", msg);
await stream.WriteAsync(msg);
byte[] buffer = new byte[512];
int len = await stream.ReadAsync(buffer);
Log.Encrypted("Result", buffer[..len]);
byte[] dec = sk.DecryptCfb(buffer[..len], sk.IV, PaddingMode.PKCS7);
Log.Decrypted("Result", dec);
string r = Encoding.UTF8.GetString(dec);
Log.Decrypted($"Result (UTF8): {JsonSerializer.Serialize(r.ToCharArray())}");
if (r == "OK")
{
Log.System("Login successful");
}
else
{
Log.System($"Failed login: {r}");
client.Dispose();
return;
}
}
await HandleUserInput(client, stream, sk, privKey);
}
async static Task RegisterClient(string user, RSA pub, RSA priv, Aes sk, NetworkStream stream)
{
Log.System("Attempting to register with public key:");
Log.System(pub.ExportRSAPublicKeyPem());
// Generate the Register msg
byte[] pubBytes = pub.ExportRSAPublicKey();
byte[] data = new byte[12];
Array.Copy(Utils.NumberToBytes(user), data, 8);
Array.Copy(BitConverter.GetBytes(pubBytes.Length), 0, data, 8, 4);
byte[] msg = Request.CreateRequest(RequestType.Register, ref Counter, data);
// Encrypt msg and send it
byte[] payload = [.. msg, .. pubBytes];
Log.Decrypted("Register payload", payload);
byte[] enc = sk.EncryptCfb(payload, sk.IV, PaddingMode.PKCS7);
Log.Encrypted("Register payload", enc);
await stream.WriteAsync(enc);
// get the 6 digit code (from "secure channel", actually an OK message is expected here but the 6 digit code kinda replaces it)
byte[] digits = new byte[6];
int len = await stream.ReadAsync(digits);
Log.System($"6 digit code actual length: {len}");
// print the 6 digit code
Log.System($"[{DateTime.Now}] 6 digit code: {string.Join(' ', digits.Select(d => d.ToString()))}");
// get the 6 digit code from the user
while (true)
{
Console.Write("> ");
string? code = Console.ReadLine()?.Trim();
if (code == null || code.Take(6).Any(c => !char.IsDigit(c)))
{
// we know the code is invalid because it HAS to be a 6 digit code
Log.System("Invalid code!");
continue;
}
byte[] codeBytes = code
.Take(6) // take the first 6 characters
.Select(d => byte.Parse(d.ToString())) // parse into bytes
.ToArray();
// Debug print the inserted value to see it works :)
Log.System(string.Join(' ', codeBytes.Select(b => b.ToString())));
// Sign the 6 digit code & Generate ConfirmRegister message
byte[] signed = priv.SignData(codeBytes, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
Log.Decrypted("Signed code", signed);
msg = Request.CreateRequest(RequestType.ConfirmRegister, ref Counter, [.. codeBytes, .. BitConverter.GetBytes(signed.Length)]);
Log.Decrypted("Signed message", msg);
enc = sk.EncryptCfb(msg, sk.IV, PaddingMode.None); // no reason to encrpy the signature
Log.Encrypted("Signed message", enc);
payload = [.. enc, .. signed]; // should be 128 (enc) + 256 (signed)
Log.Encrypted("Signed final", payload);
await stream.WriteAsync(payload);
// wait for OK/NACK response (anything other than OK is a NACK)
int incoming = await stream.ReadAsync(enc);
Log.Encrypted("Response", enc[..incoming]);
msg = sk.DecryptCfb(enc[..incoming], sk.IV, PaddingMode.PKCS7);
Log.Decrypted("Response", msg);
string r = Encoding.UTF8.GetString(msg);
Log.Decrypted($"Response (UTF8): {r}");
if (r == "OK")
{
Console.WriteLine("Registration process complete");
break;
}
else
{
Console.WriteLine("Failed reigstreation: " + r);
}
}
}
static RSA? LoadRSAFromFile(string file)
{
if (File.Exists(file))
{
string content = File.ReadAllText(file);
RSA k = RSA.Create();
k.ImportFromPem(content);
return k;
}
return null;
}
static void SaveRSAKeys(string user, RSA pub, RSA priv)
{
File.WriteAllText($"pubkey_{user}.pem", pub.ExportRSAPublicKeyPem());
File.WriteAllText($"privkey_{user}.pem", priv.ExportRSAPrivateKeyPem());
}
static async Task HandleUserInput(TcpClient client, NetworkStream stream, Aes sk, RSA privKey)
{
string? currentChat = null;
Dictionary<string, RSA> publicKeys = [];
while (client.Connected)
{
Console.Write((currentChat != null ? $"[{currentChat}] " : "") + "> ");
string? input = Console.ReadLine();
if (input == null)
{
await Task.Delay(100);
continue;
}
else if (input.StartsWith('/'))
{
string[] words = input.Split(' ');
// Commands :D, i like commands
switch (words[0].ToLower())
{
case "/quit":
case "/exit":
case "/q!":
return;
case "/chat":
case "/msg":
string? old = currentChat;
currentChat = words.Length > 1 ? words[1] : null;
if (currentChat != null && currentChat.Length > 16)
{
Log.System("Invalid number: too long");
currentChat = old;
continue;
}
if (currentChat != null && !publicKeys.ContainsKey(currentChat))
{
// attempt to get the currnet chat's key, this is also possible to do just before sending a message
// but i decided to do it here since if better fits the current structure
RSA? key = await GetPublicKey(stream, sk, currentChat);
if (key != null)
{
publicKeys[currentChat] = key;
}
else
{
currentChat = old;
Log.System($"Reverting to previous chat: {currentChat ?? "none"}");
}
}
break;
case "/read":
case "/get":
case "/fetch":
case "/pull":
await GetMessages(stream, sk, privKey, publicKeys);
break;
}
}
else
{
if (currentChat == null)
{
Log.System("No chat is active, please select chat using '/msg [number]' or '/chat [number]'");
}
else if (publicKeys.TryGetValue(currentChat!, out RSA? key))
{
// Pick the id as a random uint, good enough for the sake of testing
Message m = new((uint)Rand.Next(), User, false, input);
m.CalculateSignature(privKey);
Log.Decrypted($"Message: {JsonSerializer.Serialize(m)}");
Log.Decrypted("Message sig", m.Signature);
byte[] userMsg = [.. key.Encrypt(m.Bytes(), RSAEncryptionPadding.OaepSHA256), .. m.Signature];
Log.Encrypted("Message", userMsg);
byte[] req = Request.CreateRequest(
RequestType.SendMessage,
ref Counter,
[.. Utils.NumberToBytes(currentChat!), .. BitConverter.GetBytes(userMsg.Length)]);
Log.Decrypted("Message req", req);
req = sk.EncryptCfb(req, sk.IV);
Log.Encrypted("Message req", req);
stream.Write([.. req, .. userMsg]);
Log.System($"[{DateTime.Now}] Sent to server: {input}");
}
else
{
Log.System($"active chat exists, but no key was found...");
}
}
}
}
static async Task<RSA?> GetPublicKey(NetworkStream stream, Aes sk, string chat)
{
byte[] req = Request.CreateRequest(RequestType.GetUserKey, ref Counter, Utils.NumberToBytes(chat));
Log.Decrypted("Get key req", req);
req = sk.EncryptCfb(req, sk.IV, PaddingMode.None); // no need for padding this is exactly 128 bytes
Log.Encrypted("Get key req", req);
await stream.WriteAsync(req);
byte[] response = new byte[1024];
int len = await stream.ReadAsync(response);
Log.Encrypted("Key", response[..len]);
byte[] key = sk.DecryptCfb(response[..len], sk.IV, PaddingMode.PKCS7);
Log.Decrypted("Key", key);
if (key[0] == 1)
{
Log.System($"failed getting key for {chat}: {Encoding.UTF8.GetString(key[1..])}");
return null;
}
else
{
RSA bobsKey = RSA.Create();
bobsKey.ImportRSAPublicKey(key.AsSpan()[1..], out int _);
Log.System($"Got key:\n {bobsKey.ExportRSAPublicKeyPem()}\n");
return bobsKey;
}
}
static async Task GetMessages(NetworkStream stream, Aes sk, RSA privKey, Dictionary<string, RSA> publicKeys)
{
byte[] req = Request.CreateRequest(RequestType.GetMessages, ref Counter, []);
Log.Decrypted("Get messages", req);
req = sk.EncryptCfb(req, sk.IV, PaddingMode.None); // no need for padding this is exactly 128 bytes
Log.Encrypted("Get messages", req);
await stream.WriteAsync(req);
byte[] buffer = new byte[4096];
int len = await stream.ReadAsync(buffer);
Log.Encrypted("Response", buffer[..len]);
byte[] lengths = buffer[..16];
lengths = sk.DecryptCfb(lengths, sk.IV, PaddingMode.None);
Log.Decrypted($"Lengths: {string.Join(", ", lengths)}");
byte[] msg = new byte[1024]; // msg buffer
int start = 16; // skip the first 16 bytes since its the lengths message
for (int i = 0; i < lengths.Length - 1; i += 2)
{
int l = (lengths[i] << 8) | (lengths[i + 1]);
if (l == 0) { break; } // a 0 means we are done actually, as empty messages shouldn't be allowed
// get the msg
int end = start + l;
if (end > len)
{
// TODO: properly handle it as a buffered stream and properly buffer it
}
Log.Encrypted($"Message {i / 2}", buffer[start..end]);
// decrypt the message
int msgLen = privKey.KeySize / 8; // message length is derived from the size of the key
if (privKey.TryDecrypt(buffer.AsSpan()[start..(msgLen + start)], msg, RSAEncryptionPadding.OaepSHA256, out int written))
{
byte[] dec = msg[..written];
Log.Decrypted($"Message {i / 2}", dec);
Message m = new(dec)
{
Signature = buffer[(start + msgLen)..end]
};
Log.Decrypted($"Message {i / 2}: {JsonSerializer.Serialize(m)}");
Log.Decrypted($"Message {i / 2} sig", m.Signature);
bool sigValid = false;
if (publicKeys.TryGetValue(m.Sender, out RSA? pk) || (pk = await GetPublicKey(stream, sk, m.Sender)) != null)
{
publicKeys[m.Sender] = pk; // update the key value stored in case it was requested for in GetPublicKey
sigValid = m.IsSignatureValid(pk);
}
else
{
Log.System("Failed getting sender's public key - cannot verify signature");
}
Log.Message($"Got message from {m.Sender} (id: {m.Id}) (valid: {sigValid}): " + (m.IsAck ? "ACK" : m.Content));
// if the signature is valid we also want to send back a message ack for the same id :)
if (sigValid && !m.IsAck)
{
Message mAck = new(m.Id, User, true, "");
Log.Decrypted($"Ack {i / 2}: {JsonSerializer.Serialize(mAck)}");
mAck.CalculateSignature(privKey);
Log.Decrypted($"Ack {i / 2} sig", mAck.Signature);
byte[] userMsg = [.. publicKeys[m.Sender].Encrypt(mAck.Bytes(), RSAEncryptionPadding.OaepSHA256), .. mAck.Signature];
Log.Encrypted($"Ack {i / 2}", userMsg);
byte[] reqAck = Request.CreateRequest(
RequestType.SendMessage,
ref Counter,
[.. Utils.NumberToBytes(m.Sender), .. BitConverter.GetBytes(userMsg.Length)]);
Log.Decrypted($"Ack {i / 2} request", reqAck);
reqAck = sk.EncryptCfb(reqAck, sk.IV);
Log.Encrypted($"Ack {i / 2} request", reqAck);
stream.Write([.. reqAck, .. userMsg]);
}
}
else
{
// what if we cant decrypt the message? well, i doubt there is anything we can do about it
// even if we know who sent the message we dont know which message it is unless the server also knows
// and i dont want the server to be aware of that, i think it makes more sense for the server to act as a relay
// and a buffer than an actual participant, so if the message is failing to decrypt that will go unnoticed.
// supposedly the sender will notice the lack of response and send it again
Log.System("Incoming message failed to decrypt, unknown sender");
}
start = end;
}
bool hasMoreMessages = lengths[15] != 0;
Log.System($"hasMoreMessages: {hasMoreMessages}");
}
}