Solved

Authentication failing when using Powershell to connect to DB2 database

Posted on 2016-11-02
6
108 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
Netscaler Common Configuration How To guides

If you use NetScaler you will want to see these guides. The NetScaler How To Guides show administrators how to get NetScaler up and configured by providing instructions for common scenarios and some not so common ones.

 
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

Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Admin account lockout 10 39
Review of apps API SSL Cert policy 2 21
Exchange 2013 - Script needed 7 36
Power shell Script - Help v2 7 21
The following article is intended as a guide to using PowerShell as a more versatile and reliable form of application detection in SCCM.
Data breaches are on the rise, and companies are preparing by boosting their cybersecurity budgets. According to the Cybersecurity Market Report (http://www.cybersecurityventures.com/cybersecurity-market-report), worldwide spending on cybersecurity …
Nobody understands Phishing better than an anti-spam company. That’s why we are providing Phishing Awareness Training to our customers. According to a report by Verizon, only 3% of targeted users report malicious emails to management. With compan…
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…

778 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