Powershell and System.Security.Cryptography.X509Certificates.X509Certificate2 - security

i'm getting this error when i run the system.security namespace. This is what i am running after
$cert=New-Object System.Security.Cryptography.X509Certificates.X509Certificate2("C:\mycert.cer")
New-Object: Cannot find type [System.Security.Cryptography.X509Certificates.X509Certificate2("C:\mycert.cer")]: make sure the assembly containing this type is loaded.
At line:1 char:19
+ $cert = New-Object <<<<
+ CategoryInfo : InvalidType: (:) [New-Object], PSArgumentException
+ FullyQualifiedErrorId : TypeNotFound,Microsoft.PowerShell.Commands.NewObjectCommand**
What am i doing wrong?

Try running this to see if you have the System.dll loaded (should be by default):
[AppDomain]::CurrentDomain.GetAssemblies() |
Where {$_.Location -match '\\System\\'}
If it is loaded then this command should show the X509Certificate2 type:
[AppDomain]::CurrentDomain.GetAssemblies() |
Where {$_.Location -match '\\System\\'} |
%{$_.GetExportedTypes()} | Where {$_.Name -match 'X509Cert'}
If the System.dll isn't loaded (which would be odd) try loading it:
Add-Type -AssemblyName System
See: http://technet.microsoft.com/en-us/library/hh849914.aspx

FYI ... I got error:
Unable to find type [System.Security.Cryptography.x509Certificates.X509Certificate2UI]
when using:
$certSelect = [System.Security.Cryptography.x509Certificates.X509Certificate2UI]::SelectFromCollection($certCollection, $title, $msg, 0)
However, I had no error creating the collection earlier on in my script:
$certCollection = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2Collection
To make the error go away I had to include the following at some point earlier on:
Add-Type -AssemblyName System.Security

I've solved my problem. It's easily:
cd\
$cert=New-Object System.Security.Cryptography.X509Certificates.X509Certificate2("C:\mycert.cer")
cd\ is necessary

I ran into this in the ISE (but seems to apply to the normal command window too) and it seems that using autocomplete will automatically Add-Type for whatever you're looking for. If you start a new instance and run:
[AppDomain]::CurrentDomain.GetAssemblies() | grep Security
it will not return System.Security, but if you then type this and let intellisense do its thing:
[System.
You can then run this again:
[AppDomain]::CurrentDomain.GetAssemblies() | grep Security
And it will then return System.Security. So this is why you can write a script that works fine, and then revisit it later and it's broken. Using intellisense doesn't fix your script though, instead you have to add this line:
Add-Type System.Security
Or whatever library is not getting auto-added (it seems to need the dll filename, e.g. C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.1\System.Security.dll).
I'm pretty sure IseSteroids (a paid ISE add-in) can detect this, maybe others as well.

Related

Blazor WebAssembly Application fails to load due to integrity errors

We have developed a Blazor WebAssembly Application that has already gone into productive usage for a certain group of customers.
The Application works well in all Browsers with Standard Security settings. However, this morning I got a call from one of the customers, where the Application did not load at all in their Chrome Browser.
I saw the following Errors in the console:
Unknown error occurred while trying to verify integrity.
Failed to load resource: the server responded with a status of 403 (forbidden)
Failed to find a valid digest in the 'integrity' attribute for ressource '<somepath.dll>' with SHA-256 integrity <sha56>. the resource has been blocked
Now my question is, what could cause this? Is this a Browser Security setting, or another security setting e.g on server, in code etc.? How can I fix this?
Here's a picture of the errors mentioned above
The most likely reason why this is happening, is that some Antiviruses block the execution of downloaded .dll files. That's why it is working in some networks, but doesn't in some others.
What you can do, and what is also suggested as a Workaround by microsoft, is to rename all .dll to .bin - and also change the config json. it worked in my case.
I use the following PowerShell function for that:
Function Hide-BlazorDLL {
Param(
[string]$Path = (Get-Location).Path
)
<#
According to the following Links:
https://github.com/dotnet/aspnetcore/issues/19552
https://github.com/dotnet/aspnetcore/issues/5477#issuecomment-599148931
https://github.com/dotnet/aspnetcore/issues/21489
https://gist.github.com/Swimburger/774ca2b63bad4a16eb2fa23b47297e71
#>
# Test if path is correct and accessible
$WorkingDir = Join-Path $Path "_framework"
if (!(Test-Path $WorkingDir)) { Throw "Wrong path $Path. current location must be wwwroot folder of published application." }
# Get All Items
$AllItems = Get-ChildItem $WorkingDir -Recurse
$DLLs = $AllItems | Where-Object { $_.Name -like '*.dll*' }
$BINs = $AllItems | Where-Object { $_.Name -like '*.bin*' }
# End script if no .dll are found
if ($DLLs) {
# Delete all current .bin files
if ($BINs) {
Remove-item $BINs.FullName -Force
}
# Change .dll to .bin on files and config
$DLLs | Rename-item -NewName { $_.Name -replace ".dll\b",".bin" }
((Get-Content "$WorkingDir\blazor.boot.json" -Raw) -replace '.dll"','.bin"') | Set-Content "$WorkingDir\blazor.boot.json"
# Delete Compressed Blazor files
if (Test-Path "$WorkingDir\blazor.boot.json.gz") {
Remove-Item "$WorkingDir\blazor.boot.json.gz"
}
if (Test-Path "$WorkingDir\blazor.boot.json.br") {
Remove-Item "$WorkingDir\blazor.boot.json.br"
}
# Do the same for ServiceWorker, if it exists
$ServiceWorker = Get-Item "$Path\service-worker-assets.js" -ErrorAction SilentlyContinue
if ($ServiceWorker) {
((Get-Content $ServiceWorker.FullName -Raw) -replace '.dll"','.bin"') | Set-Content $ServiceWorker.FullName
Remove-Item ($ServiceWorker.FullName + ".gz")
Remove-Item ($ServiceWorker.FullName + ".br")
}
}
else {
Write-Host "There are no .dll Files to rename to .bin"
}
}
Basically you need to navigate to the wwwroot folder of your published application and run the function there. e.g:
PS D:\inetpub\wwwroot\<appname>\wwwroot> Hide-BlazorDLL
Solution for me was to delete the obj and the bin folder in both the client and the server project folder
This error for some reason kept happening for me when I tested my application in an anonymous browser window (Google Chrome).
Try using a normal browser window if you're getting integrity errors.
Also, if you're using Cloudflare CDN don't forget to "Purge Everything" in the cache.
We have experienced this issue using Cloudflare auto minify feature. That feature removes any comments from html, js and other files - which some of the blazor .js files seems to contain.
This means that the hash of the file contents no longer matches the hash found in blazor.boot.json -> an integrity issue will be thrown and stop the app from loading.
Disabling the auto minify feature fixed the issue.
Tech Stack:
.NET 6.0.11
I had a similar issue. In the local machine, it is working fine. But when it is deployed through GitHub Actions, I get integrity checks error. I got this issue for Blazor WebAssembly ASP.NET Core Hosted (WebAssemblyPrerendered) project. Here is the fix I followed.
Added the .gitattributes file to the solution root folder.
Added the below code at the end of the file.
# blazor dlls - treat all .dll files as binary
*.dll binary

"Upload of file '...' was successful, but error occurred while setting the permissions and/or timestamp" when using WinSCP .NET assembly in PowerShell

Exception calling "Check" with "0" argument(s): "Upload of file '2019-06-11.zip'
was successful, but error occurred while setting the permissions and/or
timestamp.
If the problem persists, turn off setting permissions or preserving timestamp.
Alternatively you can turn on 'Ignore permission errors' option.
Permission denied.
Error code: 3
Error message from server: This server does not support operations to modify
file attributes."
At line:12 char:84
+ $session.PutFiles("D:\Users\bin\*.zip", "/Outbox/").Check <<<< ()
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodException
I keep on getting above error file transferring file from Window Server to Linux. I got the same error when using the WinSCP GUI as well. I asked MFT team and they didn't any set permission. Below are my script for file transferring and some of intro version of software I'm using. Anything I missed out for my script or version of software is too old? I will have an update of server soon but have to wait another 2 yrs. This task will be set as scheduler to transfer file daily to MFT server.
Version of software:
Use .NET 4.0
Use PowerShell v2.0
Window Server 2008
Placed private.ppk, WinSCPNet.dll and WinSCP.exe at same folder
#Load WinSCP .NET assembly
Add-Type -Path "D:\Users\WinSCPnet.dll" -Verbose
$session = New-Object WinSCP.Session
$sessionOptions = New-Object WinSCP.SessionOptions
$sessionOptions.Protocol = [WinSCP.Protocol]::Sftp
$sessionOptions.HostName = "[Linux server IP]"
$sessionOptions.UserName = "[username]"
$sessionOptions.PortNumber = "[linux port number]"
$sessionOptions.Password = ""
$sessionOptions.SshPrivateKeyPath = "D:\Users\bin.ppk"
$sessionOptions.SshHostKeyFingerprint = "ssh-rsa 2048 ....="
try {
# Open the WinSCP.Session object using the WinSCP.SessionOptions object.
$session.Open($sessionOptions)
# Upload
$session.PutFiles("D:\Users\bin\*.zip", "/Outbox/").Check()
} finally {
# Disconnect, clean up
$session.Dispose()
}
The error is documented here:
https://winscp.net/eng/docs/message_preserve_time_perm
Your server does not support updating timestamps of uploaded remote files. So you need to instruct WinSCP not to attempt it:
$transferOptions = New-Object WinSCP.TransferOptions
...
$transferOptions.PreserveTimestamp = $False
$session.PutFiles("D:\Users\bin\*.zip", "/Outbox/", $False, $transferOptions).Check()

Use custom, composite resource with Azure DSC extension

I have a VM template that deploys a DSC extension. It's been working fine but my configuration is growing so I've refactored it to use a composite resource and republished it to blob storage with Publish-AzureRmVMDscConfiguration.
I verified that the .ps1.zip file in blob storage contains my custom module and that the module is listed under dscmetadata.json. However, when I deploy, the DSC extension fails. The logs under C:\WindowsAzure\Logs\Plugins\Microsoft.Powershell.DSC\2.17.0.0 reveal the reason:
C:\Packages\Plugins\Microsoft.Powershell.DSC\2.17.0.0\bin..\DSCWork\AppServerDev.ps1.0\AppserverDev.ps1
PSDesiredStateConfiguration\node : The module 'xCustomResource' could
not be loaded. For more information, run 'Import-Module
xCustomResource'.
At C:\Packages\Plugins\Microsoft.Powershell.DSC\2.17.0.0\DSCWork\AppServerDev.ps1.0\AppserverDev.ps1:9 char:3
node "localhost"
~~~~
CategoryInfo : ObjectNotFound: (xCustomResource\xCustomResource:String)
[PSDesiredStateConfiguration\node], ParentContainsErrorRecordException
FullyQualifiedErrorId : CouldNotAutoLoadModule,PSDesiredStateConfiguration\node
Here are the relevant bits of my configuration file:
configuration AppServerDev
{
param($environment)
Import-DscResource -ModuleName 'PSDesiredStateConfiguration'
Import-DscResource -ModuleName 'SaaSModule'
node "localhost"
{
LocalConfigurationManager
{
RebootNodeIfNeeded = $true
ConfigurationMode = "ApplyAndAutoCorrect"
ConfigurationModeFrequencyMins = 1440
}
xDCTPlatformVM VM {
OctopusParametersFile = $environment
ChocolateyPackages = #(
'googlechrome',
'notepadplusplus',
'7zip',
'microsoftwse',
'octopusdeploy.tentacle',
'sqlserver-cmdlineutils'
)
}
}
}
Running Get-Module -ListAvailable reveals that DankModule is found and I can, from powershell, run Import-Module DankModule and it works as expected. I assume the confusion is coming from it trying to import xCustomResource rather than DankModule but my .ps1 file under C:\Packages\Plugins\Microsoft.Powershell.DSC\2.17.0.0\DSCWork says
Import-Module "DankModule"
and not
Import-Module "xCustomType"
Why is it trying to import xCustomType rather than DankModule? How do I make it find DankModule which is available and contains xCustomType?
UPDATE: Get-Module -ListAvailable shows DankModule is installed but Get-DSCResource -Module DankModule doesn't return anything.
I'm not sure but I think this is a rookie mistake on my part because I have no experience building powershell modules. I was using this page as well as this one to construct my module and I'd gotten a valid module file by using New-ModuleManifest, I had the correct file structure mentioned in both of them e.g.
C:\Program Files\WindowsPowerShell\Modules\
DankModule
DankModule.psd1
DankModule.psm1
DSCResources
xCustomResource
xCustomResource.psd1
RootModule = ‘xCustomResource.schema.psm1'
xCustomResource.schema.psm1
Configuration, no Node block
but I didn't realize I had some tweaking left. I needed to correct the RootModule property in DankModule.psd1 to look like this:
RootModule = 'C:\Program Files\WindowsPowerShell\Modules\DankModule\DankModule.psm1'
And also needed to add to my blank DankModule.psm1 a line referencing my xCustomResource.schema.psm1 equivalent:
. .\DSCResources\xCustomResource\xCustomResource.schema.psm1
That is the only line in my module-level .psm1 file and everything is now working. I also, at one point, removed all the \0s from both my .psd1 files but now I'm not sure if that was strictly necessary.

SharePoint script fails when run as a Visual Studio post-deployment command

I have written a script that inserts some test data into a document library. I intend to use it as a post-deployment step in Visual Studio 2010, so that the library is not empty after a retract & deploy.
The relevant portions of the script are:
Install.ps1:
$scriptDirectory = Split-Path -Path $script:MyInvocation.MyCommand.Path -Parent
. "$scriptDirectory\Include.ps1"
$webUrl = "http://localhost/the_site_name"
$web = Get-SPWeb($webUrl)
...
Include.ps1:
function global:Get-SPSite($url)
{
return new-Object Microsoft.SharePoint.SPSite($url)
}
function global:Get-SPWeb($url,$site)
{
if($site -ne $null -and $url -ne $null){"Url OR Site can be given"; return}
#if SPSite is not given, we have to get it...
if($site -eq $null){
$site = Get-SPSite($url);
...
}
It works fine when run as follows from the command line, even immediately after a Visual Studio re-deploy:
powershell \source\ProjectFiles\TestData\Install.ps1
However, it does not work when I use the exact same command as a post-deployment command line in the SharePoint project's properties in Visual Studio:
Run Post-Deployment Command:
New-Object : Exception calling ".ctor" with "1" argument(s): "The Web applicati
on at http://localhost/the_site_name could not be found. Verify that you have t
yped the URL correctly. If the URL should be serving existing content, the syst
em administrator may need to add a new request URL mapping to the intended appl
ication."
At C:\source\ProjectFiles\TestData\Include.ps1:15 char:18
+ return new-Object <<<< Microsoft.SharePoint.SPSite($url)
+ CategoryInfo : InvalidOperation: (:) [New-Object], MethodInvoca
tionException
+ FullyQualifiedErrorId : ConstructorInvokedThrowException,Microsoft.Power
Shell.Commands.NewObjectCommand
Interestingly, I can reproduce the error on the command line if I run:
c:\windows\Syswow64\WindowsPowerShell\v1.0\powershell \source\ProjectFiles\TestData\Install.ps1
However, the post-deployment command fails even if I explicitly run \windows\System32\WindowsPowerShell\v1.0\powershell and \windows\Syswow64\WindowsPowerShell\v1.0\powershell.
Update: Solution found
I seem to be having a similar problem to the one discussed here:
http://social.technet.microsoft.com/Forums/en-US/sharepoint2010programming/thread/faa25866-330b-4e60-8eee-bd72dc9fa5be
I cannot access a 64-bit SharePoint API using 32-bit clients. Because Visual Studio is 32-bit, the post-deployment action will run in a 32-bit process and will fail. There is, however, a 64-bit MSBuild. If we let it run the PowerShell script, all is fine.
Wrap the script in an MSBuild file such as this:
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Install" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Target Name="Install">
<Exec Command="powershell .\Install" />
</Target>
</Project>
Then, set the post-deployment command line to:
%WinDir%\Microsoft.NET\Framework64\v4.0.30319\MSBuild $(SolutionDir)\ProjectFiles\TestData\Install.msbuild
Use
%WINDIR%\SysNative\WindowsPowerShell\v1.0\powershell.exe
It’s important that you use the virtual path of %WINDIR%\SysNative and not the actual
path of C:\Windows\System32. The reason for this is that Visual Studio 2010 is a 32-bit
application that needs to call the 64-bit version of powershell.exe to successfully load the
Microsoft.SharePoint.Powershell snap-in.
(c)"Inside Microsoft SharePoint 2010", Microsoft Press, Mar 2011
I had same situation, I needed the Post Deployment powershell script to create dummy data for lists on my local instance. I tried several other ways even using the MSBuild with the .msbuild file as suggested above, but i could not all the variables and had to hard code the file with path and url, this is not what i wanted.
I finally figured out a way to explicitly calling the 64-Bit powershell.exe
I know the 64-bit file has to be there on hard dirve. I know that WinSXS folder has all the files. So quick search for powershell.exe in C:\Windows\winsxs folder i got two files so i grabbed the path for one in amd64 folder.
This is what i have as command in post deployment option
C:\Windows\winsxs\amd64_microsoft-windows-powershell-exe_31bf3856ad364e35_6.1.7600.16385_none_c50af05b1be3aa2b\powershell.exe -command "&{$(ProjectDir)PowerShell\dataload.ps1 -xmlPath "$(ProjectDir)PowerShell\dataload.xml" -webUrl "$(SharePointSiteUrl)"}"
I hope this will help someone in future.
Visual Studio is a 32-bit application, so in 64-bit Windows it runs in a simulated 32-bit environment.
Strangely, the 32-bit environment is called "WoW64" (when 32-bit Windows did this for 16-bit apps, it was called "WoW16". The "WoW" part means "Windows on Windows".
It's similarly strange that "System32" didn't become "System64" with 64-bit Windows. The "32" is from the 16-bit -> 32-bit transition, to differentiate from "System". Whatever, that's legacy/compatibility for you.
In WoW64, everything looks like a 32-bit Windows.
For example, c:\windows\system32 just points to c:\windows\syswow64. 32-bit applications can't (easily) reach anything 64-bit.
It is possible to use PowerShell Remoting to get a 64-bit PowerShell session from a 32-bit environment.
PS>gci env:PROCESSOR_ARCH*
Name Value
---- -----
PROCESSOR_ARCHITECTURE x86
PROCESSOR_ARCHITEW6432 AMD64
PS>Invoke-Command -ConfigurationName Microsoft.PowerShell -ComputerName LOCALHOST { gci env:PROCESSOR_ARCH* }
Name Value PSComputerName
---- ----- --------------
PROCESSOR_ARCHITECTURE AMD64 localhost
I have success doing this as a post deployment command:
%comspec% /c powershell -File "c:\foo\bar.ps1"

Assembly Versioning using CruiseControl.net

I have setup CruiseControl.net for a bunch of my projects which are related.
As a result a single project tag in CruiseControl has multiple SVN checkouts and then a bunch of msbuild tasks compile all the individual sln files.
I need to update the assembly version of all the solutions when this build is being done.
However, since i'm not using nant and not using MSBuild proj files, I am unsure on how to get this.
I wonder if I'm missing something obvious. I just need a solution which can be implemented by making appropriate changes in the ccnet.config file without requiring me to make changes to csproj files.
Thanks,
Anj
What about using a shared AssemblyInfo across your projects?
This is what we do for our products:
Each project has it's own AssemblyInfo.cs - this contains AssemblyTitle, AssemblyDescription, Guid, and other attributes that are unique to that assembly.
Each project also has two other Assembly Info files, note that these are added as a link rather than a direct file (VS -> Add -> Existing File -> Add as link (little down arrow next to add))
The two link files:
CompanyAssemblyInfo.cs - AssemblyCompany, AssemblyCopyright, AssemblyConfiguration, CLSCompliant, SecurityPermission, etc. Basically everything we want standard on all our assemblies.
ProductAssemblyInfo.cs - AssemblyProduct, AssemblyVersion, AssemblyFileVersion. This allows us to push the same version across to all assemblies from the one file.
Our CI and release process is more complicated, but that's at the heart of it - a single point (file) which controls the product version (assemblies, installers, everything!)
There's a task to do just what you're asking about.
You'll need to install the MSBuildCommunity tasks, found here.
Then, you can create something like this:
<PropertyGroup>
<MyAssemblyVersion>$(CCNetLabel)</MyAssemblyVersion>
</PropertyGroup>
<Target Name="GenAssemblyInfo">
<AssemblyInfo
ContinueOnError="false"
CodeLanguage="CS"
OutputFile="$(MSBuildProjectDirectory)\YourAssembly\AssemblyInfo.cs"
AssemblyTitle="blah"
AssemblyDescription="blah blah"
AssemblyCompany="Anj Software, Inc."
AssemblyProduct="Anj's Awesome App"
AssemblyCopyright="blah blah"
CLSCompliant="false"
AssemblyVersion="$(MyAssemblyVersion)"
AssemblyFileVersion="$(MyAssemblyVersion)"
/>
</Target>
Note that you can set a build number prefix in your ccnet.config file so that your assemblies will be numbered 2.1.0.x where x is the build number. That's how we do our version numbering where I work.
You'll still need to keep a default AssemblyInfo.cs file as part of each of the projects that make up your solution.
I use powershell for this. lpath is the path to the source code, and buildnum is my buildnumber I append. That is all I actually do with this. However, it should give you enough to change or set any or all of the other fields available. I pass in lpath and I get the buildnumber from the available environment variables in CC.NET and I can use this script over and over again, just changing what I pass in on the command line in the config file. I also have one that modifies the resource files for the C++ Code if that is actually what you need to modify.
$files = Get-ChildItem $lpath -recurse -filter *AssemblyInfo.cs -name
Foreach ($file in $files)
{
$file = $lpath + "\" + $file
$fileObject=get-item $file
$fileObject.Set_IsReadOnly($False)
$sr = new-object System.IO.StreamReader( $file, [System.Text.Encoding]::GetEncoding("utf-8") )
$content = $sr.ReadToEnd()
$sr.Close()
$content = [Regex]::Replace( $content, '(?<=\[assembly: AssemblyVersion\("[0-9].[0-9].[0-9].)[0-9]?[0-9]?[0-9]', $buildnum);
$content = [Regex]::Replace( $content, '(?<=\[assembly: AssemblyFileVersion\("[0-9].[0-9].[0-9].)[0-9]?[0-9]?[0-9]', $buildnum);
$sw = new-object System.IO.StreamWriter( $file, $false, [System.Text.Encoding]::GetEncoding("utf-8") )
$sw.Write( $content )
$sw.Close()
$fileObject.Set_IsReadOnly($True)
}

Resources