Как привязать ssl-сертификат в iis powershell

I am struggling with the logic behind finding a certificate that is not expired in Powershell. I have the potential to have multiple certs with the same CN installed, most of them expired, with at LEAST one active, potentially two active for a week or two while manual renewals occur. This is causing me a logic problem that I need help with.

  1. FRIENDLYNAME, expires August 10 2024
  2. FRIENDLYNAME, expires August 21 2023
  3. FRIENDLYNAME, expires August 27 2022
cd cert:\LocalMachine\my
$today = [DateTime]::Now
get-childitem | where { $_.Subject -match 'CN=FRIEDNLYNAME' -and $_.NotAfter -gt $today }

This does accurately return only the non-expired certificate. However, I may have a time when two FRIENDLYNAME certs might be active, and as an example using the above list, number 2 was active for two weeks while number 1 was getting installed.

My logic problem is, how can I have Powershell return only the absolute latest possible expiring cert? I understand the easiest answer is to properly clean up the environments and make sure that only an active cert is installed, but in the event that I cannot do this, how can I make Powershell logic work in my favor?

Here is what I use on the IIS/Web Server front.

In all honesty, you could probably just take the Variables for expiration from my script, as well as tweak the Retrieve Cert info (and everything below) and you would have something for all certs in that LocalMachine/My store.

#Sanatize Variables Clear-Variable Results -ErrorAction SilentlyContinue Clear-Variable Sites,Bindings,Certificates -ErrorAction SilentlyContinue Clear-Variable WarningCert,CriticalCert,ExpiredCert -ErrorAction SilentlyContinue
#Load Module Try { Import-Module WebAdministration } Catch { Write-Host "Message: failed to load WebAdministration module" Exit 1 }
#Build Exclusion List If ([String]::IsNullOrWhiteSpace($Args) -eq $False) { $Exclusions = $Args }
#Set variables for expiration $WarningDate = (Get-Date).AddDays(30) $CriticalDate = (Get-Date).AddDays(7)
#Retrieve Sites Try{ Switch ([String]::IsNullOrWhiteSpace($Exclusions)) { "TRUE" { $Sites = Get-ChildItem IIS:\Sites\* -ErrorAction Stop Write-Host "Message.ExcludedSites: None" Write-Host "Statistic.ExcludedSites: 0" } "FALSE" { $Sites = Get-ChildItem IIS:\Sites\* -ErrorAction Stop | Where-Object {$_.State -eq "Started" -and $_.Name -notin $Exclusions} Write-Host "Message.ExcludedSites: $($Exclusions -Join ",")" Write-Host "Statistic.ExcludedSites: $(($Exclusions | Measure-Object).count)" } } } Catch { Write-Host "Message: failed to retrieve sites" exit 1 }
#Retrieve Bindings Try{ $Bindings = Get-ChildItem IIS:\SSLBindings -ErrorAction Stop | Where-Object {$Sites.Name -contains $_.Sites.Value} } Catch { Write-Host "Message: failed to retrieve AppPools" exit 1 }
#Retrieve Cert Info Try { $Certificates = Get-ChildItem CERT:LocalMachine/My -ErrorAction Stop | Where-Object {$Bindings.thumbprint -contains $_.Thumbprint} } Catch { Write-Host "Message: failed to retrieve certificates" }
#Total Cert information If ([String]::IsNullOrEmpty($Certificates)) { Write-Host "Statistic.TotalCerts: 0" Write-Message "Message.TotalCerts: Unable to retrieve certificates" Exit 0 } Write-Host "Statistic.TotalCerts: $(($Certificates | Measure-Object).Count)"
#Warning - 30 days $WarningCert = $Certificates | Where-Object {$_.NotAfter -lt $WarningDate} If ([String]::IsNullOrEmpty($WarningCert)) { Write-Host "Statistic.WarningExpiration: 0" Write-Host "Message.WarningExpiration: No certs expiring in 30 days" } Else { Write-Host "Statistic.WarningExpiration: $(($WarningCert | Measure-Object).count)" If (($WarningCert | Measure-Object).Count -gt 0) { Write-Host "Message.WarningExpiration: Certs expiring in 30 days. $($WarningCert.FriendlyName -join ";")" } Else { Write-Host "Message.WarningExpiration: No certs expiring in 30 days" } }
#Critical - 7 days $CriticalCert = $Certificates | Where-Object {$_.NotAfter -lt $CriticalDate} If ([String]::IsNullOrEmpty($CriticalCert)) { Write-Host "Statistic.CriticalExpiration: 0" Write-Host "Message.CriticalExpiration: No certs expiring in 7 days" } Else { Write-Host "Statistic.CriticalExpiration: $(($CriticalCert | Measure-Object).count)" If (($CriticalCert | Measure-Object).Count -gt 0) { Write-Host "Message.CriticalExpiration: Certs expiring in 7 days. $($CriticalCert.FriendlyName -join ";")" } Else { Write-Host "Message.CriticalExpiration: No certs expiring in 7 days" } }
#Expired $ExpiredCert = $Certificates | Where-Object {$_.NotAfter -lt (Get-Date)} If ([String]::IsNullOrEmpty($ExpiredCert)) { Write-Host "Statistic.Expired: 0" Write-Host "Message.Expired: No certs expired" } Else { Write-Host "Statistic.Expired: $(($ExpiredCert | Measure-Object).count)" If (($ExpiredCert | Measure-Object).Count -gt 0) { Write-Host "Message.Expired: Certs expired. $($CriticalCert.FriendlyName -join ";")" } Else { Write-Host "Message.Expired: No certs expired" } }
#Retrieves the earliest expiration date
$Closest = ($Certificates | Select-Object FriendlyName,NotAfter | Sort-Object -property NotAfter)[0]
$ClosestTime = $Closest.NotAfter - (Get-Date)
If ($ClosestTime.Days -ge 0) {
Write-Host "Message.EarliestExpiration: $($Closest.FriendlyName) expires in $($ClosestTime.days) days"
} Else {
Write-Host "Message.EarliestExpiration: $($Closest.FriendlyName) expired $([Math]::Abs($ClosestTime.days)) days ago"
}
Write-Host "Statistic.EarliestExpiration: $($ClosestTime.Days)"
Exit 0

Статья успешно отправлена на почту

Для получения самоподписанного тестового сертификата в системах Windows® 8 и Windows Server® 2012 легче всего воспользоваться Windows PowerShell 3.0.

Установка Windows PowerShell.

Для запуска консоли Windows PowerShell, выполните: Win+R, «PowerShell_ISE.exe», «Выполнить». Запускать консоль необходимо с правами локального администратора.

Как привязать ssl-сертификат в iis powershell

Далее, в окне консоли Windows PowerShell необходимо выполнить командлет «New-SelfSignedCertificate», для этого вводим команду:

New-SelfSignedCertificate -DnsName localhost -CertStoreLocation cert:LocalMachineMy

Данная команда запускает командлет, который производит генерацию самоподписанного сертификата для DNS имени localhost, и помещает его в раздел «Личные» локального хранилища сертификатов, иногда по неустановленным причинам сертификат может быть помещен в другой раздел локального хранилища, например «Промежуточные центры сертификации».

При успешном выполнении командлета в окне консоли появится информация, содержащая слепок сгенерированного сертификата.

Как привязать ssl-сертификат в iis powershell

Как привязать ssl-сертификат в iis powershell

Далее необходимо открыть оснастку «Сертификаты» с правами локального администратора, для этого запустите соответствующий файл «certmgr.msc» и произведите поиск сгенерированного сертификата по его DNS имени «localhost».

Как привязать ssl-сертификат в iis powershell

Далее, найденный сертификат необходимо переместить в раздел «Доверенные корневые центры сертификации\Сертификаты».

Как привязать ssl-сертификат в iis powershell

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

  • Как создать самоподписанный сертификат в Windows
  • Выпуск собственного SSL-сертификата

Below are the steps to configure ssl on IIS using powershell:

1. Create a Self-signed Certificate

Generating a certificate via the self-signed method involves creation of a digital certificate not associated with any certificate authority (CA).

Recommended: Creating Self-Signed SSL Certificate in Powershell

Certificates that are self-signed are typically used for validation purposes or for internal organizational functions which cannot justify the cost or complexity of procuring certificates from a CA.

Below is a detailed explanation of how to create a self-signed certificate using PowerShell:

Step 1: Open PowerShell

Step 2: Invoke New-SelfSignedCertificate Cmdlet

The command New-SelfSignedCertificate will be used to generate self-signed certificates.

$Cert = New-SelfSignedCertificate `
            -dnsName "<Server FQDN>" `
            -CertStoreLocation cert:\LocalMachine\My`
            -KeyLength 2048 `
            -NotAfter (Get-Date).AddYears(1)

Here’s a breakdown of the parameters used:

  • dnsName “<Server FQDN>”: Ensures whether your server is set up by the correct fully qualified domain name (FQDN). Put in place the exact FQDN of your server instead of <Server FQDN>.
  • CertStoreLocation cert:config=MachineKey: Defines the certificate store in which the certificate will be stored as specified by the LocalMachine\My. In this case, it’s a personal certificate store—My—locally on the machine’s certificate store.
  • KeyLength 2048: Indicates the length of the YubiKey pair that should be designed. Here, the 2048-bit key setting is used which is the state-of-the-art suite for most of the current protection schemes.
  • NotAfter (Get-Date).AddYears(1): Allows for restricting the use of the certificate to the issued duration. Here, the certificate is scheduled to lapse in exactly one year and one day from the current date. Adjust expiration date, if needed.

Step 3: Certificate Generation

After you execute the command, PowerShell shall create a self-signed certificate per the supplied parameters. It will place the respective certificate data such as thumbprint, subject, issuer and expiry date.

Step 4: Certificate Installation

Thus, it will be installed in the personal store of a machine certificate locally (My). You can confirm the installation of the certificate by opening the Certificate Manager (certmgr.msc) defining the path to “Personal > Certificates”.

:/>  Обзор мобильных ОС: сравнение 5 лучших мобильных операционных систем

Step 5: Certificate Export (Optional)

Rather than importing it into the Certificate Manager and using it there with its private key, export it as a .pfx file with its private key and use it wherever required.

2. Create an SSL binding (bind ssl certificate IIS powershell)

Step 1: Use New-WebBinding Cmdlet

Establish the new web-ssl binding via the New-WebBinding command. This cmdlet lets you specify the web site or web application, HTTPS protocol, wherein port 443 is commonly used for HTTPS.

New-WebBinding `
            -Name "Default Web Site" `
            -protocol https `
            -port 443

In this example:

  • Name “Default Web Site”: This option indicates the target’s name/Id of the website or web application over which the SSL is to be implemented. In place of the “Default Web Site” name, you should use the title of your website or app.
  • Protocol https: Describe the SSL/TLS handshake and detail the HTTPS protocol the server fetches in our instance.
  • Port 443: Sets a port number for developing HTTPS applications. Traditionally only port 443 is used for SSL and TLS, UDP, as well as TCP communication.

Step 2: Binding Creation

After that, PowerShell will generate an incoming or outgoing SSL connection and bind it to the requested website or web application. Thanks to this binding, secure interaction in HTTPS mode is using the default SSL certificate product of the respective servers.

Step 3: Verify Binding

That the binding of SSL has been properly established can be confirmed by launching “IIS Manager” and moving to the bindings entries for the named website or web app. An HTTPS TLS with port 443 should be mentioned in the binding context.

Step 4: Optional – Assign Certificate

If there is any particular SSL certificate that you want to assign for the binding, you can do so by providing it with PowerShell. It involves getting a certificate back and binding it onto HTTPS.

3. Assign the Certificate to SSL Binding

To assign a certificate to an SSL binding (powershell add ssl certificate to binding) in Internet Information Services (IIS) is a process that is used to relate an SSL certificate to a website, web application’s HTTPS binding.

It is another way by which the server matches the certificate generated when the clients secure connection through HTTPS.

Below is a detailed explanation of how to assign a certificate to an SSL binding using PowerShell (powershell iis binding ssl certificate):

Step 1: Retrieve the SSL Certificate

Retrieve an SSL certificate object preceding that to assign the certificate to the SSL binding.

This is achieved in two ways: through the obtaining of the certificate from the certificate store with the help of PowerShell or by using an existing certificate object.

Step 2: Use New-Item Cmdlet

Use the New-Item command to declare that the certificate should be used by that SSL binding, instead. In this instance, the process focuses on the indication of the location of the SSL project saving in the IIS configuration file.

$Cert | New-Item ` -path IIS:\SslBindings\0.0.0.0!443

In this example:

  • $Cert is the only variable through which you will be able to assign to the SSL binding the SSL certificate object which you will be using.
  • New-Item cmdlet is a command used to create a new item in a web server configuration. The -path parameter specifies the location of the SSL binding, which is IIS:\SslBindings\000.000.000!443.
  • 0.0.0.0.0:443 serves for the HTTPS binding protocol for the highest security. Configure it to your IP address or a port number, whichever is required.

Step 3: Binding Assignment

After that command is run, PowerShell will have vagabonded the specified SSL certificate to the SSL binding. This is as well enough to be able to understand that the server will have the right SSL certificate to the client’s computer which establishes connection over HTTPS to the specified IP address and port.

Step 4: Verify Assignment

You can be sure that the SSL certificate has been successfully deployed to the SSL binding by viewing the SSL bindings configuration in IIS Manager no matter what. Avail SSL certificate applied to the right HTTPS binding and you have already been assigned through PowerShell.

4. Testing the Default Site using HTTPS

The first recommended action is to check the default site using HTTPS for making sure that the SSL binding applies properly and the clients are able to access the website or the application of the web securely.

In order to start, visit a browser on a device linked to the same network as the server that hosts the default site. In the address bar, type the HTTPS URL for the default site, starting with https:// given after the fully qualified domain name(FQDN) of the server.

Upon accessing the site the web browser will make an effort to make the connection secure by using the SSL certificate which we have bound.

It’s important to check that the security warnings or errors are not appearing when the default webpage is loaded and that the padlock icon in the address bar indicates a secure connection.

Likewise, verify the SSL certificate details in the web browser to ensure that the correct certificate is used for the HTTPS connection with the domain. Test it across different devices or browsers as many times as it is necessary to be sure there is the consistency.

Conclusion

CheapSSLWEB is aimed at ensuring the safety of online transactions as well as preventing the misuse of confidential data with our Low-Priced SSL Certificates.

Creating Self-Signed SSL in Powershell

Self-signed certificates are useful for:

  • Testing and development environments where you need HTTPS enabled but do not require trusted certificates.
  • Internal websites, services, and tools where you control the clients.
  • Internet of Things (IoT) devices that require HTTPS but can’t get public certificates.

This guide will walk you through the steps to generate a self-signed SSL certificate using Powershell on Windows. We will also cover how to export the certificate and private key to install on servers like IIS and Apache.

Key Takeaways

  • Self-signed SSL certificates allow you to encrypt traffic to your websites and web services without needing to purchase a certificate from a certificate authority. However, users will see warnings that the certificate is not trusted since it is self-signed.
  • The New-SelfSignedCertificate cmdlet in Powershell can generate self-signed certificates easily. You can specify the subject, DNS names, key usage, extended key usage, and more.
  • Export the self-signed certificate and private key to a PFX file for installation on your web server. Protect the private key file.
  • You can create a self-signed certificate that is valid for an extended period by specifying a far-off “NotAfter” date. However, some browsers may only trust certificates with a shorter validity period.
  • Self-signed certificates provide a quick and easy way to implement HTTPS for internal sites and testing. However, for public production sites, you should purchase an SSL certificate from a trusted certificate authority.
:/>  Как предотвратить установку обновления Windows 10 до версии 1909.

Prerequisites

  • Windows 10 or Windows Server with Powershell 5.1 or later. Any edition, including desktop and server.
  • Administrator access to run Powershell commands.
  • OpenSSL (if exporting certificate and key).

The drawback is that visitors will see certificate warnings as the certificate is not trusted. Public sites should use CA-signed certificates.

Prerequisites Before Installing Self-Signed Certificate in IIS

To create and install a self-signed certificate for a website in IIS, you need:

  • IIS (Internet Information Services) installed on the Windows Server
  • Administrative access rights to the server
  • Access to IIS Manager console

Easy Steps to Create Self-Signed SSL Certificate in PowerShell

  • Create Certificate Object in Powershell
  • Create an Advanced Self-Signed Certificate
  • Export Certificate and Private Key to PFX
  • Install Certificate on Web Server
  • Trust Certificate

Step 1 – Create Certificate Object in Powershell

Powershell provides an easy way to generate self-signed SSL certificates with the New-SelfSignedCertificate cmdlet.

New-SelfSignedCertificate -DnsName "www.example.com" -CertStoreLocation "Cert:\LocalMachine\My"

This will create a self-signed certificate for the site www.example.com and place it in the My certificate store on the local machine.

Let’s break down what’s happening:

  • -DnsName “www.example.com” – Specifies the DNS Subject Alternative Name (SAN). This allows using the cert for that domain.
  • -CertStoreLocation “Cert:\LocalMachine\My” – Puts the generated cert into the My store under Local Machine rather than the default CurrentUser.

You can also provide these parameters:

  • -NotAfter – The expiration date for the cert as a DateTime object.
  • -KeyUsage – The key usage flags like DigitalSignature, KeyEncipherment, etc.
  • -Type – The certificate type is typically SSLServerAuthentication.

This generates a basic cert, but we can provide additional options for a more robust self-signed certificate next.

Step 2 – Create an Advanced Self-Signed Certificate

Specify additional parameters, such as subject, key usage, extended key usage, and more, to create a more complete self-signed certificate suitable for production use.

$today = Get-Date
$after = $today.AddYears(10)
$certificate = New-SelfSignedCertificate -DnsName "www.example.com", "example.com" -CertStoreLocation "Cert:\LocalMachine\My" `
-KeySpec "KeyExchange" -KeyUsage "DigitalSignature," "KeyEncipherment" `
-Type "SSLServerAuthentication" -NotAfter $after `
-Subject "CN=www.example.com, OU=IT, O=My Company Name, L=City, S=State, C=Country" `
-Provider "Microsoft Enhanced RSA and AES Cryptographic Provider" `
-HashAlgorithm "SHA256" -KeyLength 2048

Here’s what each additional parameter does:

  • -DnsName – Adds additional DNS names and alternative names. Allows using the cert for multiple domains/subdomains.
  • -KeySpec “KeyExchange” – Makes the key usable for key exchange, which is required for SSL/TLS.
  • -KeyUsage – Allows the use of certs for digital signatures and key encipherment.
  • -Type “SSLServerAuthentication” – Specifies this is an SSL/TLS server certificate.
  • -NotAfter – Sets expiration 10 years in the future.
  • -Subject – Specifies certificate subject attributes like country, org, etc.
  • -Provider – Sets crypto provider; this one support AES.
  • -HashAlgorithm “SHA256” – Algorthim to hash and sign the certificate.
  • -KeyLength 2048 – Bits in the RSA private key. Higher is more secure.

This creates an advanced certificate with options suitable for production use.

Step 3 – Export Certificate and Private Key to PFX

The self-signed certificate is stored in the local machine personal certificate store. To use it on a web server like IIS or Apache, you need to export the certificate and private key.

The most common format is PFX, which combines the private key and certificate chain into a single encrypted file.

First, copy the cert thumbprint, then export it along with the private key:

$cert = Get-ChildItem -Path "Cert:\LocalMachine\My\" -DnsName "www.example.com"
$thumb = $cert.Thumbprint
Export-PfxCertificate -Cert "Cert:\LocalMachine\My\$thumb" -FilePath "C:\cert\examplecert.pfx" -Password $pwd

This exports the certificate + private key to examplecert.pfx protected with the password stored in $pwd.

Keep this PFX file and password safe! It contains the private key that allows the decryption of all traffic secured with the certificate.

You can now import this PFX file into your web server, such as IIS, Apache, Nginx, etc.

Step 4 – Install Certificate on Web Server

IIS on Windows

  • Open the IIS Manager console.
  • Select your website.
  • In the Actions pane, open Server Certificates.
  • Click Import under the Actions panel on the right.
  • Import the PFX file and enter the password.
  • Select the imported cert under the SSL certificate bindings.

Apache

  • Place the PFX file in a secure folder like /etc/ssl.
  • Convert the PFX to a PKCS12 file using OpenSSL command.
openssl pkcs12 -in examplecert.pfx -out examplecert.pkcs12

Set the SSL certificate in your virtual host config.

SSLCertificateFile "/etc/ssl/examplecert.pkcs12"
SSLCertificateKeyFile "/etc/ssl/examplecert.pkcs12"
SSLCertificateChainFile "/etc/ssl/examplecert.pkcs12"

Restart Apache to apply the new certificate.

The steps vary slightly for other servers, but in general, you import the PFX file and then configure the webserver to use it.

Step 5 – Trust Certificate (Optional)

On Windows, double-click the CER file and install it under Trusted Root Certificate Authorities.

For public sites, use free or low-cost certificates from CAs like Let’s Encrypt instead for full trust.

Troubleshooting Self-Signed Certificates

Here are some common issues when using self-signed certificates and how to troubleshoot them:

Certificate Warnings in Browser

As covered earlier, self-signed certificates will show warnings in browsers because a trusted certificate authority does not sign them. You will see errors like “NET::ERR_CERT_AUTHORITY_INVALID” in Chrome or “SEC_ERROR_UNKNOWN_ISSUER” in Firefox.

This is expected behavior and can only be resolved by installing the self-signed cert as trusted on client machines, as detailed earlier. Alternatively, you can use a certificate from a public CA.

For local/testing purposes, you can bypass the warnings, but you should never do this for public production websites.

Certificate Name Mismatch

If the name in the self-signed cert does not match the site domain, you will see hostname mismatch errors.

Make sure the -DnsName parameter passed to New-SelfSignedCertificate matches your actual site domain(s).

You can also edit it later using the Set-SelfSignedCertificateDNSName cmdlet if needed.

Invalid Key Usage

Using the certificate for purposes other than what is permitted by the -KeyUsage parameter will result in errors.

:/>  Stardock Start10 1.94 (2020) РС | RePack by Tyran скачать торрент файл бесплатно

For example, if you did not include DigitalSignature usage, the cert cannot be used to sign other certificates or messages.

Make sure to specify the appropriate key usages per the examples earlier when creating the certificate.

Expired Certificate

By default, self-signed certificates are only valid for one year. Once they expire, you must regenerate them.

Use the -NotAfter parameter to explicitly specify a future expiration date further out, like 10 years.

Private Key Permission Issues

If there are permission problems accessing the certificate’s private key, you may see errors when trying to start your web server or access sites.

Final Thoughts

Self-signed SSL certificates provide an easy way to implement HTTPS on your websites and services for local testing or internal usage. The New-SelfSignedCertificate cmdlet in Powershell makes generating certificates straightforward. You can create self-signed SSL certificate in Powershell quickly and easily.

When creating production self-signed certificates, be sure to use an adequate key length and appropriate parameters. Export the certificate and private key to a PFX file and install it on your web server. Keep the private key safe!

While convenient for testing and development, avoid using self-signed certificates on public production websites. Purchase trusted SSL certificates signed by certificate authorities for public sites that need to provide a trusted identity and encrypt traffic securely.

FAQs About Self-Signed SSL Certificate in Powershell

Where does Powershell store generated self-signed certificates?

Can I use a self-signed certificate for a public production website?

What is the benefit of converting to PFX when exporting a self-signed cert?

The PFX format allows exporting the private key used to sign the certificate along with the cert itself. This allows installing the self-signed cert on a web server like IIS or Apache. PFX also optionally encrypts the private key with a password for protection.

Do self-signed certificates expire? How can I generate one that lasts longer?

Yes, self-signed certs have a default expiration of one year. Use the -NotAfter parameter to specify a future expiration date, like 10 years. Just be aware some browsers don’t trust certificates with a validity period longer than 2-3 years.

Can I sign my certificates for my internal corporate network?

Yes, you can use your enterprise root certificate authority to issue and sign certificates for services on your corporate network. Just install the root CA cert as trusted on all company devices. This avoids untrusted errors while keeping the PKI internal.

What are the main risks of using a self-signed certificate?

Learn how to bind SSL certificate in IIS Powershell. Our IIS Support team is here to help you with your questions and concerns.

How to Bind SSL certificate in IIS Powershell

Did you know that binding an SSL certificate in IIS with PowerShell involves configuring our web server to use a specific SSL certificate for secure communications with clients?

How to Bind SSL certificate in IIS Powershell

PowerShell is a scripting language that lets us automate different tasks in Windows environments.

Our experts have put together this step-by-step guide on how to bind an SSL certificate in IIS using PowerShell:

  • First, we have to make sure we have an SSL certificate ready. This certificate has to be installed on our server and available in the Windows certificate store.
  • Then, we have to open a PowerShell window with administrative privileges.
  • Next, the WebAdministration module offers cmdlets for managing IIS configurations. We can import it by running this command:
  • Now, we can opt to list the current bindings on our IIS sites to verify the existing configuration:
  • At this point, we have to use the New-WebBinding cmdlet to bind the SSL certificate to a certain site. Here is the syntax:

    New-WebBinding -Name "SiteName" -Protocol "https" -IPAddress "*" -Port 443 -SslFlags 1

    Here, we have to replace “SiteName” with our IIS site name. This command creates a new binding for HTTPS on all IP addresses, using port 443. Additionally, the -SslFlags 1 parameter indicates that the certificate should be used for SSL.

  • Next, we have to find the thumbprint of the SSL certificate we want to bind. We can access it with this command:

    Here, we have to replace “ourCertificateCommonName” with the common name (CN) of our SSL certificate.

  • Now, it is time to assign the SSL certificate to the binding we created:

    $binding = Get-WebBinding -Name "SiteName" -Protocol "https"
    $binding.AddSslCertificate($certThumbprint, "My")

  • Finally, we have to apply the changes by restarting the IIS site.

By this point, we have successfully bound an SSL certificate to an IIS site using PowerShell. This enables secure communication between clients and our web server over HTTPS.

Conclusion

Today, our Support Techs demonstrated how to bind SSL certificate in IIS.

PREVENT YOUR SERVER FROM CRASHING!

Never again lose customers to poor server speed! Let us help you.

Our server experts will monitor & maintain your server 24/7 so that it remains lightning fast and secure.

You may need to ensure Tls1.2 is enabled for SCHANNEL in the registry. Start at this key:

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\Tls12\Client

Create it if it doesn’t already exist and make sure there’s an Enabled dword set to 1. Also, any changes to the SCHANNEL configuration won’t take effect until you restart the server.

Next, check that .Net is configured in the registry to use strong cryptographic protocols:

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\v2.0.50727] "SystemDefaultTlsVersions" = dword:00000001 "SchUseStrongCrypto" = dword:00000001
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\v4.0.30319] "SystemDefaultTlsVersions" = dword:00000001 "SchUseStrongCrypto" = dword:00000001

Then this line in your PowerShell should actually be effective:

[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

But, as I indicated in a comment, you really should do whatever you need to get to permission to upgrade the server.

I should hope so, as there haven’t been any new patches released in several years.

The minimum safe version to be using today is Windows Server 2016 (2012 R2 also reaches end of life in less than a week.) This is the kind of thing worth finding a new job over, as you don’t want to the be one held responsible when (not if) this thing is breached.