diff --git a/appmgr/Cargo.lock b/appmgr/Cargo.lock index 4071c96bf..bcd63766a 100644 --- a/appmgr/Cargo.lock +++ b/appmgr/Cargo.lock @@ -799,6 +799,7 @@ dependencies = [ "libc", "log", "nix 0.22.0", + "openssh-keys", "openssl", "patch-db", "pin-project", @@ -1569,6 +1570,17 @@ version = "0.1.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7ffc5c5338469d4d3ea17d269fa8ea3512ad247247c30bd2df69e68309ed0a08" +[[package]] +name = "md-5" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b5a279bb9607f9f53c22d496eade00d138d1bdcccd07d74650387cf94942a15" +dependencies = [ + "block-buffer 0.9.0", + "digest 0.9.0", + "opaque-debug 0.3.0", +] + [[package]] name = "memchr" version = "2.4.0" @@ -1752,6 +1764,19 @@ version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "624a8340c38c1b80fd549087862da4ba43e08858af025b236e509b6649fc13d5" +[[package]] +name = "openssh-keys" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7249a699cdeea261ac73f1bf9350777cb867324f44373aafb5a287365bf1771" +dependencies = [ + "base64 0.13.0", + "byteorder", + "md-5", + "sha2 0.9.5", + "thiserror", +] + [[package]] name = "openssl" version = "0.10.35" diff --git a/appmgr/Cargo.toml b/appmgr/Cargo.toml index a2ff0f370..6c317f556 100644 --- a/appmgr/Cargo.toml +++ b/appmgr/Cargo.toml @@ -68,6 +68,7 @@ lazy_static = "1.4" libc = "0.2.86" log = "0.4.11" nix = "0.22.0" +openssh-keys = "0.5.0" openssl = { version = "0.10.30", features = ["vendored"] } patch-db = { version = "*", path = "../../patch-db/patch-db" } pin-project = "1.0.6" diff --git a/appmgr/migrations/20210629193146_Init.sql b/appmgr/migrations/20210629193146_Init.sql index 0744a69e4..2dfe21467 100644 --- a/appmgr/migrations/20210629193146_Init.sql +++ b/appmgr/migrations/20210629193146_Init.sql @@ -18,4 +18,11 @@ CREATE TABLE IF NOT EXISTS session CREATE TABLE IF NOT EXISTS password ( hash TEXT NOT NULL PRIMARY KEY +); +CREATE TABLE IF NOT EXISTS ssh_keys +( + fingerprint TEXT NOT NULL, + openssh_pubkey TEXT NOT NULL, + created_at TEXT NOT NULL, + PRIMARY KEY (fingerprint) ); \ No newline at end of file diff --git a/appmgr/sqlx-data.json b/appmgr/sqlx-data.json index 82255381f..a35673e21 100644 --- a/appmgr/sqlx-data.json +++ b/appmgr/sqlx-data.json @@ -1,5 +1,15 @@ { "db": "SQLite", + "06f2423bb5f9b9520cc3cf010132a5cb6157cccdcdb6b8a5695261fa7434f176": { + "query": "INSERT INTO ssh_keys (fingerprint, openssh_pubkey, created_at) VALUES (?, ?, datetime('now'))", + "describe": { + "columns": [], + "parameters": { + "Right": 2 + }, + "nullable": [] + } + }, "118d59de5cf930d5a3b5667b2220e9a3d593bd84276beb2b76c93b2694b0fd72": { "query": "INSERT INTO session (id, user_agent, metadata) VALUES (?, ?, ?)", "describe": { @@ -114,6 +124,16 @@ ] } }, + "6440354d73a67c041ea29508b43b5f309d45837a44f1a562051ad540d894c7d6": { + "query": "DELETE FROM ssh_keys WHERE fingerprint = ?", + "describe": { + "columns": [], + "parameters": { + "Right": 1 + }, + "nullable": [] + } + }, "8595651866e7db772260bd79e19d55b7271fd795b82a99821c935a9237c1aa16": { "query": "SELECT interface, key FROM tor WHERE package = ?", "describe": { @@ -137,5 +157,83 @@ false ] } + }, + "a6b0c8909a3a5d6d9156aebfb359424e6b5a1d1402e028219e21726f1ebd282e": { + "query": "SELECT fingerprint, openssh_pubkey, created_at FROM ssh_keys", + "describe": { + "columns": [ + { + "name": "fingerprint", + "ordinal": 0, + "type_info": "Text" + }, + { + "name": "openssh_pubkey", + "ordinal": 1, + "type_info": "Text" + }, + { + "name": "created_at", + "ordinal": 2, + "type_info": "Text" + } + ], + "parameters": { + "Right": 0 + }, + "nullable": [ + false, + false, + false + ] + } + }, + "d5117054072476377f3c4f040ea429d4c9b2cf534e76f35c80a2bf60e8599cca": { + "query": "SELECT openssh_pubkey FROM ssh_keys", + "describe": { + "columns": [ + { + "name": "openssh_pubkey", + "ordinal": 0, + "type_info": "Text" + } + ], + "parameters": { + "Right": 0 + }, + "nullable": [ + false + ] + } + }, + "de2a5e90798d606047ab8180c044baac05469c0cdf151316bd58ee8c7196fdef": { + "query": "SELECT * FROM ssh_keys WHERE fingerprint = ?", + "describe": { + "columns": [ + { + "name": "fingerprint", + "ordinal": 0, + "type_info": "Text" + }, + { + "name": "openssh_pubkey", + "ordinal": 1, + "type_info": "Text" + }, + { + "name": "created_at", + "ordinal": 2, + "type_info": "Text" + } + ], + "parameters": { + "Right": 1 + }, + "nullable": [ + false, + false, + false + ] + } } } \ No newline at end of file diff --git a/appmgr/src/error.rs b/appmgr/src/error.rs index 449ca4f10..c884c6b4f 100644 --- a/appmgr/src/error.rs +++ b/appmgr/src/error.rs @@ -47,6 +47,7 @@ pub enum ErrorKind { MigrationFailed = 39, Uninitialized = 40, ParseNetAddress = 41, + ParseSshKey = 42, } impl ErrorKind { pub fn as_str(&self) -> &'static str { @@ -93,6 +94,7 @@ impl ErrorKind { MigrationFailed => "Migration Failed", Uninitialized => "Uninitialized", ParseNetAddress => "Net Address Parsing Error", + ParseSshKey => "SSH Key Parsing Error", } } } diff --git a/appmgr/src/lib.rs b/appmgr/src/lib.rs index f841fda92..bdf0261e0 100644 --- a/appmgr/src/lib.rs +++ b/appmgr/src/lib.rs @@ -35,6 +35,7 @@ pub mod migration; pub mod net; pub mod registry; pub mod s9pk; +pub mod ssh; pub mod status; pub mod util; pub mod version; diff --git a/appmgr/src/ssh.rs b/appmgr/src/ssh.rs new file mode 100644 index 000000000..ca98d5ba8 --- /dev/null +++ b/appmgr/src/ssh.rs @@ -0,0 +1,177 @@ +use std::path::Path; + +use anyhow::anyhow; +use clap::ArgMatches; +use rpc_toolkit::command; +use sqlx::{Pool, Sqlite}; + +use crate::context::EitherContext; +use crate::util::{display_none, display_serializable, IoFormat}; +use crate::Error; + +static SSH_AUTHORIZED_KEYS_FILE: &str = "~/.ssh/authorized_keys"; + +#[derive(serde::Deserialize, serde::Serialize)] +pub struct PubKey( + #[serde(serialize_with = "crate::util::serialize_display")] + #[serde(deserialize_with = "crate::util::deserialize_from_str")] + openssh_keys::PublicKey, +); + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "kebab-case")] +pub struct SshKeyResponse { + pub alg: String, + pub hash: String, + pub hostname: String, + pub created_at: String, +} +impl std::fmt::Display for SshKeyResponse { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + write!( + f, + "{} {} {} {}", + self.created_at, self.alg, self.hash, self.hostname + ) + } +} + +impl std::str::FromStr for PubKey { + type Err = Error; + fn from_str(s: &str) -> Result { + s.parse().map(|pk| PubKey(pk)).map_err(|e| Error { + source: e.into(), + kind: crate::ErrorKind::ParseSshKey, + revision: None, + }) + } +} + +#[command(subcommands(add, remove, list,))] +pub fn ssh(#[context] ctx: EitherContext) -> Result { + Ok(ctx) +} + +#[command(display(display_none))] +pub async fn add(#[context] ctx: EitherContext, #[arg] key: PubKey) -> Result { + let pool = &ctx.as_rpc().unwrap().secret_store; + // check fingerprint for duplicates + let fp = key.0.fingerprint_md5(); + if sqlx::query!("SELECT * FROM ssh_keys WHERE fingerprint = ?", fp) + .fetch_optional(pool) + .await? + .is_none() + { + // if no duplicates, insert into DB + let raw_key = format!("{}", key.0); + sqlx::query!( + "INSERT INTO ssh_keys (fingerprint, openssh_pubkey, created_at) VALUES (?, ?, datetime('now'))" + , fp, raw_key).execute(pool).await?; + // insert into live key file, for now we actually do a wholesale replacement of the keys file, for maximum + // consistency + sync_keys_from_db(pool, Path::new(SSH_AUTHORIZED_KEYS_FILE)).await?; + } + // return fingerprint + Ok(fp) +} +#[command(display(display_none))] +pub async fn remove( + #[context] ctx: EitherContext, + #[arg] fingerprint: String, +) -> Result<(), Error> { + let pool = &ctx.as_rpc().unwrap().secret_store; + // check if fingerprint is in DB + // if in DB, remove it from DB + let n = sqlx::query!("DELETE FROM ssh_keys WHERE fingerprint = ?", fingerprint) + .execute(pool) + .await? + .rows_affected(); + // if not in DB, Err404 + if n == 0 { + Err(Error { + source: anyhow::anyhow!("SSH Key Not Found"), + kind: crate::error::ErrorKind::NotFound, + revision: None, + }) + } else { + // AND overlay key file + sync_keys_from_db(pool, Path::new(SSH_AUTHORIZED_KEYS_FILE)).await?; + Ok(()) + } +} + +fn display_all_ssh_keys(all: Vec, matches: &ArgMatches<'_>) { + use prettytable::*; + + if matches.is_present("format") { + return display_serializable(all, matches); + } + + let mut table = Table::new(); + table.add_row(row![bc => + "CREATED AT", + "ALGORITHM", + "HASH", + "HOSTNAME", + ]); + for key in all { + let row = row![ + &format!("{}", key.created_at), + &key.alg, + &key.hash, + &key.hostname, + ]; + table.add_row(row); + } + table.print_tty(false); +} + +#[command(display(display_all_ssh_keys))] +pub async fn list( + #[context] ctx: EitherContext, + #[allow(unused_variables)] + #[arg(long = "format")] + format: Option, +) -> Result, Error> { + let pool = &ctx.as_rpc().unwrap().secret_store; + // list keys in DB and return them + let entries = sqlx::query!("SELECT fingerprint, openssh_pubkey, created_at FROM ssh_keys") + .fetch_all(pool) + .await?; + Ok(entries + .into_iter() + .map(|r| { + let k = PubKey(r.openssh_pubkey.parse().unwrap()).0; + let alg = k.keytype().to_owned(); + let hash = k.fingerprint(); + let hostname = k.comment.unwrap_or("".to_owned()); + let created_at = r.created_at; + SshKeyResponse { + alg, + hash, + hostname, + created_at, + } + }) + .collect()) +} + +pub async fn sync_keys_from_db(pool: &Pool, dest: &Path) -> Result<(), Error> { + let keys = sqlx::query!("SELECT openssh_pubkey FROM ssh_keys") + .fetch_all(pool) + .await?; + let contents: String = keys + .into_iter() + .map(|k| format!("{}\n", k.openssh_pubkey)) + .collect(); + let ssh_dir = dest.parent().ok_or_else(|| { + Error::new( + anyhow!("SSH Key File cannot be \"/\""), + crate::ErrorKind::Filesystem, + ) + })?; + if tokio::fs::metadata(ssh_dir).await.is_err() { + tokio::fs::create_dir_all(ssh_dir).await?; + } + std::fs::write(dest, contents).map_err(|e| e.into()) +}