Solved

Authentication failing when using Powershell to connect to DB2 database

Posted on 2016-11-02
6
127 Views
Last Modified: 2016-11-04
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
Comment
Question by:cmoerbe
  • 4
  • 2
6 Comments
 
LVL 84

Accepted Solution

by:
oBdA earned 500 total points
ID: 41871073
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
 

Author Comment

by:cmoerbe
ID: 41871470
Thank you, very much!

Please allow me a moment to test this out.
0
 

Author Comment

by:cmoerbe
ID: 41874288
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
Does Powershell have you tied up in knots?

Managing Active Directory does not always have to be complicated.  If you are spending more time trying instead of doing, then it's time to look at something else. For nearly 20 years, AD admins around the world have used one tool for day-to-day AD management: Hyena. Discover why

 
LVL 84

Assisted Solution

by:oBdA
oBdA earned 500 total points
ID: 41874304
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
 

Author Comment

by:cmoerbe
ID: 41874469
Works like a champ! Thanks for providing this alternate solution. I do prefer it to my original plan.

Best regards
0
 

Author Closing Comment

by:cmoerbe
ID: 41874471
Thank you again for the assistance
0

Featured Post

Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Knowing where your website is hosted is as important as the features you receive, the monthly fee, and the support you receive. Due diligence should be done when choosing your next hosting provider.
In this increasingly digital world, security hacks are no longer just a threat, but a reality. As we've witnessed with Target's big identity hack 2013, Heartbleed in 2015, and now Cloudbleed, companies and their leaders need to prepare for the unthi…
Email security requires an ever evolving service that stays up to date with counter-evolving threats. The Email Laundry perform Research and Development to ensure their email security service evolves faster than cyber criminals. We apply our Threat…
The Email Laundry PDF encryption service allows companies to send confidential encrypted  emails to anybody. The PDF document can also contain attachments that are embedded in the encrypted PDF. The password is randomly generated by The Email Laundr…

839 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question