Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rust Checkerlib #64

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions examples/checker/checker_rust/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
[package]
name = "examplechecker"
version = "0.1.0"
authors = ["Your Name <[email protected]>"]
edition = "2018"

[dependencies]
checkerlib = { git = "https://github.com/siccegge/ctf-gameserver" }

34 changes: 34 additions & 0 deletions examples/checker/checker_rust/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
use checkerlib::{Checker, Error, Context, CheckerResult};


struct TrivialChecker {
context: Context
}

impl TrivialChecker {
fn new(context:Context) -> Self {
Self { context: context }
}
}

impl Checker for TrivialChecker {

fn place_flag(&mut self) -> Result<(), Error> {
self.context.store_data("test", &String::from("test"))?;
Ok(())
}

fn check_flag(&mut self, tick:u32) -> Result<(), Error> {
let _s:String = self.context.load_data("test")?;
Ok(())
}

fn check_service(&mut self) -> Result<(), Error> {
Err(Error::CheckerError(CheckerResult::Faulty))
}
}


pub fn main() {
checkerlib::run_check(TrivialChecker::new);
}
14 changes: 14 additions & 0 deletions rust/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
[package]
name = "checkerlib"
version = "0.1.0"
authors = ["Christoph Egger <[email protected]>"]
edition = "2018"
license = "ISC"
homepage = "https://ctf-gameserver.org/"

[dependencies]
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
base64 = "0.13"
log = { version = "0.4", features = ["std", "serde"] }
env_logger = "0.8"
34 changes: 34 additions & 0 deletions rust/examples/trivialchecker.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
use checkerlib::{Checker, Error, Context, CheckerResult};


struct TrivialChecker {
context: Context
}

impl TrivialChecker {
fn new(context:Context) -> Self {
Self { context: context }
}
}

impl Checker for TrivialChecker {

fn place_flag(&mut self) -> Result<(), Error> {
self.context.store_data("test", &String::from("test"))?;
Ok(())
}

fn check_flag(&mut self, tick:u32) -> Result<(), Error> {
let _s:String = self.context.load_data("test")?;
Ok(())
}

fn check_service(&mut self) -> Result<(), Error> {
Err(Error::CheckerError(CheckerResult::Faulty))
}
}


pub fn main() {
checkerlib::run_check(TrivialChecker::new);
}
100 changes: 100 additions & 0 deletions rust/src/context.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
use crate::error::Error;
use std::net::IpAddr;
use std::sync::{Arc, Mutex};

use crate::ipc::ControlInterface;

#[derive(Clone)]
pub struct Context {
pub ip: IpAddr,
pub team: u32,
pub tick: u32,
ctrl: Arc<Mutex<Ctrl>>,
pub (crate) local: bool,
}


impl Context {
pub (crate) fn new() -> Self {
use std::str::FromStr;

let mut args = std::env::args();
let _ = args.next();
let ip = IpAddr::from_str(&args.next().expect("Caller needs to provide an IP address")).expect("IP address invalid");
let team = u32::from_str( &args.next().expect("Caller needs to provide a team ID")) .expect("team ID must be an integer");
let tick = u32::from_str( &args.next().expect("Caller needs to provide a tick")) .expect("tick must be an integer");

let (local, ctrl) = get_interface(format!("_{}_state.json", team));

Context { ip:ip, team:team, tick:tick, ctrl:Arc::new(Mutex::new(ctrl)), local:local }
}

pub fn get_flag(&self, payload:&Vec<u8>) -> Result<String, Error> {
match &mut *self.ctrl.lock().unwrap() {
Ctrl::Local(ctrl) =>
ctrl.get_flag(self.tick, payload),
Ctrl::Ipc(ctrl) =>
ctrl.get_flag(self.tick, payload)
}
}


pub fn store_data<S: serde::Serialize> (&self, key:&str, data:&S) -> Result<(), Error> {
match &mut *self.ctrl.lock().unwrap() {
Ctrl::Local(ctrl) =>
ctrl.store_data(key, data),
Ctrl::Ipc(ctrl) =>
ctrl.store_data(key, data)
}
}

pub fn load_data<D: serde::de::DeserializeOwned> (&self, key:&str) -> Result<D, Error> {
match &mut *self.ctrl.lock().unwrap() {
Ctrl::Local(ctrl) =>
ctrl.load_data(key),
Ctrl::Ipc(ctrl) =>
ctrl.load_data(key)
}
}


pub fn send_log(&self, record:&log::Record) {
match &mut *self.ctrl.lock().unwrap() {
Ctrl::Local(ctrl) =>
ctrl.send_log(record),
Ctrl::Ipc(ctrl) =>
ctrl.send_log(record)
}
}


pub fn store_result(&self, result:&crate::CheckerResult) -> Result<(), Error> {
match &mut *self.ctrl.lock().unwrap() {
Ctrl::Local(ctrl) =>
ctrl.store_result(result),
Ctrl::Ipc(ctrl) =>
ctrl.store_result(result)
}
}
}

enum Ctrl {
Local(crate::local::LocalControlInterface),
Ipc(crate::ipc::IpcControlInterface)
}

fn get_interface(fname:String) -> (bool, Ctrl) {
use std::env::VarError;
let islocal = match std::env::var("CTF_CHECKERSCRIPT") {
Ok(_s) => false,
Err(VarError::NotUnicode(_s)) => false,
Err(VarError::NotPresent) => true
};
if islocal {
(islocal, Ctrl::Local(crate::local::LocalControlInterface::new(fname)))
} else {
(islocal, Ctrl::Ipc(crate::ipc::IpcControlInterface::new()))
}
}


29 changes: 29 additions & 0 deletions rust/src/error.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@

#[derive(Debug)]
pub enum Error {
IoError(std::io::Error),
SerdeError(serde_json::Error),
CheckerError(crate::CheckerResult),
NoSuchItem,
}


impl From<std::io::Error> for Error {
fn from(error: std::io::Error) -> Self {
Error::IoError(error)
}
}


impl From<serde_json::Error> for Error {
fn from(error: serde_json::Error) -> Self {
Error::SerdeError(error)
}
}


impl From<crate::CheckerResult> for Error {
fn from(error: crate::CheckerResult) -> Self {
Error::CheckerError(error)
}
}
8 changes: 8 additions & 0 deletions rust/src/flag.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@




pub fn gen_flag(_tick:u32, _payload:&Vec<u8>) -> String {
String::from("FAUST_")
}

143 changes: 143 additions & 0 deletions rust/src/ipc.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
use crate::Error;
use std::io::Write;
use std::io::BufRead;
use std::io::BufReader;

use std::fs::File;
use std::os::unix::io::FromRawFd;

use serde::{Deserialize, Serialize, de::DeserializeOwned};


pub trait ControlInterface {
fn setup () -> Result<(), Error>;
fn get_flag (&mut self, tick:u32, payload:&Vec<u8>) -> Result<String, Error>;
fn store_data<S: Serialize> (&mut self, key:&str, data:&S) -> Result<(), Error>;
fn load_data<D: DeserializeOwned> (&mut self, key:&str) -> Result<D, Error>;
fn send_log(&mut self, record:&log::Record);
fn store_result(&mut self, result:&crate::CheckerResult) -> Result<(), Error>;
}


pub struct IpcControlInterface {
input: BufReader<File>,
output: File
}


impl IpcControlInterface {
pub fn new() -> IpcControlInterface {
let infile = unsafe {std::fs::File::from_raw_fd(3)} ;
let outfile = unsafe {std::fs::File::from_raw_fd(4)} ;
IpcControlInterface { input: BufReader::new(infile),
output: outfile }
}

fn send<S: Serialize>(&mut self, key:&str, data:&S) -> Result<(), Error> {
let json = SendMessage {action: key.to_string(), param: data };
self.output.write(serde_json::to_string(&json)?.as_bytes())?;
Ok(())
}


fn communicate<S: Serialize, D: Clone + DeserializeOwned>(&mut self, key:&str, data:&S) -> Result<D, Error> {
let mut resp = String::new();
let json = SendMessage {action: key.to_string(), param: data };

self.output.write(serde_json::to_string(&json)?.as_bytes())?;
self.input.read_line(&mut resp)?;

let r:ReceiveMessage<D> = serde_json::from_reader(resp.as_bytes())?;
Ok(r.response)
}
}


impl ControlInterface for IpcControlInterface {
fn setup() -> Result<(), Error> {
Ok(())
}


fn get_flag(&mut self, tick:u32, payload:&Vec<u8>) -> Result<String, Error> {
let response:String =
self.communicate("FLAG", &SendMessageGetFlag { tick: tick, payload: base64::encode(payload.as_slice()) } )?;
Ok(response)
}


fn store_data<S: Serialize> (&mut self, key:&str, data:&S) -> Result<(), Error> {
let payload = serde_json::to_string(data)?;
self.send("STORE", &SendMessageStore { key: key.to_string(), data: payload } )?;
Ok(())
}


fn load_data<D: DeserializeOwned> (&mut self, key:&str) -> Result<D, Error> {
let response:String = self.communicate("LOAD", &key.to_string())?;
Ok(serde_json::from_reader(response.as_bytes())?)
}


fn send_log(&mut self, record:&log::Record) {
self.send("LOG", &SendMessageLog::from(record)).unwrap()
}


fn store_result(&mut self, result:&crate::CheckerResult) -> Result<(), Error> {
self.send("RESULT", result)?;
Ok(())
}
}

impl From<&::log::Record<'_>> for SendMessageLog {
fn from(record: &::log::Record) -> Self {
SendMessageLog {
level: match record.level() {
::log::Level::Error => 40,
::log::Level::Warn => 30,
::log::Level::Info => 20,
::log::Level::Debug => 10,
::log::Level::Trace => 5,
},
message: format!("{}", record.args()),
funcName: record.module_path().unwrap_or("").to_string(),
pathname: record.file().unwrap_or("").to_string(),
lineno: record.line().unwrap_or(0)
}
}
}


#[derive(Debug, Deserialize, Serialize, Clone)]
struct SendMessageStore {
key: String,
data: String
}

#[allow(non_snake_case)]
#[derive(Debug, Deserialize, Serialize, Clone)]
struct SendMessageLog {
level: u32,
message: String,
funcName: String,
pathname: String,
lineno: u32
}

#[derive(Debug, Deserialize, Serialize, Clone)]
struct SendMessageGetFlag {
payload: String,
tick: u32
}

#[derive(Debug, Deserialize, Serialize, Clone)]
struct ReceiveMessage<D> {
response: D
}

#[derive(Debug, Deserialize, Serialize, Clone)]
struct SendMessage<D> {
action: String,
param: D
}
Loading