How to set PipeSecurity of NamedPipeServerStream in .NET Core - .net-core

I'm porting a library from .NET Framework 4.6.1 to .NET Standard 2.0. In Framework, the NamedPipeServerStream constructor could take a PipeSecurity parameter, but that isn't an option in Core. How do you set the security of a NamedPipeServerStream in Core?

Net 6.0 has introduced NamedPipeServerStreamAcl Class.
You can use the Create method to create the stream with PipeSecurity...
using System.IO.Pipes;
using System.Security.AccessControl;
using System.Security.Principal;
if (!System.OperatingSystem.IsWindows())
throw new PlatformNotSupportedException("Windows only");
SecurityIdentifier securityIdentifier = new SecurityIdentifier(
WellKnownSidType.AuthenticatedUserSid, null);
PipeSecurity pipeSecurity = new PipeSecurity();
pipeSecurity.AddAccessRule(new PipeAccessRule(securityIdentifier,
PipeAccessRights.ReadWrite | PipeAccessRights.CreateNewInstance,
AccessControlType.Allow));
NamedPipeServerStream stream = NamedPipeServerStreamAcl.Create(
"SecurityTestPipe", PipeDirection.InOut,
NamedPipeServerStream.MaxAllowedServerInstances,
PipeTransmissionMode.Byte, PipeOptions.Asynchronous, 0, 0, pipeSecurity);

Apparently it's a known issue
System.IO.Pipes.AccessControl package does not work #26869. There's a workaround mentioned in the last post suggesting usage of NamedPipeServerStream.NetFrameworkVersion nuget package which will expose NamedPipeServerStreamConstructors.New(...) which should mirror behavior of all the full .NET Framework constructors.
Follows a code sample from the nuget's github
using System.IO.Pipes;
var pipeSecurity = new PipeSecurity();
pipeSecurity.AddAccessRule(new PipeAccessRule(new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null), PipeAccessRights.ReadWrite, AccessControlType.Allow));
using var serverStream = NamedPipeServerStreamConstructors.New(pipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous | PipeOptions.WriteThrough, 0, 0, pipeSecurity);

Related

XSLT3 Options for .NET Core in 2019

Has anyone got XSLT3 transforms working in .NET Core 2.x+ in 2019?
Seems that the request to MS for XSLT2/3 support hasn't moved forwards, and the Saxon people have other priorities, especially given the IKVM closedown.
Are there any other alternatives for in-process XSLT transformation? At the moment, it seems my only choice is to wrap something up via an external service or some undesirable (for us) COM-style approach that would involve lots of marshalling of data, hurting performance.
Unfortunately IKVM has never supported .NET Core, so the .NET version of Saxon cannot be made to work in that environment. In Saxonica we've been exploring alternative avenues for .NET support, but we haven't found anything remotely promising. (Anyone fancy doing a Kotlin implementation for .NET?)
I don't know what's possible using XMLPrime or Exselt, both of which target .NET.
2021 Update
Saxonica now ships SaxonCS on .NET 5, this product is built by converting the Java code of SaxonJ to C# source code using a custom transpiler.
There is one way how to use Saxon on .NET Core: via Transform.exe running as a process.
You can use code similar to this:
/// <summary>Transform XML inputFile using xsltFile and parameters. Save the result to the outputFile.</summary>
public void Transform(string inputFile, string outputFile, string xsltFile, NameValueCollection parameters)
{
//Search for the instalation path on the system
string path = GetInstalPath(#"Software\Saxonica\SaxonHE-N\Settings", "InstallPath");
string exePath = Path.Combine(path, "bin", "Transform.exe");
string parametersCmd = null;
//Set indicidual parameters
foreach (string parameter in parameters)
{
parametersCmd += String.Format("{0}={1} ", parameter, parameters[parameter]);
}
//set arguments for Transform.exe
string arguments = string.Format("-s:\"{1}\" -xsl:\"{0}\" -o:\"{3}\" {2}", xsltFile, inputFile, parametersCmd, outputFile);
//https://stackoverflow.com/questions/5377423/hide-console-window-from-process-start-c-sharp
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = exePath;
startInfo.Arguments = arguments;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
startInfo.UseShellExecute = false;
startInfo.CreateNoWindow = true;
int waitingTime = 5 * 60 * 1000; //5 minutes; time in milliseconds
Process processTemp = new Process();
processTemp.StartInfo = startInfo;
processTemp.EnableRaisingEvents = true;
try
{
processTemp.Start();
processTemp.WaitForExit(waitingTime);
}
catch (Exception e)
{
throw;
}
}
static string GetInstalPath(string comName, string key)
{
RegistryKey comKey = Registry.CurrentUser.OpenSubKey(comName);
if (comKey == null)
return null;
string clsid = (string)comKey.GetValue(key);
return clsid;
}
SaxonCS EE has been released and works with .NET 5 and .NET 6 (RC/preview) and that way allows using XSLT 3, XPath 3.1 and XQuery 3.1 with .NET Core. It is only available under a commercial license however, but you can test it with a trial license, download from Saxonica is at https://www.saxonica.com/download/dotnet.xml, also on NuGet as https://www.nuget.org/packages/SaxonCS/.
In the meantime IKVM has been updated (https://www.nuget.org/packages/IKVM.Maven.Sdk) and is capable of producing .NET 3.1, .NET 5 and .NET 6 (aka .NET core) compatible cross-compilations. Using that I have managed to cross-compile Saxon HE 11.4 Java to .NET 6 and have published two command line apps/dotnet tools on NuGet to run XSLT 3.0 or XQuery 3.1:
XSLT 3.0: https://www.nuget.org/packages/SaxonHE11NetXslt/
XQuery 3.0: https://www.nuget.org/packages/SaxonHE11NetXQuery/
I have furthermore created an extension library to ease the use of the Java s9api from .NET code, it is on NuGet at https://www.nuget.org/packages/SaxonHE11s9apiExtensions/, the GitHub repository is at https://github.com/martin-honnen/SaxonHE11s9apiExtensions.
A simple example to run some XSLT 3.0 code with .NET 6, using the IKVM cross compiled Saxon HE 11, would be:
using net.sf.saxon.s9api;
using net.liberty_development.SaxonHE11s9apiExtensions;
//using System.Reflection;
// force loading of updated xmlresolver (no longer necessary with Saxon HE 11.5)
//ikvm.runtime.Startup.addBootClassPathAssembly(Assembly.Load("org.xmlresolver.xmlresolver"));
//ikvm.runtime.Startup.addBootClassPathAssembly(Assembly.Load("org.xmlresolver.xmlresolver_data"));
var processor = new Processor(false);
Console.WriteLine($"{processor.getSaxonEdition()} {processor.getSaxonProductVersion()}");
var xslt30Transformer = processor.newXsltCompiler().Compile(new Uri("https://github.com/martin-honnen/martin-honnen.github.io/raw/master/xslt/processorTestHTML5Xslt3InitialTempl.xsl")).load30();
xslt30Transformer.callTemplate(null, processor.NewSerializer(Console.Out));
A samples project showing various examples of XPath 3.1, XQuery 3.1 and XSLT 3.0 usage is at https://github.com/martin-honnen/SaxonHE11IKVMNet6SaxonCSSamplesAdapted.

JweAlgorithm.RSA_OAEP_256, JweEncryption.A256GCM .net Core 2.0

I am trying to decrypt a JWE return by a Mulesoft API with .Net Core 2.0
I get the JWE, the stock in string. The private key and its password are also correct.
When I decode, I have an error System.Security.Cryptography.CryptographicException : 'Specified padding mode is not valid for this algorithm.'
But in the first part of jwe "eyJhbGciOiJSU0EtT0FFUC0yNTYiLCJlbmMiOiJBMjU2R0NNIn0" in base64 => {"alg":"RSA-OAEP-256","enc":"A256GCM"}
//get private key
TextReader decrypterPrivateReader = System.IO.File.OpenText(decrypterPrivateFile);
PemReader decrypterPrivatePemReader = new PemReader(decrypterPrivateReader, new PasswordFinder(decrypterPrivatePwd));
RsaPrivateCrtKeyParameters decrypterPrivateKey = (RsaPrivateCrtKeyParameters)((AsymmetricCipherKeyPair)decrypterPrivatePemReader.ReadObject()).Private;
RSAParameters decrypterPrivateParams = DotNetUtilities.ToRSAParameters(decrypterPrivateKey);
RSACryptoServiceProvider decrypterPrivateProvider = new RSACryptoServiceProvider();
decrypterPrivateProvider.ImportParameters(decrypterPrivateParams);
//decode token
return Jose.JWT.Decode(jwe, decrypterPrivateProvider, JweAlgorithm.RSA_OAEP_256, JweEncryption.A256GCM);
Thanks all
The use of RSACryptoServiceProvider is what is holding you back, the only OAEP it understands is OAEP-SHA-1.
When on .NET Core the correct RSA is always RSA.Create(). The returned object is always correct for the platform you're running on, and (as of 2.1) can always do SHA-2-based OAEP.
If you're on .NET Framework then RSA.Create() will return an RSACryptoServiceProvider, so you'll need to special case .NET Framework to build an RSACng instead.

Auto Fill Web Forms in .net-Core

I am new to .net core.
How can I auto fill forms and submit in dotnet core ?
Please find following sample URLs I want to try
https://mparivahan.in/uyt/?pur_cd=102
Value - 1 = "MH1R"
Value - 2 = "5656"
https://www.filegstrstnow.com/searchGSTTaxpayer
sample Value = "24AADCS0852Q1Z2"
With Regards
I guess you want to automate operations in browser. For this purpose you need a browser automation framework which can be used in you .NET Core 2.0 code. Something like Selenium WebDriver. In this case you code will look like this:
[Test]
public void TestWithFirefoxDriver()
{
using (var driver = new FirefoxDriver())
{
driver.Navigate().GoToUrl(#"https://parivahan.gov.in/rcdlstatus/?pur_cd=102");
driver.FindElement(By.Id("form_rcdl:tf_reg_no1")).Send("GJ01RR");
driver.FindElement(By.Id("form_rcdl:tf_reg_no2")).Send("5656");
driver.FindElement(By.Id("form_rcdl:j_idt36")).Click();
var wait = new WebDriverWait(driver, TimeSpan.FromMinutes(1));
// Find element with the result to retrieve value, and so on..
}
}
Note: I didn't check the code above in runtime, it is just for demonstration purposes.
To run Selenium automation code without opening the browser you could use PhantomJS driver instead of drivers for real browsers like FirefoxDriver. Change this line:
using (var driver = new FirefoxDriver())
to:
using (var driver = new PhantomJSDriver())

How to create a 'Binding' in asp net core 2.0?

I'm trying to create a Binding, but everytime that I do, it gives me errors about
NotSupportedException: The value 'TransportWithMessageCredential' is not supported in this context for the binding security property 'Mode'.
at System.ServiceModel.HttpBindingBase.CheckSettings()
Here's my code:
Binding CreateBinding()
{
var binding = new BasicHttpBinding();
binding.Security.Mode = BasicHttpSecurityMode.TransportWithMessageCredential;
var elements = binding.CreateBindingElements();
elements.Find<SecurityBindingElement>().IncludeTimestamp = false;
return new CustomBinding(elements);
}
Try this ... WCF in .net core (TransportWithMessageCredential)

How to publish an item in Sitecore 5.3 using the API

Using Sitecore 5.3, what API calls would be necessary to publish a given item? If there are multiple publication targets configured, how would you specify which target to publish to?
My code is actually for Sitecore 6 but we used almost the same code when we ran 5.3
Needlessly to say maybe but in the code we publish from Master to Web and we only publish items under the node /sitecore/content/home/projects/ongoing
DateTime publishDate = DateTime.Now;
var master = Sitecore.Configuration.Factory.GetDatabase("master");
var targetDB = Sitecore.Configuration.Factory.GetDatabase("web");
var pubOpts = new Sitecore.Publishing.PublishOptions(master, targetDB, Sitecore.Publishing.PublishMode.Full, Sitecore.Data.Managers.LanguageManager.GetLanguage("sv", master), publishDate);
pubOpts.Deep = true;
string idstr = master.Items["/sitecore/content/Home/Projects/Ongoing"].ID.ToString();
var id = new ID(idstr);
pubOpts.RootItem = master.Items[id];
var pub = new Sitecore.Publishing.Publisher(pubOpts);
Sitecore.Jobs.Job pubJob = pub.PublishAsync();
pubJob.Start();
You can find the code for Sitecore 5.3 on the sdn.

Resources