Solved

Authentication failing when using Powershell to connect to DB2 database

Posted on 2016-11-02
6
63 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 83

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
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
LVL 83

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

Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

Join & Write a Comment

Article by: btan
Provide an easy one stop to quickly get the relevant information on common asked question on Ransomware in Expert Exchange.
This article explains in simple steps how to renew expiring Exchange Server Internal Transport Certificate.
Sending a Secure fax is easy with eFax Corporate (http://www.enterprise.efax.com). First, Just open a new email message.  In the To field, type your recipient's fax number @efaxsend.com. You can even send a secure international fax — just include t…
When you create an app prototype with Adobe XD, you can insert system screens -- sharing or Control Center, for example -- with just a few clicks. This video shows you how. You can take the full course on Experts Exchange at http://bit.ly/XDcourse.

747 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

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now