Internal.Cryptography.CryptoThrowHelper.WindowsCryptographicException - c#

I'm getting the following error message from Visual Studio 2017 on first run of the ASP.NET Core MVC Boilerplate template (DotNet Core) regarding the SSL certificate:
"Internal.Cryptography.CryptoThrowHelper.WindowsCryptographicException
occurred HResult=0x80070002 Message=The system cannot find the
file specified Source=
StackTrace: at
Internal.Cryptography.Pal.CertificatePal.FromBlobOrFile(Byte[]
rawData, String fileName, String password, X509KeyStorageFlags
keyStorageFlags) at
System.Security.Cryptography.X509Certificates.X509Certificate..ctor(String
fileName, String password, X509KeyStorageFlags keyStorageFlags) at
Microsoft.AspNetCore.Hosting.KestrelServerOptionsHttpsExtensions.UseHttps(KestrelServerOptions
options, String fileName, String password) ... "
All other projects using SSL work fine and I've double checked that my localhost certificate is in the Trusted Root Certification Authorities for my local machine and has not expired.
The project is running IISExpress - perhaps it's not looking the correct place? I'm not sure. Any ideas where I'm going wrong?

Recently had this same issue with ASP.NET Core MVC Boilerplate.
Close Visual Studio, right click on it, "Run as Administrator". Worked for me.

One of two problems is going on.
1) The file "exists", but is a symlink. That tends to confuse the underlying system. (The response is to do File.ReadAllBytes and use the byte[] constructor).
2) The file doesn't exist.
To help diagnose #2 you can read Environment.CurrentDirectory to know where "here" is, and use Directory.EnumerateFiles() to see what is present in the directory and why your file doesn't exist.
Of course, if you didn't think you were loading by file, but thought you were loading from a certificate store: Check your configuration and try again... since you're loading from file :).

If you're running in docker, another workaround is doing a copy at startup.
# The copy is done, because wildcard_certificate.pfx is put into the container using docker secrets, which makes it a symlink.
# Reading a certificate as a symlink is not supported at this moment: https://stackoverflow.com/q/43955181/1608705
# After doing a copy, the copied version is not a symlink anymore.
ENTRYPOINT (IF EXIST "c:\certificates\wildcard_certificate.pfx" (copy c:\certificates\wildcard_certificate.pfx c:\app\wildcard_certificate.pfx)) && dotnet webapplication.dll
My application runs in the "c:\app" folder and I put my "to be copied" certificates in "c:\certificates". At startup the certificate is copied to "c:\app", which my environment variables point to.
version: "3.7"
services:
webapplication:
image: ({CONTAINER_REGISTRY})/webapplication:({LABEL})
environment:
- ASPNETCORE_URLS=https://+;http://+
- ASPNETCORE_HTTPS_PORT=443
- ASPNETCORE_Kestrel__Certificates__Default__Path=wildcard_certificate.pfx
secrets:
- source: config_secrets
target: C:/app/appsettings.json
- source: wildcard_certificate_pfx
target: c:\certificates\wildcard_certificate.pfx

Context
I'm setting up a new dotnet 6 mvcapp website and trying to install Certbot generated certificate locally. The settings for kestrel to load certificate from file was simple enough but I keep getting above errors.
Reason for that like someone has mentioned, the fullchain.pem is actually a symlink or in other word: a shortcut.
Solution for that is to right click on the '.pem file' shortcut and select Open file location and then get the actual .pem files.
Updating your settings to point to the actual files and you should be ok.
Wrong path points to live folder
"Certificates": {
"Default": {
"Path": "C:\\Certbot\\live\\{my domain}\\fullchain.pem",
"KeyPath": "C:\\Certbot\\live\\{my domain}\\privkey.pem"
}
}
Correct path points to archive folder
"Certificates": {
"Default": {
"Path": "C:\\Certbot\\archive\\{my domain}\\fullchain.pem",
"KeyPath": "C:\\Certbot\\archive\\{my domain}\\privkey.pem"
}
}

I've just spent all morning fixing this error....
I'm using the Azure.Security.KeyVault.Certificates nuget package to download a certificate from a KeyVault and use it for IdentityServer.
I recently updated nuget packages for our project so refactored a bit of code, deleting the key bit of the jigsaw.
var signingCertificate = certificateClient.DownloadCertificate(new DownloadCertificateOptions(signingCertificateName)
{
KeyStorageFlags = System.Security.Cryptography.X509Certificates.X509KeyStorageFlags.MachineKeySet,
});
X509KeyStorageFlags.MachineKeySet is the secret sauce to getting it running on Azure. I tried several other options before landing back on this one. The annoying thing is, had this in originally before I started refactoring!

Related

.NET executables do not work after overwritten with new versions

I faced very strange behaviour - after I overwrite .NET exectables with new versions from network drive it cannot start.
When try to start from Windows Explorer it shows me following error:
[Window Title]
C:\Programs\zzz\clients.net\zzzNet.exe
[Content]
C:\Programs\zzz\clients.net\zzzNet.exe
The application has failed to start because its side-by-side configuration is incorrect. Please see the application event log or use the command-line sxstrace.exe tool for more detail.
I tried to execute following commands:
SxsTrace Trace -logfile:SxsTrace.etl
SxStrace Parse -logfile:SxSTrace.etl -outfile:SxSTrace.txt
And got following result:
=================
Begin Activation Context Generation.
Input Parameter:
Flags = 0
ProcessorArchitecture = AMD64
CultureFallBacks = en-US;en;ru-RU;ru
ManifestPath = C:\Programs\zzz\clients.net\zzzNet.exe
AssemblyDirectory = C:\Programs\zzz\clients.net\
Application Config File = C:\Programs\zzz\clients.net\zzzNet.exe.Config
-----------------
INFO: Parsing Application Config File C:\Programs\zzz\clients.net\zzzNet.exe.Config.
INFO: Parsing Manifest File C:\Programs\zzz\clients.net\zzzNet.exe.
INFO: Manifest Definition Identity is (null).
ERROR: Line 0: XML Syntax error.
ERROR: Activation Context generation failed.
End Activation Context Generation.
It is quite simple .NET application (1 exe + 8 dll files). It was built for .NET 3.5 Client Profile.
I not defined any special "manifest" there. Just clicked "New Windows Forms Project" in Visual Studio and developed it.
Also app.config does not contain anything special - only primitive standard settings - appSettings and userSettings sections.
On PC where I developed it all is perfectly works. Problems only began when I copy these binaries to this particular VM and try to start.
Also please note - these executables were not installed in GAC or such, I just copied them into a folder on VM and started. And when it was 1st time all was working fine.
So, the problem pattern is following:
Copy .NET execuatbles to new VM (it is Win 7 x64), run it, all is working fine. Close it.
Build new version of .NET execuatbles on host PC, copy new .NET execuatbles to VM (with files overwriting).
Try to start - got mentioned problem.
After some shaman-style actions (like OS reboot, etc) it begin to work but why that happened at all?!
Why replacing .NET executables with new versions is causing SUCH HUGE PROBLEMS?!
Also the BIG QUESTION - is there any special procedure to replace .NET executables to keep them working? Because it is a new app development, I do not want lost so much time on every new executables installation. :-\
Could you please help? Because it looks completely weird!
Thank you in adance.
PS. I checked all VS projects - all they have PlatformTarget=AnyCPU. Also in run-time I can see ProcessType=MSIL (I show this info in AboutBox for application). So, there is no mix of x86/x64 binaries.
It seems that was related to mapped network drive behavior.
When I copied new files from network drive folder it copied wrong files - a strange random mess of new files and older ones (which were there before I updated them on VM host).
The scenario to make it working:
on VM: delete all files in a folder on network drive
on VM host: copy new files into a folder which is mapped as network drive on VM
on VM: copy files into target folder
on VM: run application - it works now
Weird thing. I remember I have seen something similar with Windows Explorer on Windows 2008 behaviour when copying updated win32 binaries.

"This application can only run in the context of an app container." - New to Visual Studio 2015 dev

I am a little desperate. I have been trying to resolve the following issue for hours.
I have developed an app which I now tried to install by using Visual Studio 2015's Setup Wizard Extension. Everything is building or (no errors) but when I open the app it highlights that it can only open in the context of an app container. What does that mean? Any advice would be highly appreciated!
The app is working with an SQlite database. Could this have something to do with the dependencies? If so, how could I approach fixing this?
UPDATE:
# Culture = "en-US"
ConvertFrom-StringData #'
###PSLOC
PromptYesString = &Yes
PromptNoString = &No
BundleFound = Found bundle: {0}
PackageFound = Found package: {0}
CertificateFound = Found certificate: {0}
DependenciesFound = Found dependency package(s):
GettingDeveloperLicense = Acquiring developer license...
InstallingCertificate = Installing certificate...
InstallingPackage = \nInstalling app...
AcquireLicenseSuccessful = A developer license was successfully acquired.
InstallCertificateSuccessful = The certificate was successfully installed.
Success = \nSuccess: Your app was successfully installed.
WarningInstallCert = \nYou are about to install a digital certificate to your computer's Trusted People certificate store. Doing so carries serious security risk and should only be done if you trust the originator of this digital certificate.\n\nWhen you are done using this app, you should manually remove the associated digital certificate. Instructions for doing so can be found here: http://go.microsoft.com/fwlink/?LinkId=243053\n\nAre you sure you wish to continue?\n\n
ElevateActions = \nBefore installing this app, you need to do the following:
ElevateActionDevLicense = \t- Acquire a developer license
ElevateActionCertificate = \t- Install the signing certificate
ElevateActionsContinue = Administrator credentials are required to continue. Please accept the UAC prompt and provide your administrator password if asked.
ErrorForceElevate = You must provide administrator credentials to proceed. Please run this script without the -Force parameter or from an elevated PowerShell window.
ErrorForceDeveloperLicense = Acquiring a developer license requires user interaction. Please rerun the script without the -Force parameter.
ErrorLaunchAdminFailed = Error: Could not start a new process as administrator.
ErrorNoScriptPath = Error: You must launch this script from a file.
ErrorNoPackageFound = Error: No package or bundle found in the script directory. Please make sure the package or bundle you want to install is placed in the same directory as this script.
ErrorManyPackagesFound = Error: More than one package or bundle found in the script directory. Please make sure only the package or bundle you want to install is placed in the same directory as this script.
ErrorPackageUnsigned = Error: The package or bundle is not digitally signed or its signature is corrupted.
ErrorNoCertificateFound = Error: No certificate found in the script directory. Please make sure the certificate used to sign the package or bundle you are installing is placed in the same directory as this script.
ErrorManyCertificatesFound = Error: More than one certificate found in the script directory. Please make sure only the certificate used to sign the package or bundle you are installing is placed in the same directory as this script.
ErrorBadCertificate = Error: The file "{0}" is not a valid digital certificate. CertUtil returned with error code {1}.
ErrorExpiredCertificate = Error: The developer certificate "{0}" has expired. One possible cause is the system clock isn't set to the correct date and time. If the system settings are correct, contact the app owner to re-create a package or bundle with a valid certificate.
ErrorCertificateMismatch = Error: The certificate does not match the one used to sign the package or bundle.
ErrorCertIsCA = Error: The certificate can't be a certificate authority.
ErrorBannedKeyUsage = Error: The certificate can't have the following key usage: {0}. Key usage must be unspecified or equal to "DigitalSignature".
ErrorBannedEKU = Error: The certificate can't have the following extended key usage: {0}. Only the Code Signing and Lifetime Signing EKUs are allowed.
ErrorNoBasicConstraints = Error: The certificate is missing the basic constraints extension.
ErrorNoCodeSigningEku = Error: The certificate is missing the extended key usage for Code Signing.
ErrorInstallCertificateCancelled = Error: Installation of the certificate was cancelled.
ErrorCertUtilInstallFailed = Error: Could not install the certificate. CertUtil returned with error code {0}.
ErrorGetDeveloperLicenseFailed = Error: Could not acquire a developer license. For more information, see http://go.microsoft.com/fwlink/?LinkID=252740.
ErrorInstallCertificateFailed = Error: Could not install the certificate. Status: {0}. For more information, see http://go.microsoft.com/fwlink/?LinkID=252740.
ErrorAddPackageFailed = Error: Could not install the app.
ErrorAddPackageFailedWithCert = Error: Could not install the app. To ensure security, please consider uninstalling the signing certificate until you can install the app. Instructions for doing so can be found here:\nhttp://go.microsoft.com/fwlink/?LinkId=243053
ANOTHER UPDATE: Ran the sideloading install script as an adiminstrator in PowerShell and now received the following error:
Package could not be registered. (Exception from HRESULT: 0x80073CF6)
Googled it but not many results for Windows 10 developers.
If this is a store/UWP app then it can only be installed via an appx package. Typically this should be via the store.
It is not possible to install a modern/store/UWP app with an MSI.
If you don't want to (or can't) distribute through the store then you can create a package that can be installed directly.
In VS go to: PROJECT > Store > Create App Packages... > And select No to building a package for the store
Before you can install the app on a machine you'll need to enable developer features on that machine:
Settings > Update & Security > For developers > select: Sideload apps
Then just run the PowerShell script created with the package to install it.
Your comment about store submission taking 7 days does not sound correct. Typically submissions will go through in under an hour and only in exceptional circumstances take more than a day.
Store Apps can only be started by the shell as far as I know. So try this:
explorer.exe shell:AppsFolder\Microsoft.WindowsAlarms_8wekyb3d8bbwe!App
Or from run (Win+R):
shell:AppsFolder\Microsoft.WindowsAlarms_8wekyb3d8bbwe!App
Have a look at this article for more details on opening and creating shortcuts: http://winaero.com/blog/exclusive-how-to-start-a-modern-app-from-desktop-without-going-to-the-metro-start-screen/
This is probably a Metro app, which aren't supposed to be deployed using a Setup, but rather using the Store.

How To Set Folder Permissions in Elastic Beanstalk Using YAML File?

I have a C# Web API Elastic Beanstalk app which needs a folder outside the deployment directory that the IUSER and IIS_USERS users can write to. I've created a .config file and put this in the top level .ebextensions folder in my project. The contents are below:
commands:
0_mkdir:
command: mkdir C:\\AppFolder\\
1_set_iuser_permissions:
command: cacls C:\\AppFolder\\ /t /e /g IUser:f IIS_Users:f
However while the folder is created successfully the permissions aren't set. If anyone has any idea what I am doing wrong I would be hugely grateful. Big thanks in advance.
In the end I switched to using Json instead of YAML as, despite my YAML being validated by several online YAML testers, AWS still wouldn't accept it. It always had issues with the parameters passed to icacls. I also changed to a folder within the application App_Data folder as setting permissions on any directory external to the application didn't appear to work. So, my final configuration file is as follows:
{
"container_commands": {
"01": {
"command": "icacls \"C:/inetpub/wwwroot/AppName_deploy/App_Data/AppFolder\" /grant DefaultAppPool:(OI)(CI)F"
}
}
}
Hope this helps someone else out.
It looks like you are using invalid .net accounts (unless these are custom accounts you created). That is part of the reason why your permissions are not being set. They should be IUSR or IIS_IUSRS
Furthermore, container_commands executes after your app/server environment has been setup, but before your deployment has started. There is no other way to set permissions on files/folders within your deployment directory other than using a wpp.targets file within visual studio.
The following SO post is a good read using wpp.targets to solve your issue.
Can Web Deploy's setAcl provider be used on a sub-directory?
Place a file 01_fix_permissions.config inside .ebextensions folder.
contents:
files:
"/opt/elasticbeanstalk/hooks/appdeploy/pre/49_change_permissions.sh":
mode: "000755"
owner: root
group: root
content: |
#!/usr/bin/env bash
sudo chown -R ec2-user:ec2-user tmp/

Firebird client installation

I'm trying to deploy my Application that uses a Firebird v2.5 database to a client machine.
I am trying to use a minimum installation, without the need to run any other installers. From what I gather, all I need to do is copy the "FBClient.dll" to the target application folder (which includes firebird database file). I have tried this and it still reports an error about not being able to find the correct .net data provider.
eg
C:\Program Files (x86)\MyApp\myApp.exe
C:\Program Files (x86)\MyApp\fbDatabase.fdb
C:\Program Files (x86)\MyApp\fbclient.dll
The error produced is:
Failed to find or load the registered .Net Framework Data Provider.
Also have copied, renamed and included fbclient.dll as fbembed.dll
I have also tried to copy a bunch of other files to the app directory, as well as placing fbclient.dll into the c:\, c:\windows, c:\windows\system.
I also tried installing the client installation, with no joy too.
Is there a way, that I can use the firebird database, without manually editing the machine.config files or using the gac and going through the hell that I went through to install firebird on the dev machine? I want an application that a user can install, not requiring that it be installed by a developer.
Please note, the application that I am writing is for a single machine, single user environment, who knows how to double click the install button, with the attention span of a gnat, that if required to do more than double click install and then press GO, will simply get bored and press the cancel, forget it button.
I add the file "FirebirdSql.Data.FirebirdClient.dll" to the application folder and I no longer get the Data provider error, instead I get the following
"Unable to complete network request to host \"DevMachine\"."
at FirebirdSql.Data.Client.Managed.Version10.GdsConnection.Connect()
at FirebirdSql.Data.FirebirdClient.ClientFactory.CreateManagedDatabase(FbConnectionString options)
at FirebirdSql.Data.FirebirdClient.ClientFactory.CreateDatabase(FbConnectionString options)
at FirebirdSql.Data.FirebirdClient.FbConnectionInternal.Connect()
I am trying to connect with the following
string file = #"C:\Program Files (x86)\MyApp\Test.FDB;";
FbConnection con = new FbConnection("User=SYSDBA;" + "Password=masterkey;" + "Database=" + file + "DataSource=Dev-VS-W7VM;" + "Port3050;" + "Dialect=3;" + "Charset=ISO8859_1;");
try
{
con.Open();
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
I have included FirebirdSql.Data.FirebirdClient in my project and installation folder (..\MyApp)
Thank you in advance.
You have to grap a zip and copy FirebirdSql.Data.FirebirdClient.dll to bin folder.
I wonder how you wrote your application that it works without the file (probably installed .msi) :)
You needed to install .net provider
http://www.firebirdsql.org/en/net-provider/
The database file resides next to your application's exe module. So, you need in local server running or embedded server in order to work with data. For embedded server a minimal set of files is (specifed relatively to an application folder):
\UDF (folder with UDF needed if any)
\Intl (with contents from FB installation)
fbembed.dll
firebird.msg
ib_util.dll
icudt30.dll
icuin30.dll
icuuc30.dll
Microsoft.VC80.CRT.manifest
msvcp80.dll
msvcr80.dll
for a full scale server (i.e. not an embedded) a list of files would be:
\UDF (folder with UDF needed if any)
\Intl (with contents from FB installation)
fbserver.exe or fb_inet_server.exe
fbclient.dll
firebird.msg
ib_util.dll
icudt30.dll
icuin30.dll
icuuc30.dll
Microsoft.VC80.CRT.manifest
msvcp80.dll
msvcr80.dll
security2.fdb
firebird.conf (if non default parameters used)
But then you would need in setting up service record for FB
or start it as an application before your application start.
Installation of the Firebird as a service could be done with
instsvc.exe utility. Appropriate commands:
instsvc install -s -a
instsvc start
Also you should take care of two things:
FileName must be a local file, not in a shared folder from another server.
Appending the firebird server IP before the filename. If you are running your app always in the firebird server, or you are using embeded fbclient.dll, than it should be like
FbConnection con = new FbConnection("User=SYSDBA;" + "Password=masterkey;" + "Database=localhost:" + file + "DataSource=Dev-VS-W7VM;" + "Port3050;" + "Dialect=3;" + "Charset=ISO8859_1;");
Some fbclient.dll version will allow you not to add localhost and still connect on local files, or use \\servername\c:\filename format instead of localhost:c:\filename, but it is deprecated and not supposed to work anymore (and can work depending on windows version).

Encryption / Decryption of app.config sections using RsaProtectedConfigurationProvider

During the installation of our program we run this method to encrpyt sections of the app.config:
// Get the application configuration file.
Configuration config =
ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
// Define the Rsa provider name.
const string provider = "RsaProtectedConfigurationProvider";
// Get the section to protect.
ConfigurationSection connStrings = config.ConnectionStrings;
if (connStrings != null)
{
if (!connStrings.SectionInformation.IsProtected)
{
if (!connStrings.ElementInformation.IsLocked)
{
// Protect the section.
connStrings.SectionInformation.ProtectSection(provider);
connStrings.SectionInformation.ForceSave = true;
config.Save(ConfigurationSaveMode.Full);
}
}
}
Works fine so far. But if I run this program, we encounter of several machines the following error "Failed to decrypt using provider 'RsaProtectedConfigurationProvider'. Error message from the provider: The RSA key container could not be opened".
Of course I searched and found this help, but this doesn't work. Any ideas?
I ran into similar issues while debugging within Visual Studio 2010 on Win 7 with UAC set to it's default protection.
In order for me to get around this issue, I had to run Visual Studio as the Administrator ("Run as Administrator").
I had the same issue with trying to run the aspnet_regiis.exe to encrypt the section of my web.config. If I didn't run the commandline/console "as Administrator" I would get a commandline error that was even more cryptic: "Object already exists."
Yes.
Reason is those machines working have RsaProtectedConfigurationProvider setup in their machine.config. Those not working, don't have it - just manually add it for those machines.
I imagine that's one of the steps aspnet_regiis.exe does. I can't imagine you want to run that on all client machines.
UPDATE
OK, I have made the main part of the error in bold in your question - you are right it is a different issue. It is a security issue. If you look at the location C:\Documents and Settings\All Users\Application Data\Microsoft\Crypto\RSA\MachineKeys or C:\ProgramData\Microsoft\Crypto\RSA\MachineKeys depending the operating system, you see a number of files. Your process does have access to the folder so just give files access to the whole folder for the identity of the application or a particular file (timestamp will tell you if you have created it).
I got this on an app.config that was running on a Windows Server set up as a SQL Server. It did not have IIS installed. The machine.config file listed RSAProtectedConfigurationProvider as the default, but when we looked in the two folders mentioned by Aliostad above the folders were empty.There were no keys installed. We used the aspnet_regiis tool to create a custom key. then we used it to grant access to the identity the batch job runs under. All of this was running cmd.exe and aspnet_regiis As Administrator.

Categories