SlideShare uma empresa Scribd logo
1 de 30
Baixar para ler offline
Juliano Atanazio
PostgreSQL: How to Store Passwords SafelyPostgreSQL: How to Store Passwords Safely
2/30
About me
Juliano Atanazio
● Graduated in Computer Science for Business Management (Informática para Gestão de
Negócios), FATEC Zona Sul, São Paulo – SP;
● PostgreSQL DBA;
● Linux admin;
● Instructor (PostgreSQL);
● LPIC-1, LPIC-2 Certified;
● Linux user since 2000;
● Free Software enthusiast;
● Favorite technologies: PostgreSQL, Linux, Python, Shell Script, FreeBSD, etc...;
● Headbanger :) m/
3/30
Plain Text Passwords
● Store passwords (in plain text) of application users in database
is not a good practice;
● The DBA doesn’t need and shouldn’t know the users passwords;
● If your database is invaded, the attacker will have access to user
passwords;
● The unencrypted password should never be stored in the
database.
4/30
Hashing and Salting
Hashing and salting is a technique to store passwords securely:
1. Generate a random string (salt) with a desired algorithm (e. g.
blowfish based);
2. This salt and the plain text password are used to generate the
hash password through hashing process;
3. Hash password is stored in the database;
The password must be encrypted in an irreversible way, that you
can not decrypt it (theoretically).
5/30
pgcrypto
pgcrypto is a extension that provides cryptographic functions for
PostgreSQL.
https://www.postgresql.org/docs/current/static/pgcrypto.html
6/30
pgcrypto
gen_salt and crypt Functions
They are specifically designed for hashing passwords. crypt()
does the hashing and gen_salt() prepares algorithm
parameters for it.
● gen_salt(): Generates a new random salt string for use in
crypt(). The salt string also tells crypt() which algorithm to
use.
● crypt(): It generate hash password through passing the
password (in plain text) and salt as parameters.
7/30
Salting and Hashing: Practice
First, you need to enable the pgcrypto extension in your database.
pgcrypto is a additional supplied module (a contrib module).
Enable the pgcrypto extension:
> CREATE EXTENSION pgcrypto;
8/30
Salting and Hashing: Practice
Password Creation
9/30
Salting and Hashing: Practice
Test; generate a salt string:
salt_string
-------------------------------
$2a$06$YmO7UZZZxkTWZfT8s7b/GO
> SELECT gen_salt('bf') AS salt_string;
blowfish algorithm
10/30
Salting and Hashing: Practice
Test; generate the password hash with the previous salt string:
pw_hash
--------------------------------------------------------------
$2a$06$YmO7UZZZxkTWZfT8s7b/GOlO0rZpMhU674srD/dbSyplwO/clTZzi
> SELECT
crypt('mypass', '$2a$06$YmO7UZZZxkTWZfT8s7b/GO')
AS pw_hash;
11/30
Salting and Hashing: Practice
Test; comparison with crypt function and previous hash string:
simple_auth_test
------------------
t
> SELECT
crypt('mypass',
'$2a$06$YmO7UZZZxkTWZfT8s7b/GOlO0rZpMhU674srD/dbSyplwO/clTZzi')
=
'$2a$06$YmO7UZZZxkTWZfT8s7b/GOlO0rZpMhU674srD/dbSyplwO/clTZzi'
AS simple_auth_test;
12/30
Salting and Hashing: Practice
Create the table:
> CREATE TABLE tb_user(
username varchar(50) PRIMARY KEY, -- natural primary key
password VARCHAR(72) NOT NULL
);
13/30
Salting and Hashing: Practice
Using CTE* to INSERT new user with password creation:
* CTE = Common Table Expressions
https://www.postgresql.org/docs/current/static/queries-with.html
> WITH x AS (
SELECT
'foo'::text AS user,
'123'::text AS pw,
gen_salt('bf')::text AS salt
)
INSERT INTO tb_user (username, password)
SELECT
x.user,
crypt(x.pw, x.salt) -- password hash
FROM x;
14/30
Salting and Hashing: Practice
Enable expanded display automatically (psql):
Querying username and password in the table:
username | password
----------+--------------------------------------------------------------
foo | $2a$06$RqHcf7F.nUGLkQF1fOea.OLAU0gyz/liF3dO58JWTB0oyVirzUdgK
> x auto
> SELECT username, password FROM tb_user;
15/30
Salting and Hashing: Practice
Password Verification
16/30
Salting and Hashing: Practice
User authentication test with correct password:
acessed
---------
t
True value (boolean) returned.
> SELECT
crypt('123', password) = password
AS acessed
FROM tb_user
WHERE username = 'foo';
Plain text (password) provided by user
17/30
Salting and Hashing: Practice
User authentication test with wrong password:
acessed
---------
f
False value (boolean) returned.
> SELECT
crypt('1234', password) = password
AS acessed
FROM tb_user
WHERE username = 'foo';
18/30
Application Test: The Code (Python)
Continue
#!/usr/bin/env python3
# _*_ encoding: utf-8 _*_
from argparse import ArgumentParser
from getpass import getpass
from os import system
from psycopg2 import connect
from psycopg2 import Error
from sys import exit
19/30
Application Test: The Code (Python)
Continue
# Argument parser
parser = ArgumentParser()
# Argument help strings
help_d = 'Database'
help_H = 'Hostname or IP address'
help_p = 'Port'
help_u = 'Username'
help_w = 'With password prompt'
20/30
Application Test: The Code (Python)
Continue
# Arguments creation
parser.add_argument('-d', '--database', type=str, help=help_d, action='store',
metavar='dbname', dest='dbname', default='postgres')
parser.add_argument('-H', '--host', type=str, help=help_H, action='store',
metavar='dbserver', dest='host', default=None)
parser.add_argument('-p', '--port', type=int, help=help_p, action='store',
metavar='port_number', dest='port', default=5432)
parser.add_argument('-u', '--user', type=str, help=help_u, action='store',
metavar='username', dest='user', default='postgres')
parser.add_argument('-w', '--with-pass', help=help_w, action='store_true',
dest='password')
# Parsed arguments
args = parser.parse_args()
21/30
Application Test: The Code (Python)
Continue
# Test if password prompt is required
if args.password:
args.password = getpass('Database user password: ')
else:
args.password = None
# Connection string variable (initially as a list)
conn_str = []
# Take all provided paramaters and make the connection string
for k, v in vars(args).items():
if v:
str_tmp = "{} = '{}'".format(k, v)
conn_str.append(str_tmp)
conn_str = ' '.join(conn_str)
22/30
Application Test: The Code (Python)
Continue
# SQL string for PREPARE command
sql_prepare = """
PREPARE q_user (text, text) AS
SELECT
crypt($2, password) = password
FROM tb_user
WHERE username = $1;
"""
# SQL string for EXECUTE command
sql_execute = "EXECUTE q_user('{}', '{}');"
# When occur authentication error...
def user_pw_error(connection):
print('nError: Invalid user and password combination!')
connection.close()
exit(1)
23/30
Application Test: The Code (Python)
Continue
try:
# Connection
conn = connect(conn_str)
# Cursor creation to execute SQL commands
cursor = conn.cursor()
# Execute the SQL string in database
cursor.execute(sql_prepare)
# Clear Screen
system('clear')
# Get user and password of the application
app_user = input('nApplication user: ')
app_user_pw = getpass('Application user password: ')
# Execute the SQL string in database
cursor.execute(sql_execute.format(app_user, app_user_pw))
24/30
Application Test: The Code (Python)
# The result of the string SQL execution
res = cursor.fetchone()
try:
# User login validation
if res[0]:
print('nAcessed!')
else:
raise
except:
user_pw_error(conn)
except Error as e:
print('nAn error has occurred!')
print(format(e))
exit(1)
# Close the database connection
conn.close()
25/30
Application Test: Execution
$ ./salting.py
A simple test access with correct password:
Application user: foo
Application user password:
Acessed!
26/30
Application Test: Execution
$ ./salting.py
A simple test access with wrong password:
Application user: foo
Application user password:
Error: Invalid user and password combination!
27/30
Conclusion
PostgreSQL has its own mechanisms of encryption passwords
which makes it very independent of the application.
This makes it easier for the application developer, may delegate
such tasks to the database, avoiding technical adjustments in the
application and finally provide a robust solution independent of
programming language.
28/30
Donate!
The elephant needs you!
Contribute!
:)
http://www.postgresql.org/about/donate/
29/30
Save our planet!Save our planet!
30/30
See you soon!!!
Juliano Atanazio
juliano777@gmail.com
http://slideshare.net/spjuliano
https://speakerdeck.com/julianometalsp
https://juliano777.wordpress.com
:)

Mais conteúdo relacionado

Mais procurados

Deep dive into PostgreSQL statistics.
Deep dive into PostgreSQL statistics.Deep dive into PostgreSQL statistics.
Deep dive into PostgreSQL statistics.Alexey Lesovsky
 
Introduction to SQL
Introduction to SQLIntroduction to SQL
Introduction to SQLEhsan Hamzei
 
Memory : operating system ( Btech cse )
Memory : operating system ( Btech cse )Memory : operating system ( Btech cse )
Memory : operating system ( Btech cse )HimanshuSharma1389
 
Operating system concepts
Operating system conceptsOperating system concepts
Operating system conceptsStarlee Lathong
 
Cassandra における SSD の活用
Cassandra における SSD の活用Cassandra における SSD の活用
Cassandra における SSD の活用Yuji Ito
 
Auditing and Monitoring PostgreSQL/EPAS
Auditing and Monitoring PostgreSQL/EPASAuditing and Monitoring PostgreSQL/EPAS
Auditing and Monitoring PostgreSQL/EPASEDB
 
Introduction to SQL Server Internals: How to Think Like the Engine
Introduction to SQL Server Internals: How to Think Like the EngineIntroduction to SQL Server Internals: How to Think Like the Engine
Introduction to SQL Server Internals: How to Think Like the EngineBrent Ozar
 
Virtual Memory
Virtual MemoryVirtual Memory
Virtual Memoryvampugani
 
pg_proctab: Accessing System Stats in PostgreSQL
pg_proctab: Accessing System Stats in PostgreSQLpg_proctab: Accessing System Stats in PostgreSQL
pg_proctab: Accessing System Stats in PostgreSQLCommand Prompt., Inc
 
Secondary storage structure-Operating System Concepts
Secondary storage structure-Operating System ConceptsSecondary storage structure-Operating System Concepts
Secondary storage structure-Operating System ConceptsArjun Kaimattathil
 
Chapter 2 - Operating System Structures
Chapter 2 - Operating System StructuresChapter 2 - Operating System Structures
Chapter 2 - Operating System StructuresWayne Jones Jnr
 
Distributed Shared Memory
Distributed Shared MemoryDistributed Shared Memory
Distributed Shared MemoryPrakhar Rastogi
 
What’s the Best PostgreSQL High Availability Framework? PAF vs. repmgr vs. Pa...
What’s the Best PostgreSQL High Availability Framework? PAF vs. repmgr vs. Pa...What’s the Best PostgreSQL High Availability Framework? PAF vs. repmgr vs. Pa...
What’s the Best PostgreSQL High Availability Framework? PAF vs. repmgr vs. Pa...ScaleGrid.io
 
Little o and little omega
Little o and little omegaLittle o and little omega
Little o and little omegaRajesh K Shukla
 
PostgreSQL Replication High Availability Methods
PostgreSQL Replication High Availability MethodsPostgreSQL Replication High Availability Methods
PostgreSQL Replication High Availability MethodsMydbops
 
Introduction to Computer theory Daniel Cohen Chapter 2 Solutions
Introduction to Computer theory Daniel Cohen Chapter 2 SolutionsIntroduction to Computer theory Daniel Cohen Chapter 2 Solutions
Introduction to Computer theory Daniel Cohen Chapter 2 SolutionsAshu
 

Mais procurados (20)

Deep dive into PostgreSQL statistics.
Deep dive into PostgreSQL statistics.Deep dive into PostgreSQL statistics.
Deep dive into PostgreSQL statistics.
 
Introduction to SQL
Introduction to SQLIntroduction to SQL
Introduction to SQL
 
Memory : operating system ( Btech cse )
Memory : operating system ( Btech cse )Memory : operating system ( Btech cse )
Memory : operating system ( Btech cse )
 
Operating system concepts
Operating system conceptsOperating system concepts
Operating system concepts
 
Sql 3
Sql 3Sql 3
Sql 3
 
Cassandra における SSD の活用
Cassandra における SSD の活用Cassandra における SSD の活用
Cassandra における SSD の活用
 
Auditing and Monitoring PostgreSQL/EPAS
Auditing and Monitoring PostgreSQL/EPASAuditing and Monitoring PostgreSQL/EPAS
Auditing and Monitoring PostgreSQL/EPAS
 
Introduction to SQL Server Internals: How to Think Like the Engine
Introduction to SQL Server Internals: How to Think Like the EngineIntroduction to SQL Server Internals: How to Think Like the Engine
Introduction to SQL Server Internals: How to Think Like the Engine
 
Virtual Memory
Virtual MemoryVirtual Memory
Virtual Memory
 
ARIES Recovery Algorithms
ARIES Recovery AlgorithmsARIES Recovery Algorithms
ARIES Recovery Algorithms
 
PostgreSQL Replication Tutorial
PostgreSQL Replication TutorialPostgreSQL Replication Tutorial
PostgreSQL Replication Tutorial
 
pg_proctab: Accessing System Stats in PostgreSQL
pg_proctab: Accessing System Stats in PostgreSQLpg_proctab: Accessing System Stats in PostgreSQL
pg_proctab: Accessing System Stats in PostgreSQL
 
Secondary storage structure-Operating System Concepts
Secondary storage structure-Operating System ConceptsSecondary storage structure-Operating System Concepts
Secondary storage structure-Operating System Concepts
 
Chapter 2 - Operating System Structures
Chapter 2 - Operating System StructuresChapter 2 - Operating System Structures
Chapter 2 - Operating System Structures
 
Distributed Shared Memory
Distributed Shared MemoryDistributed Shared Memory
Distributed Shared Memory
 
What’s the Best PostgreSQL High Availability Framework? PAF vs. repmgr vs. Pa...
What’s the Best PostgreSQL High Availability Framework? PAF vs. repmgr vs. Pa...What’s the Best PostgreSQL High Availability Framework? PAF vs. repmgr vs. Pa...
What’s the Best PostgreSQL High Availability Framework? PAF vs. repmgr vs. Pa...
 
Little o and little omega
Little o and little omegaLittle o and little omega
Little o and little omega
 
Appreciation Letter SAP ERP
Appreciation Letter SAP ERPAppreciation Letter SAP ERP
Appreciation Letter SAP ERP
 
PostgreSQL Replication High Availability Methods
PostgreSQL Replication High Availability MethodsPostgreSQL Replication High Availability Methods
PostgreSQL Replication High Availability Methods
 
Introduction to Computer theory Daniel Cohen Chapter 2 Solutions
Introduction to Computer theory Daniel Cohen Chapter 2 SolutionsIntroduction to Computer theory Daniel Cohen Chapter 2 Solutions
Introduction to Computer theory Daniel Cohen Chapter 2 Solutions
 

Destaque

Bancos de dados analíticos open source
Bancos de dados analíticos open sourceBancos de dados analíticos open source
Bancos de dados analíticos open sourceMatheus Espanhol
 
DevOps e PostgreSQL: Replicação de forma simplificada | Miguel Di Ciurcio
DevOps e PostgreSQL: Replicação de forma simplificada | Miguel Di CiurcioDevOps e PostgreSQL: Replicação de forma simplificada | Miguel Di Ciurcio
DevOps e PostgreSQL: Replicação de forma simplificada | Miguel Di CiurcioPGDay Campinas
 
Greenplum: O banco de dados open source massivamente paralelo baseado em Post...
Greenplum: O banco de dados open source massivamente paralelo baseado em Post...Greenplum: O banco de dados open source massivamente paralelo baseado em Post...
Greenplum: O banco de dados open source massivamente paralelo baseado em Post...PGDay Campinas
 
EXPLicando o Explain no PostgreSQL
EXPLicando o Explain no PostgreSQLEXPLicando o Explain no PostgreSQL
EXPLicando o Explain no PostgreSQLFabrízio Mello
 
PGDay Campinas 2013 - PL/pg…ETL – Transformação de dados para DW e BI usando ...
PGDay Campinas 2013 - PL/pg…ETL – Transformação de dados para DW e BI usando ...PGDay Campinas 2013 - PL/pg…ETL – Transformação de dados para DW e BI usando ...
PGDay Campinas 2013 - PL/pg…ETL – Transformação de dados para DW e BI usando ...PGDay Campinas
 
PGDay Campinas 2013 - Como Full Text Search pode ajudar na busca textual
PGDay Campinas 2013 - Como Full Text Search pode ajudar na busca textualPGDay Campinas 2013 - Como Full Text Search pode ajudar na busca textual
PGDay Campinas 2013 - Como Full Text Search pode ajudar na busca textualPGDay Campinas
 
PgBouncer: Pool, Segurança e Disaster Recovery | Felipe Pereira
PgBouncer: Pool, Segurança e Disaster Recovery | Felipe PereiraPgBouncer: Pool, Segurança e Disaster Recovery | Felipe Pereira
PgBouncer: Pool, Segurança e Disaster Recovery | Felipe PereiraPGDay Campinas
 
Simple SQL Change Management with Sqitch
Simple SQL Change Management with SqitchSimple SQL Change Management with Sqitch
Simple SQL Change Management with SqitchDavid Wheeler
 
PostgreSQL Modules Tutorial - chkpass, hstore, fuzzystrmach, isn
PostgreSQL Modules Tutorial - chkpass, hstore, fuzzystrmach, isn PostgreSQL Modules Tutorial - chkpass, hstore, fuzzystrmach, isn
PostgreSQL Modules Tutorial - chkpass, hstore, fuzzystrmach, isn Sagar Arlekar
 
Курс лекций на программу МВА в РУДН 16 февраля 2016 Тема "Управление изменени...
Курс лекций на программу МВА в РУДН 16 февраля 2016 Тема "Управление изменени...Курс лекций на программу МВА в РУДН 16 февраля 2016 Тема "Управление изменени...
Курс лекций на программу МВА в РУДН 16 февраля 2016 Тема "Управление изменени...Андрей Анатольевич Ващенко
 
Extensions on PostgreSQL
Extensions on PostgreSQLExtensions on PostgreSQL
Extensions on PostgreSQLAlpaca
 
יחידת הוראה לחנכה
יחידת הוראה לחנכהיחידת הוראה לחנכה
יחידת הוראה לחנכהMax Rokach
 
GSoC2014 - Uniritter Presentation May, 2015
GSoC2014 - Uniritter Presentation May, 2015GSoC2014 - Uniritter Presentation May, 2015
GSoC2014 - Uniritter Presentation May, 2015Fabrízio Mello
 
Postgres Wonderland - PGDay Cascavél 2013
Postgres Wonderland - PGDay Cascavél 2013Postgres Wonderland - PGDay Cascavél 2013
Postgres Wonderland - PGDay Cascavél 2013Fabio Telles Rodriguez
 
GSoC2014 - PGDay Ijui/RS Presentation October, 2016
GSoC2014 - PGDay Ijui/RS Presentation October, 2016 GSoC2014 - PGDay Ijui/RS Presentation October, 2016
GSoC2014 - PGDay Ijui/RS Presentation October, 2016 Fabrízio Mello
 
Sharing Code and Experiences
Sharing Code and ExperiencesSharing Code and Experiences
Sharing Code and ExperiencesFabrízio Mello
 
Keep calm and Database Continuous Deployment
Keep calm and Database Continuous DeploymentKeep calm and Database Continuous Deployment
Keep calm and Database Continuous DeploymentFabrízio Mello
 
Bad Smells (mal cheiros) em Bancos de Dados
Bad Smells (mal cheiros) em Bancos de DadosBad Smells (mal cheiros) em Bancos de Dados
Bad Smells (mal cheiros) em Bancos de DadosFabrízio Mello
 

Destaque (20)

Bancos de dados analíticos open source
Bancos de dados analíticos open sourceBancos de dados analíticos open source
Bancos de dados analíticos open source
 
DevOps e PostgreSQL: Replicação de forma simplificada | Miguel Di Ciurcio
DevOps e PostgreSQL: Replicação de forma simplificada | Miguel Di CiurcioDevOps e PostgreSQL: Replicação de forma simplificada | Miguel Di Ciurcio
DevOps e PostgreSQL: Replicação de forma simplificada | Miguel Di Ciurcio
 
Greenplum: O banco de dados open source massivamente paralelo baseado em Post...
Greenplum: O banco de dados open source massivamente paralelo baseado em Post...Greenplum: O banco de dados open source massivamente paralelo baseado em Post...
Greenplum: O banco de dados open source massivamente paralelo baseado em Post...
 
EXPLicando o Explain no PostgreSQL
EXPLicando o Explain no PostgreSQLEXPLicando o Explain no PostgreSQL
EXPLicando o Explain no PostgreSQL
 
PGDay Campinas 2013 - PL/pg…ETL – Transformação de dados para DW e BI usando ...
PGDay Campinas 2013 - PL/pg…ETL – Transformação de dados para DW e BI usando ...PGDay Campinas 2013 - PL/pg…ETL – Transformação de dados para DW e BI usando ...
PGDay Campinas 2013 - PL/pg…ETL – Transformação de dados para DW e BI usando ...
 
PGDay Campinas 2013 - Como Full Text Search pode ajudar na busca textual
PGDay Campinas 2013 - Como Full Text Search pode ajudar na busca textualPGDay Campinas 2013 - Como Full Text Search pode ajudar na busca textual
PGDay Campinas 2013 - Como Full Text Search pode ajudar na busca textual
 
PgBouncer: Pool, Segurança e Disaster Recovery | Felipe Pereira
PgBouncer: Pool, Segurança e Disaster Recovery | Felipe PereiraPgBouncer: Pool, Segurança e Disaster Recovery | Felipe Pereira
PgBouncer: Pool, Segurança e Disaster Recovery | Felipe Pereira
 
Simple SQL Change Management with Sqitch
Simple SQL Change Management with SqitchSimple SQL Change Management with Sqitch
Simple SQL Change Management with Sqitch
 
PostgreSQL Modules Tutorial - chkpass, hstore, fuzzystrmach, isn
PostgreSQL Modules Tutorial - chkpass, hstore, fuzzystrmach, isn PostgreSQL Modules Tutorial - chkpass, hstore, fuzzystrmach, isn
PostgreSQL Modules Tutorial - chkpass, hstore, fuzzystrmach, isn
 
Курс лекций на программу МВА в РУДН 16 февраля 2016 Тема "Управление изменени...
Курс лекций на программу МВА в РУДН 16 февраля 2016 Тема "Управление изменени...Курс лекций на программу МВА в РУДН 16 февраля 2016 Тема "Управление изменени...
Курс лекций на программу МВА в РУДН 16 февраля 2016 Тема "Управление изменени...
 
Extensions on PostgreSQL
Extensions on PostgreSQLExtensions on PostgreSQL
Extensions on PostgreSQL
 
יחידת הוראה לחנכה
יחידת הוראה לחנכהיחידת הוראה לחנכה
יחידת הוראה לחנכה
 
Cassandra db
Cassandra dbCassandra db
Cassandra db
 
GSoC2014 - Uniritter Presentation May, 2015
GSoC2014 - Uniritter Presentation May, 2015GSoC2014 - Uniritter Presentation May, 2015
GSoC2014 - Uniritter Presentation May, 2015
 
Postgres Wonderland - PGDay Cascavél 2013
Postgres Wonderland - PGDay Cascavél 2013Postgres Wonderland - PGDay Cascavél 2013
Postgres Wonderland - PGDay Cascavél 2013
 
GSoC2014 - PGDay Ijui/RS Presentation October, 2016
GSoC2014 - PGDay Ijui/RS Presentation October, 2016 GSoC2014 - PGDay Ijui/RS Presentation October, 2016
GSoC2014 - PGDay Ijui/RS Presentation October, 2016
 
Sharing Code and Experiences
Sharing Code and ExperiencesSharing Code and Experiences
Sharing Code and Experiences
 
Keep calm and Database Continuous Deployment
Keep calm and Database Continuous DeploymentKeep calm and Database Continuous Deployment
Keep calm and Database Continuous Deployment
 
Bad Smells (mal cheiros) em Bancos de Dados
Bad Smells (mal cheiros) em Bancos de DadosBad Smells (mal cheiros) em Bancos de Dados
Bad Smells (mal cheiros) em Bancos de Dados
 
Dojo plpgsql
Dojo plpgsqlDojo plpgsql
Dojo plpgsql
 

Semelhante a PostgreSQL: How to Store Passwords Safely

Postgresql 12 streaming replication hol
Postgresql 12 streaming replication holPostgresql 12 streaming replication hol
Postgresql 12 streaming replication holVijay Kumar N
 
Стажировка 2016-07-27 02 Денис Нелюбин. PostgreSQL и jsonb
Стажировка 2016-07-27 02 Денис Нелюбин. PostgreSQL и jsonbСтажировка 2016-07-27 02 Денис Нелюбин. PostgreSQL и jsonb
Стажировка 2016-07-27 02 Денис Нелюбин. PostgreSQL и jsonbSmartTools
 
OpenGurukul : Database : PostgreSQL
OpenGurukul : Database : PostgreSQLOpenGurukul : Database : PostgreSQL
OpenGurukul : Database : PostgreSQLOpen Gurukul
 
PostgreSQL Administration for System Administrators
PostgreSQL Administration for System AdministratorsPostgreSQL Administration for System Administrators
PostgreSQL Administration for System AdministratorsCommand Prompt., Inc
 
pg_proctab: Accessing System Stats in PostgreSQL
pg_proctab: Accessing System Stats in PostgreSQLpg_proctab: Accessing System Stats in PostgreSQL
pg_proctab: Accessing System Stats in PostgreSQLCommand Prompt., Inc
 
pg_proctab: Accessing System Stats in PostgreSQL
pg_proctab: Accessing System Stats in PostgreSQLpg_proctab: Accessing System Stats in PostgreSQL
pg_proctab: Accessing System Stats in PostgreSQLMark Wong
 
Nko workshop - node js crud & deploy
Nko workshop - node js crud & deployNko workshop - node js crud & deploy
Nko workshop - node js crud & deploySimon Su
 
pg_proctab: Accessing System Stats in PostgreSQL
pg_proctab: Accessing System Stats in PostgreSQLpg_proctab: Accessing System Stats in PostgreSQL
pg_proctab: Accessing System Stats in PostgreSQLMark Wong
 
PGDay.Amsterdam 2018 - Stefan Fercot - Save your data with pgBackRest
PGDay.Amsterdam 2018 - Stefan Fercot - Save your data with pgBackRestPGDay.Amsterdam 2018 - Stefan Fercot - Save your data with pgBackRest
PGDay.Amsterdam 2018 - Stefan Fercot - Save your data with pgBackRestPGDay.Amsterdam
 
pg_proctab: Accessing System Stats in PostgreSQL
pg_proctab: Accessing System Stats in PostgreSQLpg_proctab: Accessing System Stats in PostgreSQL
pg_proctab: Accessing System Stats in PostgreSQLMark Wong
 
Best Practices in Handling Performance Issues
Best Practices in Handling Performance IssuesBest Practices in Handling Performance Issues
Best Practices in Handling Performance IssuesOdoo
 
agri inventory - nouka data collector / yaoya data convertor
agri inventory - nouka data collector / yaoya data convertoragri inventory - nouka data collector / yaoya data convertor
agri inventory - nouka data collector / yaoya data convertorToshiaki Baba
 
計算機性能の限界点とその考え方
計算機性能の限界点とその考え方計算機性能の限界点とその考え方
計算機性能の限界点とその考え方Naoto MATSUMOTO
 
Степан Кольцов — Rust — лучше, чем C++
Степан Кольцов — Rust — лучше, чем C++Степан Кольцов — Rust — лучше, чем C++
Степан Кольцов — Rust — лучше, чем C++Yandex
 
PostgreSQL 9.6 새 기능 소개
PostgreSQL 9.6 새 기능 소개PostgreSQL 9.6 새 기능 소개
PostgreSQL 9.6 새 기능 소개PgDay.Seoul
 

Semelhante a PostgreSQL: How to Store Passwords Safely (20)

Postgresql 12 streaming replication hol
Postgresql 12 streaming replication holPostgresql 12 streaming replication hol
Postgresql 12 streaming replication hol
 
Стажировка 2016-07-27 02 Денис Нелюбин. PostgreSQL и jsonb
Стажировка 2016-07-27 02 Денис Нелюбин. PostgreSQL и jsonbСтажировка 2016-07-27 02 Денис Нелюбин. PostgreSQL и jsonb
Стажировка 2016-07-27 02 Денис Нелюбин. PostgreSQL и jsonb
 
OpenGurukul : Database : PostgreSQL
OpenGurukul : Database : PostgreSQLOpenGurukul : Database : PostgreSQL
OpenGurukul : Database : PostgreSQL
 
PostgreSQL Administration for System Administrators
PostgreSQL Administration for System AdministratorsPostgreSQL Administration for System Administrators
PostgreSQL Administration for System Administrators
 
Osol Pgsql
Osol PgsqlOsol Pgsql
Osol Pgsql
 
pg_proctab: Accessing System Stats in PostgreSQL
pg_proctab: Accessing System Stats in PostgreSQLpg_proctab: Accessing System Stats in PostgreSQL
pg_proctab: Accessing System Stats in PostgreSQL
 
pg_proctab: Accessing System Stats in PostgreSQL
pg_proctab: Accessing System Stats in PostgreSQLpg_proctab: Accessing System Stats in PostgreSQL
pg_proctab: Accessing System Stats in PostgreSQL
 
Nko workshop - node js crud & deploy
Nko workshop - node js crud & deployNko workshop - node js crud & deploy
Nko workshop - node js crud & deploy
 
pg_proctab: Accessing System Stats in PostgreSQL
pg_proctab: Accessing System Stats in PostgreSQLpg_proctab: Accessing System Stats in PostgreSQL
pg_proctab: Accessing System Stats in PostgreSQL
 
PGDay.Amsterdam 2018 - Stefan Fercot - Save your data with pgBackRest
PGDay.Amsterdam 2018 - Stefan Fercot - Save your data with pgBackRestPGDay.Amsterdam 2018 - Stefan Fercot - Save your data with pgBackRest
PGDay.Amsterdam 2018 - Stefan Fercot - Save your data with pgBackRest
 
pg_proctab: Accessing System Stats in PostgreSQL
pg_proctab: Accessing System Stats in PostgreSQLpg_proctab: Accessing System Stats in PostgreSQL
pg_proctab: Accessing System Stats in PostgreSQL
 
Best Practices in Handling Performance Issues
Best Practices in Handling Performance IssuesBest Practices in Handling Performance Issues
Best Practices in Handling Performance Issues
 
Containers for sysadmins
Containers for sysadminsContainers for sysadmins
Containers for sysadmins
 
Hacking the swisscom modem
Hacking the swisscom modemHacking the swisscom modem
Hacking the swisscom modem
 
agri inventory - nouka data collector / yaoya data convertor
agri inventory - nouka data collector / yaoya data convertoragri inventory - nouka data collector / yaoya data convertor
agri inventory - nouka data collector / yaoya data convertor
 
Operation outbreak
Operation outbreakOperation outbreak
Operation outbreak
 
計算機性能の限界点とその考え方
計算機性能の限界点とその考え方計算機性能の限界点とその考え方
計算機性能の限界点とその考え方
 
Степан Кольцов — Rust — лучше, чем C++
Степан Кольцов — Rust — лучше, чем C++Степан Кольцов — Rust — лучше, чем C++
Степан Кольцов — Rust — лучше, чем C++
 
PostgreSQL 9.6 새 기능 소개
PostgreSQL 9.6 새 기능 소개PostgreSQL 9.6 새 기능 소개
PostgreSQL 9.6 새 기능 소개
 
Full Text Search in PostgreSQL
Full Text Search in PostgreSQLFull Text Search in PostgreSQL
Full Text Search in PostgreSQL
 

Mais de Juliano Atanazio

PL/Python: Programando em Python no PostgreSQL
PL/Python: Programando em Python no PostgreSQLPL/Python: Programando em Python no PostgreSQL
PL/Python: Programando em Python no PostgreSQLJuliano Atanazio
 
Por que Python? Vamos Conhecer? Vamos Aprender?
Por que Python? Vamos Conhecer? Vamos Aprender?Por que Python? Vamos Conhecer? Vamos Aprender?
Por que Python? Vamos Conhecer? Vamos Aprender?Juliano Atanazio
 
Neutralizing SQL Injection in PostgreSQL
Neutralizing SQL Injection in PostgreSQLNeutralizing SQL Injection in PostgreSQL
Neutralizing SQL Injection in PostgreSQLJuliano Atanazio
 
Postgresql + Python = Power!
Postgresql + Python = Power!Postgresql + Python = Power!
Postgresql + Python = Power!Juliano Atanazio
 
Boas praticas em um Projeto de Banco de Dados
Boas praticas em um Projeto de Banco de DadosBoas praticas em um Projeto de Banco de Dados
Boas praticas em um Projeto de Banco de DadosJuliano Atanazio
 
Full Text Search - Busca Textual no PostgreSQL
Full Text Search -  Busca Textual no PostgreSQLFull Text Search -  Busca Textual no PostgreSQL
Full Text Search - Busca Textual no PostgreSQLJuliano Atanazio
 
Gerenciamento de Backups PostgreSQL com pgbarman
Gerenciamento de Backups PostgreSQL com pgbarmanGerenciamento de Backups PostgreSQL com pgbarman
Gerenciamento de Backups PostgreSQL com pgbarmanJuliano Atanazio
 

Mais de Juliano Atanazio (9)

PL/Python: Programando em Python no PostgreSQL
PL/Python: Programando em Python no PostgreSQLPL/Python: Programando em Python no PostgreSQL
PL/Python: Programando em Python no PostgreSQL
 
Por que Python? Vamos Conhecer? Vamos Aprender?
Por que Python? Vamos Conhecer? Vamos Aprender?Por que Python? Vamos Conhecer? Vamos Aprender?
Por que Python? Vamos Conhecer? Vamos Aprender?
 
Por que FreeBSD?
Por que FreeBSD?Por que FreeBSD?
Por que FreeBSD?
 
Neutralizing SQL Injection in PostgreSQL
Neutralizing SQL Injection in PostgreSQLNeutralizing SQL Injection in PostgreSQL
Neutralizing SQL Injection in PostgreSQL
 
Postgresql + Python = Power!
Postgresql + Python = Power!Postgresql + Python = Power!
Postgresql + Python = Power!
 
Boas praticas em um Projeto de Banco de Dados
Boas praticas em um Projeto de Banco de DadosBoas praticas em um Projeto de Banco de Dados
Boas praticas em um Projeto de Banco de Dados
 
Por que PostgreSQL?
Por que PostgreSQL?Por que PostgreSQL?
Por que PostgreSQL?
 
Full Text Search - Busca Textual no PostgreSQL
Full Text Search -  Busca Textual no PostgreSQLFull Text Search -  Busca Textual no PostgreSQL
Full Text Search - Busca Textual no PostgreSQL
 
Gerenciamento de Backups PostgreSQL com pgbarman
Gerenciamento de Backups PostgreSQL com pgbarmanGerenciamento de Backups PostgreSQL com pgbarman
Gerenciamento de Backups PostgreSQL com pgbarman
 

Último

Call Girls In Dwarka 9654467111 Escorts Service
Call Girls In Dwarka 9654467111 Escorts ServiceCall Girls In Dwarka 9654467111 Escorts Service
Call Girls In Dwarka 9654467111 Escorts ServiceSapana Sha
 
Generative AI for Social Good at Open Data Science East 2024
Generative AI for Social Good at Open Data Science East 2024Generative AI for Social Good at Open Data Science East 2024
Generative AI for Social Good at Open Data Science East 2024Colleen Farrelly
 
Kantar AI Summit- Under Embargo till Wednesday, 24th April 2024, 4 PM, IST.pdf
Kantar AI Summit- Under Embargo till Wednesday, 24th April 2024, 4 PM, IST.pdfKantar AI Summit- Under Embargo till Wednesday, 24th April 2024, 4 PM, IST.pdf
Kantar AI Summit- Under Embargo till Wednesday, 24th April 2024, 4 PM, IST.pdfSocial Samosa
 
9711147426✨Call In girls Gurgaon Sector 31. SCO 25 escort service
9711147426✨Call In girls Gurgaon Sector 31. SCO 25 escort service9711147426✨Call In girls Gurgaon Sector 31. SCO 25 escort service
9711147426✨Call In girls Gurgaon Sector 31. SCO 25 escort servicejennyeacort
 
原版1:1定制南十字星大学毕业证(SCU毕业证)#文凭成绩单#真实留信学历认证永久存档
原版1:1定制南十字星大学毕业证(SCU毕业证)#文凭成绩单#真实留信学历认证永久存档原版1:1定制南十字星大学毕业证(SCU毕业证)#文凭成绩单#真实留信学历认证永久存档
原版1:1定制南十字星大学毕业证(SCU毕业证)#文凭成绩单#真实留信学历认证永久存档208367051
 
1:1定制(UQ毕业证)昆士兰大学毕业证成绩单修改留信学历认证原版一模一样
1:1定制(UQ毕业证)昆士兰大学毕业证成绩单修改留信学历认证原版一模一样1:1定制(UQ毕业证)昆士兰大学毕业证成绩单修改留信学历认证原版一模一样
1:1定制(UQ毕业证)昆士兰大学毕业证成绩单修改留信学历认证原版一模一样vhwb25kk
 
Advanced Machine Learning for Business Professionals
Advanced Machine Learning for Business ProfessionalsAdvanced Machine Learning for Business Professionals
Advanced Machine Learning for Business ProfessionalsVICTOR MAESTRE RAMIREZ
 
GA4 Without Cookies [Measure Camp AMS]
GA4 Without Cookies [Measure Camp AMS]GA4 Without Cookies [Measure Camp AMS]
GA4 Without Cookies [Measure Camp AMS]📊 Markus Baersch
 
Saket, (-DELHI )+91-9654467111-(=)CHEAP Call Girls in Escorts Service Saket C...
Saket, (-DELHI )+91-9654467111-(=)CHEAP Call Girls in Escorts Service Saket C...Saket, (-DELHI )+91-9654467111-(=)CHEAP Call Girls in Escorts Service Saket C...
Saket, (-DELHI )+91-9654467111-(=)CHEAP Call Girls in Escorts Service Saket C...Sapana Sha
 
INTERNSHIP ON PURBASHA COMPOSITE TEX LTD
INTERNSHIP ON PURBASHA COMPOSITE TEX LTDINTERNSHIP ON PURBASHA COMPOSITE TEX LTD
INTERNSHIP ON PURBASHA COMPOSITE TEX LTDRafezzaman
 
From idea to production in a day – Leveraging Azure ML and Streamlit to build...
From idea to production in a day – Leveraging Azure ML and Streamlit to build...From idea to production in a day – Leveraging Azure ML and Streamlit to build...
From idea to production in a day – Leveraging Azure ML and Streamlit to build...Florian Roscheck
 
Building on a FAIRly Strong Foundation to Connect Academic Research to Transl...
Building on a FAIRly Strong Foundation to Connect Academic Research to Transl...Building on a FAIRly Strong Foundation to Connect Academic Research to Transl...
Building on a FAIRly Strong Foundation to Connect Academic Research to Transl...Jack DiGiovanna
 
RABBIT: A CLI tool for identifying bots based on their GitHub events.
RABBIT: A CLI tool for identifying bots based on their GitHub events.RABBIT: A CLI tool for identifying bots based on their GitHub events.
RABBIT: A CLI tool for identifying bots based on their GitHub events.natarajan8993
 
IMA MSN - Medical Students Network (2).pptx
IMA MSN - Medical Students Network (2).pptxIMA MSN - Medical Students Network (2).pptx
IMA MSN - Medical Students Network (2).pptxdolaknnilon
 
High Class Call Girls Noida Sector 39 Aarushi 🔝8264348440🔝 Independent Escort...
High Class Call Girls Noida Sector 39 Aarushi 🔝8264348440🔝 Independent Escort...High Class Call Girls Noida Sector 39 Aarushi 🔝8264348440🔝 Independent Escort...
High Class Call Girls Noida Sector 39 Aarushi 🔝8264348440🔝 Independent Escort...soniya singh
 
Call Girls in Defence Colony Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Defence Colony Delhi 💯Call Us 🔝8264348440🔝Call Girls in Defence Colony Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Defence Colony Delhi 💯Call Us 🔝8264348440🔝soniya singh
 
MK KOMUNIKASI DATA (TI)komdat komdat.docx
MK KOMUNIKASI DATA (TI)komdat komdat.docxMK KOMUNIKASI DATA (TI)komdat komdat.docx
MK KOMUNIKASI DATA (TI)komdat komdat.docxUnduhUnggah1
 
Top 5 Best Data Analytics Courses In Queens
Top 5 Best Data Analytics Courses In QueensTop 5 Best Data Analytics Courses In Queens
Top 5 Best Data Analytics Courses In Queensdataanalyticsqueen03
 
Consent & Privacy Signals on Google *Pixels* - MeasureCamp Amsterdam 2024
Consent & Privacy Signals on Google *Pixels* - MeasureCamp Amsterdam 2024Consent & Privacy Signals on Google *Pixels* - MeasureCamp Amsterdam 2024
Consent & Privacy Signals on Google *Pixels* - MeasureCamp Amsterdam 2024thyngster
 

Último (20)

Call Girls In Dwarka 9654467111 Escorts Service
Call Girls In Dwarka 9654467111 Escorts ServiceCall Girls In Dwarka 9654467111 Escorts Service
Call Girls In Dwarka 9654467111 Escorts Service
 
Generative AI for Social Good at Open Data Science East 2024
Generative AI for Social Good at Open Data Science East 2024Generative AI for Social Good at Open Data Science East 2024
Generative AI for Social Good at Open Data Science East 2024
 
E-Commerce Order PredictionShraddha Kamble.pptx
E-Commerce Order PredictionShraddha Kamble.pptxE-Commerce Order PredictionShraddha Kamble.pptx
E-Commerce Order PredictionShraddha Kamble.pptx
 
Kantar AI Summit- Under Embargo till Wednesday, 24th April 2024, 4 PM, IST.pdf
Kantar AI Summit- Under Embargo till Wednesday, 24th April 2024, 4 PM, IST.pdfKantar AI Summit- Under Embargo till Wednesday, 24th April 2024, 4 PM, IST.pdf
Kantar AI Summit- Under Embargo till Wednesday, 24th April 2024, 4 PM, IST.pdf
 
9711147426✨Call In girls Gurgaon Sector 31. SCO 25 escort service
9711147426✨Call In girls Gurgaon Sector 31. SCO 25 escort service9711147426✨Call In girls Gurgaon Sector 31. SCO 25 escort service
9711147426✨Call In girls Gurgaon Sector 31. SCO 25 escort service
 
原版1:1定制南十字星大学毕业证(SCU毕业证)#文凭成绩单#真实留信学历认证永久存档
原版1:1定制南十字星大学毕业证(SCU毕业证)#文凭成绩单#真实留信学历认证永久存档原版1:1定制南十字星大学毕业证(SCU毕业证)#文凭成绩单#真实留信学历认证永久存档
原版1:1定制南十字星大学毕业证(SCU毕业证)#文凭成绩单#真实留信学历认证永久存档
 
1:1定制(UQ毕业证)昆士兰大学毕业证成绩单修改留信学历认证原版一模一样
1:1定制(UQ毕业证)昆士兰大学毕业证成绩单修改留信学历认证原版一模一样1:1定制(UQ毕业证)昆士兰大学毕业证成绩单修改留信学历认证原版一模一样
1:1定制(UQ毕业证)昆士兰大学毕业证成绩单修改留信学历认证原版一模一样
 
Advanced Machine Learning for Business Professionals
Advanced Machine Learning for Business ProfessionalsAdvanced Machine Learning for Business Professionals
Advanced Machine Learning for Business Professionals
 
GA4 Without Cookies [Measure Camp AMS]
GA4 Without Cookies [Measure Camp AMS]GA4 Without Cookies [Measure Camp AMS]
GA4 Without Cookies [Measure Camp AMS]
 
Saket, (-DELHI )+91-9654467111-(=)CHEAP Call Girls in Escorts Service Saket C...
Saket, (-DELHI )+91-9654467111-(=)CHEAP Call Girls in Escorts Service Saket C...Saket, (-DELHI )+91-9654467111-(=)CHEAP Call Girls in Escorts Service Saket C...
Saket, (-DELHI )+91-9654467111-(=)CHEAP Call Girls in Escorts Service Saket C...
 
INTERNSHIP ON PURBASHA COMPOSITE TEX LTD
INTERNSHIP ON PURBASHA COMPOSITE TEX LTDINTERNSHIP ON PURBASHA COMPOSITE TEX LTD
INTERNSHIP ON PURBASHA COMPOSITE TEX LTD
 
From idea to production in a day – Leveraging Azure ML and Streamlit to build...
From idea to production in a day – Leveraging Azure ML and Streamlit to build...From idea to production in a day – Leveraging Azure ML and Streamlit to build...
From idea to production in a day – Leveraging Azure ML and Streamlit to build...
 
Building on a FAIRly Strong Foundation to Connect Academic Research to Transl...
Building on a FAIRly Strong Foundation to Connect Academic Research to Transl...Building on a FAIRly Strong Foundation to Connect Academic Research to Transl...
Building on a FAIRly Strong Foundation to Connect Academic Research to Transl...
 
RABBIT: A CLI tool for identifying bots based on their GitHub events.
RABBIT: A CLI tool for identifying bots based on their GitHub events.RABBIT: A CLI tool for identifying bots based on their GitHub events.
RABBIT: A CLI tool for identifying bots based on their GitHub events.
 
IMA MSN - Medical Students Network (2).pptx
IMA MSN - Medical Students Network (2).pptxIMA MSN - Medical Students Network (2).pptx
IMA MSN - Medical Students Network (2).pptx
 
High Class Call Girls Noida Sector 39 Aarushi 🔝8264348440🔝 Independent Escort...
High Class Call Girls Noida Sector 39 Aarushi 🔝8264348440🔝 Independent Escort...High Class Call Girls Noida Sector 39 Aarushi 🔝8264348440🔝 Independent Escort...
High Class Call Girls Noida Sector 39 Aarushi 🔝8264348440🔝 Independent Escort...
 
Call Girls in Defence Colony Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Defence Colony Delhi 💯Call Us 🔝8264348440🔝Call Girls in Defence Colony Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Defence Colony Delhi 💯Call Us 🔝8264348440🔝
 
MK KOMUNIKASI DATA (TI)komdat komdat.docx
MK KOMUNIKASI DATA (TI)komdat komdat.docxMK KOMUNIKASI DATA (TI)komdat komdat.docx
MK KOMUNIKASI DATA (TI)komdat komdat.docx
 
Top 5 Best Data Analytics Courses In Queens
Top 5 Best Data Analytics Courses In QueensTop 5 Best Data Analytics Courses In Queens
Top 5 Best Data Analytics Courses In Queens
 
Consent & Privacy Signals on Google *Pixels* - MeasureCamp Amsterdam 2024
Consent & Privacy Signals on Google *Pixels* - MeasureCamp Amsterdam 2024Consent & Privacy Signals on Google *Pixels* - MeasureCamp Amsterdam 2024
Consent & Privacy Signals on Google *Pixels* - MeasureCamp Amsterdam 2024
 

PostgreSQL: How to Store Passwords Safely

  • 1. Juliano Atanazio PostgreSQL: How to Store Passwords SafelyPostgreSQL: How to Store Passwords Safely
  • 2. 2/30 About me Juliano Atanazio ● Graduated in Computer Science for Business Management (Informática para Gestão de Negócios), FATEC Zona Sul, São Paulo – SP; ● PostgreSQL DBA; ● Linux admin; ● Instructor (PostgreSQL); ● LPIC-1, LPIC-2 Certified; ● Linux user since 2000; ● Free Software enthusiast; ● Favorite technologies: PostgreSQL, Linux, Python, Shell Script, FreeBSD, etc...; ● Headbanger :) m/
  • 3. 3/30 Plain Text Passwords ● Store passwords (in plain text) of application users in database is not a good practice; ● The DBA doesn’t need and shouldn’t know the users passwords; ● If your database is invaded, the attacker will have access to user passwords; ● The unencrypted password should never be stored in the database.
  • 4. 4/30 Hashing and Salting Hashing and salting is a technique to store passwords securely: 1. Generate a random string (salt) with a desired algorithm (e. g. blowfish based); 2. This salt and the plain text password are used to generate the hash password through hashing process; 3. Hash password is stored in the database; The password must be encrypted in an irreversible way, that you can not decrypt it (theoretically).
  • 5. 5/30 pgcrypto pgcrypto is a extension that provides cryptographic functions for PostgreSQL. https://www.postgresql.org/docs/current/static/pgcrypto.html
  • 6. 6/30 pgcrypto gen_salt and crypt Functions They are specifically designed for hashing passwords. crypt() does the hashing and gen_salt() prepares algorithm parameters for it. ● gen_salt(): Generates a new random salt string for use in crypt(). The salt string also tells crypt() which algorithm to use. ● crypt(): It generate hash password through passing the password (in plain text) and salt as parameters.
  • 7. 7/30 Salting and Hashing: Practice First, you need to enable the pgcrypto extension in your database. pgcrypto is a additional supplied module (a contrib module). Enable the pgcrypto extension: > CREATE EXTENSION pgcrypto;
  • 8. 8/30 Salting and Hashing: Practice Password Creation
  • 9. 9/30 Salting and Hashing: Practice Test; generate a salt string: salt_string ------------------------------- $2a$06$YmO7UZZZxkTWZfT8s7b/GO > SELECT gen_salt('bf') AS salt_string; blowfish algorithm
  • 10. 10/30 Salting and Hashing: Practice Test; generate the password hash with the previous salt string: pw_hash -------------------------------------------------------------- $2a$06$YmO7UZZZxkTWZfT8s7b/GOlO0rZpMhU674srD/dbSyplwO/clTZzi > SELECT crypt('mypass', '$2a$06$YmO7UZZZxkTWZfT8s7b/GO') AS pw_hash;
  • 11. 11/30 Salting and Hashing: Practice Test; comparison with crypt function and previous hash string: simple_auth_test ------------------ t > SELECT crypt('mypass', '$2a$06$YmO7UZZZxkTWZfT8s7b/GOlO0rZpMhU674srD/dbSyplwO/clTZzi') = '$2a$06$YmO7UZZZxkTWZfT8s7b/GOlO0rZpMhU674srD/dbSyplwO/clTZzi' AS simple_auth_test;
  • 12. 12/30 Salting and Hashing: Practice Create the table: > CREATE TABLE tb_user( username varchar(50) PRIMARY KEY, -- natural primary key password VARCHAR(72) NOT NULL );
  • 13. 13/30 Salting and Hashing: Practice Using CTE* to INSERT new user with password creation: * CTE = Common Table Expressions https://www.postgresql.org/docs/current/static/queries-with.html > WITH x AS ( SELECT 'foo'::text AS user, '123'::text AS pw, gen_salt('bf')::text AS salt ) INSERT INTO tb_user (username, password) SELECT x.user, crypt(x.pw, x.salt) -- password hash FROM x;
  • 14. 14/30 Salting and Hashing: Practice Enable expanded display automatically (psql): Querying username and password in the table: username | password ----------+-------------------------------------------------------------- foo | $2a$06$RqHcf7F.nUGLkQF1fOea.OLAU0gyz/liF3dO58JWTB0oyVirzUdgK > x auto > SELECT username, password FROM tb_user;
  • 15. 15/30 Salting and Hashing: Practice Password Verification
  • 16. 16/30 Salting and Hashing: Practice User authentication test with correct password: acessed --------- t True value (boolean) returned. > SELECT crypt('123', password) = password AS acessed FROM tb_user WHERE username = 'foo'; Plain text (password) provided by user
  • 17. 17/30 Salting and Hashing: Practice User authentication test with wrong password: acessed --------- f False value (boolean) returned. > SELECT crypt('1234', password) = password AS acessed FROM tb_user WHERE username = 'foo';
  • 18. 18/30 Application Test: The Code (Python) Continue #!/usr/bin/env python3 # _*_ encoding: utf-8 _*_ from argparse import ArgumentParser from getpass import getpass from os import system from psycopg2 import connect from psycopg2 import Error from sys import exit
  • 19. 19/30 Application Test: The Code (Python) Continue # Argument parser parser = ArgumentParser() # Argument help strings help_d = 'Database' help_H = 'Hostname or IP address' help_p = 'Port' help_u = 'Username' help_w = 'With password prompt'
  • 20. 20/30 Application Test: The Code (Python) Continue # Arguments creation parser.add_argument('-d', '--database', type=str, help=help_d, action='store', metavar='dbname', dest='dbname', default='postgres') parser.add_argument('-H', '--host', type=str, help=help_H, action='store', metavar='dbserver', dest='host', default=None) parser.add_argument('-p', '--port', type=int, help=help_p, action='store', metavar='port_number', dest='port', default=5432) parser.add_argument('-u', '--user', type=str, help=help_u, action='store', metavar='username', dest='user', default='postgres') parser.add_argument('-w', '--with-pass', help=help_w, action='store_true', dest='password') # Parsed arguments args = parser.parse_args()
  • 21. 21/30 Application Test: The Code (Python) Continue # Test if password prompt is required if args.password: args.password = getpass('Database user password: ') else: args.password = None # Connection string variable (initially as a list) conn_str = [] # Take all provided paramaters and make the connection string for k, v in vars(args).items(): if v: str_tmp = "{} = '{}'".format(k, v) conn_str.append(str_tmp) conn_str = ' '.join(conn_str)
  • 22. 22/30 Application Test: The Code (Python) Continue # SQL string for PREPARE command sql_prepare = """ PREPARE q_user (text, text) AS SELECT crypt($2, password) = password FROM tb_user WHERE username = $1; """ # SQL string for EXECUTE command sql_execute = "EXECUTE q_user('{}', '{}');" # When occur authentication error... def user_pw_error(connection): print('nError: Invalid user and password combination!') connection.close() exit(1)
  • 23. 23/30 Application Test: The Code (Python) Continue try: # Connection conn = connect(conn_str) # Cursor creation to execute SQL commands cursor = conn.cursor() # Execute the SQL string in database cursor.execute(sql_prepare) # Clear Screen system('clear') # Get user and password of the application app_user = input('nApplication user: ') app_user_pw = getpass('Application user password: ') # Execute the SQL string in database cursor.execute(sql_execute.format(app_user, app_user_pw))
  • 24. 24/30 Application Test: The Code (Python) # The result of the string SQL execution res = cursor.fetchone() try: # User login validation if res[0]: print('nAcessed!') else: raise except: user_pw_error(conn) except Error as e: print('nAn error has occurred!') print(format(e)) exit(1) # Close the database connection conn.close()
  • 25. 25/30 Application Test: Execution $ ./salting.py A simple test access with correct password: Application user: foo Application user password: Acessed!
  • 26. 26/30 Application Test: Execution $ ./salting.py A simple test access with wrong password: Application user: foo Application user password: Error: Invalid user and password combination!
  • 27. 27/30 Conclusion PostgreSQL has its own mechanisms of encryption passwords which makes it very independent of the application. This makes it easier for the application developer, may delegate such tasks to the database, avoiding technical adjustments in the application and finally provide a robust solution independent of programming language.
  • 28. 28/30 Donate! The elephant needs you! Contribute! :) http://www.postgresql.org/about/donate/
  • 30. 30/30 See you soon!!! Juliano Atanazio juliano777@gmail.com http://slideshare.net/spjuliano https://speakerdeck.com/julianometalsp https://juliano777.wordpress.com :)