
SRO PKCS11 – SSH Agent CNG è un agente Windows sovrano, ultra‑leggero e zero‑dipendenze che unifica PKCS#11, SSH-agent, Pageant e CNG/Smartcard in un unico binario robusto. Progettato per ambienti esigenti, offre crittografia hardware nativa, isolamento service/userland, supporto completo per smartcard.
Unificazione sovrana PKCS#11 + SSH-agent + Pageant + CNG/Smartcard
Un unico eseguibile Windows che unifica quattro funzioni tradizionalmente separate:
Sovrano. Nessuna dipendenza dalla CRT. Tutte le operazioni di memoria passano attraverso RtlCopyMemory, RtlZeroMemory, RtlEqualMemory (FreeCRT.h). Unicode ovunque (Win32 nativo). Nessun malloc, memcpy, strlen, printf.
Sicuro. Le chiavi private non vengono mai esportate. Nessun PIN transita. CNG/KSP gestisce l'interfaccia PIN nativa di Windows. Isolamento rigoroso servizio ↔ userland tramite pipe sicuri.
Minimalista. Un singolo binario. Nessuna DLL esterna. Nessun gonfiamento del registro. Installazione semplice (regsvr32 o -install).
Versatile. Supporto simultaneo di PKCS#11, SSH-agent, Pageant e WSL2 nello stesso processo.
┌──────────────────────────────────────────────────────────────┐ │ Clients (Git, VS, WSL, OpenSSH, PuTTY, Firefox) │ └────────────────────────┬─────────────────────────────────────┘ │ ┌───────────────┼───────────────┬─────────────────┐ │ │ │ │ SSH-agent Pageant (WM_COPYDATA) PKCS#11 WSL2 (TCP) │ │ │ │ v v v v ┌──────────────────────────────────────────────────────────────┐ │ Service Stub (session 0, SYSTEM) │ │ - Accepte connexions sur \.\pipe\openssh-ssh-agent │ │ - Crée pipe interne par client (GUID unique) │ │ - Lance helper userland avec token interactif │ │ - Forwarde messages sans manipuler de secrets │ └────────────────────────┬─────────────────────────────────────┘ │ lancé par le service v ┌──────────────────────────────────────────────────────────────┐ │ Helper Userland (session interactive) │ │ - Connecte au pipe interne │ │ - Décode protocole SSH-agent/Pageant │ │ - Invoque CNG/KSP pour signature │ │ - UI PIN native Windows (pas de relay) │ │ - Renvoie signature au service │ │ - Fenêtre Pageant cachée pour WM_COPYDATA │ │ - Listener TCP 127.0.0.1:10022 pour WSL2 │ │ - Tray icon avec menu contextuel │ └────────────────────────┬─────────────────────────────────────┘ │ v ┌──────────────────────────────────────────────────────────────┐ │ CNG/KSP Backend │ │ - NCryptSignHash avec PKCS#1/PSS padding │ │ - Enumération certificats Windows Store │ │ - Filtrage SmartCardOnly / AllowedKSP │ │ - Support RSA + ECDSA (P-256, P-384, P-521) │ │ - Support EdDSA (Ed25519, Ed448) │ │ - Support Brainpool (P256r1, P384r1, P512r1) │ │ - Cache clés + providers (4h timeout) │ └──────────────────────────────────────────────────────────────┘
---
## Modalità di esecuzione
### 1. Modalità PKCS#11 (automatica)
Caricato da:
- `ssh -I ssh-agent.exe user@host`
- Firefox (Dispositivi di sicurezza → Carica modulo PKCS#11)
- `pkcs11-tool --module ssh-agent.exe --list-objects`
Espone le esportazioni PKCS#11 standard:
- `C_Initialize`, `C_Finalize`, `C_GetInfo`
- `C_GetSlotList`, `C_GetSlotInfo`, `C_GetTokenInfo`
- `C_GetMechanismList`, `C_GetMechanismInfo`
- `C_OpenSession`, `C_CloseSession`, `C_Login`, `C_Logout`
- `C_FindObjectsInit`, `C_FindObjects`, `C_FindObjectsFinal`
- `C_GetAttributeValue`
- `C_SignInit`, `C_Sign`
- `C_VerifyInit`, `C_Verify`
- `C_DecryptInit`, `C_Decrypt`
- `C_GenerateRandom`, `C_SeedRandom`
**Meccanismi supportati (14 in totale):**
- `CKM_RSA_PKCS` (raw con padding)
- `CKM_RSA_X_509` (raw senza padding)
- `CKM_SHA1_RSA_PKCS` (legacy ssh-rsa)
- `CKM_SHA256_RSA_PKCS` (rsa-sha2-256)
- `CKM_SHA384_RSA_PKCS` (rsa-sha2-384)
- `CKM_SHA512_RSA_PKCS` (rsa-sha2-512)
- `CKM_SHA256_RSA_PKCS_PSS` (RSA-PSS SHA-256)
- `CKM_SHA384_RSA_PKCS_PSS` (RSA-PSS SHA-384)
- `CKM_SHA512_RSA_PKCS_PSS` (RSA-PSS SHA-512)
- `CKM_ECDSA` (raw)
- `CKM_ECDSA_SHA1` (legacy)
- `CKM_ECDSA_SHA256` (ecdsa-sha2-nistp256/384/521)
- `CKM_ECDSA_SHA384`
- `CKM_ECDSA_SHA512`
### 2. Modalità agente userland (standalone)```bash
ssh-agent.exe
\\.\pipe\openssh-ssh-agent nella sessione utenteCompatibile con :
set SSH_AUTH_SOCK=\\.\pipe\openssh-ssh-agent)ssh-agent.exe -install net start SROSSHAgentCNG
- Gira in sessione 0 (SYSTEM)
- Accetta connessioni su pipe globale
- Crea un pipe interno per client (protetto da SID)
- Avvia un helper userland con `CreateProcessAsUserW`
- Inoltra i messaggi senza toccare i segreti
- Pool di helper con timeout 4h (riutilizzo automatico)
- Espulsione LRU se pool pieno
**Vantaggi:**
- PIN UI nella sessione utente (non in sessione 0)
- Compatibile con ambienti rinforzati
- Isolamento stretto servizio ↔ crypto
- Multiplexing multi-utenti
### 4. Modalità helper crypto userland```bash
ssh-agent.exe -useragent -pipe \\.\pipe\ssh-ksp-helper-{GUID}
Avviato automaticamente dal servizio:
NCryptSignHash (interfaccia PIN nativa)regsvr32 ssh-agent.exe
Crea le chiavi:
- `HKLM\SOFTWARE\San@sro Inc\PKCS11-SSH-Agent`
- `HKCU\SOFTWARE\San@sro Inc\PKCS11-SSH-Agent`
- `HKCU\SOFTWARE\Mozilla\Firefox\PKCS11Modules\SROSSHAgent`
### Installare il servizio Windows```bash
ssh-agent.exe -install
net start SROSSHAgentCNG
Aggiungere al ~/.bashrc o ~/.zshrc :```bash
export SSH_AUTH_SOCK="$HOME/.ssh/agent.sock"
if ! pgrep -u $USER socat > /dev/null || [ ! -S "$SSH_AUTH_SOCK" ]; then # Nettoyage préventif rm -f "$SSH_AUTH_SOCK"
# Lancement du bridge en arrière-plan
# Note: Utiliser 127.0.0.1 si mode 'mirrored'
# sinon l'IP du host (ex: 192.168.99.x)
socat UNIX-LISTEN:"$SSH_AUTH_SOCK",fork,unlink-early \
TCP:127.0.0.1:10022 > /dev/null 2>&1 &
fi
### Disinstallare```bash
regsvr32 /u ssh-agent.exe
ssh-agent.exe -remove
Chiave: HKLM\SOFTWARE\San@sro Inc\pkcs11-cng o HKCU\SOFTWARE\San@sro Inc\pkcs11-cng
Esempio:``` StoreName = "MY" StoreLocation = "CurrentUser" SmartCardOnly = 1 AllowedKSP = "Microsoft Smart Card Key Storage Provider;YubiKey Smart Card Key Storage Provider" RelaxCheckMode = 0 LogLevel = 2
---
## Protocolli supportati
### SSH-Agent
#### SSH2_AGENTC_REQUEST_IDENTITIES (11)
Richiesta:```
[type=11]
Risposta :``` [type=12][count][key_blob_1][comment_1][key_blob_2][comment_2]...
**key_blob RSA :**```
[len]["ssh-rsa"][len][exponent][len][modulus]
key_blob ECDSA :``` [len]["ecdsa-sha2-nistp256"][len]["nistp256"][len][point]
**key_blob EdDSA :**```
[len]["ssh-ed25519"][len][point]
Richiesta :``` [type=13][len][key_blob][len][data][flags]
**Flags :**
- `0x00` : ssh-rsa (SHA-1, legacy)
- `0x02` : rsa-sha2-256
- `0x04` : rsa-sha2-512
Risposta :```
[type=14][len][signature_blob]
signature_blob :``` [len]["rsa-sha2-256"][len][signature_data]
### Pageant
Compatibile con PuTTY tramite `WM_COPYDATA`:
1. Il client crea una memoria condivisa tramite `CreateFileMapping`
2. Scrive la richiesta SSH-agent nel formato standard
3. Invia `WM_COPYDATA` alla finestra "Pageant"
4. Legge la risposta nella memoria condivisa
Formato della memoria condivisa:```
[uint32 length][SSH-agent payload]
Listener TCP su 127.0.0.1:10022 :
handle_ssh_message()Windows gestisce interamente il PIN tramite CNG/KSP e il minidriver della smartcard.
Il modulo non memorizza mai il PIN e non lo vede mai transitare:
Cache PIN: Gestito automaticamente da Windows/minidriver (nessun bisogno di cache applicativa).
Flag NCrypt:
NCRYPT_SILENT_FLAG (nessuna UI)SILENT_FLAG fallisce: Retry automatico con UICache chiavi (timeout 4h) :
CNG_KEY_INFO (handle, provider, container)Cache provider (timeout 4h) :
NCRYPT_PROV_HANDLENCryptOpenStorageProvidercng_store_enum_certificates(cfg, callback, user_data);
Filtro :
- Chiavi private disponibili
- KSP autorizzati (se `SmartCardOnly`)
- Chiavi non esportabili (se `SmartCardOnly`)
### Firma```c
cng_sign_hash(key_info, mechanism, hash, hash_len, signature, &sig_len);
Meccanismo → Padding :
CKM_RSA_PKCS → BCRYPT_PAD_PKCS1CKM_SHA256_RSA_PKCS → BCRYPT_PAD_PKCS1 + BCRYPT_SHA256_ALGORITHMCKM_SHA256_RSA_PKCS_PSS → BCRYPT_PAD_PSS + salt size = hash sizeCKM_ECDSA_SHA256 → Nessun padding (firma grezza)RSA :```c cng_cert_get_public_key(cert, modulus, &mod_len, exponent, &exp_len);
**ECDSA :**```c
cng_cert_get_ec_params(cert, params, ¶ms_len); // OID courbe
cng_cert_get_ec_point(cert, point, &point_len); // Point public
Curve supportate:
nistp256 (OID: 1.2.840.10045.3.1.7), nistp384 (1.3.132.0.34), nistp521 (1.3.132.0.35)brainpoolP256r1, brainpoolP384r1, brainpoolP512r1ed25519 (OID: 1.3.101.112), ed448 (1.3.101.113)Supporto autenticazione Active Directory:```c cng_extract_upn_from_certificate(cert, upn, upn_size);
Estrae l'estensione `szOID_NT_PRINCIPAL_NAME` per utilizzarla come commento SSH.
---
## Sicurezza
### Chiavi private
**Mai esportate.** Tutte le operazioni crittografiche sono delegate a CNG/KSP. `NCryptSignHash` viene chiamato con l'handle della chiave, mai con la chiave stessa.
### PIN
**Gestito esclusivamente da Windows (CNG/KSP/minidriver).**
Il modulo **non memorizza mai il PIN** e **non lo vede mai transitare**:
- Il PIN non viene mai trasmesso al modulo PKCS#11
- L'interfaccia PIN è mostrata dal minidriver della smartcard
- La cache del PIN è gestita automaticamente da Windows/minidriver
- In modalità servizio: l'helper userland (sessione interattiva) riceve l'interfaccia PIN
**Modalità servizio (passthrough puro):**
Il servizio stub si limita al forwarding trasparente:
- Client → Servizio → Helper (inoltro messaggio SSH-agent)
- Helper → Servizio → Client (inoltro risposta SSH-agent)
- Il servizio non analizza mai il contenuto
- Il servizio non vede mai: PIN, hash, firma, chiave
### Isolamento servizio ↔ userland
**Pipe sicure.** Ogni pipe interno è:
- Generato con un GUID univoco
- Creato con `FILE_FLAG_FIRST_PIPE_INSTANCE`
- DACL che consente solo l'utente corrente
L'helper userland invoca CNG/KSP nella sessione interattiva → interfaccia PIN nativa.
### Audit
**Log Unicode.** Tutti gli eventi sono registrati tramite `utils_log()`:
- Connessioni client
- Enumerazione chiavi
- Richieste di firma
- Errori CNG/KSP
- Conflitti agenti
**Posizione:** OutputDebugString + file opzionale (`utils_set_log_file()`).
---
## Compatibilità
| Ambiente | Modalità | Stato |
|-----------------------------|-------------------------|-------|
| OpenSSH for Windows | Standalone / Service | ✓ |
| Git for Windows | Standalone / Service | ✓ |
| Visual Studio | Standalone / Service | ✓ |
| WSL (npiperelay) | Standalone / Service | ✓ |
| WSL2 (TCP) | Standalone / Service | ✓ |
| PuTTY / plink / pscp | Pageant | ✓ |
| Firefox | PKCS#11 | ✓ |
| OpenSC / pkcs11-tool | PKCS#11 | ✓ |
| ssh -I (OpenSSH) | PKCS#11 | ✓ |
| Ambienti blindati | Service stub | ✓ |
| SmartCard GIDS | CNG/KSP | ✓ |
| SmartCard PIV | CNG/KSP | ✓ |
| YubiKey | CNG/KSP | ✓ |
| Nitrokey | CNG/KSP | ✓ |
---
## Esportazione di chiavi pubbliche
### Comando CLI```bash
ssh-agent.exe -exportkey [output.pub]
CryptUIDlgSelectCertificateFromStoreOpenSSH :``` ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC5... [email protected]
**RFC4716 :**```
---- BEGIN SSH2 PUBLIC KEY ----
Comment: "[email protected]"
AAAAB3NzaC1yc2EAAAADAQABAAABAQC5ABCDEF...
---- END SSH2 PUBLIC KEY ----
Ordine di priorità per il commento:
TRAY_MODE_USERLAND (verde) :
TRAY_MODE_SERVICE (blu) :
Tooltip dinamico:``` SRO SSH-Agent (Userland) 12 keys, 3 clients
Aggiornamento:
- Ogni 5 secondi
- Ad ogni connessione/disconnessione del client
- Al flush della cache
### Menu contestuale
**Show Keys...** : Finestra di dialogo che elenca tutte le chiavi disponibili```
═══════════════════════════════════════════════
SRO SSH-Agent - Available Keys
═══════════════════════════════════════════════
[01] RSA-2048 - [email protected]
[02] ECDSA-nistp256 - [email protected]
[03] EdDSA-Ed25519 - [email protected]
═══════════════════════════════════════════════
Total: 3 keys
💡 Tip: Use 'Export Public Key' to copy SSH format
Export Public Key... : Avvia la finestra di selezione e copia negli appunti
Flush & Reload Keys : Svuota le cache delle chiavi/provider e ricarica
Settings... : Mostra la configurazione corrente``` Current Configuration:
Store Name: MY Store Location: CurrentUser SmartCard Only: Yes Relax Key Usage Check Mode: No Log Level: 2
Edit registry to change: HKLM\SOFTWARE\San@sro Inc\pkcs11-cng
**Exit** : Arresto pulito (segnala `g_shutdown_event`)
### Thread UI dedicato
- Finestra nascosta con pompa di messaggi
- `GetMessage/DispatchMessage` loop
- Evento `g_tray_ready_event` per sincronizzazione
- Pulizia automatica (`Shell_NotifyIcon(NIM_DELETE)`)
---
## Supporto WSL2
### Architettura```
┌─────────────────────────────────────────────┐
│ WSL2 (Linux) │
│ - socat UNIX-LISTEN → TCP:127.0.0.1:10022 │
└─────────────────────────────────────────────┘
│
│ TCP
v
┌─────────────────────────────────────────────┐
│ Windows Host │
│ - ssh-agent.exe (listener 127.0.0.1:10022)│
│ - CNG/KSP → Smartcard │
└─────────────────────────────────────────────┘
Sicurezza:
g_wsl2_clients[16]CRITICAL_SECTION per slotModalità mirrored (Windows 11 22H2+):```bash
socat UNIX-LISTEN:"$SSH_AUTH_SOCK",fork,unlink-early
TCP:127.0.0.1:10022 > /dev/null 2>&1 &
**Modalità NAT classica :**```bash
# Récupérer l'IP du host Windows
HOST_IP=$(ip route | grep default | awk '{print $3}')
socat UNIX-LISTEN:"$SSH_AUTH_SOCK",fork,unlink-early \
TCP:$HOST_IP:10022 > /dev/null 2>&1 &
BOOL wsl2_network_start(WORD port, HANDLE shutdown_event); void wsl2_network_stop(void); BOOL wsl2_network_is_running(void); DWORD wsl2_network_get_client_count(void);
---
## Rilevamento dei conflitti
### Agenti rilevati```c
typedef enum {
AGENT_NONE = 0,
AGENT_OPENSSH_NATIVE, // OpenSSH for Windows (ssh-agent.exe)
AGENT_PAGEANT, // PuTTY Pageant (fenêtre "Pageant")
AGENT_SRO_USERLAND, // SRO SSH-Agent userland
AGENT_SRO_SERVICE, // SRO SSH-Agent service Windows
AGENT_UNKNOWN // Agent inconnu détecté
} AGENT_TYPE;
OpenSSH nativo :
ssh-agent.exe tramite CreateToolhelp32SnapshotPageant :
FindWindowW(L"Pageant", L"Pageant")SRO Userland :
CreateFileW(\\.\pipe\openssh-ssh-agent)SRO Service :
OpenServiceW(L"SROSSHAgentCNG")SERVICE_RUNNINGMostrato all'avvio se rilevato conflitto:``` ⚠ SSH Agent Conflict Detected
The following SSH agents are already running: • OpenSSH Native (ssh-agent.exe) • PuTTY Pageant
Running multiple agents may cause conflicts.
Do you want to continue anyway?
[Continue] [Stop conflicting agents] [Exit]
**Azioni :**
- **Continua** : Avvia comunque (rischio di conflitto)
- **Ferma** : Tenta di fermare gli agenti (se possibile)
- **Esci** : Esce senza avviare
### Funzione pubblica```c
BOOL detect_running_agents(AGENT_TYPE* detected_agents, DWORD* count);
BOOL show_agent_conflict_dialog(const AGENT_TYPE* agents, DWORD count);
const WCHAR* agent_type_to_string(AGENT_TYPE agent);
Nessuna. Il binario è autonomo e carica solo DLL di sistema:
kernel32.dll (sempre presente)advapi32.dll (registry, SCM)crypt32.dll (certificati)ncrypt.dll (CNG)bcrypt.dll (hashing)wtsapi32.dll (sessioni)shell32.dll (icona tray)ws2_32.dll (Winsock)cryptui.dll (dialogo selezione certificato)Nessun CRT. Tutte le operazioni di memoria tramite RtlCopyMemory, RtlZeroMemory, RtlEqualMemory.
SSH2_AGENTC_*_ENCRYPT).SSH2_AGENTC_ADD_ID_CONSTRAINED.MAX_HELPERS).RelaxCheckMode = 1 per utilizzarli.I contributi sono benvenuti! Si prega di:
Questo software è di proprietà di San@sro inc.
È distribuito secondo un modello di Licenza di Fiducia:
• Uso Personale e Didattico: Gratuito e incoraggiato.
• Uso Professionale/Commerciale: Richiede l'acquisto di una Licenza di Pace Tecnica.
L'uso in azienda senza licenza valida costituisce una violazione del copyright,
nonostante l'assenza volontaria di qualsiasi blocco tecnico.
La ridistribuzione è autorizzata a condizione che:
• il binario rimanga intatto,
• la firma Authenticode originale sia preservata.
Questo software è fornito «così com'è», senza garanzia di alcun tipo.
La licenza completa (FR + EN), incluse le definizioni, condizioni di ridistribuzione, durata, risoluzione e modalità di ottenimento di una Licenza di Pace Tecnica, è disponibile qui:
Per qualsiasi richiesta di licenza professionale:
📧 [email protected]
SRO PKCS11 – SSH Agent CNG non gestisce alcun segreto sensibile:
il PIN, le chiavi private e le operazioni crittografiche sono interamente gestiti da Windows (CNG/KSP/minidriver).
Per segnalare un bug, un comportamento anomalo o una potenziale vulnerabilità, una politica di divulgazione responsabile è disponibile qui:
Contatto sicurezza:
📧 [email protected]
SRO PKCS11 – SSH Agent CNG
Sovrano. Robusto. Operativo.
Un solo binario per fare tutto.
| Valore | Tipo | Descrizione |
|---|
StoreName | REG_SZ | "MY", "Root", ecc. (predefinito: "MY") |
StoreLocation | REG_SZ | "CurrentUser" o "LocalMachine" |
Mode | REG_SZ | "All" o "SmartCard" |
SmartCardOnly | REG_DWORD | 1 = filtra solo smartcard |
AllowedKSP | REG_SZ | Lista di KSP autorizzati (separati da ";") |
RelaxCheckMode | REG_DWORD | 1 = disabilita la validazione EKU/KeyUsage/dates (YubiKey PIV auto-firmato) |
LogLevel | REG_DWORD | 0=off, 1=error, 2=info, 3=debug |