mirror of
https://github.com/yuezk/GlobalProtect-openconnect.git
synced 2026-11-19 06:26:14 -05:00
feat: prepare 3.0.0 release
This commit is contained in:
252 files changed
+26210
-7457
No files matched your search
@@ -1,4 +1,6 @@
|
||||
pub mod event;
|
||||
pub mod request;
|
||||
pub mod transport;
|
||||
pub mod vpn_env;
|
||||
pub mod vpn_state;
|
||||
pub mod vpnc_script;
|
||||
@@ -1,15 +1,41 @@
|
||||
use std::collections::HashMap;
|
||||
use std::{collections::HashMap, fmt};
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use zeroize::Zeroize;
|
||||
|
||||
use crate::{
|
||||
gateway::Gateway,
|
||||
os_profile::{ClientOs, OsProfile},
|
||||
hip::HipSource,
|
||||
os_profile::{ClientOs, HostIdentity, OsProfile},
|
||||
session::ConnectionPlan,
|
||||
};
|
||||
|
||||
use super::vpn_state::ConnectInfo;
|
||||
|
||||
pub const MAX_CLIENT_IDENTITY_DATA: usize = 32 * 1024;
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
pub struct StoreEditedHipReportChunkRequest {
|
||||
pub upload_id: Option<String>,
|
||||
pub offset: usize,
|
||||
pub xml: String,
|
||||
pub complete: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
pub struct PreviewHipReportRequest {
|
||||
pub source: HipSource,
|
||||
pub client_os: ClientOs,
|
||||
pub client_version: String,
|
||||
pub host_id: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
pub struct ReadHipPreviewChunkRequest {
|
||||
pub preview_id: String,
|
||||
pub offset: usize,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
pub struct LaunchGuiRequest {
|
||||
user: String,
|
||||
@@ -30,10 +56,11 @@ impl LaunchGuiRequest {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize, Type, Clone)]
|
||||
#[derive(Deserialize, Serialize, Type, Clone)]
|
||||
pub struct ConnectArgs {
|
||||
cookie: String,
|
||||
vpnc_script: Option<String>,
|
||||
host_identity: Option<HostIdentity>,
|
||||
ignore_tls_errors: bool,
|
||||
|
||||
user_agent: Option<String>,
|
||||
os: Option<ClientOs>,
|
||||
@@ -43,11 +70,11 @@ pub struct ConnectArgs {
|
||||
|
||||
certificate: Option<String>,
|
||||
sslkey: Option<String>,
|
||||
certificate_data: Option<String>,
|
||||
sslkey_data: Option<String>,
|
||||
key_password: Option<String>,
|
||||
|
||||
hip: bool,
|
||||
csd_uid: u32,
|
||||
csd_wrapper: Option<String>,
|
||||
hip_source: HipSource,
|
||||
|
||||
reconnect_timeout: u32,
|
||||
mtu: u32,
|
||||
@@ -61,10 +88,11 @@ pub struct ConnectArgs {
|
||||
}
|
||||
|
||||
impl ConnectArgs {
|
||||
pub fn new(cookie: String) -> Self {
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
cookie,
|
||||
vpnc_script: None,
|
||||
host_identity: None,
|
||||
ignore_tls_errors: false,
|
||||
user_agent: None,
|
||||
os: None,
|
||||
os_version: None,
|
||||
@@ -72,10 +100,10 @@ impl ConnectArgs {
|
||||
host_id: None,
|
||||
certificate: None,
|
||||
sslkey: None,
|
||||
certificate_data: None,
|
||||
sslkey_data: None,
|
||||
key_password: None,
|
||||
hip: false,
|
||||
csd_uid: 0,
|
||||
csd_wrapper: None,
|
||||
hip_source: HipSource::Disabled,
|
||||
reconnect_timeout: 300,
|
||||
mtu: 0,
|
||||
disable_ipv6: false,
|
||||
@@ -87,8 +115,12 @@ impl ConnectArgs {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn cookie(&self) -> &str {
|
||||
&self.cookie
|
||||
pub fn host_identity(&self) -> Option<&HostIdentity> {
|
||||
self.host_identity.as_ref()
|
||||
}
|
||||
|
||||
pub fn ignore_tls_errors(&self) -> bool {
|
||||
self.ignore_tls_errors
|
||||
}
|
||||
|
||||
pub fn vpnc_script(&self) -> Option<String> {
|
||||
@@ -127,20 +159,28 @@ impl ConnectArgs {
|
||||
self.sslkey.clone()
|
||||
}
|
||||
|
||||
pub fn certificate_data(&self) -> anyhow::Result<Option<Vec<u8>>> {
|
||||
self
|
||||
.certificate_data
|
||||
.as_deref()
|
||||
.map(crate::utils::base64::decode_to_vec)
|
||||
.transpose()
|
||||
}
|
||||
|
||||
pub fn sslkey_data(&self) -> anyhow::Result<Option<Vec<u8>>> {
|
||||
self
|
||||
.sslkey_data
|
||||
.as_deref()
|
||||
.map(crate::utils::base64::decode_to_vec)
|
||||
.transpose()
|
||||
}
|
||||
|
||||
pub fn key_password(&self) -> Option<String> {
|
||||
self.key_password.clone()
|
||||
}
|
||||
|
||||
pub fn hip(&self) -> bool {
|
||||
self.hip
|
||||
}
|
||||
|
||||
pub fn csd_uid(&self) -> u32 {
|
||||
self.csd_uid
|
||||
}
|
||||
|
||||
pub fn csd_wrapper(&self) -> Option<String> {
|
||||
self.csd_wrapper.clone()
|
||||
pub fn hip_source(&self) -> &HipSource {
|
||||
&self.hip_source
|
||||
}
|
||||
|
||||
pub fn reconnect_timeout(&self) -> u32 {
|
||||
@@ -176,17 +216,49 @@ impl ConnectArgs {
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for ConnectArgs {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.debug_struct("ConnectArgs")
|
||||
.field("vpnc_script", &self.vpnc_script)
|
||||
.field(
|
||||
"client_auth_path",
|
||||
&(self.certificate.is_some() || self.sslkey.is_some()),
|
||||
)
|
||||
.field(
|
||||
"client_auth_data",
|
||||
&(self.certificate_data.is_some() || self.sslkey_data.is_some()),
|
||||
)
|
||||
.field("hip_source", &self.hip_source)
|
||||
.field("reconnect_timeout", &self.reconnect_timeout)
|
||||
.field("mtu", &self.mtu)
|
||||
.field("disable_ipv6", &self.disable_ipv6)
|
||||
.field("no_dtls", &self.no_dtls)
|
||||
.field("allow_extend_session", &self.allow_extend_session)
|
||||
.finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for ConnectArgs {
|
||||
fn drop(&mut self) {
|
||||
self.key_password.zeroize();
|
||||
self.certificate_data.zeroize();
|
||||
self.sslkey_data.zeroize();
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize, Type, Clone)]
|
||||
pub struct ConnectRequest {
|
||||
info: ConnectInfo,
|
||||
plan: ConnectionPlan,
|
||||
args: ConnectArgs,
|
||||
}
|
||||
|
||||
impl ConnectRequest {
|
||||
pub fn new(info: ConnectInfo, cookie: String) -> Self {
|
||||
pub fn new(info: ConnectInfo, plan: ConnectionPlan) -> Self {
|
||||
Self {
|
||||
info,
|
||||
args: ConnectArgs::new(cookie),
|
||||
plan,
|
||||
args: ConnectArgs::new(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -195,22 +267,13 @@ impl ConnectRequest {
|
||||
self
|
||||
}
|
||||
|
||||
pub fn with_hip(mut self, hip: bool) -> Self {
|
||||
self.args.hip = hip;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn with_csd_uid(mut self, csd_uid: u32) -> Self {
|
||||
self.args.csd_uid = csd_uid;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn with_csd_wrapper<T: Into<Option<String>>>(mut self, csd_wrapper: T) -> Self {
|
||||
self.args.csd_wrapper = csd_wrapper.into();
|
||||
pub fn with_hip_source(mut self, hip_source: HipSource) -> Self {
|
||||
self.args.hip_source = hip_source;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn with_os_profile(mut self, profile: &OsProfile) -> Self {
|
||||
self.args.host_identity = Some(profile.host_identity().clone());
|
||||
self.args.os = Some(profile.client_os());
|
||||
self.args.os_version = Some(profile.os_version().to_string());
|
||||
self.args.client_version = Some(profile.client_version().to_string());
|
||||
@@ -219,6 +282,11 @@ impl ConnectRequest {
|
||||
self
|
||||
}
|
||||
|
||||
pub fn with_ignore_tls_errors(mut self, ignore_tls_errors: bool) -> Self {
|
||||
self.args.ignore_tls_errors = ignore_tls_errors;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn with_certificate<T: Into<Option<String>>>(mut self, certificate: T) -> Self {
|
||||
self.args.certificate = certificate.into();
|
||||
self
|
||||
@@ -229,6 +297,16 @@ impl ConnectRequest {
|
||||
self
|
||||
}
|
||||
|
||||
pub fn with_certificate_data(mut self, certificate: Option<Vec<u8>>) -> Self {
|
||||
self.args.certificate_data = certificate.map(encode_secret);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn with_sslkey_data(mut self, sslkey: Option<Vec<u8>>) -> Self {
|
||||
self.args.sslkey_data = sslkey.map(encode_secret);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn with_key_password<T: Into<Option<String>>>(mut self, key_password: T) -> Self {
|
||||
self.args.key_password = key_password.into();
|
||||
self
|
||||
@@ -274,8 +352,8 @@ impl ConnectRequest {
|
||||
self
|
||||
}
|
||||
|
||||
pub fn gateway(&self) -> &Gateway {
|
||||
self.info.gateway()
|
||||
pub fn plan(&self) -> &ConnectionPlan {
|
||||
&self.plan
|
||||
}
|
||||
|
||||
pub fn info(&self) -> &ConnectInfo {
|
||||
@@ -287,6 +365,12 @@ impl ConnectRequest {
|
||||
}
|
||||
}
|
||||
|
||||
fn encode_secret(mut data: Vec<u8>) -> String {
|
||||
let encoded = crate::utils::base64::encode(&data);
|
||||
data.zeroize();
|
||||
encoded
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize, Type)]
|
||||
pub struct DisconnectRequest;
|
||||
|
||||
@@ -298,10 +382,19 @@ pub struct UpdateLogLevelRequest(pub String);
|
||||
pub enum WsRequest {
|
||||
Connect(Box<ConnectRequest>),
|
||||
Disconnect(DisconnectRequest),
|
||||
StopNonTunnelAttachment { connection_id: uuid::Uuid },
|
||||
StoreEditedHipReportChunk(StoreEditedHipReportChunkRequest),
|
||||
PreviewHipReport(PreviewHipReportRequest),
|
||||
GetHipApprovalStatus { approval_id: String },
|
||||
ReadHipPreviewChunk(ReadHipPreviewChunkRequest),
|
||||
GetLastSubmittedHipReport,
|
||||
UpdateLogLevel(UpdateLogLevelRequest),
|
||||
RestartGui,
|
||||
UpdateGui(UpdateGuiRequest),
|
||||
GetVpncScriptMetadata,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||
pub struct UpdateGuiRequest {
|
||||
pub path: String,
|
||||
pub checksum: String,
|
||||
@@ -313,17 +406,52 @@ mod tests {
|
||||
|
||||
use super::*;
|
||||
use crate::os_profile::OsProfileBuilder;
|
||||
use crate::{
|
||||
gateway::Gateway,
|
||||
session::{AuthenticatedGateway, GatewayAuthentication, InternalSessionPolicy},
|
||||
};
|
||||
|
||||
fn test_request(info: ConnectInfo) -> ConnectRequest {
|
||||
let plan = ConnectionPlan::new(
|
||||
vec![AuthenticatedGateway {
|
||||
gateway: info.gateway().clone(),
|
||||
binding: Some(crate::session::network::test_binding()),
|
||||
authentication: GatewayAuthentication::new("authcookie=secret-cookie&user=user".into(), "tunnel".into())
|
||||
.unwrap(),
|
||||
}],
|
||||
vec![],
|
||||
InternalSessionPolicy::default(),
|
||||
)
|
||||
.unwrap();
|
||||
ConnectRequest::new(info, plan)
|
||||
}
|
||||
|
||||
fn test_connect_info() -> ConnectInfo {
|
||||
let gateway = Gateway::new("Gateway".to_string(), "vpn.example.com".to_string());
|
||||
ConnectInfo::new("portal.example.com".to_string(), gateway.clone(), vec![gateway])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn connect_request_round_trips_a_validated_plan_and_rejects_cookie_only_wire_input() {
|
||||
let request = test_request(test_connect_info());
|
||||
let mut value = serde_json::to_value(&request).unwrap();
|
||||
assert!(value["args"].get("cookie").is_none());
|
||||
let decoded: ConnectRequest = serde_json::from_value(value.clone()).unwrap();
|
||||
assert_eq!(decoded.plan().members().len(), 1);
|
||||
assert_eq!(decoded.plan().members()[0].authentication.connection_type(), "tunnel");
|
||||
value["plan"]["members"] = json!([]);
|
||||
assert!(serde_json::from_value::<ConnectRequest>(value).is_err());
|
||||
let mut legacy = serde_json::to_value(&request).unwrap();
|
||||
legacy.as_object_mut().unwrap().remove("plan");
|
||||
legacy["args"]["cookie"] = json!("authcookie=secret-cookie&user=user");
|
||||
assert!(serde_json::from_value::<ConnectRequest>(legacy).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn connect_request_serializes_allow_extend_session() {
|
||||
let gateway = Gateway::new("Gateway".to_string(), "vpn.example.com".to_string());
|
||||
let info = ConnectInfo::new("portal.example.com".to_string(), gateway.clone(), vec![gateway]);
|
||||
let req = ConnectRequest::new(info, "authcookie=AUTH".to_string()).with_allow_extend_session(true);
|
||||
let req = test_request(info).with_allow_extend_session(true);
|
||||
let value = serde_json::to_value(req).unwrap();
|
||||
|
||||
assert_eq!(value["args"]["allowExtendSession"], json!(true));
|
||||
@@ -333,7 +461,7 @@ mod tests {
|
||||
fn with_os_profile_sets_user_agent_from_profile() {
|
||||
let profile = OsProfileBuilder::new(ClientOs::Linux).client_version("6.0.0").build();
|
||||
|
||||
let req = ConnectRequest::new(test_connect_info(), "cookie".to_string()).with_os_profile(&profile);
|
||||
let req = test_request(test_connect_info()).with_os_profile(&profile);
|
||||
|
||||
assert_eq!(req.args().user_agent(), Some(profile.user_agent().to_string()));
|
||||
}
|
||||
@@ -342,11 +470,26 @@ mod tests {
|
||||
fn with_os_profile_sets_host_id_from_profile_runtime_identity() {
|
||||
let profile = OsProfileBuilder::new(ClientOs::Linux).build();
|
||||
|
||||
let req = ConnectRequest::new(test_connect_info(), "cookie".to_string()).with_os_profile(&profile);
|
||||
let req = test_request(test_connect_info()).with_os_profile(&profile);
|
||||
|
||||
assert_eq!(
|
||||
req.args().host_id(),
|
||||
Some(profile.host_identity().host_id().to_string())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn client_identity_data_round_trips_without_debug_disclosure() {
|
||||
let req = test_request(test_connect_info())
|
||||
.with_certificate_data(Some(b"certificate".to_vec()))
|
||||
.with_sslkey_data(Some(b"private-key".to_vec()));
|
||||
let encoded = serde_json::to_vec(&req).unwrap();
|
||||
let decoded: ConnectRequest = serde_json::from_slice(&encoded).unwrap();
|
||||
|
||||
assert_eq!(decoded.args().certificate_data().unwrap().unwrap(), b"certificate");
|
||||
assert_eq!(decoded.args().sslkey_data().unwrap().unwrap(), b"private-key");
|
||||
let debug = format!("{decoded:?}");
|
||||
assert!(!debug.contains("secret-cookie"));
|
||||
assert!(!debug.contains("private-key"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
use std::fmt;
|
||||
|
||||
use ::base64::{Engine, engine::general_purpose};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid;
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
use crate::device_anchor::DeviceAnchor;
|
||||
use crate::utils::base64;
|
||||
|
||||
use super::{MAX_CREDENTIAL_FRAME, MAX_PRODUCT_VERSION, TransportError};
|
||||
|
||||
pub struct SessionCredential {
|
||||
service_instance_id: Uuid,
|
||||
session_id: Uuid,
|
||||
secret: Zeroizing<[u8; 32]>,
|
||||
product_version: String,
|
||||
device_anchor: Option<DeviceAnchor>,
|
||||
}
|
||||
|
||||
impl SessionCredential {
|
||||
pub fn generate(service_instance_id: Uuid, product_version: &str) -> Result<Self, TransportError> {
|
||||
if product_version.is_empty() || product_version.len() > MAX_PRODUCT_VERSION {
|
||||
return Err(TransportError::InvalidCredential);
|
||||
}
|
||||
|
||||
let mut secret = Zeroizing::new([0_u8; 32]);
|
||||
getrandom::fill(secret.as_mut()).map_err(|_| TransportError::InvalidState)?;
|
||||
|
||||
Ok(Self {
|
||||
service_instance_id,
|
||||
session_id: Uuid::new_v4(),
|
||||
secret,
|
||||
product_version: product_version.to_owned(),
|
||||
device_anchor: None,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn service_instance_id(&self) -> Uuid {
|
||||
self.service_instance_id
|
||||
}
|
||||
|
||||
pub fn session_id(&self) -> Uuid {
|
||||
self.session_id
|
||||
}
|
||||
|
||||
pub fn secret(&self) -> &[u8; 32] {
|
||||
&self.secret
|
||||
}
|
||||
|
||||
pub fn product_version(&self) -> &str {
|
||||
&self.product_version
|
||||
}
|
||||
|
||||
pub fn with_device_anchor(mut self, anchor: DeviceAnchor) -> Result<Self, TransportError> {
|
||||
if !anchor.validate() {
|
||||
return Err(TransportError::InvalidCredential);
|
||||
}
|
||||
self.device_anchor = Some(anchor);
|
||||
Ok(self)
|
||||
}
|
||||
|
||||
pub fn device_anchor(&self) -> Option<&DeviceAnchor> {
|
||||
self.device_anchor.as_ref()
|
||||
}
|
||||
|
||||
pub fn encode_frame(&self) -> Result<Zeroizing<Vec<u8>>, TransportError> {
|
||||
let encoded_secret = Zeroizing::new(base64::encode(self.secret()));
|
||||
let dto = CredentialDtoRef {
|
||||
service_instance_id: self.service_instance_id,
|
||||
session_id: self.session_id,
|
||||
secret: encoded_secret.as_str(),
|
||||
product_version: &self.product_version,
|
||||
device_anchor: self.device_anchor.as_ref(),
|
||||
};
|
||||
let payload = Zeroizing::new(serde_json::to_vec(&dto)?);
|
||||
|
||||
if payload.len() + 2 > MAX_CREDENTIAL_FRAME || payload.len() > u16::MAX as usize {
|
||||
return Err(TransportError::MessageTooLarge);
|
||||
}
|
||||
|
||||
let mut frame = Zeroizing::new(Vec::with_capacity(payload.len() + 2));
|
||||
frame.extend_from_slice(&(payload.len() as u16).to_be_bytes());
|
||||
frame.extend_from_slice(&payload);
|
||||
Ok(frame)
|
||||
}
|
||||
|
||||
pub fn decode_frame(frame: &[u8]) -> Result<Self, TransportError> {
|
||||
if frame.len() < 2 || frame.len() > MAX_CREDENTIAL_FRAME {
|
||||
return Err(TransportError::InvalidCredential);
|
||||
}
|
||||
|
||||
let payload_len = u16::from_be_bytes([frame[0], frame[1]]) as usize;
|
||||
if payload_len == 0 || payload_len + 2 != frame.len() {
|
||||
return Err(TransportError::InvalidCredential);
|
||||
}
|
||||
|
||||
let dto: CredentialDto = serde_json::from_slice(&frame[2..]).map_err(|_| TransportError::InvalidCredential)?;
|
||||
let CredentialDto {
|
||||
service_instance_id,
|
||||
session_id,
|
||||
secret,
|
||||
product_version,
|
||||
device_anchor,
|
||||
} = dto;
|
||||
let encoded_secret = secret;
|
||||
if device_anchor.as_ref().is_some_and(|anchor| !anchor.validate()) {
|
||||
return Err(TransportError::InvalidCredential);
|
||||
}
|
||||
if product_version.is_empty() || product_version.len() > MAX_PRODUCT_VERSION {
|
||||
return Err(TransportError::InvalidCredential);
|
||||
}
|
||||
|
||||
let mut secret = Zeroizing::new([0_u8; 32]);
|
||||
let decoded_len = general_purpose::STANDARD
|
||||
.decode_slice(encoded_secret.as_bytes(), secret.as_mut())
|
||||
.map_err(|_| TransportError::InvalidCredential)?;
|
||||
if decoded_len != secret.len() {
|
||||
return Err(TransportError::InvalidCredential);
|
||||
}
|
||||
|
||||
Ok(Self {
|
||||
service_instance_id,
|
||||
session_id,
|
||||
secret,
|
||||
product_version,
|
||||
device_anchor,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for SessionCredential {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.debug_struct("SessionCredential")
|
||||
.field("service_instance_id", &self.service_instance_id)
|
||||
.field("session_id", &self.session_id)
|
||||
.field("secret", &"[REDACTED]")
|
||||
.field("product_version", &self.product_version)
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct CredentialDtoRef<'a> {
|
||||
service_instance_id: Uuid,
|
||||
session_id: Uuid,
|
||||
secret: &'a str,
|
||||
product_version: &'a str,
|
||||
device_anchor: Option<&'a DeviceAnchor>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct CredentialDto {
|
||||
service_instance_id: Uuid,
|
||||
session_id: Uuid,
|
||||
secret: Zeroizing<String>,
|
||||
product_version: String,
|
||||
device_anchor: Option<DeviceAnchor>,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn credential_round_trips_without_debugging_secret() {
|
||||
let credential = SessionCredential::generate(Uuid::new_v4(), "2.6.4").unwrap();
|
||||
let frame = credential.encode_frame().unwrap();
|
||||
let decoded = SessionCredential::decode_frame(&frame).unwrap();
|
||||
|
||||
assert_eq!(decoded.service_instance_id(), credential.service_instance_id());
|
||||
assert_eq!(decoded.session_id(), credential.session_id());
|
||||
assert_eq!(decoded.secret(), credential.secret());
|
||||
assert_eq!(decoded.product_version(), credential.product_version());
|
||||
assert!(!format!("{credential:?}").contains(&base64::encode(credential.secret())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn credential_rejects_malformed_lengths() {
|
||||
assert!(SessionCredential::decode_frame(&[]).is_err());
|
||||
assert!(SessionCredential::decode_frame(&[0, 0]).is_err());
|
||||
assert!(SessionCredential::decode_frame(&[0, 2, b'{']).is_err());
|
||||
assert!(SessionCredential::decode_frame(&vec![0; MAX_CREDENTIAL_FRAME + 1]).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn credential_round_trips_a_validated_device_anchor() {
|
||||
let anchor = DeviceAnchor {
|
||||
hardware_id: general_purpose::URL_SAFE_NO_PAD.encode([1_u8; 32]),
|
||||
source: crate::device_anchor::AnchorSource::UnixMac,
|
||||
};
|
||||
let credential = SessionCredential::generate(Uuid::new_v4(), "2.6.5")
|
||||
.unwrap()
|
||||
.with_device_anchor(anchor.clone())
|
||||
.unwrap();
|
||||
let frame = credential.encode_frame().unwrap();
|
||||
let payload: serde_json::Value = serde_json::from_slice(&frame[2..]).unwrap();
|
||||
assert_eq!(payload["device_anchor"]["source"], 1);
|
||||
let decoded = SessionCredential::decode_frame(&frame).unwrap();
|
||||
assert_eq!(decoded.device_anchor(), Some(&anchor));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn credential_rejects_reserved_and_unknown_anchor_sources() {
|
||||
let credential = SessionCredential::generate(Uuid::new_v4(), "2.6.5").unwrap();
|
||||
let frame = credential.encode_frame().unwrap();
|
||||
let mut payload: serde_json::Value = serde_json::from_slice(&frame[2..]).unwrap();
|
||||
let hardware_id = general_purpose::URL_SAFE_NO_PAD.encode([1_u8; 32]);
|
||||
|
||||
for source in [0, 4] {
|
||||
payload["device_anchor"] = serde_json::json!({
|
||||
"hardware_id": hardware_id,
|
||||
"source": source
|
||||
});
|
||||
let bytes = serde_json::to_vec(&payload).unwrap();
|
||||
let mut invalid_frame = (bytes.len() as u16).to_be_bytes().to_vec();
|
||||
invalid_frame.extend_from_slice(&bytes);
|
||||
assert!(SessionCredential::decode_frame(&invalid_frame).is_err());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use thiserror::Error;
|
||||
use uuid::Uuid;
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum TransportError {
|
||||
#[error("invalid credential frame")]
|
||||
InvalidCredential,
|
||||
#[error("invalid transport state")]
|
||||
InvalidState,
|
||||
#[error("message exceeds transport limit")]
|
||||
MessageTooLarge,
|
||||
#[error("malformed transport message")]
|
||||
MalformedMessage,
|
||||
#[error("Noise operation failed")]
|
||||
Noise(#[from] snow::Error),
|
||||
#[error("transport serialization failed")]
|
||||
Serialization(#[from] serde_json::Error),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(tag = "type", rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub enum HandshakeRejection {
|
||||
VersionMismatch { client: String, service: String },
|
||||
HipProtocolMismatch { client: u16, service: u16 },
|
||||
ServiceRestarted { service_instance_id: Uuid },
|
||||
ReconnectSuperseded,
|
||||
Unauthorized,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum ServiceErrorCode {
|
||||
InvalidRequest,
|
||||
Busy,
|
||||
ChecksumFailed,
|
||||
InstallFailed,
|
||||
Internal,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum CloseReason {
|
||||
VersionMismatch,
|
||||
Unauthorized,
|
||||
SessionReplaced,
|
||||
HandshakeFailed,
|
||||
MalformedMessage,
|
||||
MessageTooLarge,
|
||||
AuthenticationFailed,
|
||||
HandshakeTimeout,
|
||||
ReconnectSuperseded,
|
||||
InternalError,
|
||||
ServiceRestarted,
|
||||
HeartbeatTimeout,
|
||||
}
|
||||
|
||||
impl CloseReason {
|
||||
pub const fn code(self) -> u16 {
|
||||
match self {
|
||||
Self::VersionMismatch => 4001,
|
||||
Self::Unauthorized => 4002,
|
||||
Self::SessionReplaced => 4003,
|
||||
Self::HandshakeFailed => 4004,
|
||||
Self::MalformedMessage => 4005,
|
||||
Self::MessageTooLarge => 4006,
|
||||
Self::AuthenticationFailed => 4007,
|
||||
Self::HandshakeTimeout => 4008,
|
||||
Self::ReconnectSuperseded => 4009,
|
||||
Self::InternalError => 4010,
|
||||
Self::ServiceRestarted => 4011,
|
||||
Self::HeartbeatTimeout => 4012,
|
||||
}
|
||||
}
|
||||
|
||||
pub const fn reason(self) -> &'static str {
|
||||
match self {
|
||||
Self::VersionMismatch => "VersionMismatch",
|
||||
Self::Unauthorized => "Unauthorized",
|
||||
Self::SessionReplaced => "SessionReplaced",
|
||||
Self::HandshakeFailed => "HandshakeFailed",
|
||||
Self::MalformedMessage => "MalformedMessage",
|
||||
Self::MessageTooLarge => "MessageTooLarge",
|
||||
Self::AuthenticationFailed => "AuthenticationFailed",
|
||||
Self::HandshakeTimeout => "HandshakeTimeout",
|
||||
Self::ReconnectSuperseded => "ReconnectSuperseded",
|
||||
Self::InternalError => "InternalError",
|
||||
Self::ServiceRestarted => "ServiceRestarted",
|
||||
Self::HeartbeatTimeout => "HeartbeatTimeout",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::collections::HashSet;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn close_codes_are_unique_application_codes() {
|
||||
let reasons = [
|
||||
CloseReason::VersionMismatch,
|
||||
CloseReason::Unauthorized,
|
||||
CloseReason::SessionReplaced,
|
||||
CloseReason::HandshakeFailed,
|
||||
CloseReason::MalformedMessage,
|
||||
CloseReason::MessageTooLarge,
|
||||
CloseReason::AuthenticationFailed,
|
||||
CloseReason::HandshakeTimeout,
|
||||
CloseReason::ReconnectSuperseded,
|
||||
CloseReason::InternalError,
|
||||
CloseReason::ServiceRestarted,
|
||||
CloseReason::HeartbeatTimeout,
|
||||
];
|
||||
let codes: HashSet<_> = reasons.iter().map(|reason| reason.code()).collect();
|
||||
assert_eq!(codes.len(), reasons.len());
|
||||
assert!(codes.iter().all(|code| (4000..5000).contains(code)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::{HandshakeRejection, MAX_PRELUDE, MAX_PRODUCT_VERSION, TransportError};
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct ClientPrelude {
|
||||
pub product_version: String,
|
||||
#[serde(default)]
|
||||
pub hip_protocol_version: u16,
|
||||
pub service_instance_id: Uuid,
|
||||
pub session_id: Uuid,
|
||||
}
|
||||
|
||||
impl ClientPrelude {
|
||||
pub fn encode(&self) -> Result<Vec<u8>, TransportError> {
|
||||
if self.product_version.is_empty() || self.product_version.len() > MAX_PRODUCT_VERSION {
|
||||
return Err(TransportError::MalformedMessage);
|
||||
}
|
||||
let encoded = serde_json::to_vec(self)?;
|
||||
if encoded.len() > MAX_PRELUDE {
|
||||
return Err(TransportError::MessageTooLarge);
|
||||
}
|
||||
Ok(encoded)
|
||||
}
|
||||
|
||||
pub fn decode(encoded: &[u8]) -> Result<Self, TransportError> {
|
||||
if encoded.len() > MAX_PRELUDE {
|
||||
return Err(TransportError::MessageTooLarge);
|
||||
}
|
||||
let prelude: Self = serde_json::from_slice(encoded)?;
|
||||
if prelude.product_version.is_empty() || prelude.product_version.len() > MAX_PRODUCT_VERSION {
|
||||
return Err(TransportError::MalformedMessage);
|
||||
}
|
||||
Ok(prelude)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(tag = "type", content = "data", rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub enum ServerPrelude {
|
||||
Ready,
|
||||
Rejected(HandshakeRejection),
|
||||
}
|
||||
|
||||
impl ServerPrelude {
|
||||
pub fn encode(&self) -> Result<Vec<u8>, TransportError> {
|
||||
let encoded = serde_json::to_vec(self)?;
|
||||
if encoded.len() > MAX_PRELUDE {
|
||||
return Err(TransportError::MessageTooLarge);
|
||||
}
|
||||
Ok(encoded)
|
||||
}
|
||||
|
||||
pub fn decode(encoded: &[u8]) -> Result<Self, TransportError> {
|
||||
if encoded.len() > MAX_PRELUDE {
|
||||
return Err(TransportError::MessageTooLarge);
|
||||
}
|
||||
Ok(serde_json::from_slice(encoded)?)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn preludes_reject_unknown_fields_and_invalid_versions() {
|
||||
let instance = Uuid::new_v4();
|
||||
let session = Uuid::new_v4();
|
||||
let unknown = format!(
|
||||
r#"{{"product_version":"2.6.4","service_instance_id":"{instance}","session_id":"{session}","extra":true}}"#
|
||||
);
|
||||
assert!(ClientPrelude::decode(unknown.as_bytes()).is_err());
|
||||
let legacy =
|
||||
format!(r#"{{"product_version":"2.6.4","service_instance_id":"{instance}","session_id":"{session}"}}"#);
|
||||
assert_eq!(
|
||||
ClientPrelude::decode(legacy.as_bytes()).unwrap().hip_protocol_version,
|
||||
0
|
||||
);
|
||||
assert!(
|
||||
ClientPrelude {
|
||||
product_version: String::new(),
|
||||
hip_protocol_version: super::super::HIP_PROTOCOL_VERSION,
|
||||
service_instance_id: instance,
|
||||
session_id: session,
|
||||
}
|
||||
.encode()
|
||||
.is_err()
|
||||
);
|
||||
assert!(ClientPrelude::decode(&vec![b'x'; MAX_PRELUDE + 1]).is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::hip::HipApprovalStatus;
|
||||
use crate::service::{event::WsEvent, request::WsRequest, vpn_env::VpnEnv, vpnc_script::VpncScriptMetadata};
|
||||
|
||||
use super::{MAX_PLAINTEXT, MAX_SERVICE_MESSAGE, ServiceErrorCode, TransportError};
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
#[serde(tag = "type", content = "data", rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub enum ClientMessage {
|
||||
Attach { last_event_revision: Option<u64> },
|
||||
Request { id: Uuid, request: WsRequest },
|
||||
Resync { last_event_revision: u64 },
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
#[serde(tag = "type", content = "data", rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub enum ServerMessage {
|
||||
Attached {
|
||||
connection_id: Uuid,
|
||||
current_revision: u64,
|
||||
snapshot: VpnEnv,
|
||||
},
|
||||
Reply {
|
||||
id: Uuid,
|
||||
result: ServiceResult,
|
||||
},
|
||||
Event {
|
||||
revision: u64,
|
||||
event: WsEvent,
|
||||
},
|
||||
Snapshot {
|
||||
current_revision: u64,
|
||||
snapshot: VpnEnv,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(tag = "type", content = "data", rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub enum ServiceResult {
|
||||
Accepted,
|
||||
StoredHipReport {
|
||||
report_id: String,
|
||||
},
|
||||
HipUploadProgress {
|
||||
upload_id: String,
|
||||
},
|
||||
HipPreviewChunk {
|
||||
preview_id: String,
|
||||
offset: usize,
|
||||
xml: String,
|
||||
complete: bool,
|
||||
},
|
||||
HipApprovalStatus(HipApprovalStatus),
|
||||
NoSubmittedHipReport,
|
||||
VpncScriptMetadata(Option<VpncScriptMetadata>),
|
||||
Rejected(ServiceRejection),
|
||||
}
|
||||
|
||||
impl ServiceResult {
|
||||
pub fn rejected(code: ServiceErrorCode, message: impl Into<String>) -> Self {
|
||||
Self::Rejected(ServiceRejection::new(code, message))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(try_from = "ServiceRejectionDto")]
|
||||
pub struct ServiceRejection {
|
||||
code: ServiceErrorCode,
|
||||
message: String,
|
||||
}
|
||||
|
||||
impl ServiceRejection {
|
||||
fn new(code: ServiceErrorCode, message: impl Into<String>) -> Self {
|
||||
let mut message = message.into();
|
||||
if message.len() > MAX_SERVICE_MESSAGE {
|
||||
let mut boundary = MAX_SERVICE_MESSAGE;
|
||||
while !message.is_char_boundary(boundary) {
|
||||
boundary -= 1;
|
||||
}
|
||||
message.truncate(boundary);
|
||||
}
|
||||
Self { code, message }
|
||||
}
|
||||
|
||||
pub fn code(&self) -> ServiceErrorCode {
|
||||
self.code
|
||||
}
|
||||
|
||||
pub fn message(&self) -> &str {
|
||||
&self.message
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct ServiceRejectionDto {
|
||||
code: ServiceErrorCode,
|
||||
message: String,
|
||||
}
|
||||
|
||||
impl TryFrom<ServiceRejectionDto> for ServiceRejection {
|
||||
type Error = &'static str;
|
||||
|
||||
fn try_from(value: ServiceRejectionDto) -> Result<Self, Self::Error> {
|
||||
if value.message.len() > MAX_SERVICE_MESSAGE {
|
||||
return Err("service rejection message is too long");
|
||||
}
|
||||
Ok(Self {
|
||||
code: value.code,
|
||||
message: value.message,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn encode<T: Serialize>(message: &T) -> Result<Vec<u8>, TransportError> {
|
||||
let encoded = serde_json::to_vec(message)?;
|
||||
if encoded.len() > MAX_PLAINTEXT {
|
||||
return Err(TransportError::MessageTooLarge);
|
||||
}
|
||||
Ok(encoded)
|
||||
}
|
||||
|
||||
pub(crate) fn decode<T: for<'de> Deserialize<'de>>(encoded: &[u8]) -> Result<T, TransportError> {
|
||||
if encoded.len() > MAX_PLAINTEXT {
|
||||
return Err(TransportError::MessageTooLarge);
|
||||
}
|
||||
Ok(serde_json::from_slice(encoded)?)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::{
|
||||
gateway::Gateway,
|
||||
service::{
|
||||
request::{ConnectRequest, MAX_CLIENT_IDENTITY_DATA, WsRequest},
|
||||
vpn_state::ConnectInfo,
|
||||
},
|
||||
};
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn rejects_oversized_messages() {
|
||||
assert!(encode(&"x".repeat(MAX_PLAINTEXT)).is_err());
|
||||
assert!(decode::<String>(&vec![b'x'; MAX_PLAINTEXT + 1]).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejection_messages_are_utf8_safely_bounded() {
|
||||
let ServiceResult::Rejected(rejection) = ServiceResult::rejected(ServiceErrorCode::Internal, "界".repeat(100))
|
||||
else {
|
||||
panic!("expected rejection");
|
||||
};
|
||||
assert!(rejection.message().len() <= MAX_SERVICE_MESSAGE);
|
||||
|
||||
let oversized = format!(
|
||||
r#"{{"type":"rejected","data":{{"code":"internal","message":"{}"}}}}"#,
|
||||
"x".repeat(MAX_SERVICE_MESSAGE + 1)
|
||||
);
|
||||
assert!(serde_json::from_str::<ServiceResult>(&oversized).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maximum_client_identity_fits_one_transport_message() {
|
||||
let gateway = Gateway::new("Gateway".to_string(), "vpn.example.com".to_string());
|
||||
let info = ConnectInfo::new("portal.example.com".to_string(), gateway.clone(), vec![gateway]);
|
||||
let certificate_size = MAX_CLIENT_IDENTITY_DATA / 2;
|
||||
let plan = crate::session::ConnectionPlan::new(
|
||||
vec![crate::session::AuthenticatedGateway {
|
||||
gateway: info.gateway().clone(),
|
||||
binding: Some(crate::session::network::test_binding()),
|
||||
authentication: crate::session::GatewayAuthentication::new(
|
||||
"authcookie=token&user=user".into(),
|
||||
"tunnel".into(),
|
||||
)
|
||||
.unwrap(),
|
||||
}],
|
||||
vec![],
|
||||
crate::session::InternalSessionPolicy::default(),
|
||||
)
|
||||
.unwrap();
|
||||
let request = ConnectRequest::new(info, plan)
|
||||
.with_certificate_data(Some(vec![b'c'; certificate_size]))
|
||||
.with_sslkey_data(Some(vec![b'k'; MAX_CLIENT_IDENTITY_DATA - certificate_size]));
|
||||
let message = ClientMessage::Request {
|
||||
id: Uuid::new_v4(),
|
||||
request: WsRequest::Connect(Box::new(request)),
|
||||
};
|
||||
|
||||
let encoded = encode(&message).unwrap();
|
||||
assert!(encoded.len() <= MAX_PLAINTEXT);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
mod credential;
|
||||
mod error;
|
||||
mod handshake;
|
||||
mod message;
|
||||
mod noise;
|
||||
|
||||
pub use credential::SessionCredential;
|
||||
pub use error::{CloseReason, HandshakeRejection, ServiceErrorCode, TransportError};
|
||||
pub use handshake::{ClientPrelude, ServerPrelude};
|
||||
pub use message::{ClientMessage, ServerMessage, ServiceRejection, ServiceResult};
|
||||
pub use noise::{NoiseInitiator, NoiseResponder, NoiseTransport};
|
||||
|
||||
pub const MAX_CREDENTIAL_FRAME: usize = 512;
|
||||
pub const MAX_PRELUDE: usize = 256;
|
||||
pub const MAX_PRODUCT_VERSION: usize = 64;
|
||||
pub const HIP_PROTOCOL_VERSION: u16 = 1;
|
||||
pub const MAX_PLAINTEXT: usize = 60 * 1024;
|
||||
pub const MAX_WS_MESSAGE: usize = u16::MAX as usize;
|
||||
pub const MAX_SERVICE_MESSAGE: usize = 256;
|
||||
@@ -0,0 +1,231 @@
|
||||
use snow::{Builder, HandshakeState, TransportState, params::NoiseParams};
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
use super::{MAX_PLAINTEXT, MAX_PRODUCT_VERSION, MAX_WS_MESSAGE, TransportError};
|
||||
|
||||
const NOISE_PATTERN: &str = "Noise_NNpsk0_25519_ChaChaPoly_SHA256";
|
||||
const NOISE_TAG_SIZE: usize = 16;
|
||||
|
||||
pub struct NoiseInitiator {
|
||||
state: Option<HandshakeState>,
|
||||
}
|
||||
|
||||
impl NoiseInitiator {
|
||||
pub fn new(
|
||||
product_version: &str,
|
||||
service_instance_id: uuid::Uuid,
|
||||
session_id: uuid::Uuid,
|
||||
psk: &[u8; 32],
|
||||
) -> Result<Self, TransportError> {
|
||||
let params = noise_params()?;
|
||||
let prologue = prologue(product_version, service_instance_id, session_id)?;
|
||||
Ok(Self {
|
||||
state: Some(
|
||||
Builder::new(params)
|
||||
.prologue(&prologue)?
|
||||
.psk(0, psk)?
|
||||
.build_initiator()?,
|
||||
),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn write_first(&mut self) -> Result<Vec<u8>, TransportError> {
|
||||
let state = self.state.as_mut().ok_or(TransportError::InvalidState)?;
|
||||
let mut output = vec![0_u8; 128];
|
||||
let len = state.write_message(&[], &mut output)?;
|
||||
output.truncate(len);
|
||||
Ok(output)
|
||||
}
|
||||
|
||||
pub fn read_response(mut self, message: &[u8]) -> Result<NoiseTransport, TransportError> {
|
||||
if message.len() > MAX_WS_MESSAGE {
|
||||
return Err(TransportError::MessageTooLarge);
|
||||
}
|
||||
let mut state = self.state.take().ok_or(TransportError::InvalidState)?;
|
||||
let mut output = vec![0_u8; 128];
|
||||
state.read_message(message, &mut output)?;
|
||||
Ok(NoiseTransport::new(state.into_transport_mode()?))
|
||||
}
|
||||
}
|
||||
|
||||
pub struct NoiseResponder {
|
||||
state: Option<HandshakeState>,
|
||||
}
|
||||
|
||||
impl NoiseResponder {
|
||||
pub fn new(
|
||||
product_version: &str,
|
||||
service_instance_id: uuid::Uuid,
|
||||
session_id: uuid::Uuid,
|
||||
psk: &[u8; 32],
|
||||
) -> Result<Self, TransportError> {
|
||||
let params = noise_params()?;
|
||||
let prologue = prologue(product_version, service_instance_id, session_id)?;
|
||||
Ok(Self {
|
||||
state: Some(
|
||||
Builder::new(params)
|
||||
.prologue(&prologue)?
|
||||
.psk(0, psk)?
|
||||
.build_responder()?,
|
||||
),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn read_first(&mut self, message: &[u8]) -> Result<(), TransportError> {
|
||||
if message.len() > MAX_WS_MESSAGE {
|
||||
return Err(TransportError::MessageTooLarge);
|
||||
}
|
||||
let state = self.state.as_mut().ok_or(TransportError::InvalidState)?;
|
||||
let mut output = vec![0_u8; 128];
|
||||
state.read_message(message, &mut output)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn write_response(mut self) -> Result<(Vec<u8>, NoiseTransport), TransportError> {
|
||||
let mut state = self.state.take().ok_or(TransportError::InvalidState)?;
|
||||
let mut output = vec![0_u8; 128];
|
||||
let len = state.write_message(&[], &mut output)?;
|
||||
output.truncate(len);
|
||||
let transport = NoiseTransport::new(state.into_transport_mode()?);
|
||||
Ok((output, transport))
|
||||
}
|
||||
}
|
||||
|
||||
pub struct NoiseTransport {
|
||||
state: TransportState,
|
||||
}
|
||||
|
||||
impl NoiseTransport {
|
||||
fn new(state: TransportState) -> Self {
|
||||
Self { state }
|
||||
}
|
||||
|
||||
pub fn encrypt<T: serde::Serialize>(&mut self, message: &T) -> Result<Vec<u8>, TransportError> {
|
||||
let plaintext = Zeroizing::new(super::message::encode(message)?);
|
||||
let mut output = vec![0_u8; plaintext.len() + NOISE_TAG_SIZE];
|
||||
let len = self.state.write_message(&plaintext, &mut output)?;
|
||||
output.truncate(len);
|
||||
Ok(output)
|
||||
}
|
||||
|
||||
pub fn decrypt<T: for<'de> serde::Deserialize<'de>>(&mut self, message: &[u8]) -> Result<T, TransportError> {
|
||||
if message.len() > MAX_WS_MESSAGE || message.len() < NOISE_TAG_SIZE {
|
||||
return Err(if message.len() > MAX_WS_MESSAGE {
|
||||
TransportError::MessageTooLarge
|
||||
} else {
|
||||
TransportError::MalformedMessage
|
||||
});
|
||||
}
|
||||
let mut plaintext = Zeroizing::new(vec![0_u8; message.len()]);
|
||||
let len = self.state.read_message(message, &mut plaintext)?;
|
||||
plaintext.truncate(len);
|
||||
if plaintext.len() > MAX_PLAINTEXT {
|
||||
return Err(TransportError::MessageTooLarge);
|
||||
}
|
||||
super::message::decode(&plaintext)
|
||||
}
|
||||
}
|
||||
|
||||
fn noise_params() -> Result<NoiseParams, TransportError> {
|
||||
NOISE_PATTERN.parse().map_err(|_| TransportError::InvalidState)
|
||||
}
|
||||
|
||||
fn prologue(
|
||||
product_version: &str,
|
||||
service_instance_id: uuid::Uuid,
|
||||
session_id: uuid::Uuid,
|
||||
) -> Result<Vec<u8>, TransportError> {
|
||||
if product_version.is_empty() || product_version.len() > MAX_PRODUCT_VERSION {
|
||||
return Err(TransportError::MessageTooLarge);
|
||||
}
|
||||
let mut value = Vec::with_capacity(5 + 2 + product_version.len() + 32);
|
||||
value.extend_from_slice(b"GPWS\0");
|
||||
value.extend_from_slice(&(product_version.len() as u16).to_be_bytes());
|
||||
value.extend_from_slice(product_version.as_bytes());
|
||||
value.extend_from_slice(service_instance_id.as_bytes());
|
||||
value.extend_from_slice(session_id.as_bytes());
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[derive(Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
struct Payload(String);
|
||||
|
||||
#[test]
|
||||
fn peers_exchange_directional_messages() {
|
||||
let instance = uuid::Uuid::new_v4();
|
||||
let session = uuid::Uuid::new_v4();
|
||||
let psk = [7_u8; 32];
|
||||
let mut initiator = NoiseInitiator::new("2.6.4", instance, session, &psk).unwrap();
|
||||
let mut responder = NoiseResponder::new("2.6.4", instance, session, &psk).unwrap();
|
||||
|
||||
let first = initiator.write_first().unwrap();
|
||||
responder.read_first(&first).unwrap();
|
||||
let (response, mut server) = responder.write_response().unwrap();
|
||||
let mut client = initiator.read_response(&response).unwrap();
|
||||
|
||||
let encrypted = client.encrypt(&Payload("hello".into())).unwrap();
|
||||
assert_eq!(server.decrypt::<Payload>(&encrypted).unwrap(), Payload("hello".into()));
|
||||
assert!(server.decrypt::<Payload>(&encrypted).is_err());
|
||||
|
||||
let response = server.encrypt(&Payload("world".into())).unwrap();
|
||||
assert_eq!(client.decrypt::<Payload>(&response).unwrap(), Payload("world".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wrong_psk_fails_handshake() {
|
||||
let instance = uuid::Uuid::new_v4();
|
||||
let session = uuid::Uuid::new_v4();
|
||||
let mut initiator = NoiseInitiator::new("2.6.4", instance, session, &[1; 32]).unwrap();
|
||||
let mut responder = NoiseResponder::new("2.6.4", instance, session, &[2; 32]).unwrap();
|
||||
let first = initiator.write_first().unwrap();
|
||||
assert!(responder.read_first(&first).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transcript_identity_mismatch_fails_handshake() {
|
||||
let instance = uuid::Uuid::new_v4();
|
||||
let session = uuid::Uuid::new_v4();
|
||||
let psk = [3_u8; 32];
|
||||
for mut responder in [
|
||||
NoiseResponder::new("2.6.5", instance, session, &psk).unwrap(),
|
||||
NoiseResponder::new("2.6.4", uuid::Uuid::new_v4(), session, &psk).unwrap(),
|
||||
NoiseResponder::new("2.6.4", instance, uuid::Uuid::new_v4(), &psk).unwrap(),
|
||||
] {
|
||||
let mut initiator = NoiseInitiator::new("2.6.4", instance, session, &psk).unwrap();
|
||||
let first = initiator.write_first().unwrap();
|
||||
assert!(responder.read_first(&first).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transport_rejects_tampering_truncation_and_reordering() {
|
||||
let instance = uuid::Uuid::new_v4();
|
||||
let session = uuid::Uuid::new_v4();
|
||||
let psk = [9_u8; 32];
|
||||
let mut initiator = NoiseInitiator::new("2.6.4", instance, session, &psk).unwrap();
|
||||
let mut responder = NoiseResponder::new("2.6.4", instance, session, &psk).unwrap();
|
||||
let first = initiator.write_first().unwrap();
|
||||
responder.read_first(&first).unwrap();
|
||||
let (response, mut server) = responder.write_response().unwrap();
|
||||
let mut client = initiator.read_response(&response).unwrap();
|
||||
|
||||
let first = client.encrypt(&Payload("first".into())).unwrap();
|
||||
let second = client.encrypt(&Payload("second".into())).unwrap();
|
||||
assert!(server.decrypt::<Payload>(&second).is_err());
|
||||
|
||||
let mut initiator = NoiseInitiator::new("2.6.4", instance, session, &psk).unwrap();
|
||||
let mut responder = NoiseResponder::new("2.6.4", instance, session, &psk).unwrap();
|
||||
let handshake = initiator.write_first().unwrap();
|
||||
responder.read_first(&handshake).unwrap();
|
||||
let (response, mut server) = responder.write_response().unwrap();
|
||||
let mut client = initiator.read_response(&response).unwrap();
|
||||
let mut tampered = client.encrypt(&Payload("value".into())).unwrap();
|
||||
tampered[0] ^= 1;
|
||||
assert!(server.decrypt::<Payload>(&tampered).is_err());
|
||||
assert!(server.decrypt::<Payload>(&first[..NOISE_TAG_SIZE - 1]).is_err());
|
||||
}
|
||||
}
|
||||
@@ -24,9 +24,6 @@ pub struct VpnEnv {
|
||||
/// The default VPN script path
|
||||
pub vpnc_script: Option<String>,
|
||||
|
||||
/// The default CSD wrapper script path
|
||||
pub csd_wrapper: Option<String>,
|
||||
|
||||
/// The gpauth executable path
|
||||
/// Used by the client to launch gpauth for authentication
|
||||
pub auth_executable: String,
|
||||
|
||||
@@ -1,7 +1,12 @@
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
|
||||
use crate::{gateway::Gateway, session::SessionInfo};
|
||||
use crate::{
|
||||
gateway::Gateway,
|
||||
session::{GatewayFailureSummary, GatewaySessionSummary, SessionInfo},
|
||||
};
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize, Type, Clone)]
|
||||
pub struct ConnectInfo {
|
||||
@@ -15,6 +20,9 @@ pub struct ConnectInfo {
|
||||
pub struct ConnectedInfo {
|
||||
info: Box<ConnectInfo>,
|
||||
session_info: Option<SessionInfo>,
|
||||
connected_at: u32,
|
||||
members: Vec<GatewaySessionSummary>,
|
||||
failures: Vec<GatewayFailureSummary>,
|
||||
}
|
||||
|
||||
impl ConnectedInfo {
|
||||
@@ -22,9 +30,26 @@ impl ConnectedInfo {
|
||||
Self {
|
||||
info: Box::new(info),
|
||||
session_info,
|
||||
connected_at: unix_timestamp(),
|
||||
members: vec![],
|
||||
failures: vec![],
|
||||
}
|
||||
}
|
||||
|
||||
pub fn with_members(mut self, members: Vec<GatewaySessionSummary>, failures: Vec<GatewayFailureSummary>) -> Self {
|
||||
self.members = members;
|
||||
self.failures = failures;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn members(&self) -> &[GatewaySessionSummary] {
|
||||
&self.members
|
||||
}
|
||||
|
||||
pub fn failures(&self) -> &[GatewayFailureSummary] {
|
||||
&self.failures
|
||||
}
|
||||
|
||||
pub fn info(&self) -> &ConnectInfo {
|
||||
&self.info
|
||||
}
|
||||
@@ -32,6 +57,17 @@ impl ConnectedInfo {
|
||||
pub fn session_info(&self) -> Option<&SessionInfo> {
|
||||
self.session_info.as_ref()
|
||||
}
|
||||
|
||||
pub fn connected_at(&self) -> u32 {
|
||||
self.connected_at
|
||||
}
|
||||
}
|
||||
|
||||
fn unix_timestamp() -> u32 {
|
||||
SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_secs() as u32
|
||||
}
|
||||
|
||||
impl ConnectInfo {
|
||||
@@ -52,6 +88,7 @@ impl ConnectInfo {
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum VpnState {
|
||||
Disconnected,
|
||||
Failed(String),
|
||||
Connecting(Box<ConnectInfo>),
|
||||
Connected(Box<ConnectedInfo>),
|
||||
Disconnecting,
|
||||
@@ -79,5 +116,6 @@ mod tests {
|
||||
|
||||
assert_eq!(value["connected"]["sessionInfo"]["lifetimeSecs"], 43_200);
|
||||
assert_eq!(value["connected"]["sessionInfo"]["allowExtendSession"], true);
|
||||
assert!(value["connected"]["connectedAt"].as_u64().is_some());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
use anyhow::bail;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
|
||||
use crate::utils::base64;
|
||||
|
||||
pub const MAX_VPNC_SCRIPT_SOURCE_VALUE: usize = 32 * 1024;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum VpncScriptSource {
|
||||
File,
|
||||
Command,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct VpncScriptMetadata {
|
||||
pub source: VpncScriptSource,
|
||||
pub value: String,
|
||||
}
|
||||
|
||||
impl VpncScriptMetadata {
|
||||
pub fn new(source: VpncScriptSource, value: String) -> anyhow::Result<Self> {
|
||||
if value.trim().is_empty() {
|
||||
bail!("VPNC script source is empty");
|
||||
}
|
||||
if value.contains('\0') {
|
||||
bail!("VPNC script source contains a null character");
|
||||
}
|
||||
if value.len() > MAX_VPNC_SCRIPT_SOURCE_VALUE {
|
||||
bail!(
|
||||
"VPNC script source exceeds the {} byte limit",
|
||||
MAX_VPNC_SCRIPT_SOURCE_VALUE
|
||||
);
|
||||
}
|
||||
Ok(Self { source, value })
|
||||
}
|
||||
|
||||
pub fn validate(&self) -> anyhow::Result<()> {
|
||||
Self::new(self.source, self.value.clone()).map(|_| ())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
pub struct InstallVpncScriptRequest {
|
||||
pub metadata: VpncScriptMetadata,
|
||||
contents: String,
|
||||
}
|
||||
|
||||
impl InstallVpncScriptRequest {
|
||||
pub fn new(metadata: VpncScriptMetadata, contents: &[u8]) -> Self {
|
||||
Self {
|
||||
metadata,
|
||||
contents: base64::encode(contents),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn contents(&self) -> anyhow::Result<Vec<u8>> {
|
||||
base64::decode_to_vec(&self.contents)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn install_request_round_trips_binary_contents() {
|
||||
let metadata = VpncScriptMetadata::new(VpncScriptSource::File, "/tmp/vpnc-script".to_owned()).unwrap();
|
||||
let request = InstallVpncScriptRequest::new(metadata, b"#!/bin/sh\n");
|
||||
let encoded = serde_json::to_vec(&request).unwrap();
|
||||
let decoded: InstallVpncScriptRequest = serde_json::from_slice(&encoded).unwrap();
|
||||
|
||||
assert_eq!(decoded.contents().unwrap(), b"#!/bin/sh\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn metadata_rejects_invalid_source_value() {
|
||||
assert!(VpncScriptMetadata::new(VpncScriptSource::Command, String::new()).is_err());
|
||||
assert!(VpncScriptMetadata::new(VpncScriptSource::Command, "echo\0value".to_owned()).is_err());
|
||||
assert!(VpncScriptMetadata::new(VpncScriptSource::Command, "x".repeat(MAX_VPNC_SCRIPT_SOURCE_VALUE + 1)).is_err());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user