Skip to content

Instantly share code, notes, and snippets.

@rjbs
Created September 28, 2018 03:06
Show Gist options
  • Save rjbs/56eb342a77f6fab7c6328c2a3dfcd160 to your computer and use it in GitHub Desktop.
Save rjbs/56eb342a77f6fab7c6328c2a3dfcd160 to your computer and use it in GitHub Desktop.
use std::io::{Read,Write};
use std::net::{TcpListener,TcpStream};
use std::thread;
fn read_str (stream: &mut TcpStream) -> String {
let mut buf = vec![0u8; 256];
let x = stream.read(&mut buf).unwrap();
println!("read {} bytes", x);
if buf[x-2] == b'\r' && buf[x-1] == b'\n' {
// ...
} else {
panic!("single read not CRLF terminated: {:?}", buf);
}
let str = String::from_utf8_lossy(&buf[0..x-2]);
return str.into_owned();
}
fn say_hello (stream: TcpStream) {
let mut stream = stream;
stream.write(b"[GWIZ] v15.11.17 - defense systems online\r\n").unwrap();
for _ in 0..3 {
stream.write(b"username: ").unwrap();
let uname = read_str(&mut stream);
stream.write(b"password: ").unwrap();
let pword = read_str(&mut stream);
println!("login attempt <{}> / <{}>", uname, pword);
if uname == "rjbs" && pword == "secret" { return spill_guts(stream) }
stream.write(b"invalid login\r\n").unwrap();
}
stream.write(b"too many attempts\r\n").unwrap();
}
fn spill_guts (stream: TcpStream) {
let mut stream = stream;
stream.write(b"launch codes: 123456\r\n").unwrap();
}
fn main() {
let listen = "127.0.0.1:9999";
let listener = TcpListener::bind( &listen )
.ok()
.expect( &format!("can't bind to {}!", listen) );
println!("listening started, ready to accept");
for stream in listener.incoming() {
thread::spawn(move || say_hello(stream.unwrap()) );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment