• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 317
  • Last Modified:

Authentication failing when using Powershell to connect to DB2 database

I have a PowerShell script that am using to connect to a DB2 database.

The script has the credentials hard coded at this point, and everything works fine.

I am trying to encrypt the password and call the encrypted password from a file, using get-content in PowerShell and converting to a secure string. Then sending the secure string to the database.

When I try with the encrypted method it gives me an authentication error.

 "ERROR [08001] [IBM][CLI Driver] SQL30082N  Security processing failed
ith reason "24" ("USERNAME AND/OR PASSWORD INVALID").  SQLSTATE=08001"

Can someone please advise how to properly authenticate to a database using this or a similar method to call the plain text encrypted password, to a secure string, and then to the database.

---------EXAMPLE--------------------

Before with plain text password, which works.


$datasource = "database server"
$user = "username"
$pwd = "plaintextpassword"
$connectionString = "Server=$dataSource;uid=$user; pwd=$pwd;Database=$database;Integrated Security=False;"

$query  = "random database query"


$connection = New-Object System.Data.odbc.odbcconnection
$connection.ConnectionString = "DSN=$dataSource;Uid=$user;Pwd=$pwd"
$connection.Open()
$command = $connection.CreateCommand()
$command.CommandText = $query

$result = $command.ExecuteReader()

$table = new-object "System.Data.DataTable"
$table.Load($result)

$format = @{Expression={random table data}
}

$table | Export-CSV C:\folder\output.csv -notype

$connection.Close()



After using encrypted password, which does not work.

$datasource = "database server"
$user = "username"
$pwd = Get-Content "C:\folder\encrypted.txt | ConvertTo-SecureString
$database = "Database_name"
$connectionString = "Server=$dataSource;uid=$user; pwd=$pwd;Database=$database;Integrated Security=False;"

$query  = "random database query"


$connection = New-Object System.Data.odbc.odbcconnection
$connection.ConnectionString = "DSN=$dataSource;Uid=$user;Pwd=$pwd"
$connection.Open()
$command = $connection.CreateCommand()
$command.CommandText = $query

$result = $command.ExecuteReader()

$table = new-object "System.Data.DataTable"
$table.Load($result)

$format = @{Expression=random table data}

$table | Export-CSV C:\folder\output.csv -notype

$connection.Close()
0
cmoerbe
Asked:
cmoerbe
  • 4
  • 2
2 Solutions
 
oBdACommented:
This allows you to save the password directly in the script itself, as "Alternate Data Stream".
The password can only be retrieved on the machine where it was saved, and only from the user who saved it.
Call the script with the argument -SaveCredential to save the credentials.
It's currently in test mode (lines 40-43) and will only display the logon information, then exit.
Note that some Editors (like Notepad++) remove ADS on saving, others do not (like Notepad).
The ADS will be copied as long as the target is NTFS, and will be lost otherwise.

[CmdletBinding()]
Param(
	[switch]$SaveCredential
)
$DataSource = "database server"
$DefaultUser = "username"

$ScriptItem = Get-Item -Path $MyInvocation.MyCommand.Path
$StreamName = 'MetaData'
If ($SaveCredential) {
	$gcArgs = @{'Message' = "ODBC logon information for $($DataSource)"}
	$gcArgs['User'] = Try {([Management.Automation.PSSerializer]::Deserialize((Get-Content -Path $ScriptItem.FullName -Stream $StreamName -ErrorAction SilentlyContinue))).UserName} Catch {$DefaultUser}
	If ($Credential = Get-Credential @gcArgs) {
		Try {
			$LastWriteTimeUtc = $ScriptItem.LastWriteTimeUtc
			Set-Content -Path $ScriptItem.FullName -Value ([Management.Automation.PSSerializer]::Serialize($Credential)) -Stream $StreamName -ErrorAction Stop
			$ScriptItem.LastWriteTimeUtc = $LastWriteTimeUtc
		} Catch {
			Throw "Could not save credentials: $($_.Exception.Message)"
		}
	} Else {
		"No credentials were entered, logon information was not saved!" | Write-Warning
	}
	Exit
} Else {
	If ($StreamData = (Get-Content -Path $ScriptItem.FullName -Stream $StreamName -ErrorAction SilentlyContinue)) {
		Try {
			$Credential = [Management.Automation.PSSerializer]::Deserialize($StreamData)
		} Catch {
			Throw "You are not authorized to use this script."
		}
	} Else {
		Throw "File is corrupted, password information is not available."
	}
}

$Username = $Credential.UserName
$Password = $Credential.GetNetworkCredential().Password

##### REMOVE AFTER TESTING #########################
"Username '$($UserName)', password '$($Password)'" #
EXIT                                               #
##### REMOVE AFTER TESTING #########################

$connectionString = "Server=$dataSource;uid=$Username;pwd=$Password;Database=$database;Integrated Security=False;"

$query  = "random database query"


$connection = New-Object System.Data.odbc.odbcconnection
$connection.ConnectionString = "DSN=$dataSource;Uid=$Username;Pwd=$Password"
$connection.Open()
$command = $connection.CreateCommand()
$command.CommandText = $query

$result = $command.ExecuteReader()

$table = new-object "System.Data.DataTable"
$table.Load($result)

$format = @{Expression={random table data}
}

$table | Export-CSV C:\folder\output.csv -notype

$connection.Close()

Open in new window

0
 
cmoerbeAuthor Commented:
Thank you, very much!

Please allow me a moment to test this out.
0
 
cmoerbeAuthor Commented:
I tried commenting everything out below line 44 to just test storing and retrieving the credentials.

It prompts for the credentials and exits, but does not display them back before exit. No errors generated either. Unable to determine if it saved them or not. It is NTFS and only using notepad to work with the file before .ps1.

Any thoughts?
0
Transaction-level recovery for Oracle database

Veeam Explore for Oracle delivers low RTOs and RPOs with agentless transaction log backup and transaction-level recovery of Oracle databases. You can restore the database to a precise point in time, even to a specific transaction.

 
oBdACommented:
the EXIT in line 42 will currently prevent the rest of the script running, no need to uncomment it.
You call the script once with -SaveCredentials; it will prompt for the credentials and store them.
Then you call the script again without arguments, and it should print the stored username and password.
If you call the script without arguments while no credentials are stored, you'll get an error message.
0
 
cmoerbeAuthor Commented:
Works like a champ! Thanks for providing this alternate solution. I do prefer it to my original plan.

Best regards
0
 
cmoerbeAuthor Commented:
Thank you again for the assistance
0

Featured Post

A Cyber Security RX to Protect Your Organization

Join us on December 13th for a webinar to learn how medical providers can defend against malware with a cyber security "Rx" that supports a healthy technology adoption plan for every healthcare organization.

  • 4
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now