| 1 | // Copyright 2025 LiveKit, Inc. |
| 2 | // |
| 3 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | // you may not use this file except in compliance with the License. |
| 5 | // You may obtain a copy of the License at |
| 6 | // |
| 7 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | // |
| 9 | // Unless required by applicable law or agreed to in writing, software |
| 10 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | // See the License for the specific language governing permissions and |
| 13 | // limitations under the License. |
| 14 | |
| 15 | use std::sync::Arc; |
| 16 | |
| 17 | use cxx::SharedPtr; |
| 18 | use parking_lot::Mutex; |
| 19 | use webrtc_sys::frame_cryptor::{self as sys_fc}; |
| 20 | |
| 21 | use crate::{ |
| 22 | native::packet_trailer::PacketTrailerHandler, peer_connection_factory::PeerConnectionFactory, |
| 23 | rtp_receiver::RtpReceiver, rtp_sender::RtpSender, |
| 24 | }; |
| 25 | |
| 26 | pub type OnStateChange = Box<dyn FnMut(String, EncryptionState) + Send + Sync>; |
| 27 | |
| 28 | #[derive(Copy, Clone, Debug)] |
| 29 | #[non_exhaustive] |
| 30 | pub enum KeyDerivationAlgorithm { |
| 31 | PBKDF2, |
| 32 | HKDF, |
| 33 | } |
| 34 | impl Into<sys_fc::ffi::KeyDerivationAlgorithm> for KeyDerivationAlgorithm { |
| 35 | fn into(self) -> sys_fc::ffi::KeyDerivationAlgorithm { |
| 36 | match self { |
| 37 | KeyDerivationAlgorithm::PBKDF2 => sys_fc::ffi::KeyDerivationAlgorithm::PBKDF2, |
| 38 | KeyDerivationAlgorithm::HKDF => sys_fc::ffi::KeyDerivationAlgorithm::HKDF, |
| 39 | } |
| 40 | } |
| 41 | } |
| 42 | |
| 43 | #[derive(Debug, Clone)] |
| 44 | pub struct KeyProviderOptions { |
| 45 | pub shared_key: bool, |
| 46 | pub ratchet_window_size: i32, |
| 47 | pub ratchet_salt: Vec<u8>, |
| 48 | pub failure_tolerance: i32, |
| 49 | pub key_ring_size: i32, |
| 50 | pub key_derivation_algorithm: KeyDerivationAlgorithm, |
| 51 | } |
| 52 | |
| 53 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 54 | pub enum EncryptionAlgorithm { |
| 55 | AesGcm, |
| 56 | AesCbc, |
| 57 | } |
| 58 | |
| 59 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 60 | pub enum EncryptionState { |
| 61 | New, |
| 62 | Ok, |
| 63 | EncryptionFailed, |
| 64 | DecryptionFailed, |
| 65 | MissingKey, |
| 66 | KeyRatcheted, |
| 67 | InternalError, |
| 68 | } |
| 69 | |
| 70 | #[derive(Debug, Clone)] |
| 71 | pub struct EncryptedPacket { |
| 72 | pub data: Vec<u8>, |
| 73 | pub iv: Vec<u8>, |
| 74 | pub key_index: u32, |
| 75 | } |
| 76 | |
| 77 | #[derive(Clone)] |
| 78 | pub struct KeyProvider { |
| 79 | pub(crate) sys_handle: SharedPtr<sys_fc::ffi::KeyProvider>, |
| 80 | } |
| 81 | |
| 82 | impl KeyProvider { |
| 83 | pub fn new(options: KeyProviderOptions) -> Self { |
| 84 | Self { sys_handle: sys_fc::ffi::new_key_provider(options.into()) } |
| 85 | } |
| 86 | |
| 87 | pub fn set_shared_key(&self, key_index: i32, key: Vec<u8>) -> bool { |
| 88 | self.sys_handle.set_shared_key(key_index, key) |
| 89 | } |
| 90 | |
| 91 | pub fn ratchet_shared_key(&self, key_index: i32) -> Option<Vec<u8>> { |
| 92 | self.sys_handle.ratchet_shared_key(key_index).ok() |
| 93 | } |
| 94 | |
| 95 | pub fn get_shared_key(&self, key_index: i32) -> Option<Vec<u8>> { |
| 96 | self.sys_handle.get_shared_key(key_index).ok() |
| 97 | } |
| 98 | |
| 99 | pub fn set_key(&self, participant_id: String, key_index: i32, key: Vec<u8>) -> bool { |
| 100 | self.sys_handle.set_key(participant_id, key_index, key) |
| 101 | } |
| 102 | |
| 103 | pub fn ratchet_key(&self, participant_id: String, key_index: i32) -> Option<Vec<u8>> { |
| 104 | self.sys_handle.ratchet_key(participant_id, key_index).ok() |
| 105 | } |
| 106 | |
| 107 | pub fn get_key(&self, participant_id: String, key_index: i32) -> Option<Vec<u8>> { |
| 108 | self.sys_handle.get_key(participant_id, key_index).ok() |
| 109 | } |
| 110 | |
| 111 | pub fn set_sif_trailer(&self, trailer: Vec<u8>) { |
| 112 | self.sys_handle.set_sif_trailer(trailer); |
| 113 | } |
| 114 | } |
| 115 | |
| 116 | #[derive(Clone)] |
| 117 | pub struct FrameCryptor { |
| 118 | observer: Arc<RtcFrameCryptorObserver>, |
| 119 | pub(crate) sys_handle: SharedPtr<sys_fc::ffi::FrameCryptor>, |
| 120 | } |
| 121 | |
| 122 | impl FrameCryptor { |
| 123 | pub fn new_for_rtp_sender( |
| 124 | peer_factory: &PeerConnectionFactory, |
| 125 | participant_id: String, |
| 126 | algorithm: EncryptionAlgorithm, |
| 127 | key_provider: KeyProvider, |
| 128 | sender: RtpSender, |
| 129 | ) -> Self { |
| 130 | let observer = Arc::new(RtcFrameCryptorObserver::default()); |
| 131 | let sys_handle = sys_fc::ffi::new_frame_cryptor_for_rtp_sender( |
| 132 | peer_factory.handle.sys_handle.clone(), |
| 133 | participant_id, |
| 134 | algorithm.into(), |
| 135 | key_provider.sys_handle, |
| 136 | sender.handle.sys_handle, |
| 137 | ); |
| 138 | let fc = Self { observer: observer.clone(), sys_handle: sys_handle.clone() }; |
| 139 | fc.sys_handle |
| 140 | .register_observer(Box::new(sys_fc::RtcFrameCryptorObserverWrapper::new(observer))); |
| 141 | fc |
| 142 | } |
| 143 | |
| 144 | pub fn new_for_rtp_receiver( |
| 145 | peer_factory: &PeerConnectionFactory, |
| 146 | participant_id: String, |
| 147 | algorithm: EncryptionAlgorithm, |
| 148 | key_provider: KeyProvider, |
| 149 | receiver: RtpReceiver, |
| 150 | ) -> Self { |
| 151 | let observer = Arc::new(RtcFrameCryptorObserver::default()); |
| 152 | let sys_handle = sys_fc::ffi::new_frame_cryptor_for_rtp_receiver( |
| 153 | peer_factory.handle.sys_handle.clone(), |
| 154 | participant_id, |
| 155 | algorithm.into(), |
| 156 | key_provider.sys_handle, |
| 157 | receiver.handle.sys_handle, |
| 158 | ); |
| 159 | let fc = Self { observer: observer.clone(), sys_handle: sys_handle.clone() }; |
| 160 | fc.sys_handle |
| 161 | .register_observer(Box::new(sys_fc::RtcFrameCryptorObserverWrapper::new(observer))); |
| 162 | fc |
| 163 | } |
| 164 | |
| 165 | pub fn set_enabled(self: &FrameCryptor, enabled: bool) { |
| 166 | self.sys_handle.set_enabled(enabled); |
| 167 | } |
| 168 | |
| 169 | pub fn enabled(self: &FrameCryptor) -> bool { |
| 170 | self.sys_handle.enabled() |
| 171 | } |
| 172 | |
| 173 | pub fn set_key_index(self: &FrameCryptor, index: i32) { |
| 174 | self.sys_handle.set_key_index(index); |
| 175 | } |
| 176 | |
| 177 | pub fn key_index(self: &FrameCryptor) -> i32 { |
| 178 | self.sys_handle.key_index() |
| 179 | } |
| 180 | |
| 181 | pub fn participant_id(self: &FrameCryptor) -> String { |
| 182 | self.sys_handle.participant_id() |
| 183 | } |
| 184 | |
| 185 | pub fn on_state_change(&self, handler: Option<OnStateChange>) { |
| 186 | *self.observer.state_change_handler.lock() = handler; |
| 187 | } |
| 188 | |
| 189 | pub fn set_packet_trailer_handler(&self, handler: &PacketTrailerHandler) { |
| 190 | self.sys_handle.set_packet_trailer_handler(handler.sys_handle()); |
| 191 | } |
| 192 | } |
| 193 | |
| 194 | #[derive(Clone)] |
| 195 | pub struct DataPacketCryptor { |
| 196 | pub(crate) sys_handle: SharedPtr<sys_fc::ffi::DataPacketCryptor>, |
| 197 | } |
| 198 | |
| 199 | impl DataPacketCryptor { |
| 200 | pub fn new(algorithm: EncryptionAlgorithm, key_provider: KeyProvider) -> Self { |
| 201 | Self { |
| 202 | sys_handle: sys_fc::ffi::new_data_packet_cryptor( |
| 203 | algorithm.into(), |
| 204 | key_provider.sys_handle, |
| 205 | ), |
| 206 | } |
| 207 | } |
| 208 | |
| 209 | pub fn encrypt( |
| 210 | &self, |
| 211 | participant_id: &str, |
| 212 | key_index: u32, |
| 213 | data: &[u8], |
| 214 | ) -> Result<EncryptedPacket, Box<dyn std::error::Error>> { |
| 215 | let data_vec: Vec<u8> = data.to_vec(); |
| 216 | match self.sys_handle.encrypt_data_packet(participant_id.to_string(), key_index, data_vec) { |
| 217 | Ok(packet) => Ok(packet.into()), |
| 218 | Err(e) => Err(format!("Encryption failed: {}", e).into()), |
| 219 | } |
| 220 | } |
| 221 | |
| 222 | pub fn decrypt( |
| 223 | &self, |
| 224 | participant_id: &str, |
| 225 | encrypted_packet: &EncryptedPacket, |
| 226 | ) -> Result<Vec<u8>, Box<dyn std::error::Error>> { |
| 227 | match self |
| 228 | .sys_handle |
| 229 | .decrypt_data_packet(participant_id.to_string(), &encrypted_packet.clone().into()) |
| 230 | { |
| 231 | Ok(data) => Ok(data.into_iter().collect()), |
| 232 | Err(e) => Err(format!("Decryption failed: {}", e).into()), |
| 233 | } |
| 234 | } |
| 235 | } |
| 236 | |
| 237 | #[derive(Default)] |
| 238 | struct RtcFrameCryptorObserver { |
| 239 | state_change_handler: Mutex<Option<OnStateChange>>, |
| 240 | } |
| 241 | |
| 242 | impl sys_fc::RtcFrameCryptorObserver for RtcFrameCryptorObserver { |
| 243 | fn on_frame_cryption_state_change( |
| 244 | &self, |
| 245 | participant_id: String, |
| 246 | state: sys_fc::ffi::FrameCryptionState, |
| 247 | ) { |
| 248 | let mut handler = self.state_change_handler.lock(); |
| 249 | if let Some(f) = handler.as_mut() { |
| 250 | f(participant_id, state.into()); |
| 251 | } |
| 252 | } |
| 253 | } |
| 254 | |
| 255 | impl From<sys_fc::ffi::Algorithm> for EncryptionAlgorithm { |
| 256 | fn from(value: sys_fc::ffi::Algorithm) -> Self { |
| 257 | match value { |
| 258 | sys_fc::ffi::Algorithm::AesGcm => Self::AesGcm, |
| 259 | sys_fc::ffi::Algorithm::AesCbc => Self::AesCbc, |
| 260 | _ => panic!("unknown frame cyrptor Algorithm"), |
| 261 | } |
| 262 | } |
| 263 | } |
| 264 | |
| 265 | impl From<EncryptionAlgorithm> for sys_fc::ffi::Algorithm { |
| 266 | fn from(value: EncryptionAlgorithm) -> Self { |
| 267 | match value { |
| 268 | EncryptionAlgorithm::AesGcm => Self::AesGcm, |
| 269 | EncryptionAlgorithm::AesCbc => Self::AesCbc, |
| 270 | } |
| 271 | } |
| 272 | } |
| 273 | |
| 274 | impl From<sys_fc::ffi::FrameCryptionState> for EncryptionState { |
| 275 | fn from(value: sys_fc::ffi::FrameCryptionState) -> Self { |
| 276 | match value { |
| 277 | sys_fc::ffi::FrameCryptionState::New => Self::New, |
| 278 | sys_fc::ffi::FrameCryptionState::Ok => Self::Ok, |
| 279 | sys_fc::ffi::FrameCryptionState::EncryptionFailed => Self::EncryptionFailed, |
| 280 | sys_fc::ffi::FrameCryptionState::DecryptionFailed => Self::DecryptionFailed, |
| 281 | sys_fc::ffi::FrameCryptionState::MissingKey => Self::MissingKey, |
| 282 | sys_fc::ffi::FrameCryptionState::KeyRatcheted => Self::KeyRatcheted, |
| 283 | sys_fc::ffi::FrameCryptionState::InternalError => Self::InternalError, |
| 284 | _ => panic!("unknown frame cyrptor FrameCryptionState"), |
| 285 | } |
| 286 | } |
| 287 | } |
| 288 | |
| 289 | impl From<KeyProviderOptions> for sys_fc::ffi::KeyProviderOptions { |
| 290 | fn from(value: KeyProviderOptions) -> Self { |
| 291 | Self { |
| 292 | shared_key: value.shared_key, |
| 293 | ratchet_window_size: value.ratchet_window_size, |
| 294 | ratchet_salt: value.ratchet_salt, |
| 295 | failure_tolerance: value.failure_tolerance, |
| 296 | key_ring_size: value.key_ring_size, |
| 297 | key_derivation_algorithm: value.key_derivation_algorithm.into(), |
| 298 | } |
| 299 | } |
| 300 | } |
| 301 | |
| 302 | impl From<sys_fc::ffi::EncryptedPacket> for EncryptedPacket { |
| 303 | fn from(value: sys_fc::ffi::EncryptedPacket) -> Self { |
| 304 | Self { |
| 305 | data: value.data.into_iter().collect(), |
| 306 | iv: value.iv.into_iter().collect(), |
| 307 | key_index: value.key_index, |
| 308 | } |
| 309 | } |
| 310 | } |
| 311 | |
| 312 | impl From<EncryptedPacket> for sys_fc::ffi::EncryptedPacket { |
| 313 | fn from(value: EncryptedPacket) -> Self { |
| 314 | Self { data: value.data, iv: value.iv, key_index: value.key_index } |
| 315 | } |
| 316 | } |