xsshend 0.5.2

Simple CLI tool for uploading files to multiple SSH servers
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
use anyhow::{anyhow, Context, Result};
use dialoguer::Password;
use russh::keys::{decode_secret_key, PrivateKey};
use std::collections::HashMap;
use std::fs;
use std::path::{Path, PathBuf};
use std::sync::{Arc, RwLock};

/// Cache global de passphrases pour éviter de redemander plusieurs fois
#[derive(Clone)]
pub struct PassphraseCache {
    cache: Arc<RwLock<HashMap<PathBuf, String>>>,
}

impl PassphraseCache {
    /// Créer un nouveau cache vide
    pub fn new() -> Self {
        Self {
            cache: Arc::new(RwLock::new(HashMap::new())),
        }
    }

    /// Obtenir une passphrase du cache
    pub fn get(&self, key_path: &Path) -> Option<String> {
        self.cache
            .read()
            .ok()
            .and_then(|cache| cache.get(key_path).cloned())
    }

    /// Ajouter une passphrase au cache
    pub fn set(&self, key_path: PathBuf, passphrase: String) {
        if let Ok(mut cache) = self.cache.write() {
            cache.insert(key_path, passphrase);
        }
    }

    /*     /// Vérifier si une clé est dans le cache
    pub fn contains(&self, key_path: &Path) -> bool {
        self.cache
            .read()
            .ok()
            .map(|cache| cache.contains_key(key_path))
            .unwrap_or(false)
    }

    /// Effacer tout le cache (pour sécurité)
    pub fn clear(&self) {
        if let Ok(mut cache) = self.cache.write() {
            cache.clear();
        }
    }

    /// Obtenir le nombre d'entrées dans le cache
    pub fn len(&self) -> usize {
        self.cache.read().ok().map(|cache| cache.len()).unwrap_or(0)
    }

    /// Vérifier si le cache est vide
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    } */
}

impl Default for PassphraseCache {
    fn default() -> Self {
        Self::new()
    }
}

/// Représente une clé SSH disponible
#[derive(Debug, Clone, PartialEq)]
pub struct SshKey {
    pub name: String,
    pub private_key_path: PathBuf,
    pub public_key_path: Option<PathBuf>,
    pub key_type: SshKeyType,
    pub comment: Option<String>,
}

/// Types de clés SSH supportées
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SshKeyType {
    Ed25519,
    Rsa,
    Ecdsa,
    Unknown(String),
}

impl std::fmt::Display for SshKeyType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            SshKeyType::Ed25519 => write!(f, "Ed25519"),
            SshKeyType::Rsa => write!(f, "RSA"),
            SshKeyType::Ecdsa => write!(f, "ECDSA"),
            SshKeyType::Unknown(name) => write!(f, "{}", name),
        }
    }
}

impl SshKey {
    /// Crée une nouvelle instance de SshKey
    pub fn new(name: String, private_key_path: PathBuf) -> Result<Self> {
        let public_key_path = Self::find_public_key(&private_key_path);
        let key_type = Self::detect_key_type(&private_key_path)?;
        let comment = Self::extract_comment(&public_key_path).ok();

        Ok(Self {
            name,
            private_key_path,
            public_key_path,
            key_type,
            comment,
        })
    }

    /// Trouve la clé publique correspondante
    fn find_public_key(private_key_path: &Path) -> Option<PathBuf> {
        let public_key_path = private_key_path.with_extension("pub");
        if public_key_path.exists() {
            Some(public_key_path)
        } else {
            // Essayer avec .pub ajouté au nom complet
            let mut public_key_path = private_key_path.to_path_buf();
            public_key_path.set_extension(format!(
                "{}.pub",
                private_key_path
                    .extension()
                    .and_then(|s| s.to_str())
                    .unwrap_or("")
            ));
            if public_key_path.exists() {
                Some(public_key_path)
            } else {
                None
            }
        }
    }

    /// Détecte le type de clé en analysant le fichier
    fn detect_key_type(private_key_path: &Path) -> Result<SshKeyType> {
        if let Ok(content) = fs::read_to_string(private_key_path) {
            if content.contains("BEGIN OPENSSH PRIVATE KEY") {
                // Nouvelle format OpenSSH - analyser plus en détail si nécessaire
                if private_key_path
                    .file_name()
                    .and_then(|s| s.to_str())
                    .map(|s| s.contains("ed25519"))
                    .unwrap_or(false)
                {
                    return Ok(SshKeyType::Ed25519);
                }
                // Essayer de déterminer depuis le nom du fichier
                if let Some(filename) = private_key_path.file_name().and_then(|s| s.to_str()) {
                    if filename.contains("rsa") {
                        return Ok(SshKeyType::Rsa);
                    }
                    if filename.contains("ecdsa") {
                        return Ok(SshKeyType::Ecdsa);
                    }
                    if filename.contains("ed25519") {
                        return Ok(SshKeyType::Ed25519);
                    }
                }
                return Ok(SshKeyType::Unknown("OpenSSH".to_string()));
            }

            if content.contains("BEGIN RSA PRIVATE KEY") {
                return Ok(SshKeyType::Rsa);
            }
            if content.contains("BEGIN EC PRIVATE KEY") {
                return Ok(SshKeyType::Ecdsa);
            }
            if content.contains("BEGIN DSA PRIVATE KEY") {
                return Ok(SshKeyType::Unknown("DSA".to_string()));
            }
        }

        // Fallback: essayer de deviner depuis le nom du fichier
        if let Some(filename) = private_key_path.file_name().and_then(|s| s.to_str()) {
            if filename.contains("ed25519") {
                return Ok(SshKeyType::Ed25519);
            }
            if filename.contains("rsa") {
                return Ok(SshKeyType::Rsa);
            }
            if filename.contains("ecdsa") {
                return Ok(SshKeyType::Ecdsa);
            }
        }

        Ok(SshKeyType::Unknown("Unknown".to_string()))
    }

    /// Extrait le commentaire de la clé publique
    fn extract_comment(public_key_path: &Option<PathBuf>) -> Result<String> {
        if let Some(path) = public_key_path {
            let content = fs::read_to_string(path)?;
            // Format typique: "ssh-ed25519 AAAAC3... user@hostname"
            if let Some(comment) = content.split_whitespace().nth(2) {
                return Ok(comment.to_string());
            }
        }
        Err(anyhow!("Aucun commentaire trouvé"))
    }

    /// Obtient une description formatée de la clé
    pub fn description(&self) -> String {
        let mut desc = format!("{} ({})", self.name, self.key_type);
        if let Some(comment) = &self.comment {
            desc.push_str(&format!(" - {}", comment));
        }
        desc
    }
}

/// Gestionnaire des clés SSH multiples
pub struct SshKeyManager {
    keys: Vec<SshKey>,
    ssh_dir: PathBuf,
}

impl SshKeyManager {
    /// Crée un nouveau gestionnaire de clés SSH
    pub fn new() -> Result<Self> {
        let home_dir =
            dirs::home_dir().ok_or_else(|| anyhow!("Impossible de trouver le répertoire home"))?;
        let ssh_dir = home_dir.join(".ssh");

        let mut manager = Self {
            keys: Vec::new(),
            ssh_dir,
        };

        manager.discover_keys()?;
        Ok(manager)
    }

    /// Découvre automatiquement les clés SSH disponibles
    pub fn discover_keys(&mut self) -> Result<()> {
        log::debug!("🔑 Découverte des clés SSH dans {:?}", self.ssh_dir);

        if !self.ssh_dir.exists() {
            return Err(anyhow!("Le répertoire .ssh n'existe pas"));
        }

        let mut discovered_keys = Vec::new();

        // Clés communes à chercher
        let common_key_names = ["id_ed25519", "id_rsa", "id_ecdsa", "id_dsa"];

        // Chercher les clés communes
        for key_name in &common_key_names {
            let key_path = self.ssh_dir.join(key_name);
            if key_path.exists() && key_path.is_file() {
                match SshKey::new(key_name.to_string(), key_path) {
                    Ok(key) => {
                        log::debug!("🔑 Clé trouvée: {}", key.description());
                        discovered_keys.push(key);
                    }
                    Err(e) => {
                        log::warn!("⚠️ Erreur lors de l'analyse de la clé {}: {}", key_name, e);
                    }
                }
            }
        }

        // Chercher d'autres clés privées (fichiers sans extension .pub)
        if let Ok(entries) = fs::read_dir(&self.ssh_dir) {
            for entry in entries.flatten() {
                let path = entry.path();
                if path.is_file() {
                    let filename = path.file_name().and_then(|s| s.to_str()).unwrap_or("");

                    // Ignorer les fichiers connus et les clés publiques
                    if filename.ends_with(".pub")
                        || filename == "config"
                        || filename == "known_hosts"
                        || filename == "authorized_keys"
                        || common_key_names.contains(&filename)
                    {
                        continue;
                    }

                    // Essayer de lire le fichier pour voir si c'est une clé privée
                    if let Ok(content) = fs::read_to_string(&path) {
                        if content.contains("PRIVATE KEY") {
                            match SshKey::new(filename.to_string(), path.clone()) {
                                Ok(key) => {
                                    log::debug!(
                                        "🔑 Clé additionnelle trouvée: {}",
                                        key.description()
                                    );
                                    discovered_keys.push(key);
                                }
                                Err(e) => {
                                    log::warn!(
                                        "⚠️ Erreur lors de l'analyse de la clé {}: {}",
                                        filename,
                                        e
                                    );
                                }
                            }
                        }
                    }
                }
            }
        }

        self.keys = discovered_keys;
        log::info!("🔑 {} clé(s) SSH découverte(s)", self.keys.len());
        Ok(())
    }

    /// Sélectionne automatiquement la meilleure clé disponible (non-interactive)
    ///
    /// ⚠️ Note v0.3.4: Cette méthode n'est plus utilisée dans l'authentification automatique.
    /// Le programme essaie maintenant TOUTES les clés (comme SSH natif) via `get_all_keys()`.
    /// Cette fonction est conservée pour usage futur (CLI options, mode interactif, tests).
    #[allow(dead_code)]
    pub fn select_key_auto(&self) -> Option<&SshKey> {
        if self.keys.is_empty() {
            return None;
        }

        if self.keys.len() == 1 {
            log::info!(
                "🔑 Une seule clé disponible: {}",
                self.keys[0].description()
            );
            return Some(&self.keys[0]);
        }

        self.select_best_key()
    }

    /// Sélectionne automatiquement la "meilleure" clé disponible
    ///
    /// Ordre de priorité: Ed25519 > RSA > ECDSA > Autres
    ///
    /// ⚠️ Note v0.3.4: Cette méthode n'est plus utilisée dans l'authentification automatique.
    /// Le programme essaie maintenant TOUTES les clés (comme SSH natif) via `get_all_keys()`.
    /// Cette fonction est conservée pour usage futur (CLI options, mode interactif, tests).
    #[allow(dead_code)]
    pub fn select_best_key(&self) -> Option<&SshKey> {
        if self.keys.is_empty() {
            return None;
        }

        // Priorité: Ed25519 > RSA > ECDSA > Autres
        let mut best_key = &self.keys[0];

        for key in &self.keys {
            match (&key.key_type, &best_key.key_type) {
                (SshKeyType::Ed25519, _) => best_key = key,
                (SshKeyType::Rsa, SshKeyType::Ecdsa)
                | (SshKeyType::Rsa, SshKeyType::Unknown(_)) => best_key = key,
                (SshKeyType::Ecdsa, SshKeyType::Unknown(_)) => best_key = key,
                _ => {}
            }
        }

        log::info!(
            "🔑 Clé sélectionnée automatiquement: {}",
            best_key.description()
        );
        Some(best_key)
    }

    /// Retourne toutes les clés disponibles
    /// Cette méthode est utilisée pour essayer plusieurs clés en cas d'échec d'authentification
    pub fn get_all_keys(&self) -> &[SshKey] {
        &self.keys
    }

    /// Charge une clé SSH avec gestion de passphrase interactive et cache
    ///
    /// Tente d'abord de charger la clé sans passphrase.
    /// Si la clé est protégée, vérifie le cache puis demande la passphrase de manière interactive.
    /// Si un cache est fourni, la passphrase est ajoutée au cache après utilisation réussie.
    pub fn load_key_with_passphrase(
        key_path: &Path,
        interactive: bool,
        cache: Option<&PassphraseCache>,
    ) -> Result<PrivateKey> {
        let key_content = std::fs::read_to_string(key_path)?;

        // Tentative sans passphrase
        match decode_secret_key(&key_content, None) {
            Ok(key) => {
                log::debug!("✅ Clé chargée sans passphrase: {}", key_path.display());
                Ok(key)
            }
            Err(_) => {
                // La clé nécessite une passphrase

                // 1. Vérifier le cache si disponible
                if let Some(cache) = cache {
                    if let Some(cached_passphrase) = cache.get(key_path) {
                        log::debug!(
                            "🔑 Utilisation de la passphrase en cache pour: {}",
                            key_path.display()
                        );
                        match decode_secret_key(&key_content, Some(&cached_passphrase)) {
                            Ok(key) => return Ok(key),
                            Err(_) => {
                                log::warn!(
                                    "⚠️  Passphrase en cache invalide pour {}, redemande nécessaire",
                                    key_path.display()
                                );
                                // Continuer pour demander une nouvelle passphrase
                            }
                        }
                    }
                }

                // 2. Mode non-interactif : échouer
                if !interactive {
                    anyhow::bail!(
                        "La clé {} nécessite une passphrase. Utilisez le mode interactif ou configurez ssh-agent.",
                        key_path.display()
                    );
                }

                // 3. Demander la passphrase de manière interactive
                log::info!("🔐 La clé {} nécessite une passphrase", key_path.display());

                // Ajouter un retour à la ligne avant la saisie pour plus de clarté
                eprintln!();

                let passphrase = Password::new()
                    .with_prompt(format!("Entrez la passphrase pour {}", key_path.display()))
                    .allow_empty_password(true)
                    .interact()?;

                // Ajouter un retour à la ligne après la saisie
                eprintln!();

                // 4. Charger avec passphrase
                let key = decode_secret_key(&key_content, Some(&passphrase)).context(format!(
                    "Impossible de charger la clé avec la passphrase fournie: {}",
                    key_path.display()
                ))?;

                // 5. Ajouter au cache si fourni
                if let Some(cache) = cache {
                    cache.set(key_path.to_path_buf(), passphrase);
                    log::debug!("✅ Passphrase mise en cache pour: {}", key_path.display());
                }

                Ok(key)
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use tempfile::TempDir;

    #[test]
    fn test_ssh_key_creation() {
        let temp_dir = TempDir::new().unwrap();
        let key_path = temp_dir.path().join("test_key");

        // Créer un faux fichier de clé
        fs::write(&key_path, "-----BEGIN OPENSSH PRIVATE KEY-----").unwrap();

        let key = SshKey::new("test_key".to_string(), key_path).unwrap();
        assert_eq!(key.name, "test_key");
    }

    #[test]
    fn test_key_type_detection() {
        let temp_dir = TempDir::new().unwrap();

        // Test clé Ed25519
        let ed25519_path = temp_dir.path().join("id_ed25519");
        fs::write(&ed25519_path, "-----BEGIN OPENSSH PRIVATE KEY-----").unwrap();
        let key = SshKey::new("id_ed25519".to_string(), ed25519_path).unwrap();
        assert_eq!(key.key_type, SshKeyType::Ed25519);

        // Test clé RSA
        let rsa_path = temp_dir.path().join("test_rsa");
        fs::write(&rsa_path, "-----BEGIN RSA PRIVATE KEY-----").unwrap();
        let key = SshKey::new("test_rsa".to_string(), rsa_path).unwrap();
        assert_eq!(key.key_type, SshKeyType::Rsa);
    }
}