Установка tls сертификата от let s encrypt на веб сервер iis

Установим SSL сертификаты на почтовый сервер hMailServer. Используем порты для SSL/TLS:

  • SMTP 587
  • IMAP 993
  • POP3 995

Сами сертификаты будем брать бесплатные — Let’s Encrypt.

SSL certificates are a useful step to protect your web application server by securing data exchange. This guide explains how to install a Let’s Encrypt SSL certificate on Windows Server 2019 with the Internet Information Services (IIS) web server.

In this guide, we will show you how to install and bind a free TLS/SSL Let’s Encrypt certificate for a site on the IIS web server running on Windows Server 2019/2016/2012 R2.

Для успешного подключения к ферме, нам необходимо установить SSL сертификат. В данный момент я не буду рассматривать самоподписанный, так как коммерческий стоит не так и дорого, чтоб не иметь возможности его приобрести, да и как правило в организации уже зачастую есть wildcard сертификат для других нужд. Так же совершенно спокойно можно использовать Let’s Encrypt сертификат с автоматическим перевыпуском и установкой на все необходимые сервисы, которым мы и воспользуемся.

Profile picture for user Олег

let's encrypt

Ранее я настраивал сертификат Let’s Encrypt на IIS для нескольких своих доменов.

IIS — SSL сертификат Let’s Encrypt

Один из доменов мне больше не понадобится, удаляем Let’s Encrypt SSL сертификат из IIS. Тем более что при попытке обновления сертификата из-за отсутствия работающего в IIS сайта я постоянно получаю письмо вида:

Сама оснастка управления IIS нам не понадобится, будем пользоваться ранее установленной консольной утилитой LetsEncrypt-Win-Simple.

Запускаем wacs.exe под администратором.

ssl

ssl

Выводим список сертификатов: L.

ssl

Под первым пунктом видим протухший сертификат, который уже 6 раз не удалось обновить. Подробные ошибки можно посмотреть, указав номер сертификата: 1.

ssl

но это уже не важно. Возвращаемся в главное меню и выводим больше опций: O.

ssl

Выбираем пункт Cancel sheduled renewal: C.

ssl

Указываем номер сертификата, который нужно удалить (перестать пытаться обновить): 1.

ssl

Обновление сертификата отменено.

Profile picture for user Олег

let's encrypt

Сегодня автоматизируем установку бесплатного SSL сертификата на сайт, который работает на web-сервере IIS 10. Операционная система Microsoft Windows 2016. Сертификат выдается лишь на 90 дней, но его всегда можно быстро обновить в автоматическом режиме.

Наличие SSL сертификата для сайта позволяет защитить данные пользователей, передаваемые по сети и гарантировать целостность переданных данных. Хотя, если вы попали на эту статью, то вы уже знаете для чего вам нужен сертификат.

Для установки сертификата будем использовать консольную утилиту LetsEncrypt-Win-Simple.

Подготовка

LetsEncrypt-Win-Simple берём здесь:

ssl

Я скачал версию v2.0.5.246. Распаковываем архив.

ssl

Папка win-acme.v2.0.5.246 нам потом пригодится для автоматического продления сертификатов, которое будет запускаться через Task Scheduler, не удаляйте.

При запуске wacs.exe хочет .NET Framework 4.7.2.

ssl

ssl

Качаем .NET Framework 4.7.2 и запускаем установку.

ssl

Принимаем лицензионное соглашение, Install.

ssl

mail

.NET Framework 4.7.2 установлен.

ssl

Перезагружаем сервер. Подготовка к установке сертификатов завершена.

Устанавливаем SSL сертификат

Запускаем wacs.exe под администратором.

ssl

Для начала сгенерируем простой сертификат. Для этого выбираем Create new certificate, N. Нас спрашивают, какой сертификат делаем.

ssl

Для тестирования генерируем простой сертификат без псевдонимов (для установки сертификата с псевдонимами выберите 2). Пишем 1. Нам показывают список всех доменов, забинденных в IIS.

ssl

Жертвой будет setpizza.com. Пишем 5.

ssl

ssl

Нужно принять лицензионное соглашение. Если написать «y», то откроется PDF файл с соглашением. Принимаем лицензионное соглашением.

ssl

Проверяем сертификат

ssl

Всё работает, сертификат есть.

ssl

ssl

В хранилище сертификатов:

ssl

Let’s Encrypt устанавливает также сертификаты промежуточных центров сертификации.

mail

443 порт добавился автоматически, сертификат выбрался автоматически.

ssl

В планировщике добавилось ежедневное правило для обновления сертификатов.

ssl

Дополнительные настройки

Вы можете настроить почту для уведомлений.

mail

Как нам подсказывают, нужно ручками подправить файл settings.config.

<setting name="SmtpServer" serializeAs="String">
  <value>localhost</value>
</setting>
<setting name="SmtpPort" serializeAs="String">
  <value>25</value>
</setting>
<setting name="SmtpUser" serializeAs="String">
  <value />
</setting>
<setting name="SmtpPassword" serializeAs="String">
  <value />
</setting>
<setting name="SmtpSecure" serializeAs="String">
  <value>False</value>
</setting>
<setting name="SmtpSenderName" serializeAs="String">
  <value>Let's Encrypt</value>
</setting>
<setting name="SmtpSenderAddress" serializeAs="String">
  <value>admin@yourdomain1.ru</value>
</setting>
<setting name="SmtpReceiverAddress" serializeAs="String">
  <value>admin@yourdomain2.ru</value>
</setting>
<setting name="EmailOnSuccess" serializeAs="String">
  <value>True</value>
</setting>

ssl

Лучше генерировать сертификаты с псевдонимами, например:

mail

Принцип понятен, дальше разберётесь.

Оглавление

Что за сертификат Let’s Encrypt?

Куда и зачем мне нужен был SSL сертификат

Начнём с того, что SSL (Secure Sockets Layer) сертификат защищает данные пользователей, которые передаются по сети. Для интеграции с одним из известных маркетплейсов
мне нужно было использовать web-сервис 1С и на тестовом Windows Server, на котором был развёрнут тестовый сервер 1С, был поднят IIS (internet Information Services). Веб сервер Windows.

  • Установка Windows Server
  • Установка Ролей ISS и DNS
  • Установка Сервера 1С
  • Подключение модуля расширения веб-сервера
  • Скачиваем программу LetsEncrypt для Windows
  • Настраиваем DNS
  • Настраиваем шлюз (в моём случае это был Kerio Control)
  • Выпускаем SSL сертификат LetsEncrypt
  • Проверяем привязку в Диспетчере служб IIS
  • Проверяем планировщик заданий на наличие таска для перевыпуска сертификата

Установку Windows Server и сервера 1С я тут рассматривать не буду, так как. Во-первых Windows Server установка мало чем отличается от установки обычной десктопной винды,
а по 1С можно почитать эту статью. Во-вторых я хочу рассказать именно про то как установить SSL сертификат
от Let’s Encrypt на Windows Server IIS. Начнём!

Установка SSL сертификата на IIS

Скачиваем программу LetsEncrypt-Win-Simple

Для того чтобы выпустить сертификат на Windows Server IIS на необходима программа LetsEncrypt-Win-Simple. Качаем её на официальном сайте www.win-acme.com

Скачиваем и распаковываем архив в директорию на жёстком диске. Для выпуска сертификата нам нужно будет запустить из каталога файл wacs.exe. Но это чуть позже.

Если мы сейчас попытаемся выпустить сертификат, то получим предупреждение

No sites with host bindings have been configured in IIS. Add one in the IIS Manager or choose the plugin 'Manual input' instead.

Добавим веб-сайт в Диспетчере служб IIS

Запускаем Диспетчере служб IIS через панель управления — администрирование. Или через WIN + R

InetMgr.exe

Добавляем записи в Диспетчере DNS

Открываем Диспетчер DNS через команду выполнить WIN + R (или любым удобным для вас способом 😉 )

dnsmgmt.msc

Так как домен у меня находится у хостинг провайдера, то я на всякий случай указал в Диспетчере DNS его NS сервера. В свою очередь у хостинг провайдера прописываем A запись с
нашим выделенным IP адресом. Позже мы настроим правило для того чтобы входящее соединение перебрасывало на нужный сервер.

Выпуск SSL сертификата Let’s Encrypt

И так. У нас есть 1С сервер с расширением веб-сервера, добавили DNS и CNAME записи, указали A запись. Теперь запускаем WACS.EXE и вводим букву N для
инициирования выпуска сертификата. Далее выбираем на какой домен будем выпускать сертификат, даём пару соглашений (y) и вводим email адрес, куда нам будут приходить уведомления
в случае каких-либо проблем (Enter email for notifications about problems and abuse).

В принципе всё готово. По части сертификата. Программа автоматически добавляет привязку 443 SSL порта к сайту в Диспетчере служб IIS и в Планировщике заданий таск на автоматический перевыпуск сертификата, но можно в этом убедиться самостоятельно

Настройка шлюза (роутера)






I have recently been working on a project to build and deploy a Terminal Server for a client and configure an RD Gateway to allow for external contractors to use it.

After some internal discussion, it was decided that we would use a Let’s Encrypt SSL certificate for the gateway. One downside of using Let’s Encrypt however is that the certificates expire every 90 days. As such we needed to find a solution to automate the renewal process.

We settled on using an application called Certify the Web, a GUI which allows you to obtain a Let’s Encrypt certificate and have it renew automatically.

Prerequisites

  1. Ensure you have set an FQDN for the RD Gateway server name (We’ll be using terminal.customer.domain for this example)

  2. Create an A record in your public facing DNS point the gateway FQDN to your public IP address

  3. Create a new zone & A record in your internal DNS pointing the servers FQDN it’s internal IP address.

  4. Create a NAT rule in your firewall to forward TCP port 80 and 443 from the public IP address to the servers internal IP address.

Secure an RD Gateway using Let’s Encrypt

Install Certify the Web

This will need to be installed onto your RDS server. If you downloaded it on this server then go ahead and install the application. If not, copy it to the correct server.

Configure Certify the Web

Once you have the application installed, go ahead and launch it. Immediately you will be asked for an email address contact. Provide desired email address, click the Yes I Agree option and then register.

Secure an RD Gateway using Let’s Encrypt

When you are shown the main application interface, click on New Certificate.

Secure an RD Gateway using Let’s Encrypt

On the Certificate Domains tab you will need to change the website in the dropdown to be the Default Web Site. In the Add Domains to certificate, enter the FQDN for the RD Gateway Server. Once done, click the Add Domains button.

Secure an RD Gateway using Let’s Encrypt

Once you have added the domain, you will see a new row is added to the Certificate Domains tab. Confirm that the domain is there and then click the Authorization tab.

Читать также:  Как в России устроен рынок поддельных сертификатов о вакцинации от CoViD-19

Secure an RD Gateway using Let’s Encrypt

On the Authorization tab, there are 3 pieces of information which we need to provide, the Domain Match, Challenge Type and Website root directory.

Secure an RD Gateway using Let’s Encrypt

Once these 3 field are completed, proceed to the Deployment tab. On this tab you will need to make sure that the Deployment Mode drop down is set to Single Site (Selected in Domains tab) and also ensure only the Binding hostname not specified (IP only or all Unassigned) option is set.

Secure an RD Gateway using Let’s Encrypt

Secure an RD Gateway using Let’s Encrypt

Handily, Certify the Web’s functionality can be expanded with PowerShell. The application is able to run PowerShell scripts both before and/or after renewal.

When running after renewal, the parameter $result can be passed through to PowerShell which can then used to do various things with the generated certificate. In our case, we will be using a script to update the certificate used by our different RDS roles.

param($result)

set-alias ps64 "$env:C:\Windows\System32\WindowsPowerShell\v1.0\Powershell.exe"

   $pfxpath = $result.ManagedItem.CertificatePath

   Set-RDCertificate -Role RDPublishing -ImportPath $pfxpath -Force

   Set-RDCertificate -Role RDWebAcces -ImportPath $pfxpath -Force

   Set-RDCertificate -Role RDGateway -ImportPath $pfxpath -Force

   Set-RDCertificate -Role RDRedirector -ImportPath $pfxpath -Force

Now we want to go back to our Certify the Web application. Check the Show Advanced Options button. This will add the Scripting tab. Go ahead and click on the Scripting tab.

Secure an RD Gateway using Let’s Encrypt

Excellent, we’re now ready to request and generate our certificate. Go ahead and click the Request Certificate button.

Secure an RD Gateway using Let’s Encrypt

Secure an RD Gateway using Let’s Encrypt

Verify the Certificate Installation

Now that our certificate has been generated, we need to verify that it has been bound to the IIS site and installed into our RDS roles.

Firstly, go ahead and launch IIS. Expand the site tree and locate the site which we generated the certificate for. Right click on the site and click on Bindings.

Secure an RD Gateway using Let’s Encrypt

You should be able to see the SSL certificate which we generated select in the drop down SSL certificate menu.

Secure an RD Gateway using Let’s Encrypt

Finally we need to confirm that our RDS roles have been updated. Launch Server Manager and click on the Remote Desktop Services role.

Secure an RD Gateway using Let’s Encrypt

Under the Deployment Overview section, go to Tasks -> Edit Deployment Properties.

Secure an RD Gateway using Let’s Encrypt

Go to the Certificate tabs. You should now be able to see all the RDS roles are trusted. Select each one and click View Details to confirm that our new certificate has been selected.

Secure an RD Gateway using Let’s Encrypt

Fantastic! You have successfully configured and deployed a Let’s Encrypt certificate which will automatically renew itself, update the IIS bindings and install into your RDS roles.

Follow Us

Recent Posts

Сертификат Exchange Server не является доверенным

При установке нового сервера Exchange клиентское соединение устанавливается небезопасно. Это по умолчанию. Мы войдем в Outlook Web Access (OWA), чтобы посмотреть, как это выглядит.

В Google Chrome отображается предупреждение:

Установка tls сертификата от let s encrypt на веб сервер iis

OWA сервера Exchange работает, но небезопасно. Значок замка показывает предупреждение. Если мы нажмем замок в адресной строке, мы увидим, что соединение не защищено.

То же самое происходит со всеми другими браузерами. Например, Internet Explorer показывает красную адресную строку. При нажатии на сертификат на панели инструментов показывает, что сертификат является несоответствующим адресом. Соединение с сервером Exchange не защищено.

Установка tls сертификата от let s encrypt на веб сервер iis

Мы узнали о Let’s Encrypt и увидели, что подключение к Exchange Server не является безопасным. В следующей части мы подготовим приложение для настройки сертификата. После этого мы запросим бесплатный сертификат Let’s Encrypt.

WACS Clint to Install Let’s Encrypt TLS Certificate in IIS on Windows Server

The easiest way to get an SSL certificate from Let’s Encrypt is to use the console tool Windows ACME Simple (WACS) (previously this project called LetsEncrypt-Win-Simple). It is a simple wizard that allows you to select one of the websites running on the IIS, automatically issue and bind an SSL certificate to it.

Windows ACME Simple (WACS) LetsEncrypt clicent download from github

wacs.exe

Open the elevated command prompt, go to c:\inetpub\letsencrypt directory and run wacs.exe. This will launch an interactive Let’s Encrypt certificate generation and binding to IIS site wizard. To quickly create a new certificate, select N:Create new certificates (simple for IIS).

simple acmev2 client - create new certificate for iis on windows server

Next, you need to select the certificate type. In our example, there is no need to use a certificate with aliases (multiple SAN – Subject Alternative Name), so just select an item 1. Single binding of an IIS site. If you need a Wildcard certificate, select the option 3.

Then the utility displays the list of websites running on IIS and prompts you to select a site to issue the certificate for.

select domain to issue ssl certificate

Specify your email address to which notifications about certificate renewing problems and other critical messages and abuses will be sent (you can specify multiple email addresses separated by commas). It remains to agree to the terms of use and Windows ACME Simple will connect to Let’s Encrypt servers and try to automatically generate a new SSL certificate for your website.

email for letsencrypt

The process of generating and installing SSL Let’s Encrypt certificate for IIS is fully automated.

In IIS Manager, open the Site Binding settings for your website and verify that it uses the certificate issued by Let’s Encrypt Authority X3.

certificate properties Let’s Encrypt Authority X3

You can find the Let’s Encrypt IIS certificate in the computer certificate store under Web Hosting -> Certificates.

Web Hosting -> IIS Certificates authorities with Let’s Encrypt » srcset=»http://woshub.com/wp-content/uploads/2019/09/web-hosting-greater-iis-certificates-authorities-with-l.png 548w, http://woshub.com/wp-content/uploads/2019/09/web-hosting-greater-iis-certificates-authorities-with-l-300×154.png 300w» sizes=»(max-width: 548px) 100vw, 548px»></p>
<p>Windows ACME Simple creates a new job in the Windows Task Scheduler (<code>win-acme-renew (acme-v02.api.letsencrypt.org)</code>) to automatically renew the certificate. The task starts every day, and the renewal of the certificate is performed after 60 days. This task runs the command:</p>
<p>You can use the same command to manually update Let’s Encrypt certificate.
					</p>
<p><img decoding=

Let’s Encrypt and ACME Clients for Windows

The Let’s Encrypt API interface to automatically issue the certificates is called Automated Certificate Management Environment (ACME) API. There are 3 most popular ACME API client implementations for Windows systems:

  1. Windows ACME Simple (WACS) is the command prompt tool for the interactive issue an SSL certificate and bind it to a specific site on your IIS web server;
  2. Powershell ACMESharp module – is the PowerShell library with a number of cmdlets to interact with Let’s Encrypt servers over ACME API;
  3. Certify is a Windows graphics tool to manage SSL certificates interactively using ACME API.

Тестируем подключение.

1. Заходим на RdWeb. Видим, что проблем с сертификатом ни каких нет. Соединение защищено.

Установка tls сертификата от let s encrypt на веб сервер iis

2. Давайте перед входом откроем скачанный RDP ярлык с RDWEB и посмотрим что там интересного:

Установка tls сертификата от let s encrypt на веб сервер iis
  • Есть full address, имя, на которое происходит соединение.
  • loadbalanceinfo говорит, что при соединении, Брокер нас направит на член RDSH в коллекции RDS.
  • signature – ярлык подписан SSL сертификатом, потому любой компьютер будет ему доверять и мы не получим лишние предупреждение о недоверенном издателе:
Установка tls сертификата от let s encrypt на веб сервер iis

3. Пробуем произвести соединение:

Установка tls сертификата от let s encrypt на веб сервер iis

Данное предупреждение by design. Функция безопасности.

Данное предупреждение в домене можно убрать с помощью групповой политики:

Указать отпечатки SHA1 сертификатов, представляющих доверенных издателей RDP

Установка tls сертификата от let s encrypt на веб сервер iis

4. Как видно, Брокер нас перенаправил на RDS01.

Установка tls сертификата от let s encrypt на веб сервер iis

Подготовка с работой Let’s Encrypt Win-ACME

Существует список клиентов ACME, предлагаемых третьими лицами для использования. Мы собираемся использовать Windows ACME Simple (WACS). Простой клиент ACME для Windows — для использования с Let’s Encrypt. Он автоматически обновит ваши сертификаты, поэтому после его установки и настройки у вас будет постоянно защищенный веб-сервер.

Загрузите Win-ACME с GitHub или официального сайта . 

Установка tls сертификата от let s encrypt на веб сервер iis

На момент написания файла это win-acme.v2.1.22.1289.x64.pluggable.zip. Создайте папку Lets Encrypt в папке C:\Program Files. Извлеките файлы из архива .zip в папку C:\Program Files\Lets Encrypt.

Установка tls сертификата от let s encrypt на веб сервер iis

Вы можете использовать Win-ACME из интерактивного меню или в автоматическом режиме (командная строка). С командной строкой вам не нужно прыгать по меню. Оба будут работать, и хорошо учиться обоим способам.

Установка сертификата на сервисы.

1. Заходим в оснастку конфигурации коллекции.

Установка tls сертификата от let s encrypt на веб сервер iis

2. Применяем наш сертификат для сервисов:

RD Connection BrokerPublishing
RD Web Access.
Enable Single Sign On – нас пока не интересует.

Установка tls сертификата от let s encrypt на веб сервер iis

3. Поставим чекбокс: Allow the certificate to be added to the Trusted Root Certification Authorities certificate store on the destination computers – для возможности установки сертификата на другие компьютеры с данной ролью. Это было бы справедливо с участием второго брокера в режиме высокой доступности.

Установка tls сертификата от let s encrypt на веб сервер iis

4. Как видно, всё прошло успешно.

Установка tls сертификата от let s encrypt на веб сервер iis

Create the Web Application

  1. Using Windows Explorer, create a new folder in the default IIS web server directory to store your domain’s web files. For example, you could create a folder named C:\inetpub\example.com.
  2. Press Control + R on your keyboard to open the run utility, and enter notepad in the text field.
  3. <html>
      <head>
        <title>Hello World</title>
      </head>
        <body>
          <h1>Hello World!</h1>
        </body>
    </html>
    

Save the file as index.html in your domain files directory. For example: C:\inetpub\example.com\index.html

Setup the IIS Site with your Domain Name

  1. Open the Windows start menu and navigate to the Windows Administrative Tools subgroup.
  2. Select Internet Information Services (IIS) Manager from the list.
  3. In the IIS Manager Window, click > next to your server name to expand the list.
  4. Expand Sites, and click Add Website on the right Actions bar.

    Add new IIS Site

  5. Enter your Web Application name in the Site Name: field.

  6. Under Content Directory, click ... to browse and set the Physical path: to your domain web files directory.
  7. Keep http as the Type under Binding, and 80 as the port.
  8. To assign your domain a specific IP address, select it from the drop-down list, or keep All Unassigned to use all Server IP addresses.
  9. Enter your domain name in the Hostname: field.
  10. Click OK to save changes and automatically start the website.
  11. Visit your domain to confirm successful integration.

    http://example.com
    

    The hello world HTML application should display.

Request and Install a Certificate

You can install a certificate with either Certbot or the Win-acme client. Please review both sections below before choosing an installation method.

Option 1: Install with Certbot

Option 2: Install with Win-acme Client

  1. Extract files from the downloaded win-acme zip archive.
  2. Navigate to the extracted folder and open the wacs.exe application.
  3. Click More info in the Windows Defender SmartScreen pop-up window, and Run anyway.
  4. In the open command prompt console, enter N to create a new SSL certificate with default options.
  5. Select your target IIS domain to install the SSL certificate on.
  6. Enter A to use all bindings of the IIS domain.
  7. Enter y' to continue with your selection,y’ to open with the default web server application, `y’ to agree to the Let’s Encrypt terms.
  8. Enter your email address to receive important certificate notifications.
  9. Your SSL Certificate is automatically stored in the IIS certificate store and registered for your domain name.
  10. https://example.com
    

Давайте зашифруем закрытый ключ сертификата

Лучше всего экспортировать сертификат после его выпуска и загрузки из Let’s Encrypt. Это означает, что вы должны импортировать закрытый ключ сертификата, чтобы экспортировать сертификат. Есть два способа сделать это.

Автоматический импорт закрытого ключа сертификата

Настройте settings_default.json, прежде чем запрашивать сертификат у Let’s Encrypt. Это автоматически импортирует закрытый ключ сертификата в сертификат:

  • Запустите проводник
  • Перейдите по пути C:\Program Files\Lets Encrypt
  • Откройте settings_default.json с помощью Блокнота.
  • Установите для PrivateKeyExportable значение true
  • Сохраните файл

 Файл settings_default.json будет скопирован вместе с его настройками в settings.json после запуска Win-ACME. Если вы уже запускали Win-ACME, в папке вы увидите файл settings.json . Отредактируйте значение в settings.json .

Установка tls сертификата от let s encrypt на веб сервер iis

Щелкните правой кнопкой мыши приложение wacs . Нажмите « Запуск от имени администратора» , чтобы запустить приложение.

Установка tls сертификата от let s encrypt на веб сервер iis

Появится окно клиента Win-ACME. Введите M , чтобы создать сертификат продления (полный вариант), и нажмите Enter .


 A simple Windows ACMEv2 client (WACS)
 Software version 2.1.22.1289 (release, pluggable, standalone, 64-bit)
 Connecting to https://acme-v02.api.letsencrypt.org/...
 Connection OK!
 Scheduled task not configured yet
 Please report issues at https://github.com/win-acme/win-acme

 N: Create certificate (default settings)
 M: Create certificate (full options)
 R: Run renewals (0 currently due)
 A: Manage renewals (0 total)
 O: More options...
 Q: Quit

 Please choose from the menu: M

Введите 2 для ручного ввода и нажмите Enter .

 Running in mode: Interactive, Advanced

 Please specify how the list of domain names that will be included in the
 certificate should be determined. If you choose for one of the "all bindings"
 options, the list will automatically be updated for future renewals to
 reflect the bindings at that time.

 1: Read bindings from IIS
 2: Manual input
 3: CSR created by another program
 C: Abort



How shall we determine the domain(s) to include in the certificate?: 2

Введите список имен хостов через запятую. Посмотрите на свои имена хостов Exchange и заполните их. Правильно ли вы настроили имена хостов Exchange Server? Внутренних имен быть не должно, например MBX1. Ознакомьтесь со статьей Проектирование и планирование пространства имен Exchange . Я рекомендую использовать одно и то же пространство имен для внутреннего и внешнего DNS.

В моем примере я буду использовать *.alukashin.ru После этого нажмите Enter .

Помимо перечислений имен в SAN сертификата, мы можем указать и wildcard , через wildcard мы покроем все имена 3 уровня , запись будет выглядить типа *.alukashin.ru . Получается что
Для установки SAN сертификата для двух имен мы перечисляем имена.
Для того чтобы произвести установку wildcard ssl сертификата в exchange 2016 мы ставим со *.domain.com

В данном примере мы выберем SAN серитфикат, в последующем мы установим сетификат на exchange 2016.

Description:        A host name to get a certificate for. This may be a
                     comma-separated list.

 Host: mail.alukashin.ru,autodiscover.alukashin.ru  или *.alukashin.ru

Мы не будем ничего вводить для предлагаемого понятного имени. Нажмите Enter , чтобы продолжить.

 Source generated using plugin Manual: mail.alukashin.ru and 1 alternatives

 Friendly name '[Manual] mail.alukashin.ru'. <Enter> to accept or type desired name: <Enter>

Проверку выполним по dns txt записи под номером 6 

The ACME server will need to verify that you are the owner of the domain
 names that you are requesting the certificate for. This happens both during
 initial setup *and* for every future renewal. There are two main methods of
 doing so: answering specific http requests (http-01) or create specific dns
 records (dns-01). For wildcard domains the latter is the only option. Various
 additional plugins are available from https://github.com/win-acme/win-acme/.

 1: [http-01] Save verification files on (network) path
 2: [http-01] Serve verification files from memory
 3: [http-01] Upload verification files via FTP(S)
 4: [http-01] Upload verification files via SSH-FTP
 5: [http-01] Upload verification files via WebDav
 6: [dns-01] Create verification records manually (auto-renew not possible)
 7: [dns-01] Create verification records with acme-dns (https://github.com/joohoi/acme-dns)
 8: [dns-01] Create verification records with your own script
 9: [tls-alpn-01] Answer TLS verification request from win-acme
 C: Abort

 How would you like prove ownership for the domain(s)?: 6

Введите 2 для ключа RSA и нажмите Enter .

After ownership of the domain(s) has been proven, we will create a
 Certificate Signing Request (CSR) to obtain the actual certificate. The CSR
 determines properties of the certificate like which (type of) key to use. If
 you are not sure what to pick here, RSA is the safe default.

 1: Elliptic Curve key
 2: RSA key
 C: Abort

Выберите вариант 3 , чтобы сохранить сертификат в хранилище сертификатов Windows, и нажмите Enter .

When we have the certificate, you can store in one or more ways to make it
 accessible to your applications. The Windows Certificate Store is the default
 location for IIS (unless you are managing a cluster of them).

 1: IIS Central Certificate Store (.pfx per host)
 2: PEM encoded files (Apache, nginx, etc.)
 3: PFX archive
 4: Windows Certificate Store
 5: No (additional) store steps

 How would you like to store the certificate?: 3

Создадим в корне диска C:\ папку PFX

Установка tls сертификата от let s encrypt на веб сервер iis

Укажем данный путь

 How would you like to store the certificate?: 3

 Description:        Path to write the .pfx file to.

 File path: C:\PFX

Нам предлагают защитить наш серфикат паролем, я откажусь , нажатием 1

Description:        Password to set for .pfx files exported to the folder.

 1: None
 2: Type/paste in console
 3: Search in vault

 Choose from the menu: 1

 1: IIS Central Certificate Store (.pfx per host)
 2: PEM encoded files (Apache, nginx, etc.)
 3: PFX archive
 4: Windows Certificate Store
 5: No (additional) store steps

 Would you like to store it in another way too?: 5
 Installation plugin IIS not available: This step cannot be used in combination with the specified store(s)

 With the certificate saved to the store(s) of your choice, you may choose one
 or more steps to update your applications, e.g. to configure the new
 thumbprint, or to update bindings.

 1: Create or update bindings in IIS
 2: Start external script or program
 3: No (additional) installation steps

 Which installation step should run first?: 3

Пишем Y , принимаем лицензионное соглашение

 Which installation step should run first?: 3

 Terms of service:   C:\ProgramData\win-acme\acme-v02.api.letsencrypt.org\LE-SA-v1.2-November-15-2017-w-v1.3-notice.pdf

 Open in default application? (y/n*)

Do you agree with the terms? (y*/n) - yes

Введите свой адрес электронной почты и нажмите Enter .

Enter email(s) for notifications about problems and abuse (comma-separated): administrator@alukashin.ru

Вывод покажет, что нам нужно подключится ко внешнему DNS и вручную создать TXT запись

[*.alukashin.ru] Authorizing...
 [*.alukashin.ru] Authorizing using dns-01 validation (Manual)

 Domain:             alukashin.ru
 Record:             _acme-challenge.alukashin.ru
 Type:               TXT
 Content:            "_UGiCVfFAkQDLjqPFTYJm1Xi0n9AS9ro8YShjKPQzAI"
 Note:               Some DNS managers add quotes automatically. A single set
                     is needed.

 Please press <Enter> after you've created and verified the record
Установка tls сертификата от let s encrypt на веб сервер iis

После публикации записи нам нужно подождать пока dns отреплицируется. Для проверки можно использовать инструмент от Google — Google DIG.

Установка tls сертификата от let s encrypt на веб сервер iis

После того как запись стало видно можно нажать Enter в поле окна WACS

Если валидация прошла успешно , он потребует удалить запись из внешнего dns , через google dig посмотрите прошла ли репликация, позже нажмите enter , как запись пропадет , можете нажать Enter.





[*.alukashin.ru] Authorizing...
 [*.alukashin.ru] Authorizing using dns-01 validation (Manual)

 Domain:             alukashin.ru
 Record:             _acme-challenge.alukashin.ru
 Type:               TXT
 Content:            "_UGiCVfFAkQDLjqPFTYJm1Xi0n9AS9ro8YShjKPQzAI"
 Note:               Some DNS managers add quotes automatically. A single set
                     is needed.

 Please press <Enter> after you've created and verified the record

 [*.alukashin.ru] Preliminary validation succeeded
 [*.alukashin.ru] Preliminary validation succeeded
 [*.alukashin.ru] Authorization result: valid

 Domain:             alukashin.ru
 Record:             _acme-challenge.alukashin.ru
 Type:               TXT
 Content:            "_UGiCVfFAkQDLjqPFTYJm1Xi0n9AS9ro8YShjKPQzAI"

 Please press <Enter> after you've deleted the record

Сертификат будет ждать вас в папке.

Установка tls сертификата от let s encrypt на веб сервер iis

В следующей статье мы разберем как установить сертификат на Exchange 2016

Prerequisites

  1. From the Windows start menu, open Server Manager.
  2. Click Add roles and features.
  3. Select Role-based or feature-based installation, and choose your server.
  4. Scroll through Server Roles and click Web Server (IIS).
  5. Add any additional IIS features you wish to install.
  6. Click Install to start the installation process.
  7. Test your IIS installation by visiting your public server IP address.

     http://192.0.2.123
    

    The default IIS welcome web page should display.

Redirect from HTTP to HTTPS Using the IIS URL Rewrite

<system.webServer>
<rewrite>
<rules>
<rule name=”HTTP to HTTPS Redirect” enabled=”true” stopProcessing=”true”>
<match url=”(.*)” />
<conditions>
<add input=”{HTTPS}” pattern=”off” ignoreCase=”true” />
</conditions>
<action type=”Redirect” url=”https://{HTTP_HOST}/{R:1}” appendQueryString=”true” redirectType=”Permanent” />
</rule>
</rules>
</rewrite>
</system.webServer>

You can also configure traffic redirect using the URL Rewrite extension through the IIS Manager GUI. Select Sites -> yoursitename -> URL Rewrite.

iis URL Rewrite module

Create a new rule Add Rule -> Blank rule.

  • Requested URL: Matches the Pattern
  • Using: Regular Expressions
  • Pattern: (.*)

URL-Rewrite edit inbound rule

  • Condition input: {HTTPS}
  • Check if input string: Matches the Pattern
  • Pattern: ^OFF$

url rewrite add conditions

  • Action Type: Redirect
  • Redirect URL: https://{HTTP_HOST}/{R:1}
  • Redirect type: Permanent (301)

Выпуск Let’s Encrypt сертификата.

Как Вы знаете, мы не можем включить в коммерческий сертификат внутреннее имя локального домена.

Мой внутренний домен: OilService.Local
Внешний: OilService.Group.

1. Для подключение к терминальной ферме я выберу более красивое имя: RDS.OilService.Group.

Так как у меня внутри домена нет этого имени, мы создаем новую зону просмотра и сделаем разрешение в IP адрес Брокера этого имени:

Установка tls сертификата от let s encrypt на веб сервер iis

2. Создаем такое же имя на внешнем DNS Хостинге. В моем случае на nic.ru.

Установка tls сертификата от let s encrypt на веб сервер iis

Распаковываем и кладем допустим на диск C:\

Далее нам нужно на нашем роутере открыть 80 порт для Брокера, так как Let’s Encrypt проводит проверку вэб сервиса. Я на своем роутере Mikrotik пробрасываю на IP адрес Брокера 80 порт.

Установка tls сертификата от let s encrypt на веб сервер iis

4. Выпускаем сам сертификат:

Установка tls сертификата от let s encrypt на веб сервер iis

Сертификат в формате PFX сохранился в папке: C:\ProgramData\win-acme\acme-v02.api.letsencrypt.org\Certificates

Установка tls сертификата от let s encrypt на веб сервер iis

А его пароль можем узнать из wacs. A: Manage renewals (1 total) -> D: Show details for the renewal

Установка tls сертификата от let s encrypt на веб сервер iis

В лабораторной среде мне не нужно автоматически устанавливать сертификат на все сервисы и автоматизировать процесс перевыпуска, но в продуктивной среде я пользуюсь такой командой:

Таким образом сертификат создается и привязывается автоматически ко всем сервисам RDS. В планировщике создается задача на перевыпуск. Можете спать спокойно.

Чтобы этот сценарий работал, закрытый ключ сертификата должен быть помечен как экспортируемый. Набор PrivateKeyExportable в settings.json к true.

Newsletter

Interested in becoming a part of our growing community?
Keep up with our events, best practices, news, tech articles and more.

Ссылки

IIS — SSL сертификат Let’s Encrypt

hMailServer — большой обзор

Получение сертификатов

web-сайт

Заводим на IIS сайт c адресом почтового сервера. Естественно, делаем всё это на сервере, где крутится hMailServer. Создаём там любую страничку index.html для проверки работы сайта.

ssl

Проверяем, что сайт работает.

ssl

Папка

Создаём папку для хранения сертификатов. Я создаю C:\mail\ssl.

ssl

Скрипт для перезапуска hMailServer

Сертификат Let’s Encrypt действует 90 дней. В планировщике добавится ежедневное правило для обновления сертификатов. Когда сертификат для hMailServer обновится через 90 дней, то hMailServer нужно перезагрузить, напишем для этого простой скрипт. Создадим в папке C:\mail\ssl файл restart_hmailserver.bat с содержимым.

@ECHO OFF
NET STOP hmailserver
NET START hmailserver

Выпуск сертификатов

Читаем статью IIS — SSL сертификат Let’s Encrypt и генерируем для нашего сайты SSL сертификаты Let’s Encrypt.

Запускаем wacs.exe под администратором.

ssl

Нам нужен пункт «Create new certificate» with advanced option». Пишем «m».

ssl

Выбираем «SAN certificate for all bindings of an IIS site». Пишем «2».

ssl

Находим в списке домен своего почтового сервера, пишем его номер, у меня «7».

ssl

Выбираем список доменных имён для исключения. Или ввод, если исключений нет. Я нажимаю Enter.

ssl

Я нажимаю Enter.

ssl

Выбираем способ подтверждения владения доменом. Для IIS это «4».

ssl

Тип CSR. Пишем «2».

ssl

Вот теперь важный пункт, где храним сертификаты. Выбираем «3», чтобы записать их в папку.

Нас спросят, в какую папку записывать сертификаты, указываем C:\mail\ssl.

ssl

Теперь спрашивают, нужно ли выполнить скрипт после записи сертификатов. Пишем «2», конечно нужно перезапустить hMailServer!

ssl

Просят указать путь к скрипту. Пишем C:\mail\ssl\restart_hmailserver.bat.

ssl

ssl

Здесь у меня уже был ранее создана задача перевыпуска этого сертификата, пишу «y».

ssl

И так, создаётся задача на обновление сертификата.

Происходит процедура проверки владения доменом — успех.

Экспортируются файлы сертификата в C:\mail\ssl.

Выполняется скрипт C:\mail\ssl\restart_hmailserver.bat, это нам пока не нужно, понадобится при выпуске следующих сертификатов.

Проверяем, что файлы созданы:

ssl

Настройка SSL в hMailServer

В админке hMailServer в Settings > Advanced > SSL certificates добавляем сертификат.

ssl

Certificate file — указываем путь к *-chain.PEM файлу.

Private key file — указываем путь к *.key.PEM файлу.

В админке hMailServer в Settings > Advanced > TCP/IP ports добавляем 587 SMTP порт.

  • Протокол: SMTP
  • TCP/IP adress: 0.0.0.0
  • TCP/IP port: 587
  • Connection security: SSL/TLS
  • SSL Certificate: из выпадающего списка выбираем добавленный ранее сертификат.

ssl

В админке hMailServer в Settings > Advanced > TCP/IP ports добавляем 993 IMAP порт.

  • Протокол: IMAP
  • TCP/IP adress: 0.0.0.0
  • TCP/IP port: 993
  • Connection security: SSL/TLS
  • SSL Certificate: из выпадающего списка выбираем добавленный ранее сертификат.

ssl

В админке hMailServer в Settings > Advanced > TCP/IP ports добавляем 995 POP3 порт.

  • Протокол: POP3
  • TCP/IP adress: 0.0.0.0
  • TCP/IP port: 995
  • Connection security: SSL/TLS
  • SSL Certificate: из выпадающего списка выбираем добавленный ранее сертификат.

ssl

На этом настройка SSL для hMailServer завершена.

Проверка

Проверяем на gmail

Проверяем на gmail как работает SSL на 995 порту POP3.

ssl

ssl

Импортировать письма из другого аккаунта (POP3). Далее.

ssl

ssl

Почтовый аккаунт добавлен. Готово.

Напишем на тестовый ящик письмо и проверим почту.

ssl

Поступило одно письмо. 995 POP3 через SSL работает.

Проверяем в Outlook

Проверяем в Outlook как работает SSL на 995 порту IMAP и на 578 порту SMTP. Создаём новую учётную запись в Outlook.

ssl

Выбираем «Ручная настройка или дополнительные типы серверов». Далее.

ssl

Выбираем «Протокол POP или IMAP». Далее.

ssl

Вкладка «Сервер исходящей почты»:

ssl

Указываем, что серверу исходящей почты тоже требуется авторизация.

ssl

IMAP-сервер, пишем порт 993, тип шифрования SSL.

SMTP-сервер, пишем порт 587, тип шифрования SSL.

ssl

Проверки прошли успешно.

Заключение

Мы с вами успешно настроили и протестировали настройку SSL сертификатов от Let’s Encrypt для почтового сервера hMailServer с помощью IIS. Более того, сертификаты будут автоматически обновляться и перезапускать hMailServer после обновления.

Если вы используете платные SSL сертификаты, то настройка SSL происходит таким же образом, просто пропускаете все шаги для Let’s Encrypt, сохраняете свои сертификаты в любую папку у настраиваете их в админке hMailServer.

Using Let’s Encrypt Certificates with RDS Gateway & Web Access

Then, run wacs.exe on the RD Gateway server, as described above. Select the desired IIS site (usually it is the Default Web Site. Let’s Encrypt will issue you a new certificate and bind it to the IIS website, and the automatic certificate renewal task will appear in the Task Scheduler.

You can manually export this certificate and bind it to the required RDS services through the SSL binding. But you will have to perform these steps manually every 60 days when the Let’s Encrypt certificate is renewed.

We can use the PowerShell script to automatically bind SSL certificate to the RDS Gateway after updating the Let’s Encrypt certificate.

To automatically get the certificate thumbprint from the specified IIS site, use the modified script ImportRDGateway_Cert_From_IIS.ps1 (based on the ImportRDGateway.ps1).

You can run this script manually:

powershell -File ImportRDGateway_Cert_From_IIS.ps1

If your RDS Gateway runs on the IIS “Default Web Site” with index 0, you can use the script without changes.

To get the site ID on IIS, open the PowerShell console and run:

Get-ChildItem IIS - get site listThe ID column shows the index of your site, subtract one from it. The resulting index should be specified instead of 0 in line 27 of the PowerShell script:

$NewCertThumbprint = (Get-ChildItem IIS:SSLBindings)[0].Thumbprint

change rds gateway site index in powershell script

Now open the win-acme-renew scheduler task, and on the Actions tab add a new task that runs the ImportRDGateway_Cert_From_IIS.ps1 script after updating the SSL certificate.

In order not to change the PowerShell execution policy, you can run the script with the command:

PowerShell.exe -ExecutionPolicy Bypass -File c:\inetpub\letsencrypt\ImportRDGateway_Cert_From_IIS.ps1

win-acme-renew - renew cert task and update RDS SSL binding

Now the script for binding the SSL certificate to the RDS will be executed immediately after the Let’s Encrypt certificate is renewed. In this case, the RD Gateway service is automatically restarted with the command:

Изменение адреса в Connection Bar.

Вам нравится имя вверху RDCB01.OILSERVICE.LOCAL? Мне нет. Не зря же я делал RDS.OilService.Group

Другое дело, когда группа высокой доступности и ты там обязан вписать имя соединения, выбрав какое-нибудь красивое, а если один Брокер ?

Исправить это дело можно с помощью PowerShell. Давайте выполним командлет:

Set-RDSessionCollectionConfiguration -CollectionName "RDS" -CustomRdpProperty "full address:s:rds.oilservice.group" -ConnectionBroker RDCB01.oilservice.local

Командлет выполнился успешно.

Установка tls сертификата от let s encrypt на веб сервер iis

Теперь снова скачаем ярлык с RdWeb и попробуем зайти, посмотреть что изменилось:

Установка tls сертификата от let s encrypt на веб сервер iis

Строка состояния поменяла название. Чего и хотелось.

В следующей статье мы займемся виртуальными профилями на базе FSLogix.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *