Cómo dominar las alertas de caducidad de certificados con PowerShell y mejorar la seguridad de T

Principales conclusiones

  • Alertas automáticas: el script proporciona alertas automáticas para los certificados que están a punto de caducar.
  • Parámetros personalizables: los usuarios pueden establecer parámetros para los plazos de caducidad y la exclusión de certificados autofirmados.
  • Mayor seguridad: las alertas oportunas ayudan a mantener la seguridad evitando vulnerabilidades relacionadas con certificados caducados.
  • Compatibilidad y requisitos: compatible con Windows 7 y Server 2008 en adelante, con requisitos específicos de privilegios y versiones de PowerShell.
  • Escalabilidad: más escalable y personalizable que las herramientas de gestión de certificados basadas en GUI.
  • Cumplimiento proactivo: ayuda a mantener la conformidad garantizando que los certificados se renueven a tiempo.
  • Integración con herramientas MSP: puede integrarse con soluciones MSP como NinjaOne para una gestión informática completa.

La gestión de los certificados digitales es un aspecto crucial de la seguridad y el cumplimiento de las TI. Pasar por alto la caducidad de los certificados puede conllevar importantes riesgos para la seguridad, interrupciones del sistema y pérdida de confianza. Un enfoque proactivo de la gestión de certificados es esencial para mantener la integridad y fiabilidad de los sistemas informáticos.

Contexto

Este script de PowerShell es una herramienta versátil para profesionales de TI y proveedores de servicios gestionados (MSP). Alerta a los usuarios sobre certificados locales próximos a caducar, con opciones para ignorar certificados autofirmados, caducados hace tiempo o de muy corta duración. Este script es especialmente relevante en entornos en los que la caducidad de los certificados puede causar interrupciones o vulnerabilidades de seguridad.

El script

<#
.SYNOPSIS
    Alerts when a local certificate will expire in a configurable number of days. Can optionally ignore self-signed certificates, certificates that have been expired for a long time and certificates that were only valid for an extremely short time frame.
.DESCRIPTION
    Alerts when a local certificate will expire in a configurable number of days. 
    Can optionally ignore self-signed certificates, certificates that have been expired for a long time 
    and certificates that were only valid for an extremely short time frame.
.EXAMPLE
    (No Parameters)
    
    Checking for certificates that were valid before 10/10/2023 09:07:23 and will expire before 11/11/2023 09:07:23.
    No Certificates were found with an expiration date before 11/11/2023 09:07:23 and after 07/13/2023 09:07:23.

PARAMETER: -DaysUntilExpiration "ReplaceWithNumber"
    Alerts if a certificate is set to expire within the specified number of days.
.EXAMPLE
    -DaysUntilExpiration "366"
    
    Checking for certificates that were valid before 10/10/2023 09:08:14 and will expire before 10/12/2024 09:08:14.

    WARNING: Expired Certificates found!

    ### Expired Certificates ###

    SerialNumber                     HasPrivateKey ExpirationDate        Subject
    ------------                     ------------- --------------        -------
    0AA60783EBB5076EBC2D12DA9B04C290         False 6/10/2024 4:59:59 PM  CN=Insecure.Com LLC, O=Insecure.Com...
    619DCC976458E38D471DC3DCE3603C2C          True 3/29/2024 10:19:00 AM CN=KYLE-SRV22-TEST.test.lan
    0AA60783EBB5076EBC2D12DA9B04C290         False 6/10/2024 4:59:59 PM  CN=Insecure.Com LLC, O=Insecure.Com...
    7D5FC733E3A8CF9344CDDFC0AB01CCB9          True 4/9/2024 9:53:53 AM   CN=KYLE-SRV22-TEST.test.lan
    4EDC0A79D6CD5A8D4D1E3705BC20C206          True 4/9/2024 9:58:06 AM   CN=KYLLE-SRV22-TEST.test.lan

PARAMETER: -MustBeValidBefore "ReplaceWithNumber"
    Only alert on certificates that are older than X days. This is primarily to silence alerts about certificates that were only valid for 24 hours in their entire lifetime.

PARAMETER: -Cutoff "ReplaceWithNumber"
    Don't alert on certificates that have been expired for longer than X days (default is 91 days).

PARAMETER: -IgnoreSelfSignedCerts
    Ignore certificates where the subject of the certificate and the issuer of the certificate are identical.

.OUTPUTS
    None
.NOTES
    Minimum OS Architecture Supported: Windows 7, Server 2008
    Release Notes: Initial Release
By using this script, you indicate your acceptance of the following legal terms as well as our Terms of Use at https://www.ninjaone.com/terms-of-use.
    Ownership Rights: NinjaOne owns and will continue to own all right, title, and interest in and to the script (including the copyright). NinjaOne is giving you a limited license to use the script in accordance with these legal terms. 
    Use Limitation: You may only use the script for your legitimate personal or internal business purposes, and you may not share the script with another party. 
    Republication Prohibition: Under no circumstances are you permitted to re-publish the script in any script library or website belonging to or under the control of any other software provider. 
    Warranty Disclaimer: The script is provided “as is” and “as available”, without warranty of any kind. NinjaOne makes no promise or guarantee that the script will be free from defects or that it will meet your specific needs or expectations. 
    Assumption of Risk: Your use of the script is at your own risk. You acknowledge that there are certain inherent risks in using the script, and you understand and assume each of those risks. 
    Waiver and Release: You will not hold NinjaOne responsible for any adverse or unintended consequences resulting from your use of the script, and you waive any legal or equitable rights or remedies you may have against NinjaOne relating to your use of the script. 
    EULA: If you are a NinjaOne customer, your use of the script is subject to the End User License Agreement applicable to you (EULA).
#>

[CmdletBinding()]
param (
    [Parameter()]
    [String]$ExpirationFromCustomField = "certExpirationAlertDays",
    [Parameter()]
    [int]$DaysUntilExpiration = 30,
    [Parameter()]
    [int]$MustBeValidBefore = 2,
    [Parameter()]
    [int]$Cutoff = 91,
    [Parameter()]
    [Switch]$IgnoreSelfSignedCerts = [System.Convert]::ToBoolean($env:ignoreSelfSignedCerts)
)
begin {
    # Retrieve script variables from the dynamic script form.
    if ($env:expirationFromCustomFieldName -and $env:expirationFromCustomFieldName -notlike "null") { $ExpirationFromCustomField = $env:expirationFromCustomFieldName }
    if ($env:daysUntilExpiration -and $env:daysUntilExpiration -notlike "null") { $DaysUntilExpiration = $env:daysUntilExpiration }
    if ($env:certificateMustBeOlderThanXDays -and $env:certificateMustBeOlderThanXDays -notlike "null") { $MustBeValidBefore = $env:certificateMustBeOlderThanXDays }
    if ($env:skipCertsExpiredForMoreThanXDays -and $env:skipCertsExpiredForMoreThanXDays -notlike "null") { $Cutoff = $env:skipCertsExpiredForMoreThanXDays }

    function Test-IsElevated {
        $id = [System.Security.Principal.WindowsIdentity]::GetCurrent()
        $p = New-Object System.Security.Principal.WindowsPrincipal($id)
        $p.IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator)
    }

    # If using the custom field option, check for the default value and replace it if necessary.
    if ($PSVersionTable.PSVersion.Major -gt 2) {
        $CustomField = Ninja-Property-Get -Name $ExpirationFromCustomField 2>$Null
    }

    if ($CustomField -and $DaysUntilExpiration -eq 30 -and (Test-IsElevated) -and $PSVersionTable.PSVersion.Major -gt 2) {
        Write-Host "Retrieved value of $CustomField days from Custom Field $ExpirationFromCustomField. Using it for expiration value."
        $DaysUntilExpiration = $CustomField
    }
    elseif (-not (Test-IsElevated) -or $PSVersionTable.PSVersion.Major -le 2) {
        Write-Warning "Skipping CustomField retrieval due to either incompatible PowerShell version or lack of elevation."
    }
}
process {
    # Calculate expiration and cutoff dates.
    $ExpirationDate = (Get-Date "11:59pm").AddDays($DaysUntilExpiration)
    $CutoffDate = (Get-Date "12am").AddDays(-$Cutoff)
    $MustBeValidBeforeDate = (Get-Date "12am").AddDays(-$MustBeValidBefore)

    # Retrieve all certificates.
    $Certificates = Get-ChildItem -Path "Cert:\" -Recurse

    Write-Host "Checking for certificates that were valid before $MustBeValidBeforeDate and will expire before $ExpirationDate."
    
    # Filter down to certificates that are expired in our desired date range
    $ExpiredCertificates = $Certificates | Where-Object { $_.NotAfter -le $ExpirationDate -and $_.NotAfter -gt $CutoffDate -and $_.NotBefore -lt $MustBeValidBeforeDate }

    # If we're asked to ignore self signed certs we'll filter them out
    if ($IgnoreSelfSignedCerts -and $ExpiredCertificates) {
        Write-Host "Removing Self-Signed certificates from list."
        $ExpiredCertificates = $ExpiredCertificates | Where-Object { $_.Subject -ne $_.Issuer }
    }

    if ($ExpiredCertificates) {
        Write-Host ""
        Write-Warning "Expired Certificates found!"
        Write-Host ""

        $Report = $ExpiredCertificates | ForEach-Object {
            # Subject can be a long property, we'll truncate it to maintain readability
            New-Object PSObject -Property @{
                SerialNumber   = $_.SerialNumber
                HasPrivateKey  = $_.HasPrivateKey
                ExpirationDate = $_.NotAfter
                Subject        = if ($_.Subject.Length -gt 35) { $_.Subject.Substring(0, 35) + "..." }else { $_.Subject }
            }
        }

        Write-Host "### Expired Certificates ###"
        $Report | Format-Table -AutoSize | Out-String | Write-Host

        exit 1
    }
    else {
        Write-Host "No Certificates were found with an expiration date before $ExpirationDate and after $CutoffDate."
    }
}
end {
    
    
    
}

 

Accede a más de 300 scripts en el Dojo de NinjaOne

Obtén acceso

Análisis detallado

El script funciona en varias fases distintas:

  • Inicialización: comienza estableciendo los parámetros por defecto, como el número de días hasta la expiración del certificado y varios límites. Éstas pueden anularse mediante variables de entorno.
  • Controles del entorno: el script comprueba los privilegios necesarios y la compatibilidad con la versión de PowerShell, ajustando su comportamiento en consecuencia.
  • Procesamiento de datos: Recupera todos los certificados del almacén local y los filtra en función de la caducidad, el periodo de validez y si están autofirmados, según los parámetros proporcionados.
  • Informes: si se encuentran certificados caducados, genera un informe enumerando sus detalles, de lo contrario, indica que no se encontraron certificados concernientes.

Ayudas visuales como los diagramas de flujo podrían ilustrar eficazmente estas etapas, haciendo el proceso más comprensible.

Posibles casos de uso

Piensa en un MSP que supervisa la infraestructura de TI de una organización. Despliegan este script para buscar regularmente certificados a punto de caducar. Este sistema de alerta temprana permite renovar a tiempo, evitando interrupciones del servicio o fallos de seguridad.

Comparaciones

Este enfoque de PowerShell es más personalizable e integrado que las herramientas de gestión de certificados basadas en GUI. Permite la automatización y es más escalable para las grandes empresas en comparación con las comprobaciones manuales.

FAQ

  • ¿Cómo determina el script sobre qué certificados debe alertar?
    El script utiliza parámetros como la fecha de caducidad, el periodo de validez y el estado autofirmado para filtrar los certificados.
  • ¿Puede ejecutarse este script en cualquier máquina Windows?
    Es compatible con Windows 7 y Server 2008 en adelante, pero requiere ciertos privilegios y versiones de PowerShell para una funcionalidad completa.
  • ¿Es posible personalizar los criterios de alerta?
    Sí, el script permite personalizar parámetros como los días hasta el vencimiento y los periodos de corte.

Implicaciones

No renovar los certificados puede provocar vulnerabilidades de seguridad y pérdida de confianza de los clientes. Este script ayuda a mantener una postura de seguridad óptima gestionando proactivamente las renovaciones de certificados.

Recomendaciones

  • Programa periódicamente la ejecución del script, garantizando alertas puntuales.
  • Personaliza los parámetros para adaptarlos a las necesidades específicas de tu entorno informático.
  • Asegúrate de contar con los privilegios adecuados y la configuración correcta del entorno para una ejecución precisa.

Reflexiones finales

En el contexto de la gestión integral de TI, herramientas como NinjaOne pueden aumentar las capacidades de este script. NinjaOne ofrece soluciones integradas que pueden funcionar junto con dichos scripts para agilizar las operaciones de TI, mejorar la seguridad y garantizar el cumplimiento.

Próximos pasos

La creación de un equipo de TI próspero y eficaz requiere contar con una solución centralizada que se convierta en tu principal herramienta de prestación de servicios. NinjaOne permite a los equipos de TI supervisar, gestionar, proteger y dar soporte a todos sus dispositivos, estén donde estén, sin necesidad de complejas infraestructuras locales.

Obtén más información sobre NinjaOne Remote Script Deployment, echa un vistazo a un tour en vivo, o comienza tu prueba gratuita de la plataforma NinjaOne.

Categorías:

Quizá también te interese…