#!/bin/bash set -e # Colors for output GREEN='\033[0;32m' RED='\033[0;31m' NC='\033[0m' # No Color YELLOW='\033[0;33m' # Yellow echo -e "${GREEN}[Postgre-TLS] Testing SSL connection to PostgreSQL...${NC}" # Load password PASSWORD=$([ -f secrets/postgres_password ] && cat secrets/postgres_password || echo "change_me_in_production") export PGPASSWORD="$PASSWORD" # Test basic connection OUTPUT=$(psql "host=localhost port=5432 dbname=postgre_tls user=postgre_tls_user sslmode=verify-full sslrootcert=secrets/ca.crt" \ -c "SELECT version(), current_user, current_database();" -t) || { echo -e "${RED}[Postgre-TLS] Connection failed!${NC}" exit 1 } echo "$OUTPUT" # Check SSL details echo -e "\n${GREEN}[Postgre-TLS] SSL Connection Details:${NC}" SSL_DETAILS=$(psql "host=localhost port=5432 dbname=postgre_tls user=postgre_tls_user sslmode=verify-full sslrootcert=secrets/ca.crt" \ -c "SELECT ssl, version as ssl_version, cipher as ssl_cipher, bits as ssl_bits FROM pg_stat_ssl WHERE pid = pg_backend_pid();" -t) || { echo -e "${RED}[Postgre-TLS] Failed to get SSL details!${NC}" exit 1 } echo "$SSL_DETAILS" # Test non-SSL connection (should fail) echo -e "\n${YELLOW}[Postgre-TLS] Testing non-SSL connection (expected to fail):${NC}" psql "host=localhost port=5432 dbname=postgre_tls user=postgre_tls_user sslmode=disable" -c "SELECT 1;" 2>&1 | grep "SSL" || echo -e "${GREEN}Non-SSL connection correctly refused.${NC}" # Advanced database operations over SSL echo -e "\n${GREEN}[Postgre-TLS] Performing advanced tests over SSL:${NC}" # Create test table psql "host=localhost port=5432 dbname=postgre_tls user=postgre_tls_user sslmode=verify-full sslrootcert=secrets/ca.crt" -c "CREATE TABLE IF NOT EXISTS test_table (id SERIAL PRIMARY KEY, data TEXT);" || { echo -e "${RED}Failed to create test table!${NC}"; exit 1; } echo "Test table created." # Insert data psql "host=localhost port=5432 dbname=postgre_tls user=postgre_tls_user sslmode=verify-full sslrootcert=secrets/ca.crt" -c "INSERT INTO test_table (data) VALUES ('Hello, SSL World!');" || { echo -e "${RED}Failed to insert data!${NC}"; exit 1; } echo "Data inserted." # Query data QUERY_RESULT=$(psql "host=localhost port=5432 dbname=postgre_tls user=postgre_tls_user sslmode=verify-full sslrootcert=secrets/ca.crt" -c "SELECT data FROM test_table WHERE id = (SELECT MAX(id) FROM test_table);" -t) || { echo -e "${RED}Failed to query data!${NC}"; exit 1; } echo "Queried data: $QUERY_RESULT" # Drop test table psql "host=localhost port=5432 dbname=postgre_tls user=postgre_tls_user sslmode=verify-full sslrootcert=secrets/ca.crt" -c "DROP TABLE test_table;" || { echo -e "${RED}Failed to drop test table!${NC}"; exit 1; } echo "Test table dropped." # Check if all tests passed if [ $? -eq 0 ]; then echo -e "\n${GREEN}[Postgre-TLS] All advanced SSL connection tests successful!${NC}" else echo -e "\n${RED}[Postgre-TLS] Advanced tests failed!${NC}" exit 1 fi