如何为 Windows WinRM 主机生成自签名证书并完成授信?

解读

在国内企业的 Windows 自动化场景中,WinRM(Windows Remote Management) 是 Ansible 连接 Windows 节点的唯一官方通道。由于大多数内网主机无法访问公网 CA,自签名证书成为最快捷的 HTTPS 传输加密方案。面试官问“生成+授信”,既考察你对 Windows 证书存储区的理解,也验证你是否能把 Ansible 的 win_certificate_store、winrm 配置与 PowerShell 脚本 无缝串联,最终让 Linux 端的 Ansible 控制节点信任该证书,实现 “零代理、加密通信、批量执行”。

知识点

  1. WinRM 监听模式:HTTP 5985 与 HTTPS 5986;国内安全基线要求必须关闭 HTTP,强制 HTTPS。
  2. 自签名证书核心属性:
    • 增强型密钥用法 Server Authentication (1.3.6.1.5.5.7.3.1)
    • 主题名称(Subject)必须与 真实主机名或通配符 匹配,否则 Ansible 报 “SSL: CERTIFICATE_VERIFY_FAILED”
  3. Windows 证书存储区:
    • LocalMachine\My → 存放私钥
    • LocalMachine\TrustedRoot → 让本机信任自己
    • CurrentUser\Root 对 Ansible 无效,必须写 LocalMachine
  4. Ansible 授信逻辑:
    • 控制节点把 WinRM 证书公钥写进 /etc/pki/ca-trust/source/anchors/,再执行 update-ca-trust(RHEL/CentOS)或 dpkg-reconfigure ca-certificates(Ubuntu)
    • 变量 ansible_winrm_server_cert_validation=validate 开启校验,ansible_winrm_ca_trust_path 指向合并后的 PEM,实现“证书固定”
  5. 幂等实现:
    • 用 win_certificate_store 模块的 state=exported 把公钥 idempotent 地拉回控制节点;避免每次执行都生成新证书导致指纹漂移
  6. 国内合规细节:
    • 国密算法尚未被 Ansible 官方支持,仍需 RSA 2048 + SHA256;如客户强制 SM2,需改用 gmssl 并在自定义 Python 的 winrm 传输层打补丁,面试时主动提及可加分

答案

步骤以 Ansible Playbook 一次性完成,全部任务幂等,可在国产操作系统银河麒麟、统信 UOS 上复用。

  1. 在 Windows 端生成并绑定证书
- name: Ensure WinRM HTTPS self-signed cert exists
  hosts: windows
  gather_facts: no
  vars:
    winrm_https_port: 5986
  tasks:
    - name: Generate self-signed cert if not present
      win_shell: |
        $cn = "{{ ansible_host }}"
        $cert = Get-ChildItem Cert:\LocalMachine\My |
                Where-Object { $_.Subject -like "CN=$cn" -and
                               $_.EnhancedKeyUsageList.ObjectId -contains "1.3.6.1.5.5.7.3.1" }
        if (-not $cert) {
          $param = @{
            DnsName           = $cn
            CertStoreLocation = "Cert:\LocalMachine\My"
                KeyExportPolicy   = "Exportable"
                KeySpec           = "KeyExchange"
                KeyLength         = 2048
                KeyAlgorithm      = "RSA"
                HashAlgorithm     = "SHA256"
                Provider          = "Microsoft Enhanced RSA and AES Cryptographic Provider"
                NotAfter          = (Get-Date).AddYears(5)
          }
          $cert = New-SelfSignedCertificate @param
        }
        # 把指纹写进变量供后续使用
        Write-Output $cert.Thumbprint
      register: cert_thumb
      changed_when: "'thumbprint' in cert_thumb.stdout|lower"

    - name: Bind cert to WinRM HTTPS listener
      win_shell: |
        $th = "{{ cert_thumb.stdout | trim }}"
        $exist = Get-ChildItem WSMan:\localhost\Listener -Recurse |
                 Where-Object { $_.Keys -like "Transport=HTTPS" }
        if (-not $exist) {
          New-Item -Path WSMan:\localhost\Listener -Transport HTTPS -Address * -CertificateThumbPrint $th -Force
          Restart-Service WinRM
        }
      changed_when: false
  1. 把公钥拉回控制节点并加入系统信任链
- name: Export public key back to Ansible controller
  hosts: windows
  gather_facts: no
  tasks:
    - name: Export cert without private key
      win_certificate_store:
        thumbprint: "{{ hostvars[inventory_hostname].cert_thumb.stdout | trim }}"
        store_location: local_machine
        store_name: My
        state: exported
        export_format: pem
      register: cert_pem

    - name: Copy PEM to controller
      fetch:
        src: "{{ cert_pem.export_path }}"
        dest: "/tmp/winrm_certs/{{ inventory_hostname }}.pem"
        flat: yes

- name: Merge and update system CA bundle
  hosts: localhost
  gather_facts: no
  become: yes
  tasks:
    - name: Ensure trust directory exists
      file:
        path: /etc/pki/ca-trust/source/anchors
        state: directory

    - name: Concatenate all Windows certs
      assemble:
        src: /tmp/winrm_certs
        dest: /etc/pki/ca-trust/source/anchors/winrm-ca-bundle.pem
        mode: '0644'
      notify: update ca trust

  handlers:
    - name: update ca trust
      command: update-ca-trust extract
      listen: update ca trust
  1. 在 inventory 中启用校验
[windows:vars]
ansible_connection=winrm
ansible_winrm_transport=ntlm   ; 国内域控常见
ansible_winrm_scheme=https
ansible_winrm_port=5986
ansible_winrm_server_cert_validation=validate
ansible_winrm_ca_trust_path=/etc/pki/ca-trust/source/anchors/winrm-ca-bundle.pem

执行完 playbook 后,Ansible 控制节点与 Windows 节点之间建立可信 TLS 隧道,后续任务无需 -k 或 --ignore-errors,满足等保 2.0 “传输加密+身份鉴别” 双重要求。

拓展思考

  1. 大规模场景:
    若 Windows 节点 >500,可在 AD CS(Active Directory Certificate Services) 内部署企业根 CA,通过组策略自动颁发计算机证书;Ansible 侧只需把 根证书 一次性导入 trust store,避免为每台主机维护自签名指纹,降低漂移风险。
  2. 证书续期:
    自签名证书 5 年到期前 90 天,用 win_shell 检测 NotAfter 属性,触发 New-SelfSignedCertificate 覆盖旧证;同时把新指纹同步到 WSMan 监听器,实现 无人值守续期。
  3. 多域名与负载均衡:
    对 NLB 集群 或 阿里云内网 SLB,证书需包含 Subject Alternative Name(SAN) 列表;可在 New-SelfSignedCertificate 里加 -TextExtension @("2.5.29.17={text}DNS=node1&DNS=node2&IP=10.0.0.1"),确保 Ansible 通过 VIP 连接时不报 hostname mismatch。
  4. 混合云合规:
    在 金融云 场景,客户要求 双向 TLS(mTLS)。Ansible 尚未原生支持客户端证书,可借助 winrm-ssl 的 Certificate 认证插件,结合 certmap 把客户端证书映射到本地用户,实现 “私钥不落盘、双向强身份”,面试中抛出该思路可体现深度。