P0020 Clusters, Databases, Schemas, Files and Processes

Clusters

Clusters are basic building blocks of PostgreSQL.
Users, databases and tablespaces are independent object defined on the cluster level. Each cluster can have multiple databases. Databases are independent, but each of them can access global cluster objects ( Users and Tablespaces ).
Databases are divided into schemas. Inside of the schemas we will find tables, functions, indexes, sequences and other database objects.

sudo pg_createcluster 17 testClusterIn the previous article we saw how to create a cluster. I will create cluster "testCluster".
sudo pg_ctlcluster 17 testCluster startIn the previous article we learned how to start a cluster.

We can check existence and status of our new cluster with:
pg_lsclusters.

sudo pg_ctlcluster 17 testCluster reload
sudo pg_ctlcluster 17 testCluster restart

                                                                                        
After the change of some configuration settings, we have to reload or restart our cluster. We do it like this.
sudo systemctl reload postgresql
sudo systemctl restart postgresql
It is possible to reload or restart all of the clusters at once, by using systemctl reload/restart.

It is possible to rename cluster. Before that, we have to stop the cluster.
sudo pg_ctlcluster 17 testCluster stop
sudo pg_renamecluster 17 testCluster newCluster
Our cluster now has a new name. We will use the new name to delete this cluster.

sudo pg_dropcluster 17 newCluster

Closing Cluster Mode

sudo pg_ctlcluster 17 main stopThis command by default is using "smart" mode. There are 3 modes: smart, fast and immediate.
sudo pg_ctlcluster 17 main stop -m smart
                                                                                          
This is "smart" mode when we want to be explicit. Server will wait for all of the users to end their sessions and to disconnect. New connections are not allowed. If one of the users don't disconnect, then the server will not shut down. This is good for disciplined users.
sudo pg_ctlcluster 17 main stop -m fastFast mode means that we will end all of the transactions, we will rollback all of the changes, and then we will disconnect users. The server will close fast and clean.
sudo pg_ctlcluster 17 main stop -m immediate"Immediately" means that all users will be disconnected immediately. The server will shut down in a "dirty" manner. After restarting, recovery from WAL files will be required. This should only be used in emergencies when the server freezes or other methods do not work.

I will stop 17/main cluster.  
sudo pg_ctlcluster 17 main stop -m fast
Immediatelly after, I will start the cluster again.

sudo pg_ctlcluster 17 main start

Problem With the Postgres User

This time I will make a mistake. I will take the role of the postgres user and I will stop the cluster by using "pg_ctlcluster…stop" command.
sudo -i -u postgres
pg_ctlcluster 17 main stop
This time we will get a message to use systemctl.

Closing the server with "pg_ctlcluster" command, while being "postgres" user, will not corrupt your server. The message just means that we have stopped the cluster behind the back of the systemd. This will force systemd to log that the process has failed. The problem is that postgres user has authority over PostgreSQL, but can not communicate with systemd. Only the root can do both.

Although we deliberately closed the cluster, if we check the status of this process ( as an admin ), we will see that it "failed".
sudo systemctl status postgresql@17-main

sudo systemctl start postgresql@17-main
sudo systemctl stop postgresql@17-main
sudo systemctl status postgresql@17-main
We can start/stop our cluster using canonical approach with systemctl. I will start and stop the cluster and then we will check its status.

Now the systemd is happy and will correctly label our process as inactive (dead).
sudo systemctl start postgresql@17-main #first we have to start it
sudo systemctl reload postgresql@17-main
sudo systemctl restart postgresql@17-main
This also means that it is possible to use systemctl to reload or restart a specific cluster.

postgresql vs postgresql@17-main

Systemd is Linux subsystem used to control services. The name of PostgreSQL service is "postgresql" ( postgresql.service ). This service has a configuration file with the name postgresql@.service that is at the location "/usr/lib/system/system/postgresql@.service". This is the so-called systemd unit file.

sudo systemctl reload postgresql
sudo systemctl reload postgresql@17-main
We can reload all of the PostgreSQL clusters, or we can reload just the specific one.

The relationship between "postgresql" and "postgresql@17-main" is template-instance ( parent-child ). "postgresql" is the base service, which has a systemd unit file template. When we start a new cluster, systemd will create an instance based on that template. That is why "postgresql" service ( parent ) will have "postgresql@17-main" and "postgresql@18-main" children. So, we can control all of the child services together (postgresql ), or we can control them separately ( "postgresql@17-main" and "postgresql@18-main" ).

Problem With the Postgres User Part II

I will show you one more problem that can happen with the "postgres" user.

sudo -i -u postgres
pg_ctlcluster 17 main stop
pg_ctlcluster 17 main start
I will become "postgres" user and I will stop and start 17/main cluster. Notice the messages I am getting.
exit
sudo systemctl stop postgresql@17-main
sudo systemctl start postgresql@17-main

                                                                                
This time I will exit, and I will again be admin. I will stop/start the cluster with systemctl.

I will get this error message: "Job for postgresql@17-amin.service failed because the service did not take the steps required by its unit configuration."

Now we have the real problem. "systemctl" and "pg_ctlcluster" are out of sync. We have to sync them. Do these steps as an admin.

sudo pg_ctlcluster 17 main stop
sudo systemctl stop postgresql@17-main
sudo systemctl reset-failed postgresql@17-main
sudo systemctl start postgresql@17-main
This third step is probably not needed, but do it just anyway. We have solved the problem.

Conclusions

Do not use "initdb" and "pg_ctl" on Ubuntu. We talk about that in the previous article.

Do not control "postgresql" service as a "postgres" user. Work with services is only for the administrator.

Databases

sudo -u postgres psql -p 5432 -d postgresI will login to database postgres as the user postgres.
If we type "\l", we will get the list of all of the databases in that cluster. There are three bult-in databases.

SELECT datname, oid FROM pg_database;
We can read from the system table "pg_database". Inside of it we will find the three builtin databases and their ID-s. We can find those databases in the "base" folder in the data directory. Every newly created database will be placed there.
Command "\conninfo" will list data about the current connection. We can see that we are attached to the database "postgres". Because we are admin we can easily switch to other database "\c template1".

In this way we can jump to other databases, but not to "template0" database.

Postgres Database

"postgres" database is metadata database. Inside of it we store info about users, because users are defined on the cluster level. Extensions save their data into "postgres" database. You should never store user data into this database. This database is just for metadata and administration.

Template Databases

Creation of the new databases is based on duplication of the existing database. We can not duplicate database where someone is connected to it. I will log-in once more as a "postgres" user. I am now logged twice as a "postgres" user, in the separate terminal tabs.

#NEW TAB
sudo -u postgres psql -p 5432 -d postgres  

This query will last for ten seconds. During that time, I will try to create a database in the other tab.
SELECT pg_sleep(10);
Creation of the database will fail, because of the session in the new tab. #OLD TAB
CREATE DATABASE baza TEMPLATE postgres;

Normal way of database creation is to duplicate embedded "template" database. There are two such databases. Database "template0" is the most restricted database. This database can only be used to create new databases and nothing else. This is a "sacred" PostgreSQL database. We can not change it in any way.

Database "template1" is the database that all the new databases will be based on by default. We can modify this database to suit our needs.

I will now create a table inside of the "template1" database.
CREATE TABLE templateTable ( Col1 INT );
I will then jump into "postgres" database and I will create a new database.
\c postgres
CREATE DATABASE baza TEMPLATE template1;
  #"template1" is default template.
When we log into this new database, we will find a table already there.
\c baza
SELECT * FROM templateTable;

How to Use Template Databases?

We can use any other database as a template. I will create another database "baza2" from the "baza" database.
CREATE DATABASE baza2 TEMPLATE baza;
\c baza2
SELECT * FROM templateTable;
We can use any database as a template to create new databases.

SELECT oid, datname, datistemplate FROM pg_database;
In the system table "pg_database" we can see all of the databases. Template databases are labeled with the letter "t" in the column "datistemplate".    

In the start, databases "template1" and "template0" are the same. We changed that by changing "template1". I will show you how you can reset "template1" to its vanilla state. We can not delete template databases, so we have first to remove template=TRUE attribute.

UPDATE pg_database SET datistemplate = FALSE WHERE datname = 'template1';
DROP DATABASE template1;
#we will recreate "template1" database based on the "template0" database.
CREATE DATABASE template1 TEMPLATE template0;
SELECT oid, datname, datistemplate FROM pg_database;


How to Administer Template Databases?

We should never make direct changes to "pg_database" system table. Instead of that we should use ALTER DATABASE statement.

I will jump to "postgres" database. I will make the database "baza2" a template.
\c postgres
ALTER DATABASE baza2 IS_TEMPLATE true;
DROP DATABASE baza2;

The difference is that now we can not delete "baza2", because it is a template. I will remove template property from this database and I will delete it.

ALTER DATABASE baza2 IS_TEMPLATE false;
DROP DATABASE baza2;

Schemas

Schemas are organizational units inside of the database. Every table, view, index must belong to some schema. We have one table in the database "baza".
\c baza       #we jump to that database
\dt        #this will list all of the tables
We can list all of the tables with the "\dt" command. We can see that by default; a table will belong to "public" schema.
Similar to that, we can list all of the available schemas with the "\dn".

SELECT oid, nspname
FROM pg_namespace
ORDER BY nspname;

                                       
Command "\dn" will only show user visible schema. If we want to see all of the schema then we should read from the "pg_namespace" system table.
– information_schema has set of read-only standardized metadata views.
– pg_catalog schema holds system tables.
– pt_toast is used to store very big pieces of data.

It is also possible to observe tables from all of the schemas. We can do that in three ways:

Native PostgreSQL query used to find out about tables is called "pg_tables". This query has less columns and information than the information_schema.tables query.SELECT schemaname, tablename
FROM pg_tables;

                                                      
SELECT table_schema, table_name
FROM information_schema.tables;

                                                            
There is a standard how to read metadata. That standard is based on standardized view. Such views are called "information_schema" and many different database servers have them ( Oracle, Snowflake… ).
Both queries are pulling data from the system table "pg_class". In this table, the column "realnamespace" has ID of the schema and this is connection with the "pg_namespace" table ( 2200 for "public" schema ).SELECT relnamespace, relname
FROM pg_class;

"pg_catalog" Schema

This schema stores important tables that contain database metadata. These are some of those tables and they store metadata about:

pg_class – database tables.pg_attribute – table columns.pg_proc – procedures and functions.pg_type – data types.pg_index – indexes.

Creation of the Custom Schema

I will create new schema.
CREATE SCHEMA myschema;
We can rename our schema.
ALTER SCHEMA myschema RENAME TO newname;
\dn    #read our schemas

CREATE TABLE newname.templateTable ( ColA INT );When we want to create new table inside of this schema, we should provide a schema name.
SELECT Col1 FROM public.templateTable;
SELECT ColA FROM newname.templateTable;
We now have two tables with the same name – "templateTable". They will not clash, because each of them is in the separate schema. We just have to call them by their full qualified names.
SELECT * FROM templateTable;
                                                                                                
If we run a statement like this, which doesn't use a fully qualified names, we will get the table from the "public" schema. There is a system how PostgreSQL resolve these situations, but that is the story we will talk later.

Moving Tables Between Schemas

I want to move both tables in the "public" schema, and to delete "newname" schema. First, I have to rename the table from the "newname" schema.ALTER TABLE newname.templateTable RENAME to tT;
After that, we can change the schema of our table:
ALTER TABLE newName.tT SET SCHEMA public;
                                                                                                
Let's see what tables are now inside of the "public" schema.  

SELECT schemaname, tablename FROM pg_tables WHERE schemaname = 'public';
 
There is no more a table inside of the "newname" schema. We can delete it.
DROP SCHEMA newname;
\dn  tells us that "newname" schema has been deleted.

PostgreSQL File Structure

We will exit from psql with "exit". PostgreSQL binary files are places inside of the "/usr/lib/postgresql" directory.
Inside of it we can see separate folders for the server versions 17 and 18.

Cluster files are placed in the two folders. The first one contains the cluster files, and the second one contains configuration files. I will list here some important files. We will first become a root with "sudo -i". You can check the content of these files on your computer./var/lib/postgresql/18/main # data directory  
/etc/postgresql/18/main  # configuration files

                                                                                             

cat /var/lib/postgresql/18/main/PG_VERSIONThis will return the version number of PostgreSQL. It will be number "18".
cat /var/lib/postgresql/18/main/postmaster.optsIf we start a server with some command line options, those will be written here.
cat /var/lib/postgresql/18/main/postmaster.pidHere we can find process ID, data directory ( where the cluster is ), timestamp when the server started to run ( unix timestamp ), port number, local or internet access.
cat /etc/postgresql/18/main/pg_hba.conf"hba" means host-based authentication. Here we configure authorization and authentication.
cat /etc/postgresql/18/main/pg_ident.confHere we can map Linux user to PostgreSQL user. This mapping must be referenced in the "pg_hba.conf" file to allow local user on local computer to log-in. Can not be used for remote log-in.
cat /etc/postgresql/18/main/postgresql.confThis is file with most of the configuration settings for a cluster.
cat /etc/postgresql/18/main/postgresql.auto.conf
                                                                                                
We can use ALTER SYSTEM command directly from the psql to change some settings. New values will be written here. Settings from here will override settings in the postgres.conf. This file should not be modified manually.

PostgreSQL Processes

In the separate terminal tab, I will log-in into 18/main cluster.
sudo -u postgres psql -p 5432 -d postgres  

In the original terminal tab, I will stop cluster 17.
sudo pg_ctlcluster 17 main stop    
I will run this command. This command will list all of the process that are started by the "postgres" executable.
"-a" means that we will look at processes of all of the users.
"-f" will give us a lot of data.  

ps -C postgres -af

We will get all the important PostgreSQL processes.
– The longest line is our "postgres" daemon.
– Checkpointer is for writing dirty data.
– Background writer – helper to checkpointer.
– WAL writer – writing clean data to disk.
– Autovacuum – some kind of garabage collector.
– Logical replication – used for database replication.

Every logged user will have his own process. One such process is the third process from bellow.

P0010 (Un)installing PostgreSQL on Ubuntu

Ubuntu versus Other Linux Systems

Ubuntu is based on Debian Linux distribution. Debian is distro oriented toward stability and reliability. Often, Debian repository will have PostgreSQL version that is not the newest one. Debian will rather have stable and tested version of PostgreSQL than having the newest features.I am using Linux distro that is based on the older version of Ubuntu ( LTS version, 24 ). In its repository there is only one version of PostgreSQL, and that version is 16. Debian will choose only one version of PostgreSQL and it will integrate it tightly.
  sudo apt list postgresql

It is possible to install newest versions of PostgreSQL on Debian based machines, but the strategy used by people from Debian is to:

choose one PostgreSQL versiontest it with other librariesthey will integrate it tightly into systemthey will manage it centrally

What are PostgreSQL Clusters?

A PostgreSQL cluster is a directory initialized by PostgreSQL that contains multiple databases and is managed by a single server process.

PostgreSQL prepares a directory by setting up everything needed to run a database system, including configuration files, system tables and folders for data. PostgreSQL will later be able to create and manage databases inside of that directory.

All databases inside of this directory are controlled by one "postgres" process. That "postgres" process is our server.

Each cluster is separate independent PostgreSQL server, but Debian has tools to manage several clusters centrally. Debian Linux is unique, because it has one unified system for all PostgreSQL server instances, to manage all of them from a single location.

Debian is optimized for system administration simplicity at scale. That means that:
– PostgreSQL clusters are standardized and registered.
– They are controlled through common tools ( pg_ctlcluster, pg_lsclusters ).
– They are integrated with system services ( like systemd ).

Ubuntu's Way of Installing PostgreSQL

We will now install Postgres 16 from Ubuntu's repository. It is really easy to do it.

sudo apt updatesudo apt upgrade -ysudo apt install postgresqlWe will update our repository and then we will install PostgreSQL.

Apt will install the only available version from available repositories. That is the version 16.
psql --version      #psql command line client is also installed

Default Cluster

When we use command "pg_lsclusters", we will see that we already have default cluster. It is exposed through the default port 5432.

Our "main" cluster is at the location:
/var/lib/postgresql/16/main.
This is the cluster directory, I was talking earlier. All the folders and files inside of this directory are created after PostgreSQL initialized this directory. Here the databases will be, after we create them.

Default User

During installation, PostgreSQL will create a new Linux user with the name "postgres". This user is also administrator of the clusters.
cat /etc/passwd | grep postgres

If we take a look who is the owner of the default cluster directory, it is the user "postgres".
sudo ls -l /var/lib/postgresql/16/main

Linux user "postgres" has no password. It is not possible to log-in into Linux using this user. The only way is to log-in as a Linux OS administrator and then to take the role of this user. After we take the role of this user, we can freely log-in into any database. We haven't created any database, but after the installation PostgreSQL has three embedded databases. Their names are "postgres", "template0" and "template1".

Using the Database

sudo -i -u postgres  #we become user "postgres".
psql -d postgres       #we log-in into the embedded database with the name "postgres".

#prompt 'postgres=#' means that we are inside of the "postgres" database.    
SELECT 3;        –we can run some query.        

postgres=# exit   –we log-out from "postgres" database.
postgres@fffKomp:~$ exit   #we go back being administrator Linux user.

We already learned how to install and use PostgreSQL. There is only one problem. We were working on the old version of PostgreSQL, version 16. We want to learn about the newest PostgreSQL version, version 18. I will now show you how to un-install PostgreSQL. After that we will se how to install the newest version of PostgreSQL on Ubuntu.

How to Uninstall PostgreSQL

When installed on Ubuntu, PostgreSQL will be a service. As we know, any full-blooded service on the Ubuntu is controlled by systemd.
sudo systemctl status postgresql
We can see that "postgresql" is Linux service.
Being a service, PostgreSQL will automatically start after the system reboot. That means, that in order to uninstall the PostgreSQL, we first have to stop this service.
sudo systemctl stop postgresql
We will now delete all of the "postgres*" packages, and we will remove all of the dependencies.
sudo apt purge -y postgresql*  

During the uninstall process, we will confirm that we want all of the directories deleted.
We will try to delete any leftovers so that we are completely wiped.
sudo apt autoremove -y
sudo apt autoclean
sudo pg_dropcluster --stop 16 main
#this will remove cluster if it is still there
Warning! This is for full cleanup. This will delete other clusters too!
sudo rm -rf /var/lib/postgresql/
sudo rm -rf /etc/postgresql/
sudo rm -rf /var/log/postgresql/

sudo rm -rf /var/run/postgresql

We will delete "postgres" Linux user:
sudo deluser postgres
We will refresh systemd.
sudo systemctl daemon-reexec
sudo systemctl daemon-reload
We no more have PostgreSQL on our computer.
psql --version

PGDG Way of PostgreSQL

PostgreSQL Global Development Group ( PGDG ) is the organization behind PostgreSQL. We will now see how to install the latest version of PostgreSQL using PGDG repository. We will install the version 18. First, we will update our Ubuntu system.

sudo apt updatesudo apt upgrade -y
sudo apt install -y wget gnupg2We usually already have these applications, but if we don't have them, we can install them.
– "wget" is used to download files from the internet.
– "gpg2" is used for working with gpg keys.

Installing GPG key

GPG key is a key that Ubuntu will use to verify PostgreSQL packages before installing them.

First, we will create folder /etc/apt/keyrings, if we don't have it. We will use permissions 755 on this folder. Administrator will have full access to this folder, but other users will have read and execute rights. This is necessary because "apt" application will access this GPG key, not only with administrator rights, but also as a special low-privilege user.
sudo mkdir -p /etc/apt/keyrings                #option -p means that we will create parent directories, if they do not exist.
sudo chmod 0755 /etc/apt/keyrings
We will use wget to download GPG key from the internet.
wget -qO - https://www.postgresql.org/media/keys/ACCC4CF8.asc | sudo gpg --dearmor -o /etc/apt/keyrings/postgresql.gpg  

"wget" application will quietly (-q) download gpg key from provided URL. This key will be downloaded in textual ASCII format (.asc). Option (-O) means that this downloaded file will be sent to standard out. After the pipe "|" this file will be sent to gpg application.  

Because we want to save this gpg key in binary format, we will use gpg application to transform (.asc) format into (.gpg) format, by using option "--dearmor". (-o) is for output file. Now our key is stored in "postgresql.gpg" file.

We will also change permissions on this binary ".gpg" file.
sudo chmod 0644 /etc/apt/keyrings/postgresql.gpg

This postgresql.gpg file is a binary file. We can read its content with the command:
gpg --no-default-keyring --keyring /etc/apt/keyrings/postgresql.gpg --fingerprint
--no-default-keyring                                               #This means that we will not read other GPG keys.
--keyring /etc/apt/keyrings/postgresql.gpg     #We will read only this GPG key.
--fingerprint                                                     #Because GPG key is binary file, we will only read its textual presentation, its "fingerprint".                                                                                        #This fingerprint is a long hexadecimal number.

If result of this command is equal to "B97B 0AFC AA1A 47F0 44F2  44A0 7FCC 7D46 ACCC 4CF8", then that means that we have installed the correct key.

Adding a Repository Where PostgreSQL is Stored

We will read the version of our Ubuntu system. It is "noble".
cat /etc/os-release | grep VERSION_CODENAME

Next, in folder "/etc/apt/sources.list.d" we will create a file with the name "pgdg.list".#jump to that folder
cd /etc/apt/sources.list.d 
#create new file, you will be asked to provide password
sudo touch pgdg.list    

Inside of the file we must place this text. This is address to PostgreSQL repo. We will install "main" version of PostgreSQL (not test or alpha).
deb [signed-by=/etc/apt/keyrings/postgresql.gpg] https://apt.postgresql.org/pub/repos/apt noble-pgdg main
We can add this text by running this line in the terminal:
sudo sh -c 'echo "deb [signed-by=/etc/apt/keyrings/postgresql.gpg] https://apt.postgresql.org/pub/repos/apt noble-pgdg main" >> pgdg.list'
Now our file looks like this: 

PostgreSQL installation

We will read content of this new repository and then we will install PostgreSQL. Beside the server, the client "psql" will also be installed.sudo apt updatesudo apt install -y postgresql

By default, apt will install the latest version it can find. It will skip version 16 from the Ubuntu's repository and will install the version 18 from PGDG repository.              
psql --version

We have installed PostgreSQL from PGDG repository. We could assume that now we have our server out of Ubuntu central control, but that is not the case. I will use command "pg_lsclusters" to list available clusters. We will see that Ubuntu already created one cluster. That means that our PostgreSQL installation is under control of the Ubuntu central management system.

pg_lsclusters

Tools like "pg_ctlcluster" and "pg_lsclusters" are used on Debian/Ubuntu systems. On other Linux distributions we use tools "initdb" and  "pg_ctl". It is never smart to use "intdb" and "pgctl" on Ubuntu, but that is exactly what we are going to do! I will show you how to create PostgreSQL cluster without Ubuntu interference.

Manual Creation of a Cluster

We know that PostgreSQL has data directory "/var/lib/postgresql/18/main". We will create another cluster inside of this folder "18".

cd /var/lib/postgresql/18    #we jump to this foldersudo mkdir manualCluster   #we create a folder for our cluster
We will make "postgres" user the owner of this folder.sudo chown postgres:postgres /var/lib/postgresql/18/manualCluster
/usr/lib/postgresql/18/bin/initdbPostgeSQL is installed at this location. There we can find "initdb" program. This utility is used to initialize a PostgreSQL cluster.

sudo -i -u postgres  #we must become postgres user  

Only then can we initialize this folder.
/usr/lib/postgresql/18/bin/initdb -D /var/lib/postgresql/18/manualCluster

It is important that this must be done as a "postgres" user and that this user must be the owner of the folder.

Now we have another cluster.
ls /var/lib/postgresql/18/manualCluster
Command "pg_lsclusters" will not show this new cluster. This one is outside of the control.
If we check the status of the cluster, we will find out that this server is not running. /usr/lib/postgresql/18/bin/pg_ctl -D /var/lib/postgresql/18/manualCluster statuspg_ctl: no server running

Starting of the Manual Cluster

This is how we can start the server.
/usr/lib/postgresql/18/bin/pg_ctl -D /var/lib/postgresql/18/manualCluster -o "-p 5433" start
We must be "postgres" user and we must use
other port than alredy used port 5432.
We can log into this new cluster:
psql -p 5433 -d postgres    #postgres is the name of the built-in database  

Queries:
SELECT current_database();  #postgres

and

SHOW data_directory;   #/var/lib/postgresql/18/manualCluster
, will tell us that we are inside of the new cluster.

I will exit psql. If we check for processes with the command "ps aux | grep 18/bin", we will see that we have two processes. One is for the "main", and the other one is for the "manualCluster" cluster.

I will use stop command to stop this server.  
/usr/lib/postgresql/18/bin/pg_ctl -D /var/lib/postgresql/18/manualCluster stop
I will exit to be admin again (fff@fffKomp:).  

I will delete this manually created cluster, just like any other folder.
sudo rm -rf /var/lib/postgresql/18/manualCluster

Installing Different Version of PostgreSQL

From PGDG repository we can install different versions of a PostgreSQL. If we run
apt search postgresql-   #including dash
, we will get 5.000 rows as on the image to the left. There we can find all the possible versions and packages for PostgreSQL.
sudo apt install postgresql-15 postgresql-17For installation of specific versions of PostgreSQL, we just have to specify their number. It is possible to install several versions of PostgreSQL server at once. I will install only the version 17.
In the "/usr/lib/postgresql" we can see both our servers.
cd /usr/lib/postgresql
ls -alh
Because we already have auto-created cluster, a new cluster will not be created for the version 17.
cd /var/lib/postgresql
ls -alh

Creation of a Cluster in Ubuntu Style

sudo pg_createcluster 17 mainI will use "pg_createcluster" to create one cluster for the version 17.
I will get the familiar message because "pg_createcluster" is just wrapper for "initdb".
We now have two clusters ( pg_lsclusters ), but one of them has not started. Noticed that the version 17 automatically got port number 5434.
pg_lsclusters

I will start this new cluster.
sudo pg_ctlcluster 17 main start
I will log in into this cluster as a "postgres" user.
sudo -i -u postgres
psql -p 5434 postgres  


We can see that we are inside data directory for the cluster "/var/lib/postgresql/17/main" ( for SHOW data_directory; ).

I will exit to administrator prompt by typing "exit" twice.

Auto-start Configuration Files

We have separate configuration files for the version 17 and for the version 18.
cd /etc/postgresql
ls -alh

Configuration files are placed inside of the "/etc/postgresql/18/main" folder.
One of the reasons why we have central control on Debian based systems is to make it easier to have separate versions of PostgreSQL. That is why we have everything double in our case. If we were using "initdb" and "pg_ctl" then we would have to set everything manually, and that would be much harder.
For this section, the important configuration file is "start.conf". Such file exists for each cluster on our system.
cat /etc/postgresql/17/main/start.conf
Inside of this file we can have:
– auto          # cluster will start after the reboot of the computer.
– manual     # cluster must be started manually.
– disabled   # cluster can not be started manually.

This setting is all that we have to change, to control whether the cluster will start automatically after the reboot. In order for something to start after the reboot it has to be a daemon controlled by the systemd. After we start the computer, the systemd will start PostgreSQL process "postgresql.service". This service will start pg_ctlcluster separately for each cluster. For each cluster, it will check if there is "auto" written into start.conf file. If it is, then the clusters will start automatically.

We can check the status of this postgresql.service daemon.
systemctl status postgresql.service

By using systemctl in combination with start/stop commands and enable/disable we can control all of the clusters together.

sudo systemctl stop postgresql.serviceWe will stop all of the clusters.
sudo systemctl disable postgresql.serviceWe can disable the start of all of the clusters after the reboot.
sudo systemctl enable postgresql.serviceWe can enable the start of "auto" clusters after the reboot.
sudo systemctl start postgresql.serviceWe can start all of the "auto" clusters at once.

Testing Auto-Start

After we stop "postgresql" service,
sudo systemctl stop postgresql.service,
all our clusters will stop.
For the cluster 17/main I will change the settging in the "start.conf" file to manual.   After that, I will reboot my computer with the "reboot" command.

After the reboot, only the 18/main cluster will start. This is because we set 17/main cluster to manual so that cluster will not start automatically.

I will now change the "manual" setting to "auto" again, and I will reboot again. Both of our clusters will be active this time.

L0160 Make Your Own Part 4 – PKI

Store Certificate Chains

For convenience we will create certificate chains contained in one file.

Intermediate + CA Certificate

For certificate chain verification it is convenient to store Intermediate and CA certificates in one file, in that order. We will create a new folder for storing this chain. This folder "ipublic" will be inside of the intermediate CA folder "iCA".

cd /home/fff/Desktopmkdir ./iCA/ipubliccat ./iCA/icerts/iCA.crt ./myCA/certs/myCA.crt > ./iCA/ipublic/CA-chain.crt

Now it is easy to verify leaf certificates:  openssl verify -CAfile ./iCA/ipublic/CA-chain.crt ./server/scerts/server.crt
openssl verify -CAfile ./iCA/ipublic/CA-chain.crt ./person/pcerts/pera.crt
openssl verify -CAfile ./iCA/ipublic/CA-chain.crt ./client/ccerts/client.crt

Server, Person, Client Certificate Chain

During TLS handshake, the server will send the whole certificate chain except the root certificate. It is convenient to store these chains in "cert" folders. Each leaf subject has such folder ( "scerts, pcerts, ccerts" ).cat ./server/scerts/server.crt ./iCA/icerts/iCA.crt > ./server/scerts/server-chain.crt
cat ./person/pcerts/pera.crt   ./iCA/icerts/iCA.crt > ./person/pcerts/person-chain.crt
cat ./server/scerts/server.crt ./iCA/icerts/iCA.crt > ./client/ccerts/client-chain.crt                                                                                                             

Revoking the Leaf Certificate

The leaf certificates are revoked by using Intermediate CA. In the "iindex.txt" file we currently have three issued certificates.
We issued certificates for the server, person and web client.

I will revoke person's certificate.

cd iCA
openssl ca -config iCA.cnf -revoke ../person/pcerts/pera.crt -crl_reason keyCompromise

In the "iindex.txt" file, person's certificate is labeled with "R".

We will create new CRL file. We will place it into "icrl" folder.openssl ca -config iCA.cnf -gencrl -out ./icrl/iCA.crl
We can read from this CRL file. Inside of it we will see that the certificate with the serial number 5011 is revoked.
openssl crl -in ./icrl/iCA.crl -noout -text  

# scp ./icrl/iCA.crl webserver:/var/www/html/iCA.crlCRL file must be copied to web server.

Verify CRL

There are two ways to verify the certificate revocation. We can check only the leaf certificate revocation status, or we can check both leaf and intermediate certificate revocation status.

Only the Leaf Level

First, we will verify CRL file itself.openssl crl -in ./icrl/iCA.crl -CAfile ./icerts/iCA.crt -noout -verify #verifyOK

We can verify that person's certificate is revoked. We will geta a message "error ../person/pcerts/pera.crt: verification failed".
openssl verify -CAfile ../myCA/certs/myCA.crt -untrusted ./icerts/iCA.crt -CRLfile ./icrl/iCA.crl -crl_check ../person/pcerts/pera.crt

Both Intermediate and Leaf Level

First, we will create a CRL bundle.cat ./icrl/iCA.crl ../myCA/crl/myCA.crl  > ../all.crl

We will use CRL bundle to verify person's certificate against both Intermediate and Root CRL file.
openssl verify -CAfile ../myCA/certs/myCA.crt -untrusted ./icerts/iCA.crt -CRLfile ../all.crl -crl_check_all ../person/pcerts/pera.crt   #failed

OCSP for Leaf Certificates

OCSP responses must be signed by the intermediate CA. For OCSP we must create a directory system, just like we have created for server, person and web client. This directory system will be inside of the "/iCA/iOCSP" folder.mkdir iocsp
cd iocsp
                        
mkdir oprivate
mkdir ocsr
mkdir ocerts
touch iocsp.cnf
                           

Inside of the configuration file we will place these sections.[req]
default_md          = sha256 prompt              = no
distinguished_name  = ocsp_dn req_extensions      = ocsp_req_ext  
                                                
[ocsp_dn]
C  = RS
O  = iCA organization
CN = Intermediate OCSP Responder
                                                 
[ocsp_req_ext]
keyUsage = critical, digitalSignature
extendedKeyUsage = critical, OCSPSigning
                                                            

Private Key and Certificate for OCSP

I will create a private key for OCSP.openssl genpkey -algorithm ed25519 -out ./oprivate/iocsp.key
Using the key, I will create CSR file.  openssl req -new -config iocsp.cnf -key ./oprivate/iocsp.key -out ./ocsr/iocsp.csr
openssl req -in ./ocsr/iocsp.csr -noout -text -verify

Inside of the "iCA.cnf" configuration file, we already have extensions for the OCSP responder. We will use these extensions to create a certificate.

Before signing the certificate we will jump to "iCA" root folder.
cd .. 
[v3_ocsp_responder]
basicConstraints       = critical,CA:false
keyUsage               = critical,digitalSignature
extendedKeyUsage       = critical,OCSPSigning
subjectKeyIdentifier   = hash
authorityKeyIdentifier = keyid:always,issuer
noCheck                = ignored

openssl ca -config iCA.cnf -extensions v3_ocsp_responder -in ./iocsp/ocsr/iocsp.csr -out ./iocsp/ocerts/iocsp.crt -days 30 -notext

A new line will appear in "iindex.txt".

We can verify purpose of this certificate.
openssl verify -CAfile ./ipublic/CA-chain.crt -purpose ocsphelper ./iocsp/ocerts/iocsp.crt

OpenSSL OCSP Command

OpenSSL can create a simple OCSP responder. This responder is not suitable for production. It should be only use for demonstration and testing. We will use OCSP command to show how OCSP works.

In the "iCA" configuration file, we can find that address for the OCSP service is "http://ocsp.example.com:7000". Our educational OCSP responder will not use this address, but will use a localhost.[issuer_info]
caIssuers;URI.0 = http://ica.example.com/ica.crt
OCSP;URI.0      = http://ocsp.example.com:7000

I will start the responder on the port 7000. Responses from this responder will be valid for one day. This responder will read from the "iindex.txt" file to see which certificates are valid and which are revoked.
openssl ocsp -index iindex.txt -port 7000 -CA ./icerts/iCA.crt -rsigner ./iocsp/ocerts/iocsp.crt -rkey ./iocsp/oprivate/iocsp.key -ndays 1 -text

Testing a Valid Certificate

First, we will test a valid certificate. We will open another terminal tab and there we will change working folder to  "/home/fff/Desktop/iCA".

cd /home/fff/Desktop/iCA
This will be test to see if the "server" certificate is valid.
openssl ocsp  -issuer ./icerts/iCA.crt -cert ../server/scerts/server.crt -url http://127.0.0.1:7000 -CAfile ../myCA/certs/myCA.crt -verify_other ./icerts/iCA.crt
This is the response that we will get. "This update" is the time when response was created.

Testing an Invalid Certificate

We know that we revoked the Person's certificate. We will use that certificate to test OCSP service.
openssl ocsp  -issuer ./icerts/iCA.crt -cert ../person/pcerts/pera.crt -url http://127.0.0.1:7000 -CAfile ../myCA/certs/myCA.crt -verify_other ./icerts/iCA.crt
For this certificate we will see that the certificate has been revoked.

The possible answers for OCSP service are "good, revoked, unknown".

Mutual TLS With the Web Client

We can use "s_server" and "s_client" to show how mutual TLS verification works. Mutual TLS means that both sides have their own key and certificate. With mutual TLS both sides can be verified. I will start "s_server" in the new tab. My working directory is "iCA".

I will start "s_server". I will use port 8443.
openssl s_server -accept 8443 -cert ../server/scerts/server.crt -key ../server/sprivate/server.key -cert_chain ./ipublic/CA-chain.crt -Verify 1 -CAfile ../myCA/certs/myCA.crt -verify_return_error -www
We will get interactive prompt.

"-Verify 1" option means that we are allowing only one intermediate CA. Root CA "myCA.crt" is trusted, and below it there can be only one intermediate certificate in the chain "CA-chain.crt".Option "-www" means that "s_server" will run like a simple web server.

I will go back to original tab. We will connect with "s_client" to our server.
openssl s_client -connect localhost:8443 -cert ../client/ccerts/client.crt -key ../client/cprivate/client.key -cert_chain ./ipublic/CA-chain.crt -CAfile ../myCA/certs/myCA.crt -verify_return_error -showcerts

This is interactive prompt on the side of the client. Here we can enter this GET request:
GET / HTTP/1.0

As a response we will get a long text. That text is HTML page containing TLS connection information.    

Exporting PKCS#12 Key

We can export web client certificate to PKCS#12 format which is convenient for Android and Windows clients. It will go to "cp12" folder.

openssl pkcs12 -export -name "Friendly Name of Certificate" -inkey ../client/cprivate/client.key -in ../client/ccerts/client.crt -certfile ./ipublic/CA-chain.crt -out ../client/cp12/client.p12    # enter password two times
openssl pkcs12 -in ../client/cp12/client.p12 -info -noout

L0150 Make Your Own Part 3 – Leaf Certificates

We will create a leaf certificate for our server.

Server Certificate Configuration

Creation of a Directory System and Configuration File

I will use letter "s" as a prefix to label server directories. I will not apply permissions, because this is just demonstration.

cd /home/fff/DesktopThis is our working directory. 
mkdir serverThis will be our root folder. I will jump to it "cd server".chmod 700 server
mkdir sprivateIn this folder we will save server private key.chmod 700 private
chmod 600 private/*
mkdir scsrFolder for the CSR request.chmod 755 csr
chmod 644 csr/*
mkdir scertsWe will place certificate in this directory.chmod 755 certs
chmod 644 certs/*
mkdir sp12Here we will save certificate and key as PKCS#12 container.chmod 755 sp12
chmod 644 sp12/*
touch server.cnfConfiguration file.chmod 644 server.cnf

Server Configuration File

We will paste this text into our configuration file.

[req]
prompt              = no
default_md          = sha256
distinguished_name  = server_dn
req_extensions      = server_req_ext
This time we don't have "ca" section.
[server_dn]
countryName             = RS
stateOrProvinceName     = Serbia
localityName            = Belgrade
organizationName        = Server organization
organizationalUnitName  = Server unit
commonName              = server01.example.com
Distinguish name of our server. Per the intermediate CA policy, we must supply "commonName".
[server_req_ext]
subjectAltName          = @server_alt_names
All other extensions are defined inside of the intermediate CA configuration file.
[server_alt_names]
DNS.1 = server01.example.com
DNS.2 = server02.example.com
IP.1  = 192.168.1.50
We will use the certificate to sign several domains.

Creation of a Private Key and Certificate

We will create the new private key.openssl genpkey -algorithm ed25519 -out sprivate/server.key

We should never encrypt this file. The server will have to access this key so I will leave it unencrypted.

We will create CSR request.openssl req -new -config server.cnf -key sprivate/server.key -out scsr/server.csr
We can read this CSR and verify it, in the same time.  
openssl req -in scsr/server.csr -noout -text -verify
SAN is the only extension.

We will copy CSR to intermediate CA directory.
cp scsr/server.csr ../iCA/icsr/server.csr  

We will jump to intermediate CA folder. From there we can sign the CSR.
cd /home/fff/Desktop/iCA  

We can now create certificate. We will confirm signing. We will write to the "index.txt" that belongs to intermediate CA.
openssl ca -config iCA.cnf -extfile iCA.cnf -extensions v3_server -in icsr/server.csr -out ../server/scerts/server.crt

We can read from our certificate.  
openssl x509 -in ../server/scerts/server.crt -noout -text

Inside of it we will find all of the extensions from the iCA.cnf file, but we will not find SAN extension. We have to fix this problem!

How to Include SAN extension?

Our extensions are currently inside of the intermediate ca "iCA.cnf" configuration file, while SAN extension is inside of the leaf "server.cnf" configuration file. The "ca" command will only accept extensions from one configuration file. We have somehow to consolidate these 2 files.

The solution is to use "include" command. We must go back to "iCA.cnf" file, and there we must include SAN extension.

At the top of this configuration file, we will place include command:
.include ../server/server.cnf

In the section "v3_server", of "iCA.cnf" file, I will add SAN extension.
[v3_server]
basicConstraints      = critical,CA:false
keyUsage              = critical,digitalSignature
extendedKeyUsage      = serverAuth
subjectKeyIdentifier  = hash
authorityKeyIdentifier= keyid:always,issuer
authorityInfoAccess   = @issuer_info
crlDistributionPoints = @crl_info
subjectAltName        = @server_alt_names

Now, I will again try to create correct certificate. We can verify certificate by reading from it.
openssl ca -config iCA.cnf -extfile iCA.cnf -extensions v3_server -in icsr/server.csr -out ../server/scerts/server.crt

openssl x509 -in ../server/scerts/server.crt -noout -text  
This time we will have all the extensions, including SAN.

Verifying the Certificate

We can verify the certificate.

openssl verify -CAfile icerts/iCA.crt ../server/scerts/server.crt
We can not verify it by using only intermediate CA certificate. We need the whole chain.
openssl verify -CAfile ../myCA/certs/myCA.crt -untrusted icerts/iCA.crt ../server/scerts/server.crt
                                                                                                                                                                                                         

We can also join both CA certificates into one file. Intermediate CA certificate must be first. We are starting from the bottom of a hierarchy.  
cat icerts/iCA.crt ../myCA/certs/myCA.crt > /home/fff/Desktop/all.crt
cat /home/fff/Desktop/all.crt


Now we have both certificates in one file.

We can verify the server certificate with the certificate chain file.
openssl verify -CAfile /home/fff/Desktop/all.crt ../server/scerts/server.crt
../server/scerts/server.crt: OK

We can verify purpose and hostname of a certificate as a separate property.

openssl verify -purpose sslserver -CAfile /home/fff/Desktop/all.crt ../server/scerts/server.crt../server/scerts/server.crt: OK
openssl verify -verify_hostname server01.example.com -CAfile /home/fff/Desktop/all.crt ../server/scerts/server.crt../server/scerts/server.crt: OK

Person Certificate Configuration

Creation of a Directory System and Configuration File for a Person

cd /home/fff/DesktopThis is our working directory. 
mkdir personThis will be our root folder. I will jump to it "cd person".chmod 700 person
mkdir pprivateIn this folder we will save server private key.chmod 700 pprivate
chmod 600 pprivate/*
mkdir pcsrFolder for the CSR request.chmod 755 pcsr chmod 644 pcsr/*
mkdir pcertsWe will place certificate in this directory.chmod 755 pcerts chmod 644 pcerts/*
mkdir pp12Here we will save certificate and key as PKCS#12 container.chmod 755 pp12 chmod 644 pp12/*
touch person.cnfConfiguration file.chmod 644 person.cnf

Person's Configuration File

This will be the text in the configuration file.

[req]
prompt              = no
default_md          = sha256
distinguished_name  = person_dn
req_extensions      = person_req_ext
We don't need "ca" section, only "req".
[person_dn]
countryName             = RS
stateOrProvinceName     = Serbia
localityName            = Belgrade
organizationName        = Users
organizationalUnitName  = Person
commonName              = Pera Peric
Distinguish name of person. Per the intermediate CA policy, we must supply "commonName".
[person_req_ext]
subjectAltName          = @person_alt_names
All other extensions are defined inside of the intermediate CA configuration file.
[person_alt_names]
email.1                 = pera@example.com
We will use the certificate to verify ownership of a mail address.

Person's Private Key and a CRS File

First, we will create a private key.openssl genpkey -algorithm ed25519 -out pprivate/pera.key

We'll use key to create CSR file.openssl req -new -config person.cnf -key pprivate/pera.key -out pcsr/pera.csr
We will verify CSR file.  
openssl req -in pcsr/pera.csr -noout -text -verify
We must copy CSR file to iCA folder.cp pcsr/pera.csr ../iCA/icsr/pera.csr

Person's Certificate

In order to include SAN extension in the certificate, we must include person configuration file in the "iCA" configuration file.  

At the top of the "iCA" configuration file we will add this line.
.include ../person/person.cnf  

In the "usr_cert" section, of the "iCA" file, we will add SAN extension.
[usr_cert]
basicConstraints      = critical,CA:false
keyUsage              = critical,digitalSignature
extendedKeyUsage      = emailProtection,clientAuth
authorityInfoAccess   = @issuer_info
crlDistributionPoints = @crl_info
subjectAltName        = @person_alt_names

We will jump to "iCA" folder before signing the certificate, "cd ../iCA".
openssl ca -config iCA.cnf -extfile iCA.cnf -extensions usr_cert -in icsr/pera.csr -out ../person/pcerts/pera.crt

We can list the purpose of the "pera.crt" certificate.

openssl x509 -in ../person/pcerts/pera.crt -noout -purpose

As a result, we will get a list of the purposes for which we can use this certificate.

Person's Certificate Verification

We can now verify the certificate.

openssl verify -CAfile ../myCA/certs/myCA.crt -untrusted icerts/iCA.crt ../person/pcerts/pera.crt../person/pcerts/pera.crt:OK
openssl verify -purpose sslclient -CAfile ../myCA/certs/myCA.crt -untrusted icerts/iCA.crt ../person/pcerts/pera.crt../person/pcerts/pera.crt:OK
openssl verify -verify_email pera@example.com -CAfile ../myCA/certs/myCA.crt -untrusted icerts/iCA.crt ../person/pcerts/pera.crt../person/pcerts/pera.crt:OK

Web Client Certificate Configuration

Web Client Files and Folders

Configuration for a web client is almost the same as for the Person, so I will just run through the settings.

cd /home/fff/Desktop
mkdir client #cd client
mkdir cprivate
mkdir ccsr
mkdir ccerts
mkdir cp12
touch client.cnf
chmod 700 client
chmod 700 cprivate      
chmod 600 cprivate/*
chmod 755 ccsr
chmod 644 ccsr/*
chmod 755 ccerts
chmod 644 ccerts/*
chmod 755 cp12
chmod 644 cp12/*
chmod 644 client.cnf
[req]
prompt = no
default_md = sha256
distinguished_name = client_dn  

[client_dn]
countryName = RS
stateOrProvinceName = Serbia
localityName = Belgrade
organizationName = Users
organizationalUnitName = Web Clients
commonName = Web Client
We have only changed
the names of folders,
and distinguished name.

Web client doesn't have
SAN extension. Other client
extensions are inside of the
"iCA" configuration file.

Creation of Key and Certificate for the Web Client

 We will create a private key for a web client.openssl genpkey -algorithm ed25519 -out cprivate/client.key
With the key we will create and verify CSR file.openssl req -new -config client.cnf -key cprivate/client.key -out ccsr/client.csr
openssl req -in ccsr/client.csr -noout -text -verify
We will copy CSR file, and we will jump to iCA folder.cp ccsr/client.csr ../iCA/icsr/client.csr
cd ../iCA

We can now create a certificate.
openssl ca -config iCA.cnf -extfile iCA.cnf -extensions client_cert -in icsr/client.csr -out ../client/ccerts/client.crt

We can verify this certificate too. We can verify certificate chain, and we can verify its purpose.
openssl verify -CAfile ../myCA/certs/myCA.crt -untrusted icerts/iCA.crt ../client/ccerts/client.crt                                        # OK
openssl verify -purpose sslclient -CAfile ../myCA/certs/myCA.crt -untrusted icerts/iCA.crt ../client/ccerts/client.crt   # OK

L0140 Make Your Own Part 2 – Intermediate CA

Creating Intermediate CA

Intermediate CA is almost the same as the root CA. We will follow the same steps; there will some small differences. I will use the name "iCA".

Intermediate CA File System

Everything needed for "iCA" must be placed into one file system. At the top we will have "iCA" folder, other files/folders are inside of the "iCA" folder.

iprivateThis is a folder where we will store the "iCA" private key.
inewcertsEvery certificate signed by the "iCA" will be stored here. Names of the files will be certificate serial numbers. This folder is used by OpenSSL to keep track of issued certificates, revocations, and duplicates.
iindex.txtThis is file that stores a list of all of the issued certificates.
V 280101120000Z 1000 unknown /CN=server1    # valid
E 280101120000Z 1001 unknown /CN=server2    # expired
R 270501120000Z 1002 unknown /CN=oldserver  # revoked
iserial.txtThis file will store the serial number for a new certificate. If that number is "X", the next certificate will be given serial number "X", and OpenSSL will update this text file to store the next serial number, which would be "X+1".
icertsThis directory is optional. Here we can place any certificate, and we can give meaningful names to those files. We can store here "iCA" certificate, and we can organize certificate chains for deployment.
icsrConvinient folder where we can place intermediate CA CSR's.
icrlThis is folder where we keep our CRL list.
icrlnumber.txtThis file is similar to "serial". It holds the number for the next version of CRL list.
iCA.cnfThis is configuration file used by the "iCA".

As we can see, everything is the same as for the root CA. I will use prefix "i" to differentiate root CA and intermediate CA files.

Permissions should be the same as for the "myCA" directories and files. I will not repeat those settings here.

Creation of the File System

cd /home/fff/Desktop
                                          
This is our current directory. 
mkdir iCAWe will make root folder. We will jump to that folder.cd iCA
mkdir iprivateThis empty folder is for a private key. 
mkdir inewcertsIssued certificates will be stored here. 
touch iindex.txtHere we will register newly issued certificates. 
touch iserial.txtInside of this file we will write initial hexadecimal serial number 5010.echo 5010 > iserial.txt #even number of digits
mkdir icertsThis folder is optional. 
mkdir icsrHere we will place CSRs for leaf certificates. 
mkdir icrlEmpty folder for CRL files.                                                                                                 
touch icrlnumber.txtWe will set initial hexadecimal serial number for CRLs, in this file.echo 5010 > icrlnumber.txt #even number of digits

Creation of the iCA Configuration File

[ca]
default_ca = CA_default
"[ca]" is one of the main sections. We will immediately refer to specialized section "[ca_default]".
[CA_default]
private_key       = ./iprivate/iCA.key
new_certs_dir     = ./inewcerts

database          = ./iindex.txt
serial            = ./iserial.txt
certs             = ./icerts
certificate       = ./icerts/iCA.crt
crl_dir           = ./icrl
crl               = ./icrl/iCA.crl
crlnumber         = ./icrlnumber.txt
default_days      = 365
default_crl_days  = 30
default_md        = sha256
copy_extensions   = none
crl_extensions    = crl_ext
x509_extensions   = v3_server
policy            = policy_leaf_certificate
unique_subject    = no
Not much is changed here.

Every folder/file has an "i" prefix. Length of the certificate is 365 days. That is shorter than 730 days for CA certificate.

Option "x509_extensions" refer to section with default extensions that this intermediate CA will use when signing a leaf certificate.    
[policy_leaf_certificate]
countryName             = optional
stateOrProvinceName     = optional
localityName            = optional
organizationName        = optional
organizationalUnitName  = optional
commonName              = supplied
Distinguish name in leaf CSRs must match the same values in this configuration file. If they do not match then this intermediate CA can not sign that CSR.
– match – they must match perfectly.
– supplied – value doesn't have to match, but CSR should provide some value.
– optional – whatever. There is no restriction.
[req]
default_md          = sha256
prompt              = no
distinguished_name  = intermediate_ca_dn
These settings are used for intermediate CA certificate. We will not provide any extensions for this certificate. Extensions, for intermediate CA, will be determined by the CA configuration file.
[intermediate_ca_dn]
countryName             = RS
stateOrProvinceName     = Serbia
localityName            = Belgrade
organizationName        = iCA organization
organizationalUnitName  = iCA unit
commonName              = Intermediate CA
These values will be used as intermediate CA distinguish name.
[v3_server]
basicConstraints      = critical,CA:false
keyUsage              = critical,digitalSignature
extendedKeyUsage      = serverAuth
subjectKeyIdentifier  = hash
authorityKeyIdentifier= keyid:always,issuer
authorityInfoAccess   = @issuer_info
crlDistributionPoints = @crl_info
These are extensions that will be used when we sign some server certificate. These are the default extensions that will be used if we don't provide "-extensions" command line option.

For clients and users we will have to specify their extensions with the "-extensions" command line option.

[client_cert]                                                   
basicConstraints       = critical,CA:false
keyUsage               = critical,digitalSignature
extendedKeyUsage       = clientAuth
subjectKeyIdentifier   = hash
authorityKeyIdentifier = keyed:always,issuer
authorityInfoAccess    = @issuer_info
crlDistributionPoints  = @crl_info
These are certificate extensions that are specific for client certificates.

[usr_cert]
basicConstraints      = critical,CA:false
keyUsage              = critical,digitalSignature
extendedKeyUsage      = emailProtection,clientAuth
authorityInfoAccess   = @issuer_info
crlDistributionPoints = @crl_info
These are certificate extensions that are specific for user certificates.
[issuer_info]
caIssuers;URI.0 = http://ica.example.com/ica.crt
OCSP;URI.0      = http://ocsp.example.com:7000
This is web address of from which we can download intermediate CA certificate and web address of the OCSP service.
[crl_info]
URI.0           = http://ica.example.com/iCA.crl  

[crl_ext]
authorityKeyIdentifier = keyid:always
Here are location and extensions of the CRL file.
[v3_ocsp_responder]
basicConstraints       = critical,CA:false
keyUsage               = critical,digitalSignature
extendedKeyUsage       = critical,OCSPSigning
subjectKeyIdentifier   = hash
authorityKeyIdentifier = keyid:always,issuer
noCheck                = ignored
For signing OCSP responds, we will use these extensions.

We will talk about OCSP responder later. For now, you should know that OCSP responder is a separate entity, placed on the internet facing server, that has its own private key and certificate. This OCSP responder certificate can not be verified with the same OCSP service, because that would create a circular dependency. That is the meaning behind extension "noCheck".

We will create configuration file "touch iCA.cnf", and we will copy the text from above into that file.

Creating Private Key and Certificate for Intermediate CA

We will create private key for intermediate CA.openssl genpkey -algorithm ed25519 -out iprivate/iCA.key
We can read from this key.  
openssl pkey -in iprivate/iCA.key -text -noout

Next step is to create CSR file for intermediate CA.openssl req -new -config iCA.cnf -key iprivate/iCA.key -out icsr/iCA.csr
We can read and verify this CSR in one step.  
openssl req -in icsr/iCA.csr -noout -text -verify  

Creation of the Intermediate CA Certificate

For CA to sign our CSR request, we must first copy that request. We are copying it into "myCA" folder.  
cp icsr/iCA.csr ../myCA/csr/iCA.csr
I will jump to "myCA" folder.

cd ../myCA

openssl ca -config myCA.cnf -extensions v3_intermediate_ca -in csr/iCA.csr -out ../iCA/icerts/iCA.crt

                                                                                                                                                                                                                  
We are now ready to sign intermediate CA certificate. We will use "ca" command.

We have a problem. In the DN section, organization name is different between CSR file and CA configuration file according to policy. We have to correct.
I will correct intermediate CA configuration file, and I will again generate CSR file.

cd ../iCA
openssl req -new -config iCA.cnf -key iprivate/iCA.key -out icsr/iCA.csr

cp icsr/iCA.csr ../myCA/csr/iCA.csr

cd ../myCA
openssl ca -config myCA.cnf -extensions v3_intermediate_ca -in csr/iCA.csr -out ../iCA/icerts/iCA.crt


                                                                                                                                                                                                        
I will sign CSR file again. This time I will be asked to sign the certificate. I will confirm that.
We will be asked to update "index.txt" file. When using "ca" command everything will be updated.

Verifying Changes

We can read from our certificate.
cd ../iCA
openssl x509 -in icerts/iCA.crt -noout -text  

We can see that extensions are taken from the "myCA" configuration file.

We can also notice that "authorityKeyIdentifier" doesn't include issuer data. It seems that this version of OpenSSL doesn't do that.
We can verify our intermediate CA certificate. We are using CA certificate to verify intermediate CA certificate.
openssl verify -CAfile ../myCA/certs/myCA.crt icerts/iCA.crt

This time we will check whether intermediate CA certificate is revoked or not. For that we will use "myCA.crl" file.
openssl verify -CAfile ../myCA/certs/myCA.crt  -CRLfile ../myCA/crl/myCA.crl -crl_check icerts/iCA.crt

Certificate is not revoked.

Problem is that we want to check all CRL files in the chain. I will create an empty CRL file for "iCA".
openssl ca -config iCA.cnf -gencrl -out icrl/iCA.crl

We now have two CRL files. One is for "myCA" and the other for "iCA". We can provide only one file in the option "-CRLfile". Solution is to concatenate these two files into one.  
cat ../myCA/crl/myCA.crl icrl/iCA.crl > /home/fff/Desktop/all.crl
cat /home/fff/Desktop/all.crl
I will use this concatenated file to verify intermediate CA certificate.
openssl verify -CAfile ../myCA/certs/myCA.crt -CRLfile /home/fff/Desktop/all.crl -crl_check icerts/iCA.crt

Other Changes

This is the first time we created certificate using "ca" command. Many files will change. They will change in the "myCA" folder.

We will have a new entry in the "index.txt" file. Because we used "ca" command to create a certificate, we now have one valid entry.

The number in the file "serial.txt" is increased to 2731. That number will be used for the next signed certificate.

Two new files appeared. They are both "old" files used for backup.
"serial.txt.old" holds old serial number 2730.
The file "index.txt.attr.old" is a copy that still has a value "unique_subject = no".