static public int constructor(IntPtr l) { try { LUtils o; o = new LUtils(); pushValue(l, true); pushValue(l, o); return(2); } catch (Exception e) { return(error(l, e)); } }
public static int constructor(IntPtr l) { try { LUtils o; o=new LUtils(); pushValue(l,true); pushValue(l,o); return 2; } catch(Exception e) { return error(l,e); } }
static public int ConvertDateTimeInt_s(IntPtr l) { try { System.DateTime a1; checkValueType(l, 1, out a1); var ret = LUtils.ConvertDateTimeInt(a1); pushValue(l, true); pushValue(l, ret); return(2); } catch (Exception e) { return(error(l, e)); } }
static public int NormalizeTimpstamp0_s(IntPtr l) { try { System.Int64 a1; checkType(l, 1, out a1); var ret = LUtils.NormalizeTimpstamp0(a1); pushValue(l, true); pushValue(l, ret); return(2); } catch (Exception e) { return(error(l, e)); } }
static public int GetTimeStamp_s(IntPtr l) { try { System.Boolean a1; checkType(l, 1, out a1); var ret = LUtils.GetTimeStamp(a1); pushValue(l, true); pushValue(l, ret); return(2); } catch (Exception e) { return(error(l, e)); } }
static public int GetSecondString(IntPtr l) { try { LUtils self = (LUtils)checkSelf(l); System.Int32 a1; checkType(l, 2, out a1); var ret = self.GetSecondString(a1); pushValue(l, true); pushValue(l, ret); return(2); } catch (Exception e) { return(error(l, e)); } }
static public int UnixTimestampToDateTime_s(IntPtr l) { try { System.DateTime a1; checkValueType(l, 1, out a1); System.Int64 a2; checkType(l, 2, out a2); var ret = LUtils.UnixTimestampToDateTime(a1, a2); pushValue(l, true); pushValue(l, ret); return(2); } catch (Exception e) { return(error(l, e)); } }
public void Run() { while (true) { try { logger.Log(this, "I have booted up."); TcpListener listener = new TcpListener(IPAddress.Any, TcpConstants.INFO_SERVER_PORT); listener.Start(); while (true) { TcpClient client = listener.AcceptTcpClient(); logger.Log(this, String.Format("Client {0} has connected.", LUtils.GetIpAddress(client))); Task.Run(() => { try { using (Stream stream = client.GetStream()) { TextEncoder.SendJson(stream, GetServerInfo()); } } catch (Exception exception) { logger.LogException(this, exception); } finally { client.Dispose(); } }); } } catch (Exception exception) { logger.LogException(this, exception); } } }
public static X509Certificate2 ImportFromPem(string pem) { X509Certificate2 cer = new X509Certificate2(LUtils.GetBytes(pem)); return(cer); }
public static void SendString(Stream stream, String message) { byte[] byteStr = LUtils.GetBytes(message); SendInt(stream, byteStr.Length); BinaryEncoder.SendPureBytes(stream, byteStr); }
public static ConnectionInfo Run(Stream stream, Action <string> log, ServerConfig config) { ClientHandshake clientHandshake = TextEncoder.ReadJson <ClientHandshake>(stream); X509Certificate2 clientCertificate = X509Certificate2Utils.ImportFromPem(clientHandshake.PemCertificate); log($"Logging user sent username {clientHandshake.UserName}\n Certificate:\n {clientHandshake.PemCertificate}"); ServerHandshake errorHandshake = new ServerHandshake() { Errors = "", NewUser = false, Succeeded = false, UserId = -1, UserName = "" }; if (config.Password != null && !config.Password.Equals(clientHandshake.ServerPassword)) { errorHandshake.Errors = "Server password is wrong."; TextEncoder.SendJson(stream, errorHandshake); throw new Exception(errorHandshake.Errors); } log("Generating random bytes"); byte[] randomBytes = LUtils.GenerateRandomBytes(TcpConstants.HANDSHAKE_LENGHT); log("Sending encrypted bytes"); BinaryEncoder.SendBytes(stream, RSAEncoder.Encrypt(randomBytes, clientCertificate)); byte[] received = BinaryEncoder.ReceiveBytes(stream); if (!randomBytes.SequenceEqual(received)) { log("Client's certificate verification failed."); errorHandshake.Errors = "Client's certificate verification failed."; TextEncoder.SendJson(stream, errorHandshake); throw new Exception(errorHandshake.Errors); } log("Certificate verification succeeded."); Users user; String message; Clients client; byte[] aesKey = null; bool newUser = false; using (Context context = new Context(config)) { byte[] hash = SHA256Utils.ComputeByteSha256Hash(clientCertificate); user = context.Users.SingleOrDefault(u => u.PublicCertificateSha256.SequenceEqual(hash)); if (user == null) { log("User doesn't exist yet. I'll try to create him."); newUser = true; log("Checking the uniquity of username."); String userName = clientHandshake.UserName; if (context.Users.SingleOrDefault(u => u.UserName.Equals(userName)) != null) { errorHandshake.Errors = "Username isn't unique."; TextEncoder.SendJson(stream, errorHandshake); throw new Exception(errorHandshake.Errors); } else if (userName.Length > 45) { errorHandshake.Errors = "Username is too long (max. 45 chars)"; TextEncoder.SendJson(stream, errorHandshake); throw new Exception(errorHandshake.Errors); } else if (userName.Length < 4) { errorHandshake.Errors = "Username is too short (min. 4 chars)"; TextEncoder.SendJson(stream, errorHandshake); throw new Exception(errorHandshake.Errors); } else if (!Validators.ValidateRegexUserName(userName)) { errorHandshake.Errors = "Username must match this regex ^[a-zA-Z][-a-zA-Z0-9_]+$ (Vaguely can't contain special chars and spaces)"; TextEncoder.SendJson(stream, errorHandshake); throw new Exception(errorHandshake.Errors); } log("Creating user."); user = new Users() { PublicCertificate = clientHandshake.PemCertificate, PublicCertificateSha256 = hash, UserName = clientHandshake.UserName }; context.Users.Add(user); context.SaveChanges(); message = "User successfully created."; log("User successfully created."); } else { message = "User exists."; log("User exists."); } client = new Clients() { UserId = user.Id }; if (clientHandshake.ClientId == null) { log($"Loading self-aes key."); aesKey = context.UsersKeys .Where(u => u.RecepientId == user.Id) .Where(u => u.SenderId == user.Id) .Select(u => u.AesKey) .SingleOrDefault(); context.Add(client); context.SaveChanges(); log($"Added client with Id {client.Id}."); } else { client.Id = (int)clientHandshake.ClientId; if (context.Clients.Where(u => u.Id == client.Id).Single().UserId != user.Id) { errorHandshake.Errors = "This client id isn't owned by this user."; TextEncoder.SendJson(stream, errorHandshake); throw new Exception(errorHandshake.Errors); } log($"Client with Id {client.Id} has logged in."); } } ServerHandshake toSend = new ServerHandshake() { Errors = message, NewUser = newUser, Succeeded = true, UserId = user.Id, UserName = user.UserName, ClientId = client.Id, SelfAesKey = aesKey }; TextEncoder.SendJson(stream, toSend); ConnectionInfo ret = new ConnectionInfo(user, clientCertificate, client.Id); log($"Handshake successeded. User {ret.UserName} with id {ret.UserId} has logged in. Client has id {client.Id}."); return(ret); }
private static byte[] GetSalt() { return(LUtils.GenerateRandomBytes(AESConstants.SALT_LENGHT)); }
public static String ReadString(Stream stream) { int lenght = ReadInt(stream); return(LUtils.GetText(BinaryEncoder.ReceivePureBytes(stream, lenght))); }
public static String ReadString(Stream stream) { return(LUtils.GetText(BinaryEncoder.ReceiveBytes(stream))); }
public static UserCapsula Run(Stream stream, Action <string> log, ServerConfig config) { ClientHandshake clientHandshake = TextEncoder.ReadClientHandshake(stream); X509Certificate2 clientCertificate = X509Certificate2Utils.ImportFromPem(clientHandshake.PemCertificate); log($"Logging user sent username {clientHandshake.UserName}\n Certificate:\n {clientHandshake.PemCertificate}"); log("Generating random bytes"); byte[] randomBytes = LUtils.GenerateRandomBytes(TcpConstants.HANDSHAKE_LENGHT); log("Sending encrypted bytes"); BinaryEncoder.SendBytes(stream, RSAEncoder.Encrypt(randomBytes, clientCertificate)); ServerHandshake errorHandshake = new ServerHandshake() { Errors = "", NewUser = false, Succeeded = false, UserId = -1, UserName = "" }; byte[] received = BinaryEncoder.ReceiveBytes(stream); if (!randomBytes.SequenceEqual(received)) { log("Sending error to client."); errorHandshake.Errors = "Client's certificate verification failed."; TextEncoder.SendJson(stream, errorHandshake); throw new Exception(errorHandshake.Errors); } log("Certificate verification succeeded."); Users user; String message; Clients client; bool newUser = false; using (Context context = new Context(config)) { SHA1 sha = new SHA1CryptoServiceProvider(); byte[] hash = sha.ComputeHash(clientCertificate.RawData); user = context.Users.SingleOrDefault(u => u.PublicCertificateSha1.SequenceEqual(hash)); if (user == null) { log("User doesn't exist yet. I'll try to create him."); newUser = true; log("Checking the uniquity of username."); String userName = clientHandshake.UserName; if (context.Users.SingleOrDefault(u => u.UserName.Equals(userName)) != null) { log("Username isn't unique."); errorHandshake.Errors = "Username isn't unique."; TextEncoder.SendJson(stream, errorHandshake); throw new Exception(errorHandshake.Errors); } log("Creating user."); user = new Users() { PublicCertificate = clientHandshake.PemCertificate, PublicCertificateSha1 = hash, UserName = clientHandshake.UserName }; context.Users.Add(user); context.SaveChanges(); message = "User successfully created."; log("User successfully created."); } else { message = "User exists."; log("User exists."); } client = new Clients() { UserId = user.Id }; if (clientHandshake.ClientId == null) { context.Add(client); context.SaveChanges(); log($"Added client with Id {client.Id}."); } else { log($"Client with Id {client.Id} has logged in."); } } ServerHandshake toSend = new ServerHandshake() { Errors = message, NewUser = newUser, Succeeded = true, UserId = user.Id, UserName = user.UserName, ClientId = client.Id }; TextEncoder.SendJson(stream, toSend); UserCapsula ret = new UserCapsula(user, clientCertificate); log($"Handshake successeded. User {ret.UserName} with id {ret.UserId} has logged in"); return(ret); }
public void Run(TcpClient client) { try { logger.Log(this, String.Format("Godot has been activated. Client IP address is {0}", LUtils.GetIpAddress(client))); godotCounter.IncreaseRunning(); stream = new SslStream(client.GetStream(), false, CertificateValidation); stream.AuthenticateAsServer(serverCert, true, SslProtocols.Tls12, false); logger.Log(this, "SSL authentication completed. Starting Handshake."); this.connectionInfo = Handshake.Run(stream, Log, config); bool running = true; while (running) { ConnectionCommand command = BinaryEncoder.ReadCommand(stream); switch (command) { case ConnectionCommand.TRUST_CONTACT: Log("TRUST_CONTACT command received."); TrustContact(); break; case ConnectionCommand.UNTRUST_CONTACT: Log("UNTRUST_CONTACT command received."); UntrustContact(); break; case ConnectionCommand.PULL: #if (DEBUG) Log("PULL command received."); #endif Push(); break; case ConnectionCommand.PUSH: #if (DEBUG) Log("PUSH command received."); #endif Pull(); break; case ConnectionCommand.SEARCH_CONTACT: Log("SEARCH_CONTACT command received."); SearchContact(); break; case ConnectionCommand.END_CONNECTION: Log("END_CONNECTION command received."); running = false; break; default: throw new Exception("Received unknown command."); } } } catch (Exception ex) { logger.Log(this, "Godot has crashed."); logger.LogException(this, ex); } finally { stream.Close(); client.Close(); godotCounter.IncreaseDestroyed(); logger.Log(this, "Godot has died."); } }
public static void ExportToPkcs12File(X509Certificate2 cert, String fileName) { LUtils.WriteToFile(ExportToPkcs12(cert), fileName); }
public void Run(TcpClient client) { try { logger.Log(this, String.Format("Godot has been activated. Client IP address is {0}", LUtils.GetIpAddress(client))); godotCounter.IncreaseRunning(); stream = new SslStream(client.GetStream(), false, CertificateValidation); stream.AuthenticateAsServer(serverCert, true, SslProtocols.Tls12, false); logger.Log(this, "SSL authentication completed. Starting Handshake."); this.user = Handshake.Run(stream, Log, config); InitSync(); bool running = true; while (running) { ConnectionCommand command = TextEncoder.ReadCommand(stream); switch (command) { case ConnectionCommand.TRUST_CONTACT: Log("TRUST_CONTACT command received."); TrustContact(); break; case ConnectionCommand.UNTRUST_CONTACT: Log("UNTRUST_CONTACT command received."); UntrustContact(); break; case ConnectionCommand.PULL: #if (DEBUG) Log("PULL command received."); #endif Push(); break; case ConnectionCommand.PUSH: #if (DEBUG) Log("PUSH command received."); #endif Pull(); break; case ConnectionCommand.CREATE_ONLIVE_TUNNEL: Log("CREATE_ONLIVE_TUNNEL command received."); CreateOnliveTunnel(); break; case ConnectionCommand.END_CONNECTION: Log("END_CONNECTION command received."); running = false; break; default: throw new ChatovatkoException(this, "Received unknown command."); } } } catch (Exception ex) { logger.Log(this, String.Format("Godot has crashed. Exception:\n{0}\n{1}\n{2}", ex.GetType().Name, ex.Message, ex.StackTrace)); } finally { stream.Close(); client.Close(); godotCounter.IncreaseDestroyed(); logger.Log(this, "Godot has died."); } }
public static X509Certificate2 ImportFromPkcs12File(String fileName, bool exportable = false) { byte[] certData = LUtils.ReadFromFile(fileName); return(ImportFromPkcs12(certData, exportable)); }
public static AESPassword GenerateAESPassword() { return(new AESPassword(LUtils.GenerateRandomBytes(AESConstants.PASSWORD_LENGHT))); }