private void SetClientCertificate(ClientCertificate certificate) { if (certificate == null) { return; } byte[] bytes; try { bytes = Convert.FromBase64String(certificate.RawData); } catch (Exception ex) { throw new HttpRequestException(FailureMessages.InvalidRawData, ex); } var options = NSDictionary.FromObjectsAndKeys(new object[] { certificate.Passphrase }, new object[] { "passphrase" }); var status = SecImportExport.ImportPkcs12(bytes, options, out NSDictionary[] items); var identityRef = items[0]["identity"]; var identity = new SecIdentity(identityRef.Handle); SecCertificate[] certs = { identity.Certificate }; this.UrlCredential = new NSUrlCredential(identity, certs, NSUrlCredentialPersistence.ForSession); }
public void P12_Success() { NSDictionary[] array; using (NSMutableDictionary options = new NSMutableDictionary()) { options [SecImportExport.Passphrase] = new NSString("farscape"); Assert.That(SecImportExport.ImportPkcs12(farscape_pfx, options, out array), Is.EqualTo(SecStatusCode.Success), "Success"); } Assert.That(array.Length, Is.EqualTo(1), "1"); NSDictionary dict = array [0]; foreach (var x in dict) { switch (x.Key.ToString()) { case "trust": case "identity": Assert.That(x.Value, Is.TypeOf(typeof(NSObject)), "NSObject"); break; case "chain": Assert.True(x.Value is NSArray, "NSArray"); NSArray a = (x.Value as NSArray); Assert.That(a.Count, Is.EqualTo((nuint)1), "Count"); break; default: Assert.Fail("Unexpected {0}", x.Key); break; } } }
/// <summary> /// Import the specified certificate and its associated private key. /// </summary> /// <param name="certificate">The certificate and key, in PKCS12 format.</param> /// <param name="passphrase">The passphrase that protects the private key.</param> public void Import(byte[] certificate, string passphrase) { NSDictionary opt; if (string.IsNullOrEmpty(passphrase)) { opt = new NSDictionary(); } else { opt = NSDictionary.FromObjectAndKey(new NSString(passphrase), SecImportExport.Passphrase); } var status = SecImportExport.ImportPkcs12(certificate, opt, out NSDictionary[] array); if (status == SecStatusCode.Success) { var identity = new SecIdentity(array[0]["identity"].Handle); NSArray chain = array[0]["chain"] as NSArray; SecCertificate[] certs = new SecCertificate[chain.Count]; for (System.nuint i = 0; i < chain.Count; i++) { certs[i] = chain.GetItem <SecCertificate>(i); } Credential = new NSUrlCredential(identity, certs, NSUrlCredentialPersistence.ForSession); } }
public void P12_AuthFailed() { using (NSMutableDictionary options = new NSMutableDictionary()) { options [SecImportExport.Passphrase] = new NSString("b5"); NSDictionary[] array; Assert.That(SecImportExport.ImportPkcs12(farscape_pfx, options, out array), Is.EqualTo(SecStatusCode.AuthFailed), "AuthFailed"); } }
static public SecIdentity GetIdentity() { using (var options = NSDictionary.FromObjectAndKey(new NSString("farscape"), SecImportExport.Passphrase)) { NSDictionary[] array; if (SecImportExport.ImportPkcs12(ImportExportTest.farscape_pfx, options, out array) != SecStatusCode.Success) { Assert.Fail("ImportPkcs12"); } return(new SecIdentity(array [0].LowlevelObjectForKey(SecImportExport.Identity.Handle))); } }
/// <summary> /// Import the specified certificate and its associated private key. /// </summary> /// <param name="certificate">The certificate and key, in PKCS12 format.</param> /// <param name="passphrase">The passphrase that protects the private key.</param> public void Import(byte[] certificate, string passphrase) { NSDictionary opt; if (string.IsNullOrEmpty(passphrase)) { opt = new NSDictionary(); } else { opt = NSDictionary.FromObjectAndKey(new NSString(passphrase), SecImportExport.Passphrase); } var status = SecImportExport.ImportPkcs12(certificate, opt, out NSDictionary[] array); if (status == SecStatusCode.Success) { var identity = new SecIdentity(array[0]["identity"].Handle); SecCertificate[] certs = { identity.Certificate }; Credential = new NSUrlCredential(identity, certs, NSUrlCredentialPersistence.ForSession); } }
protected INativeObject GetINativeInstance(Type t) { var ctor = t.GetConstructor(Type.EmptyTypes); if ((ctor != null) && !ctor.IsAbstract) { return(ctor.Invoke(null) as INativeObject); } if (!NativeObjectInterfaceType.IsAssignableFrom(t)) { throw new ArgumentException("t"); } switch (t.Name) { case "CFAllocator": return(CFAllocator.SystemDefault); case "CFBundle": var bundles = CFBundle.GetAll(); if (bundles.Length > 0) { return(bundles [0]); } else { throw new InvalidOperationException(string.Format("Could not create the new instance for type {0}.", t.Name)); } case "CFNotificationCenter": return(CFNotificationCenter.Darwin); case "CFReadStream": case "CFStream": CFReadStream readStream; CFWriteStream writeStream; CFStream.CreatePairWithSocketToHost("www.google.com", 80, out readStream, out writeStream); return(readStream); case "CFWriteStream": CFStream.CreatePairWithSocketToHost("www.google.com", 80, out readStream, out writeStream); return(writeStream); case "CFUrl": return(CFUrl.FromFile("/etc")); case "CFPropertyList": return(CFPropertyList.FromData(NSData.FromString("<string>data</string>")).PropertyList); case "DispatchData": return(DispatchData.FromByteBuffer(new byte [] { 1, 2, 3, 4 })); case "AudioFile": var path = Path.GetFullPath("1.caf"); var af = AudioFile.Open(CFUrl.FromFile(path), AudioFilePermission.Read, AudioFileType.CAF); return(af); case "CFHTTPMessage": return(CFHTTPMessage.CreateEmpty(false)); case "CFMutableString": return(new CFMutableString("xamarin")); case "CGBitmapContext": byte[] data = new byte [400]; using (CGColorSpace space = CGColorSpace.CreateDeviceRGB()) { return(new CGBitmapContext(data, 10, 10, 8, 40, space, CGBitmapFlags.PremultipliedLast)); } case "CGContextPDF": var filename = Environment.GetFolderPath(Environment.SpecialFolder.CommonDocuments) + "/t.pdf"; using (var url = new NSUrl(filename)) return(new CGContextPDF(url)); case "CGColorConversionInfo": var cci = new GColorConversionInfoTriple() { Space = CGColorSpace.CreateGenericRgb(), Intent = CGColorRenderingIntent.Default, Transform = CGColorConversionInfoTransformType.ApplySpace }; return(new CGColorConversionInfo((NSDictionary)null, cci, cci, cci)); case "CGDataConsumer": using (NSMutableData destData = new NSMutableData()) { return(new CGDataConsumer(destData)); } case "CGDataProvider": filename = "xamarin1.png"; return(new CGDataProvider(filename)); case "CGFont": return(CGFont.CreateWithFontName("Courier New")); case "CGPattern": return(new CGPattern( new RectangleF(0, 0, 16, 16), CGAffineTransform.MakeIdentity(), 16, 16, CGPatternTiling.NoDistortion, true, (cgc) => {})); case "CMBufferQueue": return(CMBufferQueue.CreateUnsorted(2)); case "CTFont": CTFontDescriptorAttributes fda = new CTFontDescriptorAttributes() { FamilyName = "Courier", StyleName = "Bold", Size = 16.0f }; using (var fd = new CTFontDescriptor(fda)) return(new CTFont(fd, 10)); case "CTFontCollection": return(new CTFontCollection(new CTFontCollectionOptions())); case "CTFontDescriptor": fda = new CTFontDescriptorAttributes(); return(new CTFontDescriptor(fda)); case "CTTextTab": return(new CTTextTab(CTTextAlignment.Left, 2)); case "CTTypesetter": return(new CTTypesetter(new NSAttributedString("Hello, world", new CTStringAttributes() { ForegroundColorFromContext = true, Font = new CTFont("ArialMT", 24) }))); case "CTFrame": var framesetter = new CTFramesetter(new NSAttributedString("Hello, world", new CTStringAttributes() { ForegroundColorFromContext = true, Font = new CTFont("ArialMT", 24) })); var bPath = UIBezierPath.FromRect(new RectangleF(0, 0, 3, 3)); return(framesetter.GetFrame(new NSRange(0, 0), bPath.CGPath, null)); case "CTFramesetter": return(new CTFramesetter(new NSAttributedString("Hello, world", new CTStringAttributes() { ForegroundColorFromContext = true, Font = new CTFont("ArialMT", 24) }))); case "CTGlyphInfo": return(new CTGlyphInfo("copyright", new CTFont("ArialMY", 24), "Foo")); case "CTLine": return(new CTLine(new NSAttributedString("Hello, world", new CTStringAttributes() { ForegroundColorFromContext = true, Font = new CTFont("ArialMT", 24) }))); case "CGImageDestination": var storage = new NSMutableData(); return(CGImageDestination.Create(new CGDataConsumer(storage), "public.png", 1)); case "CGImageMetadataTag": using (NSString name = new NSString("tagName")) using (var value = new NSString("value")) return(new CGImageMetadataTag(CGImageMetadataTagNamespaces.Exif, CGImageMetadataTagPrefixes.Exif, name, CGImageMetadataType.Default, value)); case "CGImageSource": filename = "xamarin1.png"; return(CGImageSource.FromUrl(NSUrl.FromFilename(filename))); case "SecPolicy": return(SecPolicy.CreateSslPolicy(false, null)); case "SecIdentity": using (var options = NSDictionary.FromObjectAndKey(new NSString("farscape"), SecImportExport.Passphrase)) { NSDictionary[] array; var result = SecImportExport.ImportPkcs12(farscape_pfx, options, out array); if (result != SecStatusCode.Success) { throw new InvalidOperationException(string.Format("Could not create the new instance for type {0} due to {1}.", t.Name, result)); } return(new SecIdentity(array [0].LowlevelObjectForKey(SecImportExport.Identity.Handle))); } case "SecTrust": X509Certificate x = new X509Certificate(mail_google_com); using (var policy = SecPolicy.CreateSslPolicy(true, "mail.google.com")) return(new SecTrust(x, policy)); case "SslContext": return(new SslContext(SslProtocolSide.Client, SslConnectionType.Stream)); case "UIFontFeature": return(new UIFontFeature(CTFontFeatureNumberSpacing.Selector.ProportionalNumbers)); case "NetworkReachability": return(new NetworkReachability(IPAddress.Loopback, null)); case "VTCompressionSession": case "VTSession": return(VTCompressionSession.Create(1024, 768, CMVideoCodecType.H264, (sourceFrame, status, flags, buffer) => { }, null, (CVPixelBufferAttributes)null)); case "VTFrameSilo": return(VTFrameSilo.Create()); case "VTMultiPassStorage": return(VTMultiPassStorage.Create()); case "CFString": return(new CFString("test")); case "DispatchBlock": return(new DispatchBlock(() => { })); case "DispatchQueue": return(new DispatchQueue("com.example.subsystem.taskXYZ")); case "DispatchGroup": return(DispatchGroup.Create()); case "CGColorSpace": return(CGColorSpace.CreateDeviceCmyk()); case "CGGradient": CGColor[] cArray = { UIColor.Black.CGColor, UIColor.Clear.CGColor, UIColor.Blue.CGColor }; return(new CGGradient(null, cArray)); case "CGImage": filename = "xamarin1.png"; using (var dp = new CGDataProvider(filename)) return(CGImage.FromPNG(dp, null, false, CGColorRenderingIntent.Default)); case "CGColor": return(UIColor.Black.CGColor); case "CMClock": return(CMClock.HostTimeClock); case "CMTimebase": return(new CMTimebase(CMClock.HostTimeClock)); case "CVPixelBufferPool": return(new CVPixelBufferPool( new CVPixelBufferPoolSettings(), new CVPixelBufferAttributes(CVPixelFormatType.CV24RGB, 100, 50) )); case "SecCertificate": using (var cdata = NSData.FromArray(mail_google_com)) return(new SecCertificate(cdata)); case "SecCertificate2": using (var cdata = NSData.FromArray(mail_google_com)) return(new SecCertificate2(new SecCertificate(cdata))); case "SecTrust2": X509Certificate x2 = new X509Certificate(mail_google_com); using (var policy = SecPolicy.CreateSslPolicy(true, "mail.google.com")) return(new SecTrust2(new SecTrust(x2, policy))); case "SecIdentity2": using (var options = NSDictionary.FromObjectAndKey(new NSString("farscape"), SecImportExport.Passphrase)) { NSDictionary[] array; var result = SecImportExport.ImportPkcs12(farscape_pfx, options, out array); if (result != SecStatusCode.Success) { throw new InvalidOperationException(string.Format("Could not create the new instance for type {0} due to {1}.", t.Name, result)); } return(new SecIdentity2(new SecIdentity(array [0].LowlevelObjectForKey(SecImportExport.Identity.Handle)))); } case "SecKey": SecKey private_key; SecKey public_key; using (var record = new SecRecord(SecKind.Key)) { record.KeyType = SecKeyType.RSA; record.KeySizeInBits = 512; // it's not a performance test :) SecKey.GenerateKeyPair(record.ToDictionary(), out public_key, out private_key); return(private_key); } case "SecAccessControl": return(new SecAccessControl(SecAccessible.WhenPasscodeSetThisDeviceOnly)); default: throw new InvalidOperationException(string.Format("Could not create the new instance for type {0}.", t.Name)); } }
public override void DidReceiveChallenge(NSUrlSession session, NSUrlSessionTask task, NSUrlAuthenticationChallenge challenge, Action <NSUrlSessionAuthChallengeDisposition, NSUrlCredential> completionHandler) { if (challenge.ProtectionSpace.AuthenticationMethod == NSUrlProtectionSpace.AuthenticationMethodNTLM) { NetworkCredential credentialsToUse; if (This.Credentials != null) { if (This.Credentials is NetworkCredential) { credentialsToUse = (NetworkCredential)This.Credentials; } else { var uri = this.getResponseForTask(task).Request.RequestUri; credentialsToUse = This.Credentials.GetCredential(uri, "NTLM"); } var credential = new NSUrlCredential(credentialsToUse.UserName, credentialsToUse.Password, NSUrlCredentialPersistence.ForSession); completionHandler(NSUrlSessionAuthChallengeDisposition.UseCredential, credential); } return; } if (challenge.ProtectionSpace.AuthenticationMethod == NSUrlProtectionSpace.AuthenticationMethodClientCertificate) { Console.WriteLine("Client Cert!"); var password = "******"; var options = NSDictionary.FromObjectAndKey(NSObject.FromObject(password), SecImportExport.Passphrase); var path = Path.Combine(NSBundle.MainBundle.BundlePath, "Content", "client.p12"); var certData = File.ReadAllBytes(path); NSDictionary[] importResult; X509Certificate cert = new X509Certificate(certData, password); SecStatusCode statusCode = SecImportExport.ImportPkcs12(certData, options, out importResult); var identityHandle = importResult[0][SecImportExport.Identity]; var identity = new SecIdentity(identityHandle.Handle); var certificate = new SecCertificate(cert.GetRawCertData()); SecCertificate[] certificates = { certificate }; NSUrlCredential credential = NSUrlCredential.FromIdentityCertificatesPersistance(identity, certificates, NSUrlCredentialPersistence.ForSession); completionHandler(NSUrlSessionAuthChallengeDisposition.UseCredential, credential); return; } if (!This.customSSLVerification) { goto doDefault; } if (challenge.ProtectionSpace.AuthenticationMethod != "NSURLAuthenticationMethodServerTrust") { goto doDefault; } if (ServicePointManager.ServerCertificateValidationCallback == null) { goto doDefault; } // Convert Mono Certificates to .NET certificates and build cert // chain from root certificate var serverCertChain = challenge.ProtectionSpace.ServerSecTrust; var chain = new X509Chain(); X509Certificate2 root = null; var errors = SslPolicyErrors.None; if (serverCertChain == null || serverCertChain.Count == 0) { errors = SslPolicyErrors.RemoteCertificateNotAvailable; goto sslErrorVerify; } if (serverCertChain.Count == 1) { errors = SslPolicyErrors.RemoteCertificateChainErrors; goto sslErrorVerify; } var netCerts = Enumerable.Range(0, serverCertChain.Count) .Select(x => serverCertChain[x].ToX509Certificate2()) .ToArray(); for (int i = 1; i < netCerts.Length; i++) { chain.ChainPolicy.ExtraStore.Add(netCerts[i]); } root = netCerts[0]; chain.ChainPolicy.RevocationFlag = X509RevocationFlag.EntireChain; chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck; chain.ChainPolicy.UrlRetrievalTimeout = new TimeSpan(0, 1, 0); chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllowUnknownCertificateAuthority; if (!chain.Build(root)) { errors = SslPolicyErrors.RemoteCertificateChainErrors; goto sslErrorVerify; } var subject = root.Subject; var subjectCn = cnRegex.Match(subject).Groups[1].Value; if (String.IsNullOrWhiteSpace(subjectCn) || !Utility.MatchHostnameToPattern(task.CurrentRequest.Url.Host, subjectCn)) { errors = SslPolicyErrors.RemoteCertificateNameMismatch; goto sslErrorVerify; } sslErrorVerify: var hostname = task.CurrentRequest.Url.Host; bool result = ServicePointManager.ServerCertificateValidationCallback(hostname, root, chain, errors); if (result) { completionHandler( NSUrlSessionAuthChallengeDisposition.UseCredential, NSUrlCredential.FromTrust(challenge.ProtectionSpace.ServerSecTrust)); } else { completionHandler(NSUrlSessionAuthChallengeDisposition.CancelAuthenticationChallenge, null); } return; doDefault: completionHandler(NSUrlSessionAuthChallengeDisposition.PerformDefaultHandling, challenge.ProposedCredential); return; }