From 7e1627e16535ca41166e255585f52faf1259cf80 Mon Sep 17 00:00:00 2001 From: c0repwn3r Date: Thu, 11 May 2023 13:13:30 -0400 Subject: [PATCH] enrollment codes --- trifid-api/src/config.rs | 5 + trifid-api/src/main.rs | 1 + trifid-api/src/routes/v1/hosts.rs | 229 +++++++++++++++++- .../trifid_api_entities/src/entity/host.rs | 8 + .../src/entity/host_enrollment_code.rs | 32 +++ .../trifid_api_entities/src/entity/mod.rs | 1 + .../trifid_api_entities/src/entity/prelude.rs | 1 + trifid-api/trifid_api_migration/src/lib.rs | 2 + ...0511_create_table_host_enrollment_codes.rs | 43 ++++ 9 files changed, 320 insertions(+), 2 deletions(-) create mode 100644 trifid-api/trifid_api_entities/src/entity/host_enrollment_code.rs create mode 100644 trifid-api/trifid_api_migration/src/m20230511_120511_create_table_host_enrollment_codes.rs diff --git a/trifid-api/src/config.rs b/trifid-api/src/config.rs index e1d3f95..5f26f5e 100644 --- a/trifid-api/src/config.rs +++ b/trifid-api/src/config.rs @@ -81,6 +81,8 @@ pub struct TrifidConfigTokens { pub totp_setup_timeout_time_seconds: u64, #[serde(default = "mfa_tokens_expiry_time")] pub mfa_tokens_expiry_time_seconds: u64, + #[serde(default = "enrollment_tokens_expiry_time")] + pub enrollment_tokens_expiry_time: u64 } #[derive(Serialize, Deserialize, Debug)] @@ -115,3 +117,6 @@ fn totp_setup_timeout_time() -> u64 { fn mfa_tokens_expiry_time() -> u64 { 600 } // 10 minutes +fn enrollment_tokens_expiry_time() -> u64 { + 600 +} // 10 minutes \ No newline at end of file diff --git a/trifid-api/src/main.rs b/trifid-api/src/main.rs index a77ee9d..ffaea11 100644 --- a/trifid-api/src/main.rs +++ b/trifid-api/src/main.rs @@ -101,6 +101,7 @@ async fn main() -> Result<(), Box> { .service(routes::v1::hosts::delete_host) .service(routes::v1::hosts::edit_host) .service(routes::v1::hosts::block_host) + .service(routes::v1::hosts::enroll_host) }) .bind(CONFIG.server.bind)? .run() diff --git a/trifid-api/src/routes/v1/hosts.rs b/trifid-api/src/routes/v1/hosts.rs index bf8a26e..0da947f 100644 --- a/trifid-api/src/routes/v1/hosts.rs +++ b/trifid-api/src/routes/v1/hosts.rs @@ -39,13 +39,23 @@ // This endpoint is considered done. No major features should be added or removed, unless it fixes bugs. // This endpoint requires the `definednetworking` extension to be enabled to be used. // This endpoint has additional functionality enabled by the extended_hosts feature flag. +// +//#POST /v1/hosts/{host_id}/block t+parity:full t+type:documented t+status:done t+feature:definednetworking +// This endpoint has full parity with the original API. It has been recreated from the original API documentation. +// This endpoint is considered done. No major features should be added or removed, unless it fixes bugs. +// This endpoint requires the `definednetworking` extension to be enabled to be used. +// +//#POST /v1/hosts/{host_id}/enrollment-code t+parity:full t+type:documented t+status:done t+feature:definednetworking +// This endpoint has full parity with the original API. It has been recreated from the original API documentation. +// This endpoint is considered done. No major features should be added or removed, unless it fixes bugs. +// This endpoint requires the `definednetworking` extension to be enabled to be used. use crate::auth_tokens::{enforce_2fa, enforce_api_token, TokenInfo}; use crate::cursor::Cursor; use crate::error::{APIError, APIErrorsResponse}; use crate::routes::v1::trifid::SUPPORTED_EXTENSIONS; -use crate::timers::TIME_FORMAT; -use crate::tokens::random_id; +use crate::timers::{expires_in_seconds, TIME_FORMAT}; +use crate::tokens::{random_id, random_token}; use crate::AppState; use actix_web::web::{Data, Json, Path, Query}; use actix_web::{delete, get, post, put, HttpRequest, HttpResponse}; @@ -61,6 +71,7 @@ use std::net::{Ipv4Addr, SocketAddrV4}; use std::str::FromStr; use std::time::{SystemTime, UNIX_EPOCH}; use trifid_api_entities::entity::{host, host_static_address, network, organization}; +use crate::config::CONFIG; #[derive(Serialize, Deserialize)] pub struct ListHostsRequestOpts { @@ -1780,3 +1791,217 @@ pub async fn block_host( metadata: BlockHostResponseMetadata {}, }) } + +#[derive(Serialize, Deserialize)] +pub struct CodeResponse { + pub code: String, + #[serde(rename = "lifetimeSeconds")] + pub lifetime_seconds: u64 +} + +#[derive(Serialize, Deserialize)] +pub struct EnrollmentCodeResponse { + pub data: EnrollmentCodeResponseData, + pub metadata: EnrollmentCodeResponseMetadata +} + +#[derive(Serialize, Deserialize)] +pub struct EnrollmentCodeResponseData { + #[serde(rename = "enrollmentCode")] + pub enrollment_code: CodeResponse +} + +#[derive(Serialize, Deserialize)] +pub struct EnrollmentCodeResponseMetadata {} + +#[post("/v1/hosts/{host_id}/enrollment-code")] +pub async fn enroll_host(id: Path, req_info: HttpRequest, db: Data) -> HttpResponse { + let session_info = enforce_2fa(&req_info, &db.conn) + .await + .unwrap_or(TokenInfo::NotPresent); + let api_token_info = enforce_api_token(&req_info, &["hosts:enroll"], &db.conn) + .await + .unwrap_or(TokenInfo::NotPresent); + + // If neither are present, throw an error + if matches!(session_info, TokenInfo::NotPresent) + && matches!(api_token_info, TokenInfo::NotPresent) + { + return HttpResponse::Unauthorized().json(APIErrorsResponse { + errors: vec![ + APIError { + code: "ERR_UNAUTHORIZED".to_string(), + message: "This endpoint requires either a fully authenticated user or a token with the hosts:enroll scope".to_string(), + path: None, + } + ], + }); + } + + // If both are present, throw an error + if matches!(session_info, TokenInfo::AuthToken(_)) + && matches!(api_token_info, TokenInfo::ApiToken(_)) + { + return HttpResponse::BadRequest().json(APIErrorsResponse { + errors: vec![ + APIError { + code: "ERR_AMBIGUOUS_AUTHENTICATION".to_string(), + message: "Both a user token and an API token with the proper scope was provided. Please only provide one.".to_string(), + path: None + } + ], + }); + } + + let org_id = match api_token_info { + TokenInfo::ApiToken(tkn) => tkn.organization, + _ => { + // we have a session token, which means we have to do a db request to get the organization that this user owns + let user = match session_info { + TokenInfo::AuthToken(tkn) => tkn.session_info.user, + _ => unreachable!(), + }; + + let org = match organization::Entity::find() + .filter(organization::Column::Owner.eq(user.id)) + .one(&db.conn) + .await + { + Ok(r) => r, + Err(e) => { + error!("database error: {}", e); + return HttpResponse::InternalServerError().json(APIErrorsResponse { + errors: vec![ + APIError { + code: "ERR_DB_ERROR".to_string(), + message: "There was an error performing the database request, please try again later.".to_string(), + path: None, + } + ], + }); + } + }; + + if let Some(org) = org { + org.id + } else { + return HttpResponse::Unauthorized().json(APIErrorsResponse { + errors: vec![ + APIError { + code: "ERR_NO_ORG".to_string(), + message: "This user does not own any organizations. Try using an API token instead.".to_string(), + path: None + } + ], + }); + } + } + }; + + let net_id; + + let net = match network::Entity::find() + .filter(network::Column::Organization.eq(&org_id)) + .one(&db.conn) + .await + { + Ok(r) => r, + Err(e) => { + error!("database error: {}", e); + return HttpResponse::InternalServerError().json(APIErrorsResponse { + errors: vec![ + APIError { + code: "ERR_DB_ERROR".to_string(), + message: "There was an error performing the database request, please try again later.".to_string(), + path: None, + } + ], + }); + } + }; + + if let Some(net) = net { + net_id = net.id; + } else { + return HttpResponse::Unauthorized().json(APIErrorsResponse { + errors: vec![APIError { + code: "ERR_NO_NET".to_string(), + message: "This user does not own any networks. Try using an API token instead." + .to_string(), + path: None, + }], + }); + } + + let host = match host::Entity::find() + .filter(host::Column::Id.eq(id.into_inner())) + .one(&db.conn) + .await + { + Ok(h) => h, + Err(e) => { + error!("Database error: {}", e); + return HttpResponse::InternalServerError().json(APIErrorsResponse { + errors: vec![APIError { + code: "ERR_DB_ERROR".to_string(), + message: "There was an error with the database query. Please try again later." + .to_string(), + path: None, + }], + }); + } + }; + + let host = match host { + Some(h) => h, + None => { + return HttpResponse::Unauthorized().json(APIErrorsResponse { + errors: vec![APIError { + code: "ERR_UNAUTHORIZED".to_string(), + message: + "This resource does not exist or you do not have permission to access it." + .to_string(), + path: None, + }], + }) + } + }; + + if host.network != net_id { + return HttpResponse::Unauthorized().json(APIErrorsResponse { + errors: vec![APIError { + code: "ERR_UNAUTHORIZED".to_string(), + message: "This resource does not exist or you do not have permission to access it." + .to_string(), + path: None, + }], + }); + } + + let enrollment_code = trifid_api_entities::entity::host_enrollment_code::Model { + id: random_token("ec"), + host: host.id, + expires_on: expires_in_seconds(CONFIG.tokens.enrollment_tokens_expiry_time) as i64, + }; + let ec_am = enrollment_code.into_active_model(); + + let code = match ec_am.insert(&db.conn).await { + Ok(h) => h, + Err(e) => { + error!("Database error: {}", e); + return HttpResponse::InternalServerError().json(APIErrorsResponse { + errors: vec![APIError { + code: "ERR_DB_ERROR".to_string(), + message: "There was an error with the database query. Please try again later." + .to_string(), + path: None, + }], + }); + } + }; + + HttpResponse::Ok().json(EnrollmentCodeResponse { + data: EnrollmentCodeResponseData { enrollment_code: CodeResponse { code: code.id, lifetime_seconds: CONFIG.tokens.enrollment_tokens_expiry_time } }, + metadata: EnrollmentCodeResponseMetadata {}, + }) +} \ No newline at end of file diff --git a/trifid-api/trifid_api_entities/src/entity/host.rs b/trifid-api/trifid_api_entities/src/entity/host.rs index 73c4cf7..be78625 100644 --- a/trifid-api/trifid_api_entities/src/entity/host.rs +++ b/trifid-api/trifid_api_entities/src/entity/host.rs @@ -27,6 +27,8 @@ pub struct Model { pub enum Relation { #[sea_orm(has_many = "super::host_config_override::Entity")] HostConfigOverride, + #[sea_orm(has_many = "super::host_enrollment_code::Entity")] + HostEnrollmentCode, #[sea_orm(has_many = "super::host_static_address::Entity")] HostStaticAddress, #[sea_orm( @@ -53,6 +55,12 @@ impl Related for Entity { } } +impl Related for Entity { + fn to() -> RelationDef { + Relation::HostEnrollmentCode.def() + } +} + impl Related for Entity { fn to() -> RelationDef { Relation::HostStaticAddress.def() diff --git a/trifid-api/trifid_api_entities/src/entity/host_enrollment_code.rs b/trifid-api/trifid_api_entities/src/entity/host_enrollment_code.rs new file mode 100644 index 0000000..8f8c7ab --- /dev/null +++ b/trifid-api/trifid_api_entities/src/entity/host_enrollment_code.rs @@ -0,0 +1,32 @@ +//! `SeaORM` Entity. Generated by sea-orm-codegen 0.11.2 + +use sea_orm::entity::prelude::*; + +#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq)] +#[sea_orm(table_name = "host_enrollment_code")] +pub struct Model { + #[sea_orm(primary_key, auto_increment = false)] + pub id: String, + pub host: String, + pub expires_on: i64, +} + +#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)] +pub enum Relation { + #[sea_orm( + belongs_to = "super::host::Entity", + from = "Column::Host", + to = "super::host::Column::Id", + on_update = "Cascade", + on_delete = "Cascade" + )] + Host, +} + +impl Related for Entity { + fn to() -> RelationDef { + Relation::Host.def() + } +} + +impl ActiveModelBehavior for ActiveModel {} diff --git a/trifid-api/trifid_api_entities/src/entity/mod.rs b/trifid-api/trifid_api_entities/src/entity/mod.rs index d82ab21..1fbb5ce 100644 --- a/trifid-api/trifid_api_entities/src/entity/mod.rs +++ b/trifid-api/trifid_api_entities/src/entity/mod.rs @@ -8,6 +8,7 @@ pub mod auth_token; pub mod firewall_rule; pub mod host; pub mod host_config_override; +pub mod host_enrollment_code; pub mod host_static_address; pub mod magic_link; pub mod network; diff --git a/trifid-api/trifid_api_entities/src/entity/prelude.rs b/trifid-api/trifid_api_entities/src/entity/prelude.rs index 2042b24..b0b0d3b 100644 --- a/trifid-api/trifid_api_entities/src/entity/prelude.rs +++ b/trifid-api/trifid_api_entities/src/entity/prelude.rs @@ -6,6 +6,7 @@ pub use super::auth_token::Entity as AuthToken; pub use super::firewall_rule::Entity as FirewallRule; pub use super::host::Entity as Host; pub use super::host_config_override::Entity as HostConfigOverride; +pub use super::host_enrollment_code::Entity as HostEnrollmentCode; pub use super::host_static_address::Entity as HostStaticAddress; pub use super::magic_link::Entity as MagicLink; pub use super::network::Entity as Network; diff --git a/trifid-api/trifid_api_migration/src/lib.rs b/trifid-api/trifid_api_migration/src/lib.rs index ef066c6..c3ba411 100644 --- a/trifid-api/trifid_api_migration/src/lib.rs +++ b/trifid-api/trifid_api_migration/src/lib.rs @@ -17,6 +17,7 @@ mod m20230404_133813_create_table_firewall_rules; mod m20230427_170037_create_table_hosts; mod m20230427_171517_create_table_hosts_static_addresses; mod m20230427_171529_create_table_hosts_config_overrides; +mod m20230511_120511_create_table_host_enrollment_codes; #[async_trait::async_trait] impl MigratorTrait for Migrator { @@ -37,6 +38,7 @@ impl MigratorTrait for Migrator { Box::new(m20230427_170037_create_table_hosts::Migration), Box::new(m20230427_171517_create_table_hosts_static_addresses::Migration), Box::new(m20230427_171529_create_table_hosts_config_overrides::Migration), + Box::new(m20230511_120511_create_table_host_enrollment_codes::Migration), ] } } diff --git a/trifid-api/trifid_api_migration/src/m20230511_120511_create_table_host_enrollment_codes.rs b/trifid-api/trifid_api_migration/src/m20230511_120511_create_table_host_enrollment_codes.rs new file mode 100644 index 0000000..aca855f --- /dev/null +++ b/trifid-api/trifid_api_migration/src/m20230511_120511_create_table_host_enrollment_codes.rs @@ -0,0 +1,43 @@ +use sea_orm_migration::prelude::*; +use crate::m20230427_170037_create_table_hosts::Host; + +#[derive(DeriveMigrationName)] +pub struct Migration; + +#[async_trait::async_trait] +impl MigrationTrait for Migration { + async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> { + manager + .create_table( + Table::create() + .table(HostEnrollmentCode::Table) + .col(ColumnDef::new(HostEnrollmentCode::Id).string().not_null().primary_key()) + .col(ColumnDef::new(HostEnrollmentCode::Host).string().not_null()) + .col(ColumnDef::new(HostEnrollmentCode::ExpiresOn).big_integer().not_null()) + .foreign_key( + ForeignKey::create() + .from(HostEnrollmentCode::Table, HostEnrollmentCode::Host) + .to(Host::Table, Host::Id) + .on_update(ForeignKeyAction::Cascade) + .on_delete(ForeignKeyAction::Cascade) + ) + .to_owned(), + ) + .await + } + + async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> { + manager + .drop_table(Table::drop().table(HostEnrollmentCode::Table).to_owned()) + .await + } +} + +/// Learn more at https://docs.rs/sea-query#iden +#[derive(Iden)] +pub enum HostEnrollmentCode { + Table, + Id, + Host, + ExpiresOn +}