- Установка бесплатного TLS/SSL сертификата Let’s Encrypt в IIS/RDS в Windows Server 2016/2012 R2
- Let’s Encrypt и ACME клиенты для Windows
- Клиент WACS для установки TLS сертификата Let’s Encrypt в IIS на Windows Server
- Перенаправление трафика IIS сайта с HTTP на HTTPS адрес
- Использование сертификата Let’s Encrypt для Remote Desktop Services
- Запасной вариант для Let’s Encrypt — бесплатные автоматические УЦ
- Протокол ACME
- BuyPass
- ZeroSSL
- Другие серверы ACME
- Settings.json
- Client
- ClientName
- ConfigurationPath
- LogPath
- VersionCheck
- DateFormat
- PageSize
- TextEncoding
- DefaultBaseUri
- DefaultBaseUriTest
- DefaultBaseUriImport
- PostAsGet
- RetryCount
- RetryInterval
- PreferredIssuer
- Proxy
- Username
- Password
- Cache
- ReuseDays
- DeleteStaleFiles
- Scheduled task
- RenewalDays
- StartBoundary
- ExecutionTimeLimit
- RandomDelay
- Notifications
- SmtpServer
- SmtpPort
- SmtpUser
- SmtpPassword
- SmtpSecure
- SmtpSecureMode
- SmtpSenderName
- SenderAddress
- ReceiverAddresses
- EmailOnSuccess
- ComputerName
- Security
- RSAKeyBits
- ECCurve
- PrivateKeyExportable
- EncryptConfig
- Script
- Timeout
- Target
- DefaultTarget
- Validation
- DefaultValidation
- DefaultValidationMode
- DisableMultiThreading
- CleanupFolders
- PreValidateDns
- PreValidateDnsRetryCount
- PreValidateDnsRetryInterval
- AllowDnsSubstition
- DnsServers
- Order
- DefaultOrder
- DefaultCsr
- Store
- DefaultStore
- CertificateStore.DefaultStore
- CentralSsl.DefaultPath
- CentralSsl.DefaultPassword
- Pemfiles.DefaultPath
- Pemfiles.DefaultPassword
- PfxFile.DefaultPath
- PfxFile.DefaultPassword
- Installation
- DefaultInstallation
- Validation problems
- Testing
- General validation issues
- DNSSEC
- CAA records
- Protocols and cipher suites
- Let’s Encrypt limitations
- Domain count limit
- Non-public domains
- HTTP validation issues
- Firewall
- IPv6 configuration
- FileSystem plugin IIS issues
Установка бесплатного TLS/SSL сертификата Let’s Encrypt в IIS/RDS в Windows Server 2016/2012 R2
В этом обзоре мы расскажем об особенностях установки и привязки бесплатного TLS/SSL сертификата от Let’s Encrypt для сайта на веб сервере IIS, запущенного на Windows Server 2019/2016/2012 R2.
Let’s Encrypt и ACME клиенты для Windows
API интерфейс, позволяющий автоматически выпускать сертификаты называется Automated Certificate Management Environment (ACME) API. Для Windows систем на данный момент имеется 3 самых популярных реализации клиента ACME API:
Клиент WACS для установки TLS сертификата Let’s Encrypt в IIS на Windows Server
Самый простой способ получить SSL сертификат от Let’s Encrypt — воспользоваться консольной утилитой Windows ACME Simple (WACS) (ранее проект назывался LetsEncrypt-Win-Simple). Она представляет собой простой мастер, который позволяет выбрать один из сайтов, запущенных на IIS, и автоматически выпустить и привязать к нему SSL сертификат.
Итак, предположим у нас имеется веб сайт на IIS, развёрнутый под управлением Windows Server 2016. Наша задача, переключить его в HTTPS режим, установив SSL сертификат от Let’s Encrypt.
Скачайте последний релиз клиента WACS со страницы проекта на GitHub https://github.com/PKISharp/win-acme/releases (в моем случае это версия v2.0.10 – файл win-acme.v2.0.10.444.zip).
Распакуйте архив в каталог на сервере с IIS: c:\inetpub\letsencrypt
Откройте командную строку с правами администратора, перейдите в каталог c:\inetpub\ letsencrypt и запустите wacs.exe.
Запустится интерактивный мастер генерации сертификата Let’s Encrypt и привязки его к сайту IIS. Чтобы быстро создать новый сертификат выберите N: — Create new certificates (simple for IIS).
Затем нужно выбрать тип сертификата. В нашем примере нет необходимости использовать сертификат с псевдонимами (несколькими SAN — Subject Alternative Name), поэтому достаточно выбрать пункт 1. Single binding of an IIS site. Если вам нужен Wildcard-сертификат, выберите опцию 3.
Далее утилита выведет список сайтов, запущенных на сервере IIS и предложит выбрать сайт, для которого нужно создать и привязать новый SSL сертификат.
Укажите ваш email, на который будут отправляться уведомления о проблемах с обновлением сертификата сайта и другие о повешения (можно указать несколько email через запятую). Осталось согласится с условиями использования и Windows ACME Simple подключится к серверам Let’s Encrypt и попытается автоматически сгенерировать новый SSL сертификат для вашего сайта.
Процесс генерации и установки SSL сертификата Let’s Encrypt для IIS полностью автоматизирован.
По умолчанию выполняется валидация домена в режиме http-01 validation (SelfHosting). Для этого нужно, чтобы в DNS домена имелась запись, указывающая на ваш веб сервера. При запуске WACS в ручном режиме можно выбрать валидацию типа — 4 [http-01] Create temporary application in IIS (recommended). В этом случае на веб-сервере IIS будет создано небольшое приложение, через которое сервера Let’s Encrypt смогут провести валидацию.
Утилита WACS сохраняет закрытый ключ сертификата (*.pem), сам сертфикат и ряд других файлов в каталог C:\Users\%username%\AppData\Roaming\letsencrypt-win-simple. Затем она в фоновом режиме установит сгенерированный SSL сертификат Let’s Encrypt и привяжет его к вашему сайту IIS. Если на сайте уже установлен SSL сертификат (например, самоподписанный), он будет заменен новым.
В IIS Manager откройте меню Site Binding для вашего сайта и убедитесь, что для него используется сертификат, выданный Let’s Encrypt Authority X3.
Windows ACME Simple создает новое правило в планировщике заданий Windows (win-acme-renew (acme-v02.api.letsencrypt.org)) для автоматического продления сертификата. Задание запускается каждый день, продление сертификата выполняется через 60 дней. Планировщик запускает команду:
Эту же команду вы можете использовать для ручного обновления сертфиката.
Перенаправление трафика IIS сайта с HTTP на HTTPS адрес
Чтобы перенаправить весь входящий HTTP трафик на HTTPS сайт, нужно установить модуль Microsoft URL Rewrite Module (https://www.iis.net/downloads/microsoft/url-rewrite), и убедиться, что в настройках сайта не включена опция обязательного использования SSL (Require SSL). Осталось настроить редирект в файле web.config:
Укажите имя правила и измените значения параметров:
Теперь в блоке Action выберите:
Откройте браузер и попробуйте открыть ваш сайт по HTTP адресу, вас должно автоматически перенаправить на HTTPS URL.
Использование сертификата Let’s Encrypt для Remote Desktop Services
Если вы используете для подключения внешних пользователей в корпоративную сеть шлюз Remote Desktop Gateway/ RD Web Access, вы можете использовать нормальный SSL сертификат Let’s Encrypt вместо обычного самоподписанного сертификата. Рассмотрим, как корректно установить сертификат Let’s Encrypt для зажиты служб Remote Desktop Services в Windows Server.
Затем на сервере RDP GW, запускаете wacs.exe, как описано выше, и вы выбираете нужный сайт IIS (обычно, Default Web Site). Let’s Encrypt выдает вам новый сертификат, который устанавливается для веб-сайта и в планировщике появляется задание на автоматические обновление сертификата.
Вы можете вручную экспортировать данный сертификат и привязать его к нужным службам RDS через SSL binding. Но вам придется выполнять эти действия вручную каждые 60 дней при перевыпуске сертификата Let’s Encrypt.
Нам нужен скрипт, который бы сразу после получения (продления) сертификата Let’s Encrypt применял бы его для RD Gateway.
В проекте win-acme есть готовый PowerShell скрипт ImportRDGateway.ps1 (https://github.com/PKISharp/win-acme/tree/master/dist/Scripts), который позволяет установить выбранный SSL сертификат для служб Remote Desktop. Главный недостаток скрипта – приходится вручную указывать отпечаток нового сертификата:
ImportRDGateway.ps1
Для автоматического получения отпечатка сертификата с указанного сайта IIS используйте доработанный скрипт ImportRDGateway_Cert_From_IIS.ps1 (основан на стандартном ImportRDGateway.ps1).
Вы можете запустить это скрипт вручную:
Если у вас RDS Gateway живет на стандартном IIS сайте «Default Web Site» с индексом 0, можете использовать скрипт без изменений.
Import-Module WebAdministration
Get-ChildItem IIS:Sites
Получите список вида:
В колонке ID указан индекс вашего сайта, отнимите от него единицу. Полученный индекс вашего сайта нужно указать вместо 0 в 27 строке скрипта PowerShell:
Теперь откройте задание планировщика win-acme-renew (acme-v02.api.letsencrypt.org) и на вкладке Action добавьте новое задание, которое запускает скрипт ImportRDGateway_Cert_From_IIS.ps1 после обновления сертификата.
Чтобы не менять разрешения на выполнение скриптов PowerShell, вы можете вызывать скрипт командой:
Теперь скрипт привязки SSL сертификата к службам RDS будет выполнятся сразу после продления сертификата Let’s Encrypt. При этом автоматически перезапускается служба RD Gateway командой:
При перезапуске службы TSGateway все текущие сессии пользователей разрываются, поэтому желательно изменить периодичность запуска задания обновления сертфиката на 1 раз в 60 дней.
Отметим, что сертификаты Let’s Encrypt в настоящий момент широко используются на сайтах многих крупных компаний и им доверяют все браузеры. Надеюсь, что судьба бесплатного центра сертификации Let’s Encrypt не постигнет участь WoSign и StartCom.
Запасной вариант для Let’s Encrypt — бесплатные автоматические УЦ
Для многих Let’s Encrypt стал неотъемлемой частью веб-разработки, а автоматическое обновление сертификата каждые 90 дней — рутинной процедурой. Фактически, сейчас это самый популярный удостоверяющий центр в интернете. Это великолепно, но и опасно.
Возникает вопрос: а что, если серверы Let’s Encrypt временно перестанут работать? Не хочется думать о возможных причинах сбоя. Но желательно предусмотреть запасной вариант. То есть такой же удобный автоматизированный центр бесплатной сертификации.
К счастью, запасные варианты есть. Как минимум два. Такие же бесплатные автоматизированные УЦ, созданные по образцу Let’s Encrypt.
Протокол ACME
Все коммуникации с Let’s Encrypt происходят про протоколу ACME (Automated Certificate Management Environment). Это открытый протокол для автоматизации взаимодействия с УЦ. В нём нет ничего специфичного для Let’s Encrypt, его поддерживает несколько других УЦ.
Сейчас как раз тот момент, когда всё больше УЦ начинают работать через ACME. Это означает, что практически все наши инструменты, скрипты и процессы для получения сертификатов из Let’s Encrypt будут отлично работать и с другими центрами, которые поддерживают ACME.
Чтобы перестроиться на другой УЦ, достаточно просто изменить адрес API в настроенных скриптах с https://acme-v02.api.letsencrypt.org/directory (Let’s Encrypt) на https://api.buypass.com/acme/directory (BuyPass, о нём см. ниже) или какой-нибудь другой.
BuyPass
Нам нужен УЦ, который соответствует двум критериям:
Бесплатная услуга называется BuyPass Go SSL: это автоматическая выдача и продление сертификатов + поддержка ACME. То, что и нужно.
Техническая документация объясняет, как настроить получение и обновление сертификата с помощью Certbot — официального клиента от Фонда электронных рубежей для работы с Let’s Encrypt или любым другим УЦ, который поддерживает протокол ACME.
Регистрация в УЦ и получение сертификата в BuyPass элементарны, как и в случае Let’s Encrypt, здесь никакой разницы.
Регистрация с указанием своего адреса электронной почты для уведомлений (‘YOUR_EMAIL’) и согласием на условия пользования (—agree-tos):
Впоследствии при необходимости используются другие команды Certbot для отзыва сертификата ( revoke ), продления истёкших сертификатов ( renew ) и удаления сертификата ( delete ).
Команду продления рекомендуется поместить в cron и выполнять автоматически, чтобы на всякий случай проверять истёкшие сертификаты. Например, так:
У BuyPass есть некоторые лимиты на ACME. Основной лимит — количество сертификатов на зарегистрированный домен (20 в неделю). Здесь имеется в виду та часть домена, которая куплена у регистратора доменных имён. То есть это лимит на все поддомены в общей сложности. Другой лимит — 5 дубликатов в неделю. Это лимит сертификатов на каждый конкретный поддомен. Есть лимиты на ошибки валидации — по 5 штук на аккаунт, на хост и в час.
Максимальное количество авторизаций в процессе (Pending Authorisations): 300 штук.
Вместо Certbot можно использовать другой клиент acme.sh, который тоже изначально настроен на Let’s Encrypt, но легко направляется на другой УЦ с поддержкой ACME.
ZeroSSL
Ещё один УЦ, который выдаёт бесплатные 90-дневные сертификаты по протоколу ACME — это австрийский ZeroSSL.
В вышеупомянутой программе acme.sh есть поддержка ZeroSSL, так что зарегистрироваться очень просто:
Далее одна команда для генерации сертификата:
Лимитов на обращение к API не существует. Есть и другие преимущества: этот УЦ даёт бесплатные сертификаты не только на 90 дней, но и на 1 год, есть панель веб-мониторинга и техподдержка.
Кстати, ZeroSSL генерирует сертификаты даже через веб-интерфейс, в пошаговом режиме с верификацией домена по электронной почте. Но для автоматизации такой способ, конечно, не годится.
Другие серверы ACME
Вот список всех известных серверов ACME. Их пока немного, но число растёт.
Let’s Encrypt — выдающаяся организация, которая делает отличное дело. Но опасно класть все яйца в одну корзину. Чем больше УЦ работает по протоколу ACME и раздаёт бесплатные сертификаты в автоматическом режиме, тем более разнообразна и надёжна экосистема в целом.
У Let’s Encrypt может случиться даунтайм или он может временно приостановить деятельность — и тогда на подстраховку придут Buypass и ZeroSSL. Наличие этих запасных вариантов в конечном итоге повышает доверие к самому Let’s Encrypt, потому что это теперь не единая точка отказа. А сменить УЦ по ACME — дело нескольких секунд.
Settings.json
Client
ClientName
ConfigurationPath
Change the location where the program stores its (temporary) files. If not specified this resolves to %programdata%\
LogPath
VersionCheck
Automatically check for new versions at startup.
DateFormat
Default: «yyyy/M/d H:mm:ss»
A string that is used to format the date of the certificates friendly name. Documentation for possibilities is available from Microsoft.
PageSize
The number of items to display per page in list views.
TextEncoding
Encoding to use for the console output. A list of possible values can be found here. For certain languages «unicode» might give better results displaying the characters, but note that this reduces compatibility with other programs processing the output.
DefaultBaseUri
Default ACMEv2 endpoint to use when none is specified with the command line.
DefaultBaseUriTest
DefaultBaseUriImport
Default ACMEv1 endpoint to import renewal settings from.
PostAsGet
Use [POST-as-GET] mode as defined in RFC8555, will be required by Let’s Encrypt in production from November 2020, and in test from November 2019.
RetryCount
Maximum numbers of times to refresh validation and order status, while waiting for the ACME server to complete its tasks.
RetryInterval
Amount of time in seconds to wait for each retry.
PreferredIssuer
In some exceptional cases an ACME service will offer multiple certificates signed by different root authorities. This setting can be used to give a preference. I.e. «ISRG Root X1» can be used to prefer Let’s Encrypt first fully self-signed root before it becomes the default on January 11th, 2021, and «DST Root CA X3» can be set for backwards compatibility with old Android releases (until September 30th, 2021).
Proxy
Configures a proxy server to use for communication with the ACME server and other HTTP requests done by the program. The default setting uses the system proxy. Passing an empty string will try to bypass the system proxy.
Username
Username used to access the proxy server.
Password
Password used to access the proxy server.
Cache
ReuseDays
When renewing or re-creating a previously requested certificate that has the exact same set of domain names, the program will used a cached version for this many days, to prevent users from running into rate limits while experimenting. Set this to a high value if you regularly re-request the same certificates, e.g. for a Continuous Deployment scenario.
DeleteStaleFiles
Automatically delete files older than 120 days from the CertificatePath folder. Running with default settings, these should only be long-expired certificates, generated for abandoned renewals. However we do advise caution.
Scheduled task
RenewalDays
The number of days to renew a certificate after. Let’s Encrypt certificates are currently for a max of 90 days so it is advised to not increase the days much. If you increase the days, please note that you will have less time to fix any issues if the certificate doesn’t renew correctly.
StartBoundary
Default: «09:00:00» (9:00 am)
Configures start time for the scheduled task.
ExecutionTimeLimit
Default: «02:00:00» (2 hours)
Configures time after which the scheduled task will be terminated if it hangs for whatever reason.
RandomDelay
Configures random time to wait for starting the scheduled task.
Notifications
SmtpServer
SMTP server to use for sending email notifications. Required to receive renewal failure notifications.
SmtpPort
SMTP server port number.
SmtpUser
User name for the SMTP server, in case of authenticated SMTP.
SmtpPassword
Password for the SMTP server, in case of authenticated SMTP.
SmtpSecure
Change to true to enable secure SMTP.
SmtpSecureMode
Value | Meaning |
---|---|
1 | Automatic (based on port number) |
2 | Implicit TLS |
3 | Explicit TLS (required) |
4 | Explicit TLS (when available) |
SmtpSenderName
Display name to use as the sender of notification emails. Defaults to the ClientName setting when empty.
SenderAddress
Email address to use as the sender of notification emails. Required to receive renewal failure notifications.
ReceiverAddresses
Email address to receive notification emails. Required to receive renewal failure notifications. The correct format for the receiver is [«example@example.com»] for a single address and [«example1@example.com», «example2@example.com»] for multiple addresses.
EmailOnSuccess
ComputerName
This value replaces the Windows machine name reported in emails.
Security
RSAKeyBits
The key size to sign the certificate with. Minimum is 2048.
ECCurve
The curve to use for EC certificates.
PrivateKeyExportable
EncryptConfig
Uses Microsoft Data Protection API to encrypt sensitive parts of the configuration, e.g. passwords. This may be disabled to share the configuration across a cluster of machines.
Script
Timeout
Time in seconds to allow installation and DNS scripts to run before terminating them forcefully.
Target
DefaultTarget
Default target plugin. This only affects the menu in the UI. null equivalent to «iis» with «manual» as backup for non-administrators or systems without IIS.
Validation
DefaultValidation
Default validation plugin, null currently equivalent to «selfhosting» with «filesystem» as backup for non-administrators.
DefaultValidationMode
DisableMultiThreading
Disable multithreading features for validation. Inceases runtime but may help to fix bugs caused by race conditions.
CleanupFolders
PreValidateDns
PreValidateDnsRetryCount
Maximum numbers of times to retry DNS pre-validation, while waiting for the name servers to start providing the expected answer.
PreValidateDnsRetryInterval
Amount of time in seconds to wait between each retry.
AllowDnsSubstition
If your goal is to get a certificate for example.com using DNS validation, but the DNS provider for that domain does not support automation and/or your security policy doesn’t allow third party tools like win-acme to access the DNS configuration, then you can set up a CNAME from _acme-challenge.example.com to another (sub)domain under your control that doesn’t have these limitations. acme-dns is based on this principle, but the same trick can be applied to any of the DNS plugins. Set this value to false to disable the feature.
DnsServers
Default: [ «8.8.8.8», «1.1.1.1», «8.8.4.4» ]
A list of servers to query during DNS prevalidation checks to verify whether or not the validation record has been properly created and is visible for the world. These servers will be used to located the actual authoritative name servers for the domain. You can use the string [System] to have the program query your servers default, but note that this can lead to prevalidation failures when your Active Directory is hosting a private version of the DNS zone for internal use.
Order
DefaultOrder
Default order plugin, null currently equivalent to «single»
DefaultCsr
Default order plugin, null currently equivalent to «rsa»
Store
DefaultStore
CertificateStore.DefaultStore
The certificate store to save the certificates in. If left empty, certificates will be installed either in the WebHosting store, or if that is not available, the My store (better known as Personal ).
CentralSsl.DefaultPath
CentralSsl.DefaultPassword
Pemfiles.DefaultPath
Pemfiles.DefaultPassword
PfxFile.DefaultPath
PfxFile.DefaultPassword
Installation
DefaultInstallation
Default installation plugin(s), null currently equivalent to «none» for unattended usage and «iis» for interactive mode. This may be a comma seperated value for multiple default installation plugins.
Validation problems
Validation is an important aspect of the ACME and Let’s Encrypt, but there are many subtle ways that it can fail. This page is meant for people who run into problems to help figure out what the issue might be.
Testing
General validation issues
DNSSEC
ACME providers will typically validate your DNSSEC configuration. If there is anything suspicious about it, your browser might not complain, but you will not be able to get a certificate. A useful tool to check your (provider’s) DNSSEC configuration from the perspective of a strict external observer is the Unbound DNS checker.
CAA records
ACME providers will check for the existence and validity of a CAA record for your domain. You may have to add a record like `example.com. CAA 0 issue “letsencrypt.org” to your DNS server in order to allow the provider to issue certificates for your domain. This can be checked using Let’s Debug.
Protocols and cipher suites
Tools like IISCrypto are often used configure the cipher suites of Windows systems according to the latest best practices. Changing these settings always brings some risk of breaking compatibility between two parties though. Too restrictive cipher suites have been known to hamper the ability to communicate with the ACME API endpoint and its validation servers. If that happens try more conservative settings. Test if the API endpoint is accessible from a web browser on your server.
Let’s Encrypt limitations
The following limitations apply to Let’s Encrypt and may not be true for every ACME service provider.
Domain count limit
Let’s Encrypt does not support more than 100 domain names per certificate.
Non-public domains
Let’s Encrypt can only be used to issue certificates for domains living on the public internet. Interal domains or Active Directory host names are therefor not possible to use.
HTTP validation issues
Firewall
HTTP validation happens on port 80, so it will have to open on your firewall(s). Let’s Encrypt doesn’t disclose IP address range(s) for their validation servers, meaning port 80 will have to be accessible from any origin, at least for the duration of the validation.
IPv6 configuration
Let’s Encrypt will check IPv6 access to your site if AAAA records are configured. Many browsers and networks don’t use IPv6 yet or automatically fallback to IPv4 when an error occurs, so it might not be immediately obvious that your site is unreachable on IPv6. You can test it here.
FileSystem plugin IIS issues
Note that it’s recommended to use the default SelfHosting validation plugin in combination with IIS. The FileSystem validation is great of other web servers such as Apache, but using it in combination with IIS leads to many potentials issues, described in the following sections.
CMS modules
Your CMS might intercept the request and redirect the user to an (error) page. The solution is to configure your CMS to allow unlimited access to the /.well-known/acme-challenge/ path.
Problems with httpHanders
IIS might not be configured to serve static extensionless files.
Anonymous authentication
Your website might require Windows authentication, client certificates or other authentication methods. Enable anonymous authentication to the /.well-known/acme-challenge/ path to allow access from the ACME server.
Require SSL
Your website might be configured to exclusively accept SSL traffic, while the validation request comes in on port 80. Disable the “Require SSL” setting for the /.well-known/acme-challenge/ path to fix that.
IP Address and Domain Restrictions
Your website might use IP Address and Domain Restrictions to provide extra security. The ACME server will have to bypass though. Let’s Encrypt does not publicize a list of IP addresses that they can use for validation, so this features needs to be disabled for the /.well-known/acme-challenge/ path.
URL Rewrite
If you are using URL Rewrite the validation request might get caught up in that, so you have to make exceptions for the /.well-known/acme-challenge/ path. For example like so: