"Ubuntu дээр Postgresql гаднаас хандалттай болгож PGAdmin-аар холбогдох"-ны өөр хувилбарууд

Дусал нэвтэрхий толь-с
 
(Хэрэглэгчид 14 дундын хувилбарууд харагдахгүй)
3-р мөр: 3-р мөр:
 
1. Login as postgres user using su / sudo command, enter:
 
1. Login as postgres user using su / sudo command, enter:
  
    su - postgres
+
<pre>
 
+
sudo su
OR
+
su - postgres
 
+
</pre>
Get root permission
 
    sudo su
 
  
  
=== postgresql тохиргоо 1 ===
+
=== postgresql тохиргоо (postgresql.conf) ===
  
 
2. Edit the file:
 
2. Edit the file:
    vim /etc/postgresql/[version_number]/main/postgresql.conf
+
<pre>
 +
vim /etc/postgresql/[version_number]/main/postgresql.conf
 +
</pre>
  
 
Find configuration line that read as follows:
 
Find configuration line that read as follows:
31-р мөр: 31-р мөр:
  
  
=== postgresql тохиргоо 2 ===
+
=== postgresql тохиргоо (pg_hba.conf) ===
  
 
3. Edit the file:
 
3. Edit the file:
 +
 
     vim /etc/postgresql/[version_number]/main/pg_hba.conf
 
     vim /etc/postgresql/[version_number]/main/pg_hba.conf
  
Append the following configuration lines to give access to 10.10.1.0/24 network:
+
#X.X.X.0-255 IP-аас хандах боломжтой тохируулах үед доорх мөрийг нэмж өгнө:
     host ''database user'' 10.10.1.0/24 md5
+
 
 +
<pre>
 +
host    dbName     dbUsername    X.X.X.0/24   md5
 +
</pre>
 +
 
 +
X.X.X.X, dbName, dbUsername тохирох утгуудыг оруулна.
 +
Анхаар: host гэсэн тохиргоо нь plain холболт тул секюрити эрсдэлтэй тул production орчинд hostssl тохируулах хэрэгтэй.
 +
Доорх зааврыг харна уу!!
  
database, user хоёрын оронд "хандах баазын нэр" ба "хэрэглэгчийн нэрийг" оруулна. Бас энэ host гэсэн тохиргоо нь plain холболт тул секюрити эрсдэлтэй тул SSL тохируулах хэрэгтэй.
 
Эхний ээлжинд туршиж холбож үзээд доор байгаа заавраар SSL тохируулаарай. Тэгээд host > hostssl гэж солих хэрэгтэй.
 
  
 
=== postgresql дахин ачааллах ===
 
=== postgresql дахин ачааллах ===
47-р мөр: 53-р мөр:
  
 
     systemctl restart postgresql
 
     systemctl restart postgresql
 +
 +
OR
 +
эсвэл олон хувилбар суусан бол тохируулсан хувилбарын сервисийг:
 +
 +
    systemctl restart postgresql@10-main.service
  
 
=== Firewall дээр порт нээх ===
 
=== Firewall дээр порт нээх ===
63-р мөр: 74-р мөр:
  
  
Аль болох IP зааж өгвөл аюулгүй байдлын хувьд илүү. Мөн түр нээгээд хаах бол:
+
Аль болох IP зааж өгвөл аюулгүй байдлын хувьд илүү.  
 +
 
 +
 
 +
Мөн буцааж хаах тохиолдолд:
  
 
     ufw status numbered
 
     ufw status numbered
92-р мөр: 106-р мөр:
 
=== postgresql SSL тохируулах ===
 
=== postgresql SSL тохируулах ===
  
7. SSL тохируулах  
+
7. SSL тохируулах
  
Эх сурвалж: https://www.percona.com/blog/enabling-and-enforcing-ssl-tls-for-postgresql-connections/
+
==== Generate SSL Certificates for PostgreSQL server ====
  
Enabling SSL in PostgreSQL is very straightforward. In just three steps we can make sure the connections to it are more secure, using in-transit encryption via SSL/TLS:
+
* Login as the postgres user and change the directory to the data directory:
  
1. Make sure we have the server certificate and key files available
+
    sudo su
2. Enable the SSL configuration (ssl = on)
+
    su - postgres
3. Make sure the pg_hba.conf file rules are updated accordingly
+
    cd /var/lib/postgresql/[version_number]/main
  
In this blog post, we are going to go through these steps, and we’ll also see how we can check and validate the connections are indeed using the safer SSL protocol.
+
* Create a Certificate Signing Request (CN=X.X.X.X) CNs are important!!! IP or Domain if there is. -days 3650 шаардлагатай бол өөрчлөөрэй. CompanyName, DepartmentName, example@example.com, X.X.X.X зэрэг утгуудын оронд өөрийн тохирох утгаа оруулна.
What is SSL/TLS?
 
  
SSL (Secure Sockets Layer) is an encryption protocol designed to make network communications between two nodes secure. Without some form of network encryption, any third party that can examine network packets will have access to the data sent between the client and server (in this case, the PostgreSQL data, which means users, passwords, and even SQL statements). TLS (Transport Layer Security) is the more modern definition of it, and even if SSL is deprecated, it is still common to use it for naming purposes. To all intents and purposes, we are using them as aliases in this blog.
+
    umask u=rw,go= && openssl req -days 3650 -new -text -nodes -subj '/C=MN/ST=Ulaanbaatar/L=Ulaanbaatar/O=CompanyName/OU=DepartmentName/emailAddress=example@example.com/CN=X.X.X.X' -keyout server.key -out server.csr
  
The PostgreSQL documentation pages offer us some more insight in this respect. If needed, consult the Secure TCP/IP Connections with SSL and SSL Support entries for more information.
+
* Generate self-signed certificate
Trying to enable SSL without Cert/Key Files
 
  
Let’s now see what happens when we try to enable SSL without having the needed certificate and key files in place:
+
    umask u=rw,go= && openssl req -days 3650 -x509 -text -in server.csr -key server.key -out server.crt
 +
 
 +
* Also make the server certificate to be the root-CA certificate
 +
 
 +
    umask u=rw,go= && cp server.crt root.crt
 +
 
 +
* Remove the now-redundant CSR
 +
 
 +
    rm server.csr
 +
 
 +
Ингээд postgresql.conf файлд доорх тохиргоог хийнэ
  
 
<pre>
 
<pre>
postgres=# alter system set ssl=on;
+
ssl = on
ALTER SYSTEM
+
ssl_cert_file = 'server.crt'
postgres=# select pg_reload_conf();
+
ssl_key_file = 'server.key'
pg_reload_conf
+
ssl_ca_file = 'root.crt'
----------------
 
t
 
(1 row)
 
 
</pre>
 
</pre>
  
 +
Жич: Тест орчинд бол шууд ssl-cert-snakeoil ашиглаж болох ч хугацаа нь бага бас илүү нууцлал багатай байдаг гэнэ.
  
We don’t see any errors, but are we really using SSL? If we check the error log, we’ll indeed see the errors:
+
===== Enforcing SSL/TLS =====
 +
 
 +
pg_hba.conf файлд доорх мөрүүдийг нэмнэ:
  
 
<pre>
 
<pre>
2022-06-23 20:43:54.713 UTC [5284] LOG:  received SIGHUP, reloading configuration files
+
vim pg_hba.conf
2022-06-23 20:43:54.714 UTC [5284] LOG:  parameter "ssl" changed to "on"
 
2022-06-23 20:43:54.715 UTC [5284] LOG:  could not load server certificate file "server.crt": No such file or directory
 
2022-06-23 20:43:54.715 UTC [5284] LOG:  SSL configuration was not reloaded
 
 
</pre>
 
</pre>
  
==== Creating certificates ====
+
X.X.X.0-255 IP-аас хандах боломжтой тохируулах үед доорх мөрүүдийг нэмнэ:
  
So, we first need to create the aforementioned files. If you don’t already have valid certificate and key files, a quick one-liner for this is the following openssl command (it’s not the focus here to delve too much into this part of the process):
 
 
<pre>
 
<pre>
[root@node0 ~]# cd /etc/ssl/private/
+
hostssl    dbName    dbUsername    X.X.X.0/24  md5
[root@node0 data]# openssl req -nodes -new -x509 -keyout server.key -out server.crt -subj '/C=US/L=NYC/O=Woovoo/CN=postgres'
+
hostnossl all            all            X.X.X.0/24    reject
Generating a 2048 bit RSA private key
 
....+++
 
.........................+++
 
writing new private key to 'server.key'
 
-----
 
 
</pre>
 
</pre>
  
We have changed the current working directory to the PostgreSQL data directory. If you are on a Debian-based one, you should store the files in /etc/ssl/certs/ and /etc/ssl/private/ or define/check ssl_cert_file and ssl_key_file PostgreSQL configuration variables, respectively. Also, make sure the postgres user owns them, and they are only readable to it:
+
OR
  
==== Permission тохируулах ====
+
Эсвэл зөвхөн 1 X.X.X.X IP-аас хандахаар тохируулах үед доорх мөрүүдийг нэмнэ:
  
 
<pre>
 
<pre>
[root@node0 data]# chmod 400 server.{crt,key}
+
hostssl    dbName    dbUsername    X.X.X.X/32  md5
[root@node0 data]# chown postgres:postgres server.{crt,key}
+
hostnossl all            all            X.X.X.0/24    reject
[root@node0 data]# ll server.{crt,key}
+
</pre>
-r--------. 1 postgres postgres 1212 Jun 23 20:49 server.crt
 
-r--------. 1 postgres postgres 1704 Jun 23 20:49 server.key
 
</pre.
 
  
==== Enabling SSL/TLS ====
+
'''X.X.X.X, dbName, dbUsername''' тохирох утгуудыг оруулна. Энэ зааврын дээд хэсэгт дурдсан дагуу host гээд plain холболтоор холбох боломжтой төстэй мөрийг өмнө нь оруулсан бол тэр мөрөө хасах хэрэгтэй.
  
Now we can enable SSL and reload the configuration again; this time with no errors shown:
 
  
<pre>
+
==== postgresql дахин ачааллаж тохиргоог идэвхжүүлэх ====
postgres=# alter system set ssl=on;
 
ALTER SYSTEM
 
postgres=# select pg_reload_conf();
 
pg_reload_conf
 
----------------
 
t
 
(1 row)
 
</pre>
 
  
<pre>
+
    systemctl restart postgresql
​​2022-06-23 20:52:05.823 UTC [5284] LOG:  received SIGHUP, reloading configuration files
 
2022-06-23 20:52:05.823 UTC [5284] LOG:  parameter "ssl" changed to "on"
 
</pre>
 
  
So far, we have enabled SSL, but unless we modify the pg_hba.conf file these settings won’t apply to any users (at least not in a forceful manner). This is the first step that can give us a false sense of security, so let’s go ahead and see how to fix it.
+
OR
 +
эсвэл олон хувилбар суусан бол тохируулсан хувилбарын сервисийг:
  
 +
    systemctl restart postgresql@10-main.service
  
==== Enforcing SSL/TLS ====
 
  
As mentioned, the pg_hba.conf file is where we can tune which connections are going to be required to use SSL. We can instruct PostgreSQL to enforce this by using the “hostssl” keyword instead of the plain “host” one. Note that you can see some connections starting to use SSL at this point because the plain “host” keyword will allow for connections that want to use SSL to use it. However, this is not enforcing SSL to be used (i.e.: if the client doesn’t want to use SSL, PostgreSQL will not deny the connection).
+
==== Test the Connection ====
  
Let’s imagine this is the pg_hba.conf file we have been using so far:
+
Ингээд доорх байдлаар холбогдоод үзэхэд SSL connection гэж харагдаж байвал болсон гэсэн үг. X.X.X.X, dbName, dbUsername тохирох утгуудыг оруулна:
  
 
<pre>
 
<pre>
hostssl    database    user   10.10.1.0/24  md5
+
psql "host=X.X.X.X dbname=dbName user=dbUsername"
 +
Password for user dbUsername:
 +
psql (14.5, server 10.15 (Ubuntu 10.15-0ubuntu0.18.04.1))
 +
SSL connection (protocol: TLSv1.3, cipher: TLS_AES_256_GCM_SHA384, bits: 256, compression: off)
 +
Type "help" for help.
 +
 
 +
postgres=#
 
</pre>
 
</pre>
  
Again, this is not enough if we are adamant about really enforcing connections to use SSL. We have to call pg_reload_conf() once more to make sure they are loaded into PostgreSQL itself:
+
Type \Q to exit the PostgreSQL client.
  
 
<pre>
 
<pre>
postgres=# select pg_reload_conf();
+
postgres=# \q
pg_reload_conf
+
root@~#
----------------
 
t
 
(1 row)
 
 
</pre>
 
</pre>
  
At this point, new remote non-SSL connections will be denied:
+
(Харин pgAdmin 4-с холбогдохдоо SSL tab дээр sslmode=required тохируулж өгч болно.)
 +
 
 +
==== Client сертификаттай холболт тохируулах (optional) ====
 +
 
 +
Зөвхөн нууц үг биш давхар хамгаалж секюритиг чангатгах боломжтой.
 +
 
 +
Generate client certificates to be used by clients/connections
 +
Create a Certificate Signing Request (CN=dbUsername гэдэг дээр өгөгдлийн баазын хэрэглэгчийн нэр) -days 3650 шаардлагатай бол өөрчлөөрэй. CompanyName, DepartmentName, example@example.com, dbUsername зэрэг утгуудын оронд өөрийн тохирох утгаа оруулна.
  
<pre>
+
    umask u=rw,go= && openssl req -days 3650 -new -nodes -subj '/C=MN/ST=Ulaanbaatar/L=Ulaanbaatar/O=CompanyName/OU=DepartmentName/emailAddress=example@example.com/CN=dbUsername' -keyout client.key -out client.csr
[root@node1 ~]# psql "host=10.10.1.132 sslmode=disable"
+
 
psql: error: connection to server at "10.10.1.132", port 5432 failed: FATAL:  no pg_hba.conf entry for host "10.10.1.113", user "postgres", database "postgres", no encryption
+
Create a signed certificate for the client using our root certificate
</pre>
 
  
So, can we finally say we are fully secure now? No, not yet! Connections that were already established are not forced to use SSL until they reconnect.
+
    umask u=rw,go= && openssl x509 -days 3650 -req  -CAcreateserial -in client.csr -CA root.crt -CAkey server.key -out client.crt
Checking for connections using SSL/TLS
 
  
We can check for connections using SSL with the following query:
+
Remove the now-redundant CSR
  
<pre>
+
    rm client.csr
postgres=# select pg_ssl.pid, pg_ssl.ssl, pg_ssl.version,
 
          pg_sa.backend_type, pg_sa.usename, pg_sa.client_addr
 
          from pg_stat_ssl pg_ssl
 
          join pg_stat_activity pg_sa
 
            on pg_ssl.pid = pg_sa.pid;
 
pid  | ssl | version |  backend_type  | usename  |  client_addr
 
------+-----+---------+----------------+----------+---------------
 
5547 | f  |        | walsender      | postgres | 10.10.1.113
 
5549 | f  |        | client backend | postgres | 10.10.1.132
 
5556 | f  |        | client backend | postgres | 10.10.1.113
 
(3 rows)
 
</pre>
 
  
In this case, the replication connection (walsender) is not yet using SSL and neither are the two other clients connected, so we need to force a restart if we want them to reconnect. As always, we recommend that you try all these steps in a testing environment first and that when it’s time to do it in production you do them in a properly established maintenance window (no matter how trivial the steps seem to be).
+
Ингээд root.crt, client.crt, client.key файлуудыг хуулж авна. Эдгээр файлуудыг дараа нь холбогдохдоо ашиглана. Эдгээр файлуудаа мэдээж маш сайн нууцлах шаардлагатай ба ил задгай дамжуулж болохгүй.
  
To force the replication connections to use SSL, one can either restart the service in the replica or use pg_terminate_backend (which will send the SIGTERM signal to the process and is safe to use in this context). In this case, we are using pg_terminate_backend in the primary itself, but it can also be used in the replica, provided we are using the correct PID number.
+
X.X.X.0-255 IP-аас хандах боломжтой тохируулах үед доорх байдлаар өөрчилнө:
  
 
<pre>
 
<pre>
postgres=# select pg_terminate_backend(5547);
+
hostssl    dbName    dbUsername    X.X.X.0/24  md5 clientcert=1
pg_terminate_backend
+
hostnossl all            all            X.X.X.0/24    reject
----------------------
 
t
 
 
</pre>
 
</pre>
  
After that, we should see the new replica connection correctly using the SSL/TLS protocol:
+
OR
 +
эсвэл зөвхөн 1 X.X.X.X IP-аас хандахаар тохируулах үед доорх байдлаар өөрчилнө:
  
 
<pre>
 
<pre>
postgres=# select pg_ssl.pid, pg_ssl.ssl, pg_ssl.version,
+
hostssl    dbName    dbUsername    X.X.X.X/32  md5 clientcert=1
          pg_sa.backend_type, pg_sa.usename, pg_sa.client_addr
+
hostnossl all            all            X.X.X.0/24    reject
          from pg_stat_ssl pg_ssl
 
          join pg_stat_activity pg_sa
 
            on pg_ssl.pid = pg_sa.pid;
 
pid  | ssl | version |  backend_type  | usename  |  client_addr
 
------+-----+---------+----------------+----------+---------------
 
5557 | t  | TLSv1.2 | walsender      | postgres | 10.10.1.113
 
5549 | f  |        | client backend | postgres | 10.10.1.132
 
5556 | f  |        | client backend | postgres | 10.10.1.113
 
(3 rows)
 
 
</pre>
 
</pre>
  
PID 5549 is our own connection, so that’s an easy fix:
+
'''clientcert=1''' нэмэгдсэнийг анхаарна уу.
 +
 
 +
 
 +
==== postgresql дахин ачааллаж тохиргоог идэвхжүүлэх ====
  
<pre>
+
    systemctl restart postgresql
postgres=# select pg_backend_pid();
+
 
pg_backend_pid
+
OR
----------------
+
эсвэл олон хувилбар суусан бол тохируулсан хувилбарын сервисийг:
          5549
+
 
(1 row)
+
    systemctl restart postgresql@10-main.service
</pre>
+
 
 +
 
 +
==== Test the Connection with client certificate ====
 +
 
 +
Connect to the database from another machine with the PostgreSQL client installed. Replace dbName, X.X.X.X, dbUsername values with yours.
  
Connection from 5556 would be the remaining one for us to check if we need to enforce SSL on all. On the client-side, we can use \conninfo to check information on our current connection:
+
    psql "host=X.X.X.X dbname=dbName user=dbUsername sslmode=verify-ca sslcert=client.crt sslkey=client.key sslrootcert=root.crt"
  
<pre>
+
You should see the PostgreSQL prompt.
postgres=# \conninfo
 
You are connected to database "postgres" as user "postgres" on host "10.10.1.132" at port "5432".
 
SSL connection (protocol: TLSv1.2, cipher: ECDHE-RSA-AES256-GCM-SHA384, bits: 256, compression: off)
 
</pre>
 
  
Disabling SSL/TLS
+
    Password for user dbUsername:
 +
    psql (14.5, server 10.15 (Ubuntu 10.15-0ubuntu0.18.04.1))
 +
    SSL connection (protocol: TLSv1.3, cipher: TLS_AES_256_GCM_SHA384, bits: 256, compression: off)
 +
    Type "help" for help.
 +
    postgres=#
  
If you want to disable SSL instead, be sure to not lose the client connection after you set ssl=off and make changes to the pg_hba.conf file, otherwise you may be locked out if you don’t have any accounts using “host” only access method, and your only way out is to restart the service. To be safe, first, edit and reload pg_hba.conf file to include entries with “host”, and only then fully disable SSL (ssl=off).
 
Conclusion
 
  
Enabling SSL/TLS for in-transit connection encryption is easy, but there are some pitfalls to be aware of when it comes to enforcing its usage. Simply enabling the configuration for it is not enough for it to be enforced, even if by default some connections may prefer using SSL when it’s available. If you need to ensure that all connections use SSL, edit the pg_hba.conf file accordingly and make sure it’s loaded. Remember that “hostssl” entries are the ones that force this behavior.
+
Type \Q to exit the PostgreSQL client.
  
We can use tcpdump and wireshark to check if connections are indeed being encrypted. But, that’s a topic for another blog…
+
    postgres=# \q
 +
    root@~#
  
 +
Харин pgAdmin 4-с холбогдохдоо SSL tab дээр sslmode=verify-ca ба сертификатын 3 файлаа тохируулж өгнө.
  
  
 
[[Ангилал:Сисадмин]]
 
[[Ангилал:Сисадмин]]

02:12, 2 Арваннэгдүгээр сар 2022-ий байдлаарх одоогийн засвар

Эрх авах

1. Login as postgres user using su / sudo command, enter:

sudo su
su - postgres


postgresql тохиргоо (postgresql.conf)

2. Edit the file:

vim /etc/postgresql/[version_number]/main/postgresql.conf

Find configuration line that read as follows:

   listen_addresses='localhost'

Дээрх мөрийг комэнт аут хийгээд доорхыг оронд нь нэмнэ. Энэ нь бүх хаягнаас хандах боломжийг нээнэ:

   listen_addresses='*'

OR

Болж өгвөл * биш яг хандах IP хаягнуудаа таслалаар зааглан оруулах нь дээр

   listen_addresses = '10.10.1.105,127.0.0.1,localhost'


postgresql тохиргоо (pg_hba.conf)

3. Edit the file:

   vim /etc/postgresql/[version_number]/main/pg_hba.conf
  1. X.X.X.0-255 IP-аас хандах боломжтой тохируулах үед доорх мөрийг нэмж өгнө:
host    dbName     dbUsername    X.X.X.0/24   md5

X.X.X.X, dbName, dbUsername тохирох утгуудыг оруулна. Анхаар: host гэсэн тохиргоо нь plain холболт тул секюрити эрсдэлтэй тул production орчинд hostssl тохируулах хэрэгтэй. Доорх зааврыг харна уу!!


postgresql дахин ачааллах

4. Ингээд postgresql дээрх тохиргоо болно.

   systemctl restart postgresql

OR эсвэл олон хувилбар суусан бол тохируулсан хувилбарын сервисийг:

   systemctl restart postgresql@10-main.service

Firewall дээр порт нээх

5. ufw дээр порт нээж өгөх.

   ufw allow 5432

OR

   ufw allow from 10.10.1.0/24 to any port 5432

OR

   ufw allow from 10.10.1.105 to any port 5432


Аль болох IP зааж өгвөл аюулгүй байдлын хувьд илүү.


Мөн буцааж хаах тохиолдолд:

   ufw status numbered

тушаалаар харж байгаад урд талын дугаараар нь жишээ нь 5 дахь дүрмийг устгах бол:

   ufw delete 5

гэх мэт буцааж арилгана.

Ингээд хандах боломжтой болно.

pgAdmin 4-с хандах

6. pgAdmin 4-с хандахдаа:

Servers баруун дараа Register > Server...

Нээгдсэн цонхонд Name дээр ямар нэгэн нэр оруулаад Connection tab дээр тохиргоо хийнэ:

  • Hostname
  • Port
  • Username
  • Password

утгуудыг тохируулаад холбогдоход холбогдох ёстой.

postgresql SSL тохируулах

7. SSL тохируулах

Generate SSL Certificates for PostgreSQL server

  • Login as the postgres user and change the directory to the data directory:
   sudo su
   su - postgres
   cd /var/lib/postgresql/[version_number]/main
  • Create a Certificate Signing Request (CN=X.X.X.X) CNs are important!!! IP or Domain if there is. -days 3650 шаардлагатай бол өөрчлөөрэй. CompanyName, DepartmentName, example@example.com, X.X.X.X зэрэг утгуудын оронд өөрийн тохирох утгаа оруулна.
   umask u=rw,go= && openssl req -days 3650 -new -text -nodes -subj '/C=MN/ST=Ulaanbaatar/L=Ulaanbaatar/O=CompanyName/OU=DepartmentName/emailAddress=example@example.com/CN=X.X.X.X' -keyout server.key -out server.csr
  • Generate self-signed certificate
   umask u=rw,go= && openssl req -days 3650 -x509 -text -in server.csr -key server.key -out server.crt
  • Also make the server certificate to be the root-CA certificate
   umask u=rw,go= && cp server.crt root.crt
  • Remove the now-redundant CSR
   rm server.csr

Ингээд postgresql.conf файлд доорх тохиргоог хийнэ

ssl = on
ssl_cert_file = 'server.crt'
ssl_key_file = 'server.key'
ssl_ca_file = 'root.crt'

Жич: Тест орчинд бол шууд ssl-cert-snakeoil ашиглаж болох ч хугацаа нь бага бас илүү нууцлал багатай байдаг гэнэ.

Enforcing SSL/TLS

pg_hba.conf файлд доорх мөрүүдийг нэмнэ:

vim pg_hba.conf

X.X.X.0-255 IP-аас хандах боломжтой тохируулах үед доорх мөрүүдийг нэмнэ:

hostssl    dbName     dbUsername    X.X.X.0/24   md5
hostnossl all            all             X.X.X.0/24     reject

OR

Эсвэл зөвхөн 1 X.X.X.X IP-аас хандахаар тохируулах үед доорх мөрүүдийг нэмнэ:

hostssl    dbName     dbUsername    X.X.X.X/32   md5
hostnossl all            all             X.X.X.0/24    reject

X.X.X.X, dbName, dbUsername тохирох утгуудыг оруулна. Энэ зааврын дээд хэсэгт дурдсан дагуу host гээд plain холболтоор холбох боломжтой төстэй мөрийг өмнө нь оруулсан бол тэр мөрөө хасах хэрэгтэй.


postgresql дахин ачааллаж тохиргоог идэвхжүүлэх

   systemctl restart postgresql

OR эсвэл олон хувилбар суусан бол тохируулсан хувилбарын сервисийг:

   systemctl restart postgresql@10-main.service


Test the Connection

Ингээд доорх байдлаар холбогдоод үзэхэд SSL connection гэж харагдаж байвал болсон гэсэн үг. X.X.X.X, dbName, dbUsername тохирох утгуудыг оруулна:

psql "host=X.X.X.X dbname=dbName user=dbUsername"
Password for user dbUsername: 
psql (14.5, server 10.15 (Ubuntu 10.15-0ubuntu0.18.04.1))
SSL connection (protocol: TLSv1.3, cipher: TLS_AES_256_GCM_SHA384, bits: 256, compression: off)
Type "help" for help.

postgres=#

Type \Q to exit the PostgreSQL client.

postgres=# \q
root@~#

(Харин pgAdmin 4-с холбогдохдоо SSL tab дээр sslmode=required тохируулж өгч болно.)

Client сертификаттай холболт тохируулах (optional)

Зөвхөн нууц үг биш давхар хамгаалж секюритиг чангатгах боломжтой.

Generate client certificates to be used by clients/connections Create a Certificate Signing Request (CN=dbUsername гэдэг дээр өгөгдлийн баазын хэрэглэгчийн нэр) -days 3650 шаардлагатай бол өөрчлөөрэй. CompanyName, DepartmentName, example@example.com, dbUsername зэрэг утгуудын оронд өөрийн тохирох утгаа оруулна.

   umask u=rw,go= && openssl req -days 3650 -new -nodes -subj '/C=MN/ST=Ulaanbaatar/L=Ulaanbaatar/O=CompanyName/OU=DepartmentName/emailAddress=example@example.com/CN=dbUsername' -keyout client.key -out client.csr

Create a signed certificate for the client using our root certificate

   umask u=rw,go= && openssl x509 -days 3650 -req  -CAcreateserial -in client.csr -CA root.crt -CAkey server.key -out client.crt

Remove the now-redundant CSR

   rm client.csr

Ингээд root.crt, client.crt, client.key файлуудыг хуулж авна. Эдгээр файлуудыг дараа нь холбогдохдоо ашиглана. Эдгээр файлуудаа мэдээж маш сайн нууцлах шаардлагатай ба ил задгай дамжуулж болохгүй.

X.X.X.0-255 IP-аас хандах боломжтой тохируулах үед доорх байдлаар өөрчилнө:

hostssl    dbName     dbUsername    X.X.X.0/24   md5 clientcert=1
hostnossl all            all             X.X.X.0/24     reject

OR эсвэл зөвхөн 1 X.X.X.X IP-аас хандахаар тохируулах үед доорх байдлаар өөрчилнө:

hostssl    dbName     dbUsername    X.X.X.X/32   md5 clientcert=1
hostnossl all            all             X.X.X.0/24    reject

clientcert=1 нэмэгдсэнийг анхаарна уу.


postgresql дахин ачааллаж тохиргоог идэвхжүүлэх

   systemctl restart postgresql

OR эсвэл олон хувилбар суусан бол тохируулсан хувилбарын сервисийг:

   systemctl restart postgresql@10-main.service


Test the Connection with client certificate

Connect to the database from another machine with the PostgreSQL client installed. Replace dbName, X.X.X.X, dbUsername values with yours.

   psql "host=X.X.X.X dbname=dbName user=dbUsername sslmode=verify-ca sslcert=client.crt sslkey=client.key sslrootcert=root.crt"

You should see the PostgreSQL prompt.

   Password for user dbUsername:
   psql (14.5, server 10.15 (Ubuntu 10.15-0ubuntu0.18.04.1))
   SSL connection (protocol: TLSv1.3, cipher: TLS_AES_256_GCM_SHA384, bits: 256, compression: off)
   Type "help" for help.
   postgres=#


Type \Q to exit the PostgreSQL client.

   postgres=# \q
   root@~#

Харин pgAdmin 4-с холбогдохдоо SSL tab дээр sslmode=verify-ca ба сертификатын 3 файлаа тохируулж өгнө.