leejunyoung5819 wayland-android-remote
공개Ubuntu(Wayland/X11)에서 Android 기기 화면 미러링 및 원격 제어 (Rust)
| 1 | //! 호스트 PC의 Ed25519 신원 키 (기획서 5.3). |
| 2 | |
| 3 | use std::fs; |
| 4 | use std::io::{self, Write}; |
| 5 | use std::os::unix::fs::{OpenOptionsExt, PermissionsExt}; |
| 6 | use std::path::{Path, PathBuf}; |
| 7 | |
| 8 | use ed25519_dalek::{Signer, SigningKey}; |
| 9 | |
| 10 | use crate::protocol::MAX_HOSTNAME_LEN; |
| 11 | |
| 12 | /// 호스트 PC를 식별하는 Ed25519 키와 기기에 보여줄 호스트명. |
| 13 | pub struct HostIdentity { |
| 14 | key: SigningKey, |
| 15 | hostname: String, |
| 16 | } |
| 17 | |
| 18 | impl HostIdentity { |
| 19 | /// 기본 키 파일 경로: `~/.config/android-remote/device_key`. |
| 20 | pub fn default_path() -> Option<PathBuf> { |
| 21 | crate::config::config_dir().map(|d| d.join("device_key")) |
| 22 | } |
| 23 | |
| 24 | /// 키 파일(32바이트 시드)을 읽고, 없으면 새로 만들어 0600 권한으로 저장한다. |
| 25 | pub fn load_or_create(path: &Path) -> io::Result<Self> { |
| 26 | match fs::read(path) { |
| 27 | Ok(bytes) => { |
| 28 | let seed: [u8; 32] = bytes.as_slice().try_into().map_err(|_| { |
| 29 | io::Error::new( |
| 30 | io::ErrorKind::InvalidData, |
| 31 | "키 파일 크기가 32바이트가 아닙니다", |
| 32 | ) |
| 33 | })?; |
| 34 | Ok(Self::from_seed(seed)) |
| 35 | } |
| 36 | Err(e) if e.kind() == io::ErrorKind::NotFound => { |
| 37 | let identity = Self::generate()?; |
| 38 | if let Some(dir) = path.parent() { |
| 39 | fs::create_dir_all(dir)?; |
| 40 | } |
| 41 | let mut f = fs::OpenOptions::new() |
| 42 | .write(true) |
| 43 | .create_new(true) |
| 44 | .mode(0o600) |
| 45 | .open(path)?; |
| 46 | f.write_all(&identity.key.to_bytes())?; |
| 47 | f.set_permissions(fs::Permissions::from_mode(0o600))?; |
| 48 | Ok(identity) |
| 49 | } |
| 50 | Err(e) => Err(e), |
| 51 | } |
| 52 | } |
| 53 | |
| 54 | /// 저장하지 않는 새 키를 만든다. |
| 55 | pub fn generate() -> io::Result<Self> { |
| 56 | let mut seed = [0u8; 32]; |
| 57 | getrandom::fill(&mut seed).map_err(io::Error::other)?; |
| 58 | Ok(Self::from_seed(seed)) |
| 59 | } |
| 60 | |
| 61 | pub fn from_seed(seed: [u8; 32]) -> Self { |
| 62 | Self { |
| 63 | key: SigningKey::from_bytes(&seed), |
| 64 | hostname: local_hostname(), |
| 65 | } |
| 66 | } |
| 67 | |
| 68 | pub fn with_hostname(mut self, hostname: impl Into<String>) -> Self { |
| 69 | self.hostname = truncate_utf8(hostname.into(), MAX_HOSTNAME_LEN); |
| 70 | self |
| 71 | } |
| 72 | |
| 73 | pub fn public_key(&self) -> [u8; 32] { |
| 74 | self.key.verifying_key().to_bytes() |
| 75 | } |
| 76 | |
| 77 | pub fn hostname(&self) -> &str { |
| 78 | &self.hostname |
| 79 | } |
| 80 | |
| 81 | pub fn sign(&self, message: &[u8]) -> [u8; 64] { |
| 82 | self.key.sign(message).to_bytes() |
| 83 | } |
| 84 | } |
| 85 | |
| 86 | fn local_hostname() -> String { |
| 87 | let name = fs::read_to_string("/proc/sys/kernel/hostname") |
| 88 | .map(|s| s.trim().to_owned()) |
| 89 | .unwrap_or_default(); |
| 90 | let name = if name.is_empty() { |
| 91 | "linux-host".to_owned() |
| 92 | } else { |
| 93 | name |
| 94 | }; |
| 95 | truncate_utf8(name, MAX_HOSTNAME_LEN) |
| 96 | } |
| 97 | |
| 98 | fn truncate_utf8(mut s: String, max: usize) -> String { |
| 99 | if s.len() > max { |
| 100 | let mut end = max; |
| 101 | while !s.is_char_boundary(end) { |
| 102 | end -= 1; |
| 103 | } |
| 104 | s.truncate(end); |
| 105 | } |
| 106 | s |
| 107 | } |
| 108 | |
| 109 | #[cfg(test)] |
| 110 | mod tests { |
| 111 | use super::*; |
| 112 | use ed25519_dalek::{Signature, VerifyingKey}; |
| 113 | |
| 114 | #[test] |
| 115 | fn key_file_roundtrip_and_permissions() { |
| 116 | let dir = std::env::temp_dir().join(format!("ar-identity-{}", std::process::id())); |
| 117 | let path = dir.join("device_key"); |
| 118 | let _ = fs::remove_dir_all(&dir); |
| 119 | |
| 120 | let a = HostIdentity::load_or_create(&path).unwrap(); |
| 121 | let b = HostIdentity::load_or_create(&path).unwrap(); |
| 122 | assert_eq!(a.public_key(), b.public_key()); |
| 123 | let mode = fs::metadata(&path).unwrap().permissions().mode() & 0o777; |
| 124 | assert_eq!(mode, 0o600); |
| 125 | fs::remove_dir_all(&dir).unwrap(); |
| 126 | } |
| 127 | |
| 128 | #[test] |
| 129 | fn signature_verifies() { |
| 130 | let id = HostIdentity::generate().unwrap(); |
| 131 | let sig = id.sign(b"hello"); |
| 132 | let vk = VerifyingKey::from_bytes(&id.public_key()).unwrap(); |
| 133 | vk.verify_strict(b"hello", &Signature::from_bytes(&sig)) |
| 134 | .unwrap(); |
| 135 | } |
| 136 | |
| 137 | #[test] |
| 138 | fn hostname_is_truncated_on_char_boundary() { |
| 139 | let id = HostIdentity::generate() |
| 140 | .unwrap() |
| 141 | .with_hostname("가".repeat(100)); |
| 142 | assert!(id.hostname().len() <= MAX_HOSTNAME_LEN); |
| 143 | assert!(id.hostname().chars().all(|c| c == '가')); |
| 144 | } |
| 145 | } |