Automatic renewal of LetsEncrypt certificates in MDaemon mail server: step-by-step instructions


    Some time ago, a good friend of mine approached me with a problem that had suddenly arisen in him and asked for help in solving it. The problem was this: the organization in which he worked had a Windows server with the MDaemon mailer from Alt-N Technologies. A couple of years ago, the StartSSL SSL certificate from StartCom was installed on this mailer. And everything worked quite fine, it didn’t ask for porridge, when suddenly a sad letter came from StartCom informing that soon all of their certificates would receive a full and unconditional kirdyk. Like, save yourself - who can, until it is bombed. Today I will tell you how we were saved - you look, this information will be useful to someone.

    Some lyrics

    What is the first thing that a normal person thinks of when they ask him a question about replacing a certificate? There are two options: or - why don't you buy it? Or - so there’s the wonderful Let's Encrypt artel, which distributes certificates for free right and left! The first option was embarrassingly rejected as insolvent, due to the fact that, as was said earlier, the server was working, did not ask for porridge, and there was no desire to explain to management why it should part with the nth amount of evergreen money. The second option was simply super-attractive, but there were some problems looming on the horizon that were to go round: the window of the mailer suggested sad thoughts about its compatibility with LetsEncrypt scripts, and I did not want to receive and install a certificate manually every three months.

    Therefore, the second option was chosen - only it was necessary to find a way to automate the processes of obtaining a certificate and binding it to a mailer.

    We began, of course, by digging up the great and terrible Internet in search of a ready-made solution. And lo! It turned out that the valiant programmers from Alt-N Technologies had already taken care of this and turned up scripts that did everything they needed! As they say - take off my hat! But there was a fly in the ointment: these scripts were simply not distributed to everyone and everyone, but were included in the latest versions of MDaemon. However, our ward server had on board a rather old version of MDaemon - 13.6.3. The software was completely legal, once bought for the most real money, it worked great and its upgrade was certainly not included in the management plans (see the paragraph on buying a certificate).

    Therefore, it was decided to try to transplant scripts from the new version of MDaemon to the old one and make them work there. Thought - done: the latest trial version of MDaemon was installed on the virtual machine at that time and the LetsEncrypt folder with all the contents was removed from it. What to do now with this good? - read below.

    Initial data

    • Server running Windows Server 2008 R2.
    • MDaemon mail server version 13.6.3.
    • On the same server, IIS was launched, which serves the organization’s corporate website.
    • MDaemon used its own embedded WorldClient WEB server, which was accessible from the Internet through port 3000.

    Mandatory Requirements

    As was written in this article , the LetsEncrypt scripts for MDaemon are not completely universal and require the following prerequisites to be met:

    • The presence of PowerShell version 3.0.
    • The presence of the installed Microsoft .NET framework version no lower than 4.0.
    • The presence of the installed package IIS Management Scripts and Tools.
    • From the Internet through port 80, a WorldClient server should be available - either directly or through IIS.

    As you can see, some of these requirements were not initially fulfilled, so the WorldClient was first bound to IIS in order to transfer it to port 80. Information on how to do this was obtained from this article from the Alt-N website.

    A few words about the "rake"

    Before proceeding with the description of the step-by-step instructions, I want to keep your attention on some unforeseen troubles that complicated the process of transplanting scripts and obtaining certificates.

    Firstly, almost at the very beginning of the script, a check was made that the 'EnableWCServer' parameter in the 'Mdaemon.ini' file was set to 'Yes'. And if this was not so, then the script immediately exited with a critical error message 'Error: WorldClient must be enabled'. But, oddly enough, in our case this parameter was set to 'No' - despite the fact that we had already bound WorldClient to IIS and WorldClient was perfectly open from the Internet. Without thinking twice, we turned off this check by commenting it out in the script. This allowed the script to continue working.

    Secondly, the corporate site was raised on the same server and access to some pages of this site was done using the https protocol using a self-signed certificate. And old Windows-servers assume that only one certificate can be attached to one IP. We stepped on this rake at the very end of the path - when the certificate from LE was already successfully obtained, but could not bind to the address As a result, the problem was solved in a quick, but somewhat crooked way: WorldClient was sent to a separate IP address (fortunately, it was available) and again I had to edit the script - an IP address was added to the list of its input parameters, to which it was necessary to bind certificate. And since the binding of WorldClient to IIS was already completely completed, we did not start our own MDaemon WEB server and left everything as it is.


    Part 1: pre-training

    1. In any way known to you, we make a buck server!
    2. Install .NET version higher or equal to 4.0.
    3. Add Role Services: go to 'Control Panel' -> 'Administrative Tools' -> 'Server Manager' -> 'Roles' and click on the link 'Add Role Services'.

      We put kryzhiki on:
      • Web Server / Application Development / ISAPI Extensions
      • Web Server / Application Development / ISAPI Filters
      • Management Tools / IIS Management Scripts and Tools

      Click 'Next', and so on.
    4. Install Windows Management Framework 3.0 - this will install PowerShell version 3.0 into the system (see the Required Requirements section):
      • Download WMF 3.0 from the Microsoft website.
      • Install the desired WMF. For Windows Server 2008 R2, this is 'Windows6.1-KB2506143-x64.msu'.
      • Reboot the server.

    Part 2: creating an IIS site to access the WorldClient server

    Note 1: if you use the WorldClient server built into MDaemon and it already sits solely on port 80, you can safely skip this part and go directly to part 3.

    Note 2: the 'host name' of the site should be the same as the full The domain name of the MDaemon host, by which it is accessible from the Internet.

    To find out the fully qualified domain name of the MDaemon host: start the Mdaemon GUI, go to the menu: 'Settings' -> 'Primary domain / servers' -> 'Default domain and servers' -> 'Domain' and look at the 'Full host domain name' field .

    So let's get started. We launch the IIS manager and add a new site to it:

    1. In the field 'Site name' enter the name of the site - which one you like.
    2. In the field 'Physical path' enter the path to the HTML folder of the World-client.
    3. In the 'Host name' field, specify the fully qualified domain name of the host (see note 2 above).
    4. In the 'IP-address' field, leave 'All unassigned' if the interface is used exclusively, or select the IP belonging to the mailer from the list.
    5. The fields 'Type' and 'Port' are left as they are - 'http' and '80', respectively.

    Edit the list of default site documents - go to the subsection 'Default Document':

    1. We clear the whole list.
    2. Add the document 'WorldClient.dll': in the right panel 'Actions' click 'Add ...' and in the field 'Name' type 'WorldClient.dll'.
    3. Add the document 'MDSyncML.dll': in the right panel 'Actions' click 'Add ...' and in the field 'Name' type 'MDSyncML.dll'.
    4. Put 'WorldClient.dll' first in the list: select it and click 'Move Up' in the right panel 'Actions'.

    Go to the 'Handler Mappings' section:

    1. Edit 'Feature Permissions': in the right panel 'Actions' click on 'Edit Feature Permissions ...' and put all the gooseberries - 'Read', 'Script' and 'Execute'.
    2. We find in the list of 'ISAPI-dll' and go into it.

    3. In the field 'Request path' write 'WorldClient.dll'.
    4. In the 'Module' list, select 'IsapiModule'.
    5. In the field 'Executable (optional)' indicate the path to WorldClient.dll.
    6. Add a new handler: in the right panel 'Actions' click 'Add Module Mapping ...'

    7. In the field 'Request path' write 'MDSyncML.dll'.
    8. In the 'Module' list, select 'IsapiModule'.
    9. In the field 'Executable (optional)' indicate the path to MDSyncML.dll.
    10. In the field 'Name' write something articulate. For example, 'SyncML-ISAPI'.

    We edit 'MIME Types' - if this is not done, then the LetsEncrypt robot will not be able to receive a file from us without the extension:

    1. Go to the section 'MIME Types'.
    2. In the right panel of 'Actions' click 'Add ...'.
    3. In the field 'File name extension' write a point.
    4. In the field 'MIME type' write 'text / plain'.

    We edit the 'Application Pool', automatically created when creating our site:

    1. Go to 'Application Pools' -> 'MDaemon WorldClient' -> 'Advanced Settings ...'.
    2. In the 'Process Model' section, change 'Identity' to 'Network Service'.
    3. If the OS is 64-bit, then in the section 'General' we change 'Enable 32-Bit Applications' to 'True'.

    Close the console. IIS is configured.

    Next, we give users 'IUSR' and 'NETWORK SERVICE' full access to the MDaemon folder:

    1. We go into the explorer, open the 'Properties' folder of the 'MDaemon' folder, go to the 'Security' tab, click on 'Edit'.
    2. Click 'Add' -> 'Advanced' -> 'Find Now' - select the user 'IUSR' in the list of 'Search Results', click 'OK'.
    3. Put the gooseberry 'Full control' in the list of 'Permissions for IUSR'.
    4. Click 'Add' -> 'Advanced' -> 'Find Now' - select the user 'NETWORK SERVICE' in the list of 'Search Results', click 'OK'.
    5. Put the gooseberry 'Full control' in the list of 'Permissions for NETWORK SERVICE'.
    6. Close both windows by clicking on 'OK'.

    WorldClient is configured. We verify that WorldClient opens normally by going to it with a browser over the Internet using the fully qualified domain name of the host.

    Part 3: installing and configuring LetsEncrypt scripts

    1. Download the archive with scripts from here and unpack it to the root of the 'MDaemon' folder. Important note: in the script, the main LetsEncrypt server is replaced with a test one - to prevent ban due to repeated attempts to obtain a certificate during the debugging process. In the next part, it will be written how to switch to the main server.
    2. Add the path to the modules used by the script in the environment variable 'PSModulePath':

      • Go to 'Control Panel' -> 'System' -> 'Advanced system settings' -> 'Advanced' -> 'Environment Variables'.
      • We are looking for the variable 'PSModulePath' in the list of 'System Variables'.
      • Add through ';' at its end is the path to the 'Modules' folder located inside the 'LetsEncrypt' folder. In my case, this: 'c: \ MDaemon \ LetsEncrypt \ Modules \'
      • We are logged in.
    3. Launch the cmd console.
    4. Run the letsencrypt.ps1 script with the command:

      powershell -ExecutionPolicy ByPass -File c:\mdaemon\letsencrypt\letsencrypt.ps1
      Here the parameter 'File' sets the path to the script.

      You can use additional parameters:
      • -IISSiteName "MDaemon WorldClient"
        If WorldClient works through IIS, then this parameter must specify the script the name of the WorldClient site (see part 2)
      • -WCIPAddress
        This parameter sets the IP address to which the script should attach the received certificate. It is not necessary to specify it if no other certificates are attached to port 443.
      • -To “”
        This parameter sets the email to which the log of the script will be sent in case of any error.

      We look in the console window - the script should run without errors.

      If something goes wrong - you have to deal with this problem yourself.

      If everything was successful, then you can try to access the WorldClient browser using the https protocol: since we used the LetsEncrypt test server, the browser should curse the site certificate with the message 'SEC_ERROR_UNKNOWN_ISSUER'.

      By the way, remember - I talked about the "rake" with the parameter 'EnableWCServer' in the file 'Mdaemon.ini' - that when using the bundle with IIS it is set to 'No'? So, after successfully working out the script, this parameter changed to 'Yes'. However, this happened a bit late, so we did not comment on the verification of this parameter in the script.

    Part 4: translating the script into "combat mode"

    1. Open the letsencrypt.ps1 script from the LetsEncrypt folder in a text editor.
    2. We find the lines in it:

      #Initialize-ACMEVault -ErrorVariable LogText
      Initialize-ACMEVault -BaseURI -ErrorVariable LogText
    3. Uncomment the first line, and comment the second:

      Initialize-ACMEVault -ErrorVariable LogText
      #Initialize-ACMEVault -BaseURI -ErrorVariable LogText
    4. Save the script.

    Part 5: Removing all traces of “test” life

    If this is not done, then the script will continue to give us a "fake" certificate for a couple of months, despite the fact that we have made the necessary changes to the script.

    1. Delete the test certificate from MDaemon:
      • Launch the MDaemon GUI and go to the menu 'Security' -> 'Security Settings' -> 'SSL & TLS'.
      • In the list of certificates, select our test certificate (it will have 'Fake LE Intermediate X1' in the 'Sender' field) and click on the 'Delete' button under the list.
      • If the list of certificates is empty, you will have to create a self-signed certificate, otherwise MDaemon will swear when trying to close the window.
    2. Delete the keystore created by the script: if you worked under the admin account, then go to 'c: \ ProgramData \', and if under the user account go to 'C: \ Users \ username \ AppData \ Local \' and delete the folder 'ACMESharp' from there along with all the content.
    3. Delete the XML file created by the script: go to the 'MDaemon \ LetsEncrypt' folder and delete the LetsEncrypt.XML file from there.
    4. Delete the test certificate: go to the folder 'MDaemon \ Pem', find the certificate there (file with the extension 'pfx') and delete it.

    Part 6: Scheduled script execution setup

    1. Идём в 'Control Panel' -> 'Administrative Tools' -> 'Computer Management' -> 'System Tools' -> 'Task Scheduler' -> 'Task Scheduler Library'.
    2. Создаём новую задачу: нажимаем 'Create Task...' в правой панели 'Actions'.
    3. На закладке 'General':
      • В поле 'Name' пишем имя задачи — произвольно по вашему желанию.
      • В подразделе 'Security Options' выбираем пункт 'Run whether user is logged on or not'.
    4. На закладке 'Triggers':
      • Нажимаем кнопку 'New...' — откроется окно 'New Trigger'.
      • В списке 'Begin the task' выбираем 'On a schedule'.
      • Устанавливаем подходящую периодичность запуска: например, раз в неделю по воскресеньям. Скрипт при каждом старте будет проверять — сколько сертификату осталось жить: и если меньше месяца, то обновит его.
    5. На закладке 'Actions':
      • Нажимаем кнопку 'New' — откроется окно 'New Action'.
      • В списке 'Action' выбираем 'Start a program'.
      • В поле 'Program/script' пишем 'powershell'.
      • В поле 'Add arguments (optional)' пишем '-ExecutionPolicy ByPass -File c:\MDaemon\LetsEncrypt\letsencrypt.ps1'. В хвост строки дописываем требуемые дополнительные параметры (см. часть 3).
    6. На закладке 'Conditions' ставим крыжики по своему усмотрению.
    7. На закладке 'Settings' ставим крыжики:
      • Allow task to be run on demand
      • Stop the task if it runs longer than 1 hour
      • If the running task does not end when requested, force it to stop
    8. Click the 'OK' button. Enter the password of the current user.

    Part 7: the first "combat" launch

    We start the script manually:

    1. Select the newly created task in the list.
    2. Click 'Run' in the right pane Actions'. No window will open.
    3. From time to time we refresher the task list - to see the changes in the 'Status' field: 'Status' should change to 'Run'. Refresh the list until 'Status' becomes 'Ready' again.
    4. We look at the result of the script in the log file 'MDaemon \ Logs \ LetsEncrypt.log'.

    If, judging by the log file, everything went well, then the job is done - the certificate is received and you can check the functionality of receiving / sending mail on a secure channel. And yes, do not forget to log into the mailer using the https protocol - to make sure that WorldClient also works without problems.

    Part last - final

    In conclusion, I want to say that at the time of writing the article, I no longer had access to the combat server, so all screenshots were taken from a virtual machine on which an even older version of MDaemon was installed - 13.0.4 - due to which the appearance of windows can be different from other versions.

    That's it. All that I knew was told. Happy New Year to all! I wish you health and good luck!

    Also popular now: