Untitled

 avatar
unknown
plain_text
16 days ago
2.7 kB
4
Indexable
function Sign-UserCertificate {
    param (
        [string]$CsrFile,
        [string]$CrtFile
    )
    
    # Validation basique des paramètres
    if ([string]::IsNullOrEmpty($CsrFile) -or [string]::IsNullOrEmpty($CrtFile)) {
        Write-Error "The CSR file and the certificate file are mandatory"
        return
    }

    $csrPath = "$MINICA_CSR\$CsrFile"
    if (-not (Test-Path $csrPath)) {
        Write-Error "CSR file not found: $csrPath"
        return
    }
    
    # Vérification que la CA existe
    if (-not (Test-Path "$MINICA_PATH\index.txt")) {
        Write-Error "CA not initialized. Run -create-ca first."
        return
    }
    
    # Extraire le nom d'utilisateur et l'email du CSR pour les extensions
    $username = [System.IO.Path]::GetFileNameWithoutExtension($CsrFile)
    $csrText = openssl req -in $csrPath -noout -text
    
    # Extraire l'email pour le subjectAltName
    $emailMatch = $csrText | Select-String -Pattern "emailAddress\s*:\s*([\w\.-]+@[\w\.-]+\.\w+)"
    if ($emailMatch -and $emailMatch.Matches.Count -gt 0) {
        $email = $emailMatch.Matches[0].Groups[1].Value.Trim()
    } else {
        # Si on ne peut pas extraire l'email, utiliser un par défaut basé sur le nom d'utilisateur
        $email = "$username@epitaf.fr"
    }
    
    # Créer un fichier temporaire pour les extensions spécifiques au certificat
    $extFile = "$MINICA_PATH\temp_extensions.cnf"
    @"
nsComment = "Certificate for $username"
nsCertType = client, email
subjectAltName = email:$email,otherName:1.3.6.1.4.1.311.20.2.3;UTF8:$username@EPITAF.local
"@ | Out-File -Encoding ASCII $extFile
    
    # Signer le CSR pour générer le certificat (valide 30 jours)
    $certPath = "$MINICA_CERT\$CrtFile"
    
    # Utiliser la politique de OpenSSL pour la validation
    openssl ca -config "$MINICA_PATH\openssl.cnf" -in $csrPath -out $certPath -days 30 `
        -extfile $extFile -extensions usr_cert -batch
    
    # Si la commande a échoué, c'est probablement à cause d'une violation de politique
    if ($LASTEXITCODE -ne 0) {
        Write-Error "Certificate signing failed. The CSR likely doesn't meet policy requirements."
        # Supprimer le fichier temporaire
        Remove-Item $extFile -Force
        return
    }
    
    # Nettoyer le fichier temporaire
    Remove-Item $extFile -Force
    
    Write-Host "Certificate signed and saved at $certPath (valid for 30 days)"
    
    # Copier le certificat dans le dossier public pour distribution
    Copy-Item $certPath -Destination "$MINICA_PUBLIC\$CrtFile" -Force
    Write-Host "Certificate also available for distribution at \\EPITAF.fr\PKI\$CrtFile"
}
Editor is loading...
Leave a Comment