How to make and use a self-signed certificate

In computer encryption and security, we often encounter self-signed security certificates.

Because self-signed certificates are simpler to issue than commercial certificates, they cost less (except for the electricity bill) and are easy to update. Therefore, it is particularly common in the development field and even some minority scenarios, such as TLS authentication in K8S/MySQL cluster, Intranet services of some large groups and companies, website security certificates, management background of enterprise router equipment, and “security access client” used to manage enterprise employees.

This article discusses how to quickly generate certificates and how to install and deploy them in different environments.

Writing in the front

It is often said that using self-signed certificates is insecure and can lead to man-in-the-middle attacks. For a self-signed certificate is needed here “name”, if you make the generated certificate is safekeeping (i.e., no leakage and secondary use), and add it to your limited equipment (for private use, teams use) certificate trust list, the clear your device access address (not involving the DNS attack), you are not in the middle attack.

For example, when you encounter similar to the following scenario, not necessarily will have unsafe, could only administrator forgot to replace outdated certificate, or after you generate its own certificate, use a table without trust certificates of equipment for a visit, but also may be no administrator want to public issuance of the certificate, do you want to be a private web site:

Most of the time we see insecure certificates as a result of application misconfiguration, DNS address-based attacks, certificate expiration, or even the fact that we have not configured the certificate trust whitelist correctly.

Once we generate the certificate correctly, after storing the certificate properly, and after whitelisting the limited device, there is little difference between the use of our certificate and that of the commercial certificate (except for the inability to use OCSP and EV certificates with some extra work).

So let’s talk about how to generate certificates quickly.

Use the command line script to generate a self-signed certificate

The most common and common approach is to install and configure a system with an OpenSSL environment and then use the command line to execute commands like the following:

openssl req -x509 -newkey rsa:2048 -keyout ssl/${fileName}.key -out ssl/${fileName}.crt -days 3600 -nodes ...
Copy the code

If you choose not to use a configuration file here, refer to the OpenSSL documentation with a bunch of parameters, or a bunch of options that need to be entered interactively, and hope there are no errors in each step, such as the following:

enerating a RSA private key . . . + + + +... ++++ writing new private key to 'example.key' ----- 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]:CN State or Province Name (full name) [Some-State]:XX Locality Name (eg, city) []:XXXX Organization Name (eg, company) [Internet Widgits Pty Ltd]:Example, Inc Organizational Unit Name (eg, section) []:IT Common Name (e.g. server FQDN or YOUR name) []:example.com Email Address []:[email protected]Copy the code

In contrast, it is slightly easier to generate a certificate with a configuration like the following:

#! /bin/sh OUTPUT_FILENAME="lab.com" printf "[req] prompt = no default_bits = 4096 default_md = sha256 encrypt_key = no string_mask = utf8only distinguished_name = cert_distinguished_name req_extensions = req_x509v3_extensions x509_extensions = req_x509v3_extensions [ cert_distinguished_name ] C = CN ST = BJ L = BJ O = HomeLab OU = HomeLab CN = lab.com [req_x509v3_extensions] basicConstraints = critical,CA:true subjectKeyIdentifier = hash keyUsage = critical,digitalSignature,keyCertSign,cRLSign #,keyEncipherment extendedKeyUsage = critical,serverAuth #, clientAuth subjectAltName = @alt_names [alt_names] DNS.1 = lab.com DNS.2 = *.lab.com DNS.3 = *.page.lab.com ">ssl/${OUTPUT_FILENAME}.conf openssl req -x509 -newkey rsa:2048 -keyout ssl/$OUTPUT_FILENAME.key -out ssl/$OUTPUT_FILENAME.crt -days 3600 -nodes -config ssl/${OUTPUT_FILENAME}.confCopy the code

A similar script, which I mentioned in the Traefik sample script: github.com/soulteary/t… .

Is there an easier solution? Especially if you are constantly modifying DNS and want to use script automation to sign certificates?

Quick Certificate Generation

I wrote a script and wrapped it in a container to make it possible to generate certificates using a very simple command line and to simplify the need to install OpenSSL dependencies locally “out of the box.” Related code I have open source, project address: github.com/soulteary/c…

For example, if you want to generate a slightly more complex site certificate, simply execute the following command:

docker run --rm -it -e CERT_DNS="domain.com; *.domain.com; *.a.domain.com" -v `pwd`/certs:/ssl soulteary/certs-makerCopy the code

After execution you should see a log similar to the following:

User Input: { CERT_DNS: 'domain.com; *.domain.com; *.a.domain.com' } Generating a RSA private key . . + + + + +... +++++ writing new private key to 'ssl/domain.com.key' -----Copy the code

And be able to see our generated certificate file in the SSL directory.

For other uses, such as generating a hybrid certificate with multiple domain names or generating a single certificate, just adjust the value of the CERT_DNS parameter. If you want to further customize the certificate details mentioned above, such as the country and province where the certificate is issued, you can refer to how the open source project repository is used and add additional parameters, which will not be described here.

Generated using Docker-compose

If you want to save your commands as code in the repository, you can also consider writing a compose file:

version: '2' services: certs-maker: image: soulteary/certs-maker environment: - CERT_DNS=a.com; b.com; c.com; *.d.com; volumes: - ./certs:/sslCopy the code

Save the above content as docker-compose. Yml, then execute docker-compose up and you will see the generated certificate file in the certs directory.

Use certificate

Once the certificate is generated, let’s talk about how to use it.

Import certificates on various systems

You can refer to the following documents to import a certificate. The process is simple: boot the certificate and restart the application that needs the certificate.

  • Apple documentation: Certificate description file for trusting manual installation in iOS and iPadOS
  • VMware document: Import the internal CA certificate to a Windows host
  • SSL document: Generate certificate signing request (CSR) in macOS keystring access
  • Qunhui documents: Use self-signed certificates

Trust self-signed certificates in Java applications

If you use a Java application to access a self-signed website, the application will reject the connection due to a certificate error.

It’s not that complicated, just do a little extra work, add the certificate to the keystore, and restart the Java application:

sudo keytool -import -alias charles -file /Path-To-Certs/key.crt -keystore $JAVA_HOME/jre/lib/security/cacerts -storepass changeit
Copy the code

This operation in the case of certificate expired, equally effective, and there is an article has described earlier, use Docker and Traefik v2 structures, Confluence was 7.3.

Trust certificates in Debian/Ubuntu/Alpine systems

For Debian/Ubuntu systems, the trust certificate is quite simple, just copy the certificate to the “to install directory” and run the certificate update command:

cp *.crt /usr/local/share/ca-certificates/
update-ca-certificates
Copy the code

The same goes for Alpine, considering how often we use it in container scenarios, so here’s a full Dockerfile example:

FROM alpine

RUN apk update && apk add ca-certificates && rm -rf /var/cache/apk/*

ADD ./ssl/*.crt /usr/local/share/ca-certificates/

RUN update-ca-certificates --fresh
Copy the code

Set up the Web service used with the certificate installation

If you want to install a certificate on a client (especially a mobile phone), you will encounter problems transferring files across systems. To facilitate distribution and installation, here you can start a Web service for shared certificate installation using Nginx.

Building a common service

We can use the ngx_HTTP_sub_module and ** ngx_HTTP_autoindex_module modules of Nginx to build a service that automatically enumerates the certificate directory:

server { listen 80; server_name localhost; location = /favicon.ico { empty_gif; } location / { root /public; autoindex on; sub_filter '<h1>Index of /</h1>' '<h1>Get Certs</h1>'; sub_filter_once on; }}Copy the code

After saving the above as default.conf, create a configuration file called docker-comemage.yml:

Version: '2' Services: nginx: Image: Nginx :1.19.6 -Alpine Ports: -80800:80 Volumes: - ./default.conf:/etc/nginx/templates/default.conf.template:ro - ./public:/public:roCopy the code

Docker-compose up: docker-compose up: docker-compose up: docker-compose up: docker-compose up: docker-compose up: docker-compose up: docker-compose up: docker-compose up

Simpler configuration

In the above pattern, we split the configuration and service choreography files into two files. Considering the simplicity of this Nginx configuration, is there any way to simplify it?

The answer is yes. By tweaking the command, we can write both the creation of the Nginx configuration and the service startup into the docker-comemage.yml choreographer:

Version: '2' services: nginx: image: nginx:1.19.6-alpine Ports: -8080 :80 Volumes: -./public:/public:ro Command: > /bin/sh -c " echo \"daemon off; \" >> /etc/nginx/nginx.conf; echo \"server { listen 80; server_name localhost; location = /favicon.ico { empty_gif; } location / { root /public; autoindex on; sub_filter '<h1>Index of /</h1>' '<h1>Get Certs</h1>'; sub_filter_once on; } }\" > /etc/nginx/conf.d/default.conf; nginx; "Copy the code

The last

Recently, I started with three lightning data cables. It is almost the New Year. Maybe I can toss about the development of lightning data cable network.

–EOF


I now have a small toss group, which gathered some like to toss small partners.

In the case of no advertisement, we will talk about software, HomeLab and some programming problems together, and also share some technical salon information in the group from time to time.

Like to toss small partners welcome to scan code to add friends. (Please indicate the source and purpose, enter the group with real name, otherwise it will not pass the audit)

All this stuff about getting into groups


This article is published under a SIGNATURE 4.0 International (CC BY 4.0) license. Signature 4.0 International (CC BY 4.0)

Author: Su Yang

Creation time: 02, 2021 6 statistical word count: 6822 words reading time: 14 minutes to read this article links: soulteary.com/2021/02/06/…