SSL Cheat Sheet

From Coolscript
Jump to navigation Jump to search

WCF

Using httptools

Add a Certificate for WCF using httptools

  • Get the MS Support Tools (httpcfg.exe)
  • Add the certificate by adding a website in IIS
  • Get the SSL thumbprint by looking into the certificate property
  • Get the SSL Hash by:
httpcfg query ssl
  • Add the WCF certificate:

ATTENTION If your Hash has spaces then fill them with 0
INFORMATION The application ID is also known as GUID. The Hash is also known as Thumbprint

httpcfg set ssl -i 0.0.0.0:7712 -c MY -g {4dc3e181-e14b-4a21-b022-59fc669b0914}  -h fd9327cd63cb13ef837d4ce67f834b1337b0ecb9

Using netsh

netsh http add sslcert ipport=0.0.0.0:7718 appid="{4dc3e181-e14b-4a21-b022-59fc669b0914}" certhash=76ac8611e0fe7f5ca28dc4aaa25ddc673b742973
netsh http show sslcert

OpenSSL

Create a Private Key

The openssl toolkit is used to generate an RSA Private Key and CSR (Certificate Signing Request).
It can also be used to generate self-signed certificates which can be used for testing purposes
or internal usage.

The first step is to create your RSA Private Key. This key is a 1024 bit RSA key which is encrypted using Triple-DES and stored in a PEM format so that it is readable as ASCII text.

openssl genrsa -des3 -out icinga.server.com.key 1024
Generating RSA private key, 1024 bit long modulus
.........................................................++++++
........++++++
e is 65537 (0x10001)
Enter PEM pass phrase:
Verifying password - Enter PEM pass phrase:

Create a CSR (Certificate Signing Request)

Once the private key is generated a Certificate Signing Request can be generated. The CSR is then used in one of two ways. Ideally, the CSR will be sent to a Certificate Authority, such as Thawte or Verisign who will verify the identity of the requestor and issue a signed certificate. The second option is to self-sign the CSR, which will be demonstrated in the next section.

During the generation of the CSR, you will be prompted for several pieces of information. These are the X.509 attributes of the certificate. One of the prompts will be for "Common Name (e.g., YOUR name)". It is important that this field be filled in with the fully qualified domain name of the server to be protected by SSL. If the website to be protected will be https://icinga.server.com, then enter icinga.server.com at this prompt. The command to generate the CSR is as follows:

openssl req -new -key icinga.server.com.key -out icinga.server.com.csr


Country Name (2 letter code) [GB]:DE
State or Province Name (full name) [Berkshire]:Frankfurt am Main
Locality Name (eg, city) [Newbury]:Frankfurt am Main
Organization Name (eg, company) [My Company Ltd]:SomeCorp
Organizational Unit Name (eg, section) []:MIS
Common Name (eg, your name or your server's hostname) []:icinga.server.com
Email Address []:mis@server.com
Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:

Remove Passphrase from Key

One unfortunate side-effect of the pass-phrased private key is that Apache will ask for the pass-phrase each time the web server is started. Obviously this is not necessarily convenient as someone will not always be around to type in the pass-phrase, such as after a reboot or crash. mod_ssl includes the ability to use an external program in place of the built-in pass-phrase dialog, however, this is not necessarily the most secure option either. It is possible to remove the Triple-DES encryption from the key, thereby no longer needing to type in a pass-phrase. If the private key is no longer encrypted, it is critical that this file only be readable by the root user! If your system is ever compromised and a third party obtains your unencrypted private key, the corresponding certificate will need to be revoked. With that being said, use the following command to remove the pass-phrase from the key:

cp icinga.server.com.key icinga.server.com.key.org
openssl rsa -in icinga.server.com.key.org -out icinga.server.com.key

The newly created icinga.server.com.key file has no more passphrase in it.

Create a Self-Signed Certificate

At this point you will need to generate a self-signed certificate because you either don't
plan on having your certificate signed by a CA, or you wish to test your new SSL implementation
while the CA is signing your certificate. This temporary certificate will generate an error in the
client browser to the effect that the signing certificate authority is unknown and not trusted.

To generate a temporary certificate which is good for 3650 days, issue the following command:

openssl genrsa -out server.com.key 2048                  #Create Priv.Key
cp server.com.key server.com.key.org                     #Copy pric key tmp
openssl rsa -in server.com.key.org -out server.com.key   #Remove paasphrase
openssl req -new -key server.com.key -out server.com.csr #Create CSR
#Self Sign
openssl x509 -req -days 3650 -in server.com.csr -signkey server.com.key -out server.com.crt
Signature ok
subject=/C=DE....
Technology/CN=...
Getting Private key

Alternative way without specifying a domain name

openssl genrsa -out self.key 2048                #Create Priv.Key
cp self.key self.key.org                         #Copy pric key tmp
openssl rsa -in self.key.org -out self.key       #Remove paasphrase
#Self Sign
openssl req -x509 -days 3000 -nodes -newkey rsa:2048 -keyout /etc/ssl/self/self.key -out /etc/ssl/self/self.crt


Apache configuration sample Use the self signed cert for example in your apache configuration, this way the certificate would be used as default

<VirtualHost _default_:443>
 DocumentRoot /var/www/html
 SSLCertificateFile    /etc/ssl/self/self.crt
 SSLCertificateKeyFile /etc/ssl/self/self.key
</VirtualHost>

Installing the Private Key and Certificate

When Apache with mod_ssl is installed, it creates several directories in the Apache config directory. The location of this directory will differ depending on how Apache was compiled.

   cp icinga.server.com.crt /etc.apache/ssl
   cp icinga.server.com.key /etc.apache/ssl

Export private key and certificate from PFX

  • Export private key
openssl pkcs12 -in api-test.server.com.pfx -nocerts -out api-test.server.com.key
  • Remove password
cp api-test.server.com.key api-test.server.com.key.org
openssl rsa -in api-test.server.com.key.org -out api-test.server.com.key
  • Export certificate
openssl pkcs12 -in api-test.server.com.pfx -clcerts -nokeys -out api-test.server.com.crt
  • Verify
openssl rsa -in api-test.server.com.key -check
openssl x509 -in api-test.server.com.crt -text -noout



Howto to convert a existing Apache/SSL Site to a PFX File

  • Choose any Linux workstation to use openssl, export the key:
openssl pkcs12 -inkey privatekey.pem -in certificate.txt -export -out iis-import-file.pfx

Important: If the process fails with "unable to load private key" then please check your pivate key, specialy if you have copied the key trhough the clipboard, watch for special charcters such as UTF etc. at the beginning of the file, also put a start and end quotation into the file like:

-----BEGIN RSA PRIVATE KEY-----
the key follows here ....
-----END RSA PRIVATE KEY-----


Create your own Certification Authority (CA)

Sample of howto create a CA and then sign a wildcard certificate, Note: a backup of the keys has been copied here: vm-ops02://usr/local/www/wiki.intern/download/

Create CA Root Key

openssl genrsa -out RootCA.key 2048

Create CA Certificate

openssl req -x509 -new -nodes -key RootCA.key -sha256 -days 10950 -out RootCA.pem
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [AU]:DE
State or Province Name (full name) [Some-State]:Hessen
Locality Name (eg, city) []:Frankfurt am Main
Organization Name (eg, company) [Internet Widgits Pty Ltd]:SomeCorp - Ansible CA Trust
Organizational Unit Name (eg, section) []:MIS
Common Name (e.g. server FQDN or YOUR name) []:vm-ansible01.server.com
Email Address []:mis@server.com

Convert pem to binary

openssl x509 -outform der -in RootCA.pem -out RootCA.crt

Create a CSR for a wildcard certificate

openssl req -new -key server.com.wildcard.key -out server.com.wildcard.csr
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [AU]:DE
State or Province Name (full name) [Some-State]:Hessen
Locality Name (eg, city) []:Frankfurt am Main
Organization Name (eg, company) [Internet Widgits Pty Ltd]:SomeCorp-Ansible-Certificate
Organizational Unit Name (eg, section) []:MIS
Common Name (e.g. server FQDN or YOUR name) []:*.server.com
Email Address []:mis@server.com

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:omega
An optional company name []:SomeCorp

Adding extended attributes to your certificate

*Create ext.cfg
extendedKeyUsage=serverAuth,clientAuth
subjectAltName=DNS:*.server.com

Sign the wildcard certificate

openssl x509 -req -in server.com.wildcard.csr -CA RootCA.pem -CAkey RootCA.key -CAcreateserial -out server.com.wildcard.crt -days 9125 -sha256 -extfile ext.cfg

Convert to pfx

openssl pkcs12 -inkey server.com.wildcard.key -in server.com.wildcard.crt -export -out server.com.wildcard.pfx

Importing the CA Certificate

Linux
  • On Debian, copy the CA pem file to the certification directory
cp RootCA.pem /usr/local/share/ca-certificates/SomeCorpCA.crt
  • Run
update-ca-certificates
  • To delete:
rm /usr/local/share/ca-certificates/SomeCorpRootCA.crt
  • Run
update-ca-certificates --fresh
  • To control you may look into /etc/ssl/certs/ca-certificates.crt
Windows
  • Copy RootCA.pem to your local disk, rename it to RootCA.crt
  • Method1:
    • Double click the certificate, click install, choose Local Machine, Import to Trusted Root Certification Authorities
  • Method2:
    • Run mmc, add the snap in Certificates, navigate to Trusted Root Certification Authorities, right click Certificates, All Tasks / Import


Important notice Keep in mind that Firefox has it's own CA management




PowerShell

Verify by Thumbprint

PS C:\Users\operator> $thumbprint = "10767ae8c7ff178937b59d78383c1d4af4231b16"
Get-ChildItem -Path cert:\LocalMachine\My -Recurse | Where-Object { $_.Thumbprint -eq $thumbprint } | Select-Object *



PSPath                   : Microsoft.PowerShell.Security\Certificate::LocalMachine\My\10767AE8C7FF178937B59D78383C1D4AF4231B16
PSParentPath             : Microsoft.PowerShell.Security\Certificate::LocalMachine\My
PSChildName              : 10767AE8C7FF178937B59D78383C1D4AF4231B16
PSDrive                  : Cert
PSProvider               : Microsoft.PowerShell.Security\Certificate
PSIsContainer            : False
EnhancedKeyUsageList     : {Server Authentication (1.3.6.1.5.5.7.3.1), Client Authentication (1.3.6.1.5.5.7.3.2)}
DnsNameList              : {admin.agent.server.com, www.admin.agent.server.com}
SendAsTrustedIssuer      : False
EnrollmentPolicyEndPoint : Microsoft.CertificateServices.Commands.EnrollmentEndPointProperty
EnrollmentServerEndPoint : Microsoft.CertificateServices.Commands.EnrollmentEndPointProperty
PolicyId                 : 
Archived                 : False
Extensions               : {System.Security.Cryptography.Oid, System.Security.Cryptography.Oid, System.Security.Cryptography.Oid, 
                           System.Security.Cryptography.Oid...}
FriendlyName             : admin.agent.server.com
IssuerName               : System.Security.Cryptography.X509Certificates.X500DistinguishedName
NotAfter                 : 11.10.2020 01:59:59
NotBefore                : 13.07.2017 02:00:00
HasPrivateKey            : True
PrivateKey               : 
PublicKey                : System.Security.Cryptography.X509Certificates.PublicKey
RawData                  : {48, 130, 5, 92...}
SerialNumber             : 5483E0BCAE4BC69ED3539744DBBD7F62
SubjectName              : System.Security.Cryptography.X509Certificates.X500DistinguishedName
SignatureAlgorithm       : System.Security.Cryptography.Oid
Thumbprint               : 10767AE8C7FF178937B59D78383C1D4AF4231B16
Version                  : 3
Handle                   : 543341245552
Issuer                   : CN=COMODO RSA Domain Validation Secure Server CA, O=COMODO CA Limited, L=Salford, S=Greater Manchester, C=GB
Subject                  : CN=admin.agent.server.com, OU=Domain Control Validated

Self Sign Certificate

Easy command

New-SelfSignedCertificate -Subject "Test" -DnsName "*.costoso100.com" -CertStoreLocation "cert:\LocalMachine\My"

List Certificate Store

dir cert:\LocalMachine\my 
or
dir cert:\localmachine\my | Where-Object { $_.hasPrivateKey }

Export to PFX

$mypwd = ConvertTo-SecureString -String "omega" -Force -AsPlainText
Get-ChildItem -Path cert:\localMachine\my\4E1E4D2DAC9158A6E7F7112C1A6ECB02D0777AF8 | Export-PfxCertificate -FilePath C:\temp\mypfx.pfx -Password $mypwd

HTTP Server Samples

Apache Config

# =================================================
# SSL/TLS settings
# =================================================
<VirtualHost *:443>
 ServerName icinga.intern
 DocumentRoot /usr/local/icinga/share
 SSLEngine on
 SSLOptions +StrictRequire
 <Directory />
   SSLRequireSSL
 </Directory>
 SSLProtocol -all +TLSv1 +SSLv3
 SSLCipherSuite HIGH:MEDIUM:!aNULL:+SHA1:+MD5:+HIGH:+MEDIUM
 SSLCertificateFile /etc/apache2/ssl/icinga.server.com.crt
 SSLCertificateKeyFile /etc/apache2/ssl/icinga.server.com.key
 SSLVerifyClient none
 SSLProxyEngine off
 <IfModule mime.c>
  AddType application/x-x509-ca-cert      .crt
  AddType application/x-pkcs7-crl         .crl
 </IfModule>
 SetEnvIf User-Agent ".*MSIE.*" \
 #nokeepalive ssl-unclean-shutdown \
 #downgrade-1.0 force-response-1.0
</VirtualHost>


NGINX configuration sample with reverse proxy

server {
   listen 443;
   server_name api-test.server.com;
   ssl                  on;
   ssl_certificate /etc/nginx/ssl/api-test.server.com.crt;
   ssl_certificate_key /etc/nginx/ssl/api-test.server.com.key;
   #https://cipherli.st/
   ssl_protocols TLSv1.2;
   ssl_prefer_server_ciphers on;
   ssl_dhparam /etc/nginx/dhparam.pem; # openssl dhparam -out /etc/nginx/dhparam.pem 4096
   ssl_ciphers ECDHE-RSA-AES256-GCM-SHA512:DHE-RSA-AES256-GCM-SHA512:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-SHA384;
   ssl_ecdh_curve secp384r1; # Requires nginx >= 1.1.0
   ssl_session_timeout  10m;
   ssl_session_cache shared:SSL:10m;
   ssl_session_tickets off; # Requires nginx >= 1.5.9
   ssl_stapling on; # Requires nginx >= 1.3.7
   ssl_stapling_verify on; # Requires nginx => 1.3.7
   #resolver $DNS-IP-1 $DNS-IP-2 valid=300s;
   #resolver_timeout 5s;
   add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload";
   add_header X-Frame-Options DENY;
   add_header X-Content-Type-Options nosniff;
   add_header X-XSS-Protection "1; mode=block";
   location / {
       proxy_pass  http://api.server.com:7725/api;
       proxy_set_header Host $host;
       proxy_set_header X-Real-IP $remote_addr;
       proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
       proxy_set_header X-Forwarded-Proto https;
   }
}









Letsencrypt

On Debian install:

apt-get install certbot

Spin up an own webserver

letsencrypt certonly --domain domain.org --renew-by-default  --standalone

Use webroot

Use the follwoing parameters to start signing via www root, this way you can let apache2 running, no need to stop

letsencrypt certonly --webroot --webroot-path /var/www/domain.org/ --renew-by-default --text --agree-tos -d domain.org
  • If the apache site is password protected then overwrite the authentication to the well-down directory:
<Directory "/usr/local/www/hftext.server.com/cgi-bin/.well-known">
 Order allow,deny
 Allow from all
 Require all granted
</Directory>
  • If redirects are configured then check if a trailing slash has been set:
<VirtualHost *:80>
 ServerName hftext.server.com
 ...
 Redirect / https://hftext.server.com/
</VirtualHost>






Create csr using templates

Create a CSR using a template file, then covert for Apache or PFX

  • Gen Priv Key
openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:3072 -out common.server.com.key -aes-256-cbc -pass pass:secretstring


  • Create File: common.server.com.req
[req]
default_bits = 3072
extendedKeyUsage = serverAuth
prompt = no
default_md = sha256
req_extensions = req_ext
distinguished_name = dn

[dn]
C=US
ST = Nevada
L = Las Vegas
O = MGM
OU = Grand
emailAddress = common@server.com
CN = common.server.com

[req_ext]
subjectAltName = @alt_names
[alt_names]
DNS.0 = common.server.com
DNS.1 = www.common.server.com


  • Create CSR
openssl req -batch -new -key common.server.com.key -config common.server.com.req -extensions req_ext -out common.server.com.csr -passin pass:secret
  • View to check
openssl req -noout -text -in common.server.com.csr   
  • Optional Remove Pwd
openssl rsa -in common.server.com.key -out common.server.com.key_v2               
  • Send CSR and wait for the Cert (common.server.com.cer)
  • Convert to PEM
openssl x509 -inform der -in common.server.com.cer -out common.server.com.pem
  • Display information
openssl x509 -in common.server.com.pem -text -noout
  • Konvert to pfx
openssl pkcs12 -export -inkey common.server.com.key -in common.server.com.pem -out common.server.com.pfx -name CERT

Certutil

Use certutil to import a pfx certificate using the Microsoft RSA SChannel Cryptographic Provider

certutil -csp "Microsoft RSA SChannel Cryptographic Provider" -importpfx c:\common.server.com.pfx

Test commands

  • Show certificate
openssl s_client -showcerts -connect fqdn:443
  • Show certificate
openssl s_client -connect fqdn:443 -ssl3
  • Show certificate
gnutls-cli -d 5 fqdn -p 443
  • Show certificate
curl -vvvvv https://api.server.com:443
  • Enumerate cipher suites
nmap -sV --script ssl-enum-ciphers -p 443 server.com
  • Obtain expiry
 cat /etc/ssl/certs/ca-name.pem | openssl x509 -noout -enddate
  • Verify LDAP CA Cert with root cert
openssl s_client -connect fqdn:636 -servername fqdn -showcerts > ca-cert.pem
openssl verify -verbose -CAfile cacert.pem /etc/ssl/certs/ca-name.pem

Links