How to Create a TCP Client connection with a Client Certificate in Powershell - ssl

With Following code i can establish a SSL Connection:
$cert = dir cert:\CurrentUser\My | where {$_.Subject -like "*Alice*"}
$computerName = "google.com"
$port = "443"
$socket = New-Object Net.Sockets.TcpClient($computerName, $port)
$stream = $socket.GetStream()
$sslStream = New-Object System.Net.Security.SslStream $stream,$false
$sslStream.AuthenticateAsClient($computerName)
$sslStream
This Works fine. But now i wan't to add a Client Certificate for Authentication.
Think i just need to substitute
$sslStream.AuthenticateAsClient($computerName)
with
$sslStream.BeginAuthenticateAsClient($computerName,$cert,"SslProtocols",$false,"Foo" ,"Bar")
But i wasn't lucky to get the Arguments right. Can Sombody solve the Assync Calls please ;-)
Maybe i need some C# code for this?!?
Arguments are:
System.IAsyncResult BeginAuthenticateAsClient(
string targetHost,
System.Security.Cryptography.X509Certificates.X509CertificateCollection clientCertificates,
System.Security.Authentication.SslProtocols enabledSslProtocols,
bool checkCertificateRevocation,
System.AsyncCallback asyncCallback,
System.Object asyncState)
What i finally want to achieve is to list and later specify the CipherSuites the client is connected to. (I could use Wireshark i know ;-) )

Finally got it working, wasnt argument 4 but the $Cert which was no collection.
$cert = dir cert:\CurrentUser\My | where {$_.Subject -like "*alice*"}
$computerName = "google.com"
$port = "443"
[System.Security.Authentication.SslProtocols]$protocol = "ssl3"
$certcol = New-object System.Security.Cryptography.X509Certificates.X509CertificateCollection
$certcol.Add($cert)
$socket = New-Object Net.Sockets.TcpClient($computerName, $port)
$stream = $socket.GetStream()
$sslStream = New-Object System.Net.Security.SslStream $stream,$false
#$sslStream.AuthenticateAsClient($computerName)
$sslStream.AuthenticateAsClient($computerName,$certcol,$protocol,$false)
$sslStream

According to the documentation, the difference between AuthenticateAsClient and BeginAuthenticateAsClient is that the latter is for asynchronous use.
You should try AuthenticateAsClient(String, X509CertificateCollection, SslProtocols, Boolean), where the second argument is a collection of client certificates that can be used (preferably X509Certificate2, since you'll need the private key associated with the certificate for it to be usable for authentication).

Related

Powershell Salesforce SOAP API SessionHeader Type Converion Issue

Hi I am having trouble setting the SessionHeaderValue. I am basing my code on c#.Net. The login works and I receive the serviceUrl and sessionId in the login result but I can't get the session Id set in the session header
Here is the code
$uri = "c:\installs\sforce.wsdl"
$username = "username"
$password = "password"
# Proxy
$service = New-WebServiceProxy -Uri $uri -Namespace sforce -UseDefaultCredential
# Login
$loginResult = $service.login($username, $password)
$service.Url = $loginResult.serverUrl
$service.SessionHeaderValue = New-Object sforce.SessionHeader
This is the error I get which is a bit odd.
Exception setting "SessionHeaderValue": "Cannot convert the "sforce.SessionHeader" value of type "sforce.SessionHeader" to type "sforce.SessionHeader"."
I have been playing with this for a few hours now and have run out of ideas.
Any help is appreciated.
Anthony
The real problem is that you can't reuse $service. Your instance of $service is only good for the login, and that's it. I think it's due to the way New-WebServiceProxy works. Check this little script out:
$uri = 'file://C:\projects\CRM\SalesForce\Integration\enterprise.xml'
$api = new-webserviceproxy -uri $uri -NameSpace SalesForce
$api.GetType().Module.Assembly.ManifestModule.ScopeName
$api = new-object SalesForce.SforceService.ScopeName
$api.GetType().Module.Assembly.ManifestModule
If you were to run this script, (of course you'd need to substitute your own WSDL), you'd see something like this (the DLLs are dynamic, so the names will be different):
mhgl0l5w.dll
vzecopaq.dll
Notice that not only are the object references for $api different, but the dynamic assembly that New-WebServiceProxy creates is different for each one, which isn't what you might expect. That's why your cast is failing; your objects with the same name are different because they come from different dynamic assemblies. I'm not sure why the behavior is this way - if it's a peculiarity of New-WebServiceProxy, or somehow in SalesForce's WSDL.
The solution is actually pretty simple. Recreate your service object off the namespace generated by New-WebServiceProxy like so:
$uri = "c:\installs\sforce.wsdl"
$username = "username"
$password = "password"
# Proxy
$service = New-WebServiceProxy -Uri $uri -Namespace sforce -UseDefaultCredential
# Login
$loginResult = $service.login($username, $password)
$service = New-Object sforce.SforceService
$service.Url = $loginResult.serverUrl
$service.SessionHeaderValue = New-Object sforce.SessionHeader
I found a webpage that implies the the $service.SessionHeaderValue instance should be created using something like:
$service.SessionHeaderValue = New-ObjectFromProxy -proxy $service -proxyAttributeName "SessionHeaderValue" -typeName "SessionHeader"
There was a definition for the New-ObjectFromProxy function in PowerShell + SOAP + AuthenticationInfoValue:
function New-ObjectFromProxy {
param($proxy, $proxyAttributeName, $typeName)
# Locate the assembly for $proxy
$attribute = $proxy | gm | where { $_.Name -eq $proxyAttributeName }
$str = "`$assembly = [" + $attribute.TypeName + "].assembly"
invoke-expression $str
# Instantiate an AuthenticationHeaderValue object.
$type = $assembly.getTypes() | where { $_.Name -eq $typeName }
return $assembly.CreateInstance($type)
}
I don't profess to be a powershell expert, but it appears the instance of the object that New-Object creates isn't really the same type that the proxy object is expecting. Confusingly, they do have the same name.
It's also worth noting that you cannot define a web service proxy twice for the same namespace. This is required for a flow where you need to go to SOAP API to login, then pass the session id to the metadata API to make your requests.
Compare:
$LoginResponse = $sf.login($username, $password)
$newSession = $LoginResponse.sessionId
$newURL = $LoginResponse.serverUrl
$service = New-Object sforce.SforceService
$service.Url = $LoginResponse.serverUrl
$service.SessionHeaderValue = New-Object sforce.SessionHeader
$service.SessionHeaderValue.sessionId = $LoginResponse.sessionId
# Set the batch size to 2000
# Though, if it contains two long text area fields, it will set it as 200
# This is to avoid long SOAP messages and is controlled by SF
$service.QueryOptionsValue = new-Object sforce.QueryOptions
$service.QueryOptionsValue.batchSize = 2000
$service.QueryOptionsValue.batchSizeSpecified = $true
$mdservice= new-WebServiceProxy -URI $mdwsdl -Namespace sforce
$mdservice = New-Object sforce.MetadataService
$mdservice.Url = $LoginResponse.metadataServerUrl
$mdservice.SessionHeaderValue = New-Object sforce.SessionHeader
$mdservice.SessionHeaderValue.sessionId = $LoginResponse.sessionId
This will generate the following error:
"sforce.SessionHeader" to type "sforce.SessionHeader"."
At line:22 char:5
+ $mdservice.SessionHeaderValue = New-Object sforce.SessionHeader
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], SetValueInvocationException
+ FullyQualifiedErrorId : ExceptionWhenSetting
The property 'sessionId' cannot be found on this object. Verify that the property exists and can be set.
At line:23 char:5
+ $mdservice.SessionHeaderValue.sessionId = $LoginResponse.sessionI ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : PropertyNotFound
Whereas the below code will not error:
$sf = new-WebServiceProxy -URI $pwsdl -Namespace sforce
$LoginResponse = $sf.login($username, $password)
$newSession = $LoginResponse.sessionId
$newURL = $LoginResponse.serverUrl
$service = New-Object sforce.SforceService
$service.Url = $LoginResponse.serverUrl
$service.SessionHeaderValue = New-Object sforce.SessionHeader
$service.SessionHeaderValue.sessionId = $LoginResponse.sessionId
# Set the batch size to 2000
# Though, if it contains two long text area fields, it will set it as 200
# This is to avoid long SOAP messages and is controlled by SF
$service.QueryOptionsValue = new-Object sforce.QueryOptions
$service.QueryOptionsValue.batchSize = 2000
$service.QueryOptionsValue.batchSizeSpecified = $true
$mdservice= new-WebServiceProxy -URI $mdwsdl #Don't set namespace here
# Notice that we are getting the namespace dynamically
$type = $mdservice.GetType().NameSpace
$mdservice = New-Object ($type + '.MetadataService')
$mdservice.Url = $LoginResponse.metadataServerUrl
$mdservice.SessionHeaderValue = New-Object ($type + '.SessionHeader')
$mdservice.SessionHeaderValue.sessionId = $LoginResponse.sessionId
Exception setting "SessionHeaderValue": "Cannot convert the "sforce.SessionHeader" value of type "sforce.SessionHeader" to type "sforce.SessionHeader"."
$service.SessionHeaderValue = New-Object sforce.SessionHeader
After New-Object you have to specify the correct class name. Try this:
#Login to Salesforce
$loginResults = $service.login($username,$password)
#set the session Id in partner Object
$service.Url = $loginResults.serverUrl
$sessionHeaderObjClassName = ($service.GetType().FullName) -replace "SforceService","SessionHeader"
$service.SessionHeaderValue = New-Object $sessionHeaderObjClassName
$service.SessionHeaderValue.sessionId = $loginResults.sessionId

Upload a file to Sharepoint 2010 with powershell 2.0

I'm struggling since a couple of days to upload files to Sharepoint 2010 with powershell.
I'm on a win7 machine with powershell v2 trying to upload to a SP 2010 site.
I'm having 2 major issues
$Context.web value is always empty even after Executequery() and no
error is shown. My $Context variable gets the server version (14.x.x.x.x) but nothing more
$Context.Load($variable) which always returns the error Cannot find an overload for "Load" and the argument count: "1".
I copied Sharepoint DLLs to my Win7 machine and I import the reference to my script.
The below script is a mix of many parts I took from the net.
I'v already tried unsuccessfully to add an overload on the clientcontext defining Load method without Type parameter suggested in the following post
http://soerennielsen.wordpress.com/2013/08/25/use-csom-from-powershell/
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client")
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client.Runtime")
$site = "https://Root-of-my-site"
$listname = "My-folder"
$context = New-Object Microsoft.SharePoint.Client.ClientContext($site)
[Microsoft.SharePoint.Client.Web]$web = $context.Web
[Microsoft.SharePoint.Client.List]$list = $web.Lists.GetByTitle($listName)
$Folder = "C:\temp\Certificates"
$List = $Context.Web.Lists.GetByTitle($listname)
Foreach ($File in (dir $Folder))
{
$FileCreationInfo = New-Object Microsoft.SharePoint.Client.FileCreationInformation
$FileCreationInfo.Overwrite = $true
$FileCreationInfo.Content = get-content -encoding byte -path $File.Fullname
$FileCreationInfo.URL = $File
$Upload = $List.RootFolder.Files.Add($FileCreationInfo)
$Context.Load($Upload)
$Context.ExecuteQuery()
}
The error is
Cannot find an overload for "Load" and the argument count: "1".
At C:\temp\uploadCertToSharepoint.ps1:48 char:14
+ $Context.Load <<<< ($Upload)
+ CategoryInfo : NotSpecified: (:) [], MethodException
+ FullyQualifiedErrorId : MethodCountCouldNotFindBest
Can someone please help me sorting this issue?
I'll need to upload around 400 files with ad-hoc fields to a sharepoint site in a couple of weeks and at the moment I'm completely stuck. Running the script server side is unfortunately not possible.
Thanks,
Marco
This error occurs since ClientRuntimeContext.Load is a Generics Method:
public void Load<T>(
T clientObject,
params Expression<Func<T, Object>>[] retrievals
)
where T : ClientObject
and Generics methods are not supported natively in PowerShell (V1, V2) AFAIK.
The workaround is to invoke a generic methods using MethodInfo.MakeGenericMethod method as described in article Invoking Generic Methods on Non-Generic Classes in PowerShell
In case of ClientRuntimeContext.Load method, the following PS function could be used:
Function Invoke-LoadMethod() {
param(
$clientObjectInstance = $(throw “Please provide an Client Object instance on which to invoke the generic method”)
)
$ctx = $clientObjectInstance.Context
$load = [Microsoft.SharePoint.Client.ClientContext].GetMethod("Load")
$type = $clientObjectInstance.GetType()
$clientObjectLoad = $load.MakeGenericMethod($type)
$clientObjectLoad.Invoke($ctx,#($clientObjectInstance,$null))
}
Then, in your example the line:
$Context.Load($Upload)
could be replaced with this one:
Invoke-LoadMethod -clientObjectInstance $Upload
References
Invoking Generic Methods on Non-Generic Classes in PowerShell
Some tips and tricks of using SharePoint Client Object Model in
PowerShell. Part 1
It throws the error because in powershell 2.0 you cannot call generic method directly.
You need to create closed method using MakeGenericMethod. Try to use code below.
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client")
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client.Runtime")
$site = "http://server"
$listname = "listName"
$Folder = "C:\PS\Test"
$context = New-Object Microsoft.SharePoint.Client.ClientContext($site)
[Microsoft.SharePoint.Client.Web]$web = $context.Web
[Microsoft.SharePoint.Client.List]$list = $web.Lists.GetByTitle($listName)
$method = $Context.GetType().GetMethod("Load")
$closedMethod = $method.MakeGenericMethod([Microsoft.SharePoint.Client.File])
Foreach ($File in (dir $Folder))
{
$FileCreationInfo = New-Object Microsoft.SharePoint.Client.FileCreationInformation
$FileCreationInfo.Overwrite = $true
$FileCreationInfo.Content = (get-content -encoding byte -path $File.Fullname)
$FileCreationInfo.URL = $File
$Upload = $List.RootFolder.Files.Add($FileCreationInfo)
$closedMethod.Invoke($Context, #($Upload, $null) )
$Context.ExecuteQuery()
}

How to test authentication to remote IP address

I have one powershell script that invokes another powershell script.
The first script is invoked with an ip address, which gets passed to the second script. The second script is supposed to return the userId in form Domain\User
The first script uses ProcessStartInfo and Process to get elevated credentials to call the second script
# part of first script
$startInfo = New-Object System.Diagnostics.ProcessStartInfo
$startInfo.FileName = "powershell.exe"
$startInfo.Arguments = "C:\script\second_script.ps1 "
$startInfo.RedirectStandardOutput = $true
$startInfo.UseShellExecute = $false
$startInfo.CreateNoWindow = $false
$startInfo.Username = Service_Account
$startInfo.Domain = Domain
$startInfo.Password = password
$process = New-Object System.Diagnostics.Process
$process.StartInfo = $startInfo
$process.Start() | Out-Null
$standardOut = $process.StandardOutput.ReadToEnd()
$process.WaitForExit()
The second script has many try-catch blocks, such as checking whether we can ping the machine, checking whether we can access WMI
# part of second
# Can we ping the machine?
try{
Test-Connection $Sender_IP -count 1 -ErrorAction Stop | out-null
}
catch [Exception]
{
$userId = "Unknown/CannotPing "
return $output = "userId=" + $userId
}
try
{
<#Gather information on the computer corresponding to $Sender_IP#>
$Win32OS = Get-WmiObject -Class Win32_OperatingSystem -ComputerName $Sender_IP -ErrorAction Stop
}
catch [Exception]
{
$userId = "Unknown/CannotDetectOS "
return $output = "userId=" + $userId
}
The script was unable to access WMI of many IP addresses. And when I was trying to troubleshoot by manually remoting into the IP address with the service account, I was unable to.
Now, I am trying to figure out a way for the script to check whether it can authenticate to the IP address. If the script is unable to authenticate to the IP address, it should throw and exception and not even check whether it can access WMI.
What cmdlets can help with this?

System.DirectoryServices.DirectorySearcher works if called from PowerShell but not if called from cmd.exe

I wrote an script for PowerShell 1.0 (now using 2.0) that executes a search on my Active Directory. The code is the following:
$filter = "some filter"
$rootEntry = New-Object System.DirectoryServices.DirectoryEntry
$searcher = New-Object System.DirectoryServices.DirectorySearcher
$searcher.SearchRoot = $rootEntry
$searcher.Filter = $filter
$searcher.SearchScope = "Subtree"
$colResults = $searcher.FindAll()
After calling FindAll() method of the DirectorySearcher instance, I print the results to see what I got.
The thing is, if I start PowerShell.exe and call the script on the prompt I'm able to see results. But if I try to call it using cmd.exe using the same filter I don't see any results. FindAll() returns an empty result set.
I'm running this on a Windows 2003 Server. It did not came with PowerShell 1.0 so I downloaded it and installed it on the server. It does have .Net Framework 2.0.
Any suggestions?
Thanks a lot.
By defaul your $rootEntry point on the root of you local AD i you are running on a server, and this with the credetial of the current process. you don't show what is your filter and how you use your result.
Here is a small sample of an ADSI search from PowerShell
Clear-Host
# ADSI Bind with current process credentials
#$dn = [adsi] "LDAP://192.168.30.200:389/dc=dom,dc=fr"
# ADSI Bind with specific credentials
$dn = New-Object System.DirectoryServices.DirectoryEntry ("LDAP://192.168.183.138:389/dc=societe,dc=fr","administrateur#societe.fr","test.2011")
# Look for users
$Rech = new-object System.DirectoryServices.DirectorySearcher($dn)
$rc = $Rech.filter = "((objectCategory=person))"
$rc = $Rech.SearchScope = "subtree"
$rc = $Rech.PropertiesToLoad.Add("distinguishedName");
$rc = $Rech.PropertiesToLoad.Add("sAMAccountName");
$rc = $Rech.PropertiesToLoad.Add("ipphone");
$rc = $Rech.PropertiesToLoad.Add("telephoneNumber");
$rc = $Rech.PropertiesToLoad.Add("memberOf");
$rc = $Rech.PropertiesToLoad.Add("distinguishedname");
$rc = $Rech.PropertiesToLoad.Add("physicalDeliveryOfficeName"); # Your attribute
$liste = $Rech.findall()
Finally got it working by doing two things:
Upgrade to PowerShell 2.0.
Run with -File option.
So the command was run like this:
>>powershell -file ./script.ps1 "dn" "uid"
I'm not sure what the difference between the -File and -Command options are (does anyone?) but it worked.
Thanks.

How can you add a Certificate to WebClient in Powershell

I wan't to examine a Webpage which requires Client Side Certificate Authentication.
How can i provide my Cert from the Certstore to the Webrequest:
Is there a way to specify this in Credentials odr within the Proxy?
$webclient = New-Object Net.WebClient
# The next 5 lines are required if your network has a proxy server
$webclient.Credentials = [System.Net.CredentialCache]::DefaultCredentials
if($webclient.Proxy -ne $null) {
$webclient.Proxy.Credentials = `
[System.Net.CredentialCache]::DefaultNetworkCredentials
}
# This is the main call
$output = $webclient.DownloadString("$URL")
PS: Maybe this helps: How can you add a Certificate to WebClient (C#)? But i don't get it.. ;-)
Using the new Add-Type functionality in PowerShell v2, you can craft a custom class that you can then use to make your typical WebRequest. I have included a method on the custom class to allow you to add certificates that can be used for authentication.
PS C:\> $def = #"
public class ClientCertWebClient : System.Net.WebClient
{
System.Net.HttpWebRequest request = null;
System.Security.Cryptography.X509Certificates.X509CertificateCollection certificates = null;
protected override System.Net.WebRequest GetWebRequest(System.Uri address)
{
request = (System.Net.HttpWebRequest)base.GetWebRequest(address);
if (certificates != null)
{
request.ClientCertificates.AddRange(certificates);
}
return request;
}
public void AddCerts(System.Security.Cryptography.X509Certificates.X509Certificate[] certs)
{
if (certificates == null)
{
certificates = new System.Security.Cryptography.X509Certificates.X509CertificateCollection();
}
if (request != null)
{
request.ClientCertificates.AddRange(certs);
}
certificates.AddRange(certs);
}
}
"#
PS C:\> Add-Type -TypeDefinition $def
You would perhaps want to limit the certificates being added to just the one (or ones) you would want to use rather than just use every available certificate in the Current User store, but here is an example that just loads all of them:
PS C:\> $wc = New-Object ClientCertWebClient
PS C:\> $certs = dir cert:\CurrentUser\My
PS C:\> $wc.AddCerts($certs)
PS C:\> $wc.DownloadString("http://stackoverflow.com")