Skip to content

Commit

Permalink
rotate key
Browse files Browse the repository at this point in the history
  • Loading branch information
dr-bonez committed Nov 17, 2023
1 parent d03aadb commit 89a6049
Show file tree
Hide file tree
Showing 8 changed files with 147 additions and 9 deletions.
2 changes: 1 addition & 1 deletion build/lib/scripts/dhclient-exit-hook
Original file line number Diff line number Diff line change
@@ -1 +1 @@
embassy-cli net dhcp update $interface
start-cli net dhcp update $interface
9 changes: 8 additions & 1 deletion core/models/src/id/interface.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,18 @@
use std::path::Path;
use std::str::FromStr;

use serde::{Deserialize, Deserializer, Serialize};

use crate::Id;
use crate::{Id, InvalidId};

#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
pub struct InterfaceId(Id);
impl FromStr for InterfaceId {
type Err = InvalidId;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(Self(Id::try_from(s.to_owned())?))
}
}
impl From<Id> for InterfaceId {
fn from(id: Id) -> Self {
Self(id)
Expand Down

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

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

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

96 changes: 95 additions & 1 deletion core/startos/src/net/keys.rs
Original file line number Diff line number Diff line change
@@ -1,17 +1,25 @@
use std::collections::BTreeMap;

use clap::ArgMatches;
use color_eyre::eyre::eyre;
use models::{Id, InterfaceId, PackageId};
use openssl::pkey::{PKey, Private};
use openssl::sha::Sha256;
use openssl::x509::X509;
use p256::elliptic_curve::pkcs8::EncodePrivateKey;
use sqlx::PgExecutor;
use rpc_toolkit::command;
use sqlx::{Acquire, PgExecutor};
use ssh_key::private::Ed25519PrivateKey;
use torut::onion::{OnionAddressV3, TorSecretKeyV3};
use zeroize::Zeroize;

use crate::config::{configure, ConfigureContext};
use crate::context::RpcContext;
use crate::disk::fsck::RequiresReboot;
use crate::net::ssl::CertPair;
use crate::prelude::*;
use crate::util::crypto::ed25519_expand_key;
use crate::util::display_none;

// TODO: delete once we may change tor addresses
async fn compat(
Expand Down Expand Up @@ -271,3 +279,89 @@ pub fn test_keygen() {
key.tor_key();
key.openssl_key_nistp256();
}

fn display_requires_reboot(arg: RequiresReboot, matches: &ArgMatches) {
if arg.0 {
println!("Server must be restarted for changes to take effect");
}
}

#[command(rename = "rotate-key", display(display_requires_reboot))]
pub async fn rotate_key(
#[context] ctx: RpcContext,
#[arg] package: Option<PackageId>,
#[arg] interface: Option<InterfaceId>,
) -> Result<RequiresReboot, Error> {
let mut pgcon = ctx.secret_store.acquire().await?;
let mut tx = pgcon.begin().await?;
if let Some(package) = package {
let Some(interface) = interface else {
return Err(Error::new(
eyre!("Must specify interface"),
ErrorKind::InvalidRequest,
));
};
sqlx::query!(
"DELETE FROM tor WHERE package = $1 AND interface = $2",
&package,
&interface,
)
.execute(&mut *tx)
.await?;
sqlx::query!(
"DELETE FROM network_keys WHERE package = $1 AND interface = $2",
&package,
&interface,
)
.execute(&mut *tx)
.await?;
let new_key =
Key::for_interface(&mut *tx, Some((package.clone(), interface.clone()))).await?;
ctx.db
.mutate(|v| {
let installed = v
.as_package_data_mut()
.as_idx_mut(&package)
.or_not_found(&package)?
.as_installed_mut()
.or_not_found("installed")?;
installed.as_status_mut().as_configured_mut().ser(&false)?;
let addrs = installed
.as_interface_addresses_mut()
.as_idx_mut(&interface)
.or_not_found(&interface)?;
if let Some(lan) = addrs.as_lan_address_mut().transpose_mut() {
lan.ser(&new_key.local_address())?;
}
if let Some(lan) = addrs.as_tor_address_mut().transpose_mut() {
lan.ser(&new_key.tor_address().to_string())?;
}

Ok(())
})
.await?;
configure(
&ctx,
&package,
ConfigureContext {
breakages: BTreeMap::new(),
timeout: None,
config: None,
overrides: BTreeMap::new(),
dry_run: false,
},
)
.await?;
Ok(RequiresReboot(false))
} else {
sqlx::query!("UPDATE account SET tor_key = NULL, network_key = gen_random_bytes(32)")
.execute(&mut *tx)
.await?;
let new_key = Key::for_interface(&mut *tx, None).await?;
let url = format!("https://{}", new_key.tor_address()).parse()?;
ctx.db
.mutate(|v| v.as_server_info_mut().as_tor_address_mut().ser(&url))
.await?;
Ok(RequiresReboot(true))
}
}
2 changes: 1 addition & 1 deletion core/startos/src/net/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ pub mod wifi;

pub const PACKAGE_CERT_PATH: &str = "/var/lib/embassy/ssl";

#[command(subcommands(tor::tor, dhcp::dhcp, ssl::ssl))]
#[command(subcommands(tor::tor, dhcp::dhcp, ssl::ssl, keys::rotate_key))]
pub fn net() -> Result<(), Error> {
Ok(())
}
Expand Down
5 changes: 0 additions & 5 deletions core/startos/src/net/tor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,11 +53,6 @@ lazy_static! {
static ref PROGRESS_REGEX: Regex = Regex::new("PROGRESS=([0-9]+)").unwrap();
}

#[test]
fn random_key() {
println!("x'{}'", hex::encode(rand::random::<[u8; 32]>()));
}

#[command(subcommands(list_services, logs, reset))]
pub fn tor() -> Result<(), Error> {
Ok(())
Expand Down

0 comments on commit 89a6049

Please sign in to comment.