Skip to content

Commit

Permalink
Add optional secret for authenticating clients (#1)
Browse files Browse the repository at this point in the history
* Add optional secret for authenticating clients

* Add server challenge to authentication

* Refactor and simplify code, reduce dependencies

* Update README to describe HMAC authentication

Co-authored-by: Eric Zhang <ekzhang1@gmail.com>
  • Loading branch information
jtroo and ekzhang authored Apr 8, 2022
1 parent ebae014 commit d5089ca
Show file tree
Hide file tree
Showing 9 changed files with 260 additions and 19 deletions.
90 changes: 90 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,11 @@ path = "src/main.rs"
anyhow = { version = "1.0.56", features = ["backtrace"] }
clap = { version = "3.1.8", features = ["derive"] }
dashmap = "5.2.0"
hex = "0.4.3"
hmac = "0.12.1"
serde = { version = "1.0.136", features = ["derive"] }
serde_json = "1.0.79"
sha2 = "0.10.2"
tokio = { version = "1.17.0", features = ["full"] }
tracing = "0.1.32"
tracing-subscriber = "0.3.10"
Expand Down
28 changes: 21 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ This will expose your local port at `localhost:8000` to the public internet at `

Similar to [localtunnel](https://github.com/localtunnel/localtunnel) and [ngrok](https://ngrok.io/), except `bore` is intended to be a highly efficient, unopinionated tool for forwarding TCP traffic that is simple to install and easy to self-host, with no frills attached.

(`bore` totals less than 300 lines of safe, async Rust code and is trivial to set up — just run a single binary for the client and server.)
(`bore` totals less than 400 lines of safe, async Rust code and is trivial to set up — just run a single binary for the client and server.)

## Detailed Usage

Expand All @@ -38,7 +38,7 @@ You can optionally pass in a `--port` option to pick a specific port on the remo
The full options are shown below.

```shell
bore-local 0.1.0
bore-local 0.1.1
Starts a local proxy to the remote server

USAGE:
Expand All @@ -48,10 +48,11 @@ ARGS:
<LOCAL_PORT> The local port to listen on

OPTIONS:
-h, --help Print help information
-p, --port <PORT> Optional port on the remote server to select [default: 0]
-t, --to <TO> Address of the remote server to expose local ports to
-V, --version Print version information
-h, --help Print help information
-p, --port <PORT> Optional port on the remote server to select [default: 0]
-s, --secret <SECRET> Optional secret for authentication
-t, --to <TO> Address of the remote server to expose local ports to
-V, --version Print version information
```
### Self-Hosting
Expand All @@ -67,7 +68,7 @@ That's all it takes! After the server starts running at a given address, you can
The full options for the `bore server` command are shown below.
```shell
bore-server 0.1.0
bore-server 0.1.1
Runs the remote proxy server
USAGE:
Expand All @@ -76,6 +77,7 @@ USAGE:
OPTIONS:
-h, --help Print help information
--min-port <MIN_PORT> Minimum TCP port number to accept [default: 1024]
-s, --secret <SECRET> Optional secret for authentication
-V, --version Print version information
```
Expand All @@ -87,6 +89,18 @@ Whenever the server obtains a connection on the remote port, it generates a secu
For correctness reasons and to avoid memory leaks, incoming connections are only stored by the server for up to 10 seconds before being discarded if the client does not accept them.
## Authentication
On a custom deployment of `bore server`, you can optionally require a _secret_ to prevent the server from being used by others. The protocol requires clients to verify possession of the secret on each TCP connection by answering random challenges in the form of HMAC codes. (This secret is only used for the initial handshake, and no further traffic is encrypted by default.)
```shell
# on the server
bore server --secret my_secret_string
# on the client
bore local <LOCAL_PORT> --to <TO> --secret my_secret_string
```
## Acknowledgements
Created by Eric Zhang ([@ekzhang1](https://twitter.com/ekzhang1)). Licensed under the [MIT license](LICENSE).
Expand Down
79 changes: 79 additions & 0 deletions src/auth.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
//! Auth implementation for bore client and server.
use anyhow::{bail, ensure, Result};
use hmac::{Hmac, Mac};
use sha2::{Digest, Sha256};
use tokio::io::{AsyncBufRead, AsyncWrite};
use uuid::Uuid;

use crate::shared::{recv_json, send_json, ClientMessage, ServerMessage};

/// Wrapper around a MAC used for authenticating clients that have a secret.
pub struct Authenticator(Hmac<Sha256>);

impl Authenticator {
/// Generate an authenticator from a secret.
pub fn new(secret: &str) -> Self {
let hashed_secret = Sha256::new().chain_update(secret).finalize();
Self(Hmac::new_from_slice(&hashed_secret).expect("HMAC can take key of any size"))
}

/// Generate a reply message for a challenge.
pub fn answer(&self, challenge: &Uuid) -> String {
let mut hmac = self.0.clone();
hmac.update(challenge.as_bytes());
hex::encode(hmac.finalize().into_bytes())
}

/// Validate a reply to a challenge.
///
/// ```
/// use uuid:Uuid;
/// use crate::auth::Authenticator;
///
/// let auth = Authenticator::new("secret");
/// let challenge = Uuid::new_v4();
///
/// assert!(auth.validate(&challenge, auth.answer(&challenge)));
/// assert!(!auth.validate(&challenge, "wrong answer"));
/// ```
pub fn validate(&self, challenge: &Uuid, tag: &str) -> bool {
if let Ok(tag) = hex::decode(tag) {
let mut hmac = self.0.clone();
hmac.update(challenge.as_bytes());
hmac.verify_slice(&tag).is_ok()
} else {
false
}
}

/// As the server, send a challenge to the client and validate their response.
pub async fn server_handshake(
&self,
stream: &mut (impl AsyncBufRead + AsyncWrite + Unpin),
) -> Result<()> {
let challenge = Uuid::new_v4();
send_json(stream, ServerMessage::Challenge(challenge)).await?;
match recv_json(stream, &mut Vec::new()).await? {
Some(ClientMessage::Authenticate(tag)) => {
ensure!(self.validate(&challenge, &tag), "invalid secret");
Ok(())
}
_ => bail!("server requires secret, but no secret was provided"),
}
}

/// As the client, answer a challenge to attempt to authenticate with the server.
pub async fn client_handshake(
&self,
stream: &mut (impl AsyncBufRead + AsyncWrite + Unpin),
) -> Result<()> {
let challenge = match recv_json(stream, &mut Vec::new()).await? {
Some(ServerMessage::Challenge(challenge)) => challenge,
_ => bail!("expected authentication challenge, but no secret was required"),
};
let tag = self.answer(&challenge);
send_json(stream, ClientMessage::Authenticate(tag)).await?;
Ok(())
}
}
32 changes: 27 additions & 5 deletions src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ use tokio::{io::BufReader, net::TcpStream};
use tracing::{error, info, info_span, warn, Instrument};
use uuid::Uuid;

use crate::auth::Authenticator;
use crate::shared::{proxy, recv_json, send_json, ClientMessage, ServerMessage, CONTROL_PORT};

/// State structure for the client.
Expand All @@ -22,18 +23,31 @@ pub struct Client {

/// Port that is publicly available on the remote.
remote_port: u16,

/// Optional secret used to authenticate clients.
auth: Option<Authenticator>,
}

impl Client {
/// Create a new client.
pub async fn new(local_port: u16, to: &str, port: u16) -> Result<Self> {
let stream = TcpStream::connect((to, CONTROL_PORT)).await?;
pub async fn new(local_port: u16, to: &str, port: u16, secret: Option<&str>) -> Result<Self> {
let stream = TcpStream::connect((to, CONTROL_PORT))
.await
.with_context(|| format!("could not connect to {to}:{CONTROL_PORT}"))?;
let mut stream = BufReader::new(stream);

let auth = secret.map(Authenticator::new);
if let Some(auth) = &auth {
auth.client_handshake(&mut stream).await?;
}

send_json(&mut stream, ClientMessage::Hello(port)).await?;
let remote_port = match recv_json(&mut stream, &mut Vec::new()).await? {
Some(ServerMessage::Hello(remote_port)) => remote_port,
Some(ServerMessage::Error(message)) => bail!("server error: {message}"),
Some(ServerMessage::Challenge(_)) => {
bail!("server requires authentication, but no client secret was provided");
}
Some(_) => bail!("unexpected initial non-hello message"),
None => bail!("unexpected EOF"),
};
Expand All @@ -45,6 +59,7 @@ impl Client {
to: to.to_string(),
local_port,
remote_port,
auth,
})
}

Expand All @@ -62,6 +77,7 @@ impl Client {
let msg = recv_json(&mut conn, &mut buf).await?;
match msg {
Some(ServerMessage::Hello(_)) => warn!("unexpected hello"),
Some(ServerMessage::Challenge(_)) => warn!("unexpected challenge"),
Some(ServerMessage::Heartbeat) => (),
Some(ServerMessage::Connection(id)) => {
let this = Arc::clone(&this);
Expand All @@ -86,9 +102,15 @@ impl Client {
let local_conn = TcpStream::connect(("localhost", self.local_port))
.await
.context("failed TCP connection to local port")?;
let mut remote_conn = TcpStream::connect((&self.to[..], CONTROL_PORT))
.await
.context("failed TCP connection to remote port")?;
let mut remote_conn = BufReader::new(
TcpStream::connect((&self.to[..], CONTROL_PORT))
.await
.context("failed TCP connection to remote port")?,
);

if let Some(auth) = &self.auth {
auth.client_handshake(&mut remote_conn).await?;
}

send_json(&mut remote_conn, ClientMessage::Accept(id)).await?;
proxy(local_conn, remote_conn).await?;
Expand Down
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
#![forbid(unsafe_code)]
#![warn(missing_docs)]

pub mod auth;
pub mod client;
pub mod server;
pub mod shared;
Loading

0 comments on commit d5089ca

Please sign in to comment.