apiary/honeypot/ssh/store/postgres.go

216 lines
5.9 KiB
Go
Raw Normal View History

2021-04-10 05:58:01 +00:00
package store
import (
"database/sql"
"fmt"
2021-04-14 16:01:11 +00:00
"net"
2021-04-10 05:58:01 +00:00
2022-01-13 08:10:36 +00:00
"git.t-juice.club/torjus/apiary/models"
2021-04-10 05:58:01 +00:00
_ "github.com/jackc/pgx/v4/stdlib"
)
2022-08-26 10:21:52 +00:00
var _ LoginAttemptStore = &PostgresStore{}
2021-04-10 05:58:01 +00:00
const DBSchema = `
CREATE TABLE IF NOT EXISTS login_attempts(
id serial PRIMARY KEY,
date timestamptz,
remote_ip inet,
username text,
password text,
client_version text,
connection_uuid uuid,
country varchar(2)
);
`
type PostgresStore struct {
db *sql.DB
}
func NewPostgresStore(dsn string) (*PostgresStore, error) {
db, err := sql.Open("pgx", dsn)
if err != nil {
return nil, err
}
rs := &PostgresStore{
db: db,
}
return rs, nil
}
func (s *PostgresStore) InitDB() error {
_, err := s.db.Exec(DBSchema)
return err
}
func (s *PostgresStore) AddAttempt(l *models.LoginAttempt) error {
stmt := `INSERT INTO
login_attempts(date, remote_ip, username, password, client_version, connection_uuid, country)
VALUES ($1, $2, $3, $4, $5, $6, $7)
RETURNING id;`
tx, err := s.db.Begin()
if err != nil {
return err
}
defer tx.Rollback() // nolint: errcheck
2021-04-10 05:58:01 +00:00
var id int
if err := tx.QueryRow(stmt, l.Date, l.RemoteIP.String(), l.Username, l.Password, l.SSHClientVersion, l.ConnectionUUID, l.Country).Scan(&id); err != nil {
return err
}
l.ID = id
2021-04-10 07:33:11 +00:00
return tx.Commit()
2021-04-10 05:58:01 +00:00
}
2022-08-26 10:21:52 +00:00
func (s *PostgresStore) All() (<-chan models.LoginAttempt, error) {
2021-04-10 05:58:01 +00:00
stmt := `SELECT date, remote_ip, username, password, client_version, connection_uuid, country FROM login_attempts`
2021-04-10 07:33:11 +00:00
rows, err := s.db.Query(stmt)
2021-04-10 05:58:01 +00:00
if err != nil {
return nil, err
}
2022-08-26 10:21:52 +00:00
ch := make(chan models.LoginAttempt)
go func() {
defer rows.Close()
for rows.Next() {
var a models.LoginAttempt
var ip string
if err := rows.Scan(&a.Date, &ip, &a.Username, &a.Password, &a.SSHClientVersion, &a.SSHClientVersion, &a.Country); err != nil {
panic(err)
}
a.RemoteIP = net.ParseIP(ip)
ch <- a
2021-04-10 05:58:01 +00:00
}
2022-08-26 10:21:52 +00:00
close(ch)
}()
2021-04-10 05:58:01 +00:00
2022-08-26 10:21:52 +00:00
return ch, nil
2021-04-10 05:58:01 +00:00
}
func (s *PostgresStore) Stats(statType LoginStats, limit int) ([]StatsResult, error) {
var stmt string
if statType == LoginStatsTotals {
return s.statsTotal(limit)
}
switch statType {
case LoginStatsCountry:
2021-04-10 10:07:11 +00:00
stmt = `select country, count(country) from login_attempts group by country order by count desc`
2021-04-10 05:58:01 +00:00
case LoginStatsIP:
2021-04-10 10:07:11 +00:00
stmt = `select remote_ip, count(remote_ip) from login_attempts group by remote_ip order by count desc`
2021-04-10 05:58:01 +00:00
case LoginStatsPasswords:
2021-04-10 10:07:11 +00:00
stmt = `select password, count(password) from login_attempts group by password order by count desc`
2021-04-10 05:58:01 +00:00
case LoginStatsUsername:
2021-04-10 10:07:11 +00:00
stmt = `select username, count(username) from login_attempts group by username order by count desc`
2021-04-10 13:18:55 +00:00
default:
return nil, fmt.Errorf("invalid stat type")
2021-04-10 05:58:01 +00:00
}
if limit > 0 {
stmt = fmt.Sprintf("%s limit %d", stmt, limit)
}
rows, err := s.db.Query(stmt)
if err != nil {
return nil, err
}
defer rows.Close()
var results []StatsResult
for rows.Next() {
var r StatsResult
if err := rows.Scan(&r.Name, &r.Count); err != nil {
return nil, err
}
results = append(results, r)
}
return results, nil
}
2021-11-05 23:41:27 +00:00
func (s *PostgresStore) IsHealthy() error {
if err := s.db.Ping(); err != nil {
return ErrStoreUnhealthy
}
return nil
2021-11-05 23:37:28 +00:00
}
2021-04-10 05:58:01 +00:00
func (s *PostgresStore) statsTotal(limit int) ([]StatsResult, error) {
2021-04-10 06:26:03 +00:00
uniquePasswordStmt := `select count(*) from (select distinct password from login_attempts) as temp`
uniqueUsernameStmt := `select count(*) from (select distinct username from login_attempts) as temp`
uniqueIPStmt := `select count(*) from (select distinct remote_ip from login_attempts) as temp`
uniqueCountryStmt := `select count(*) from (select distinct country from login_attempts) as temp`
attemptsCountStmt := `select count(1) from login_attempts`
var uniquePasswordsCount int
if err := s.db.QueryRow(uniquePasswordStmt).Scan(&uniquePasswordsCount); err != nil {
return nil, err
}
var uniqueUsernameCount int
if err := s.db.QueryRow(uniqueUsernameStmt).Scan(&uniqueUsernameCount); err != nil {
return nil, err
}
var uniqueIPCount int
if err := s.db.QueryRow(uniqueIPStmt).Scan(&uniqueIPCount); err != nil {
return nil, err
}
var uniqueCountryCount int
if err := s.db.QueryRow(uniqueCountryStmt).Scan(&uniqueCountryCount); err != nil {
return nil, err
}
var attemptsCount int
if err := s.db.QueryRow(attemptsCountStmt).Scan(&attemptsCount); err != nil {
return nil, err
}
return []StatsResult{
{Name: "UniquePasswords", Count: uniquePasswordsCount},
{Name: "UniqueUsernames", Count: uniqueUsernameCount},
{Name: "UniqueIPs", Count: uniqueIPCount},
{Name: "UniqueCountries", Count: uniqueCountryCount},
{Name: "TotalLoginAttempts", Count: attemptsCount},
}, nil
2021-04-10 05:58:01 +00:00
}
2021-04-13 05:30:07 +00:00
func (s *PostgresStore) Query(query AttemptQuery) ([]models.LoginAttempt, error) {
var stmt string
2021-04-14 15:55:44 +00:00
queryString := query.Query
2021-04-13 05:30:07 +00:00
const limit = 10000
2021-04-13 05:30:07 +00:00
switch query.QueryType {
case AttemptQueryTypeIP:
stmt = `SELECT id, date, remote_ip, username, password, client_version, connection_uuid, country
FROM login_attempts WHERE remote_ip = $1 order by date desc limit $2`
2021-04-13 05:30:07 +00:00
case AttemptQueryTypePassword:
stmt = `SELECT id, date, remote_ip, username, password, client_version, connection_uuid, country
FROM login_attempts WHERE password = $1 order by date desc limit $2`
2021-04-13 05:30:07 +00:00
case AttemptQueryTypeUsername:
stmt = `SELECT id, date, remote_ip, username, password, client_version, connection_uuid, country
FROM login_attempts WHERE username = $1 order by date desc limit $2`
2021-04-13 05:30:07 +00:00
default:
2021-09-17 00:01:43 +00:00
return nil, fmt.Errorf("invalid query type")
2021-04-13 05:30:07 +00:00
}
rows, err := s.db.Query(stmt, queryString, limit)
2021-04-13 05:30:07 +00:00
if err != nil {
2021-09-17 00:01:43 +00:00
return nil, fmt.Errorf("unable to query database: %w", err)
2021-04-13 05:30:07 +00:00
}
defer rows.Close()
var results []models.LoginAttempt
for rows.Next() {
var la models.LoginAttempt
2021-04-14 16:01:11 +00:00
var ipString string
if err := rows.Scan(&la.ID, &la.Date, &ipString, &la.Username, &la.Password, &la.SSHClientVersion, &la.ConnectionUUID, &la.Country); err != nil {
2021-09-17 00:01:43 +00:00
return nil, fmt.Errorf("unable to unmarshal data from database: %w", err)
2021-04-13 05:30:07 +00:00
}
2021-04-14 16:01:11 +00:00
la.RemoteIP = net.ParseIP(ipString)
2021-04-13 05:30:07 +00:00
results = append(results, la)
}
return results, nil
}