Skip to content
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
7 changes: 6 additions & 1 deletion config-schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,8 @@
"inactivity_timeout": "5m",
"keepalive_interval": null,
"keys": "./data/keys",
"listen": "[::]:2222"
"listen": "[::]:2222",
"temporary_client_certificate_validity": "1m"
}
},
"sso_providers": {
Expand Down Expand Up @@ -416,6 +417,10 @@
"listen": {
"$ref": "#/$defs/ListenEndpoint",
"default": "[::]:2222"
},
"temporary_client_certificate_validity": {
"type": "string",
"default": "1m"
}
}
},
Expand Down
7 changes: 6 additions & 1 deletion tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,18 +120,21 @@ def stop(self):
pass
p.kill()

def start_ssh_server(self, trusted_keys=[], extra_config=""):
def start_ssh_server(self, trusted_keys=[], extra_config="", trusted_ca=[]):
port = alloc_port()
data_dir = self.ctx.tmpdir / f"sshd-{uuid.uuid4()}"
data_dir.mkdir(parents=True)
authorized_keys_path = data_dir / "authorized_keys"
authorized_keys_path.write_text("\n".join(trusted_keys))
config_path = data_dir / "sshd_config"
ssh_ca = data_dir / "trusted_ca"
ssh_ca.write_text("\n".join(trusted_ca))
config_path.write_text(
dedent(
f"""\
Port 22
AuthorizedKeysFile {authorized_keys_path}
TrustedUserCAKeys {ssh_ca}
AllowAgentForwarding yes
AllowTcpForwarding yes
GatewayPorts yes
Expand All @@ -147,9 +150,11 @@ def start_ssh_server(self, trusted_keys=[], extra_config=""):
"""
)
)

data_dir.chmod(0o700)
authorized_keys_path.chmod(0o600)
config_path.chmod(0o600)
ssh_ca.chmod(0o600)

self.start(
[
Expand Down
1 change: 1 addition & 0 deletions tests/images/ssh-server/Dockerfile
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
FROM alpine:3.14@sha256:0f2d5c38dd7a4f4f733e688e3a6733cb5ab1ac6e3cb4603a5dd564e5bfb80eed
RUN apk add openssh curl
RUN adduser -D foo && echo "foo:bar" | chpasswd
RUN passwd -u root
ENTRYPOINT ["/usr/sbin/sshd", "-De"]
152 changes: 152 additions & 0 deletions tests/test_ssh_target_auth.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
from pathlib import Path
from uuid import uuid4

from .api_client import admin_client, sdk
from .conftest import ProcessManager, WarpgateProcess
from .util import wait_port

USER_PUBLIC_KEY_PATH = Path("ssh-keys/id_ed25519.pub")
USER_PRIVATE_KEY_PATH = "ssh-keys/id_ed25519"


class Test:
@staticmethod
def _create_user_role_and_target(api, ssh_port, username: str, auth):
role = api.create_role(
sdk.RoleDataRequest(name=f"role-{uuid4()}"),
)
user = api.create_user(sdk.CreateUserRequest(username=f"user-{uuid4()}"))
api.create_public_key_credential(
user.id,
sdk.NewPublicKeyCredential(
label="Public Key",
openssh_public_key=USER_PUBLIC_KEY_PATH.read_text().strip(),
),
)
api.add_user_role(user.id, role.id)
ssh_target = api.create_target(
sdk.TargetDataRequest(
name=f"ssh-{uuid4()}",
options=sdk.TargetOptions(
sdk.TargetOptionsTargetSSHOptions(
kind="Ssh",
host="localhost",
port=ssh_port,
username=username,
auth=sdk.SSHTargetAuth(auth),
)
),
)
)
api.add_target_role(ssh_target.id, role.id)
return user, ssh_target

@staticmethod
def _run_ssh_ls(
processes: ProcessManager,
shared_wg: WarpgateProcess,
user,
ssh_target,
):
ssh_client = processes.start_ssh_client(
f"{user.username}:{ssh_target.name}@localhost",
"-p",
str(shared_wg.ssh_port),
"-o",
f"IdentityFile={USER_PRIVATE_KEY_PATH}",
"-o",
"PreferredAuthentications=publickey",
"ls",
"/bin/sh",
)
return ssh_client

def test_password(
self,
processes: ProcessManager,
timeout,
shared_wg: WarpgateProcess,
):
ssh_port = processes.start_ssh_server()

wait_port(ssh_port)

url = f"https://localhost:{shared_wg.http_port}"
with admin_client(url) as api:
user, ssh_target = self._create_user_role_and_target(
api,
ssh_port,
username="foo",
auth=sdk.SSHTargetAuthSshTargetPasswordAuth(
kind="Password",
password="bar",
),
)

ssh_client = self._run_ssh_ls(
processes,
shared_wg,
user,
ssh_target,
)
assert ssh_client.communicate(timeout=timeout)[0] == b"/bin/sh\n"
assert ssh_client.returncode == 0

def test_certificate(
self,
processes: ProcessManager,
wg_c_ed25519_pubkey: Path,
timeout,
shared_wg: WarpgateProcess,
):
ssh_port = processes.start_ssh_server(
trusted_ca=[wg_c_ed25519_pubkey.read_text()]
)

wait_port(ssh_port)

url = f"https://localhost:{shared_wg.http_port}"
with admin_client(url) as api:
user, ssh_target = self._create_user_role_and_target(
api,
ssh_port,
username="root",
auth=sdk.SSHTargetAuthSshTargetCertificateAuth(kind="Certificate"),
)

ssh_client = self._run_ssh_ls(
processes,
shared_wg,
user,
ssh_target,
)
assert ssh_client.communicate(timeout=timeout)[0] == b"/bin/sh\n"
assert ssh_client.returncode == 0

def test_none(
self,
processes: ProcessManager,
timeout,
shared_wg: WarpgateProcess,
):
ssh_port = processes.start_ssh_server()

wait_port(ssh_port)

url = f"https://localhost:{shared_wg.http_port}"
with admin_client(url) as api:
user, ssh_target = self._create_user_role_and_target(
api,
ssh_port,
username="root",
auth=sdk.SSHTargetAuthSshTargetPublicKeyAuth(kind="PublicKey"),
)

ssh_client = self._run_ssh_ls(
processes,
shared_wg,
user,
ssh_target,
)
assert ssh_client.communicate(timeout=timeout)[0] == b""
assert ssh_client.returncode != 0
4 changes: 4 additions & 0 deletions warpgate-common/src/config/defaults.rs
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,10 @@ pub const fn _default_ssh_inactivity_timeout() -> Duration {
Duration::from_secs(60 * 5)
}

pub const fn _default_temporary_client_certificate_validity() -> Duration {
Duration::from_secs(60)
}

#[allow(clippy::unnecessary_wraps)]
pub fn _default_postgres_idle_timeout_str() -> Option<String> {
Some("10m".to_string())
Expand Down
10 changes: 9 additions & 1 deletion warpgate-common/src/config/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use defaults::{
_default_http_listen, _default_kubernetes_listen, _default_mysql_listen,
_default_postgres_listen, _default_recordings_path, _default_retention,
_default_session_max_age, _default_ssh_inactivity_timeout, _default_ssh_keys_path,
_default_ssh_listen,
_default_ssh_listen, _default_temporary_client_certificate_validity,
};
use poem::http::uri;
use poem_openapi::{Object, Union};
Expand Down Expand Up @@ -307,6 +307,13 @@ pub struct SshConfig {

#[serde(default)]
pub keepalive_interval: Option<Duration>,

#[serde(
default = "_default_temporary_client_certificate_validity",
with = "humantime_serde"
)]
#[schemars(with = "String")]
pub temporary_client_certificate_validity: Duration,
}

impl Default for SshConfig {
Expand All @@ -320,6 +327,7 @@ impl Default for SshConfig {
external_host: None,
inactivity_timeout: _default_ssh_inactivity_timeout(),
keepalive_interval: None,
temporary_client_certificate_validity: _default_temporary_client_certificate_validity(),
}
}
}
Expand Down
5 changes: 5 additions & 0 deletions warpgate-common/src/config/target.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,8 @@ pub enum SSHTargetAuth {
Password(SshTargetPasswordAuth),
#[serde(rename = "publickey")]
PublicKey(SshTargetPublicKeyAuth),
#[serde(rename = "certificate")]
Certificate(SshTargetCertificateAuth),
#[serde(rename = "iam_role")]
IamRole(SshTargetIamRoleAuth),
}
Expand All @@ -59,6 +61,9 @@ pub struct SshTargetPasswordAuth {
#[derive(Debug, Deserialize, Serialize, Clone, PartialEq, Eq, Object, Default)]
pub struct SshTargetPublicKeyAuth {}

#[derive(Debug, Deserialize, Serialize, Clone, PartialEq, Eq, Object, Default)]
pub struct SshTargetCertificateAuth {}

#[derive(Debug, Deserialize, Serialize, Clone, PartialEq, Eq, Object, Default)]
pub struct SshTargetIamRoleAuth {}

Expand Down
2 changes: 2 additions & 0 deletions warpgate-db-migrations/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ mod m00038_fix_target_auth_tags;
mod m00039_show_session_menu;
mod m00040_allowed_ip_range;
mod m00041_fix_user_role_assignment_dates;
mod m00042_target_ssh_cert;

pub struct Migrator;

Expand Down Expand Up @@ -91,6 +92,7 @@ impl MigratorTrait for Migrator {
Box::new(m00039_show_session_menu::Migration),
Box::new(m00040_allowed_ip_range::Migration),
Box::new(m00041_fix_user_role_assignment_dates::Migration),
Box::new(m00042_target_ssh_cert::Migration),
]
}
}
Expand Down
105 changes: 105 additions & 0 deletions warpgate-db-migrations/src/m00042_target_ssh_cert.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
use sea_orm::prelude::*;
use sea_orm::{ActiveModelTrait, ColumnTrait, EntityTrait, JsonValue, QueryFilter, Set};
use sea_orm_migration::prelude::*;

use crate::m00007_targets_and_roles::target;

pub struct Migration;

impl MigrationName for Migration {
fn name(&self) -> &str {
"m00042_target_ssh_cert"
}
}

#[async_trait::async_trait]
impl MigrationTrait for Migration {
async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
let conn = manager.get_connection();

// Find SSH targets
let ssh_targets = target::Entity::find()
.filter(target::Column::Kind.eq(target::TargetKind::Ssh))
.all(conn)
.await?;

for target in ssh_targets {
let mut options = target
.options
.get("ssh")
.unwrap_or_default()
.clone();

if let Some(auth) = options.get_mut("auth") {
if auth.get("kind").is_some() {
continue;
} else if let Some(password) = auth.get("password").cloned() {
*auth = serde_json::json!({
"kind": "password",
"password": password,
});
} else {
*auth = serde_json::json!({
"kind": "publickey",
});
}

let mut target: target::ActiveModel = target.into();
let options = serde_json::json!({"ssh": options});
target.options = Set(options);
target.update(conn).await?;
}
}
Ok(())
}

async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
let conn = manager.get_connection();

// Find SSH targets
let ssh_targets = target::Entity::find()
.filter(target::Column::Kind.eq(target::TargetKind::Ssh))
.all(conn)
.await?;

// Check if there is a target authenticated by a certificate
let has_certificates = ssh_targets
.iter()
.filter_map(|t| t.options.get("ssh"))
.filter_map(|t| t.get("auth"))
.any(|t| {
let value = JsonValue::String("certificate".to_string());
t.get("kind") == Some(&value)
});

if has_certificates {
// At least one target is using certificate auth
// reversing would fallback to pubkey, which would not work
assert!(!has_certificates, "This migration cannot be reversed");
}

for target in ssh_targets {
let mut options = target
.options
.get("ssh")
.unwrap_or(Default::default())
.clone();

if let Some(auth) = options.get_mut("auth") {
if let Some(password) = auth.get("password").cloned() {
*auth = serde_json::json!({
"password": password,
});
} else {
*auth = serde_json::json!({});
}

let mut target: target::ActiveModel = target.into();
let options = serde_json::json!({"ssh": options});
target.options = Set(options);
target.update(conn).await?;
}
}
Ok(())
}
}
Loading
Loading