public static CipherSuiteCollection GetSupportedCiphers (bool server, SecurityProtocolType protocol) { switch (protocol) { case SecurityProtocolType.Default: case SecurityProtocolType.Tls: return CipherSuiteFactory.GetTls1SupportedCiphers (); case SecurityProtocolType.Ssl3: return CipherSuiteFactory.GetSsl3SupportedCiphers (); case SecurityProtocolType.Ssl2: default: throw new NotSupportedException ("Unsupported security protocol type"); } }
public ServerContext( SslServerStream stream, SecurityProtocolType securityProtocolType, X509Certificate serverCertificate, bool clientCertificateRequired) : base(securityProtocolType) { this.sslStream = stream; this.clientCertificateRequired = clientCertificateRequired; // Convert the System.Security cert to a Mono Cert MonoX509.X509Certificate cert = new MonoX509.X509Certificate(serverCertificate.GetRawCertData()); // Add server certificate to the certificate collection this.ServerSettings.Certificates = new MonoX509.X509CertificateCollection(); this.ServerSettings.Certificates.Add(cert); this.ServerSettings.UpdateCertificateRSA(); // Add requested certificate types this.ServerSettings.CertificateTypes = new ClientCertificateType[1]; this.ServerSettings.CertificateTypes[0] = ClientCertificateType.RSA; // Add certificate authorities MonoX509.X509CertificateCollection trusted = MonoX509.X509StoreManager.TrustedRootCertificates; string[] list = new string [trusted.Count]; int i = 0; foreach (MonoX509.X509Certificate root in trusted) { list [i++] = root.IssuerName; } this.ServerSettings.DistinguisedNames = list; }
public ServerContext( SslServerStream stream, SecurityProtocolType securityProtocolType, X509Certificate serverCertificate, bool clientCertificateRequired) : base(securityProtocolType) { this.sslStream = stream; this.clientCertificateRequired = clientCertificateRequired; // Convert the System.Security cert to a Mono Cert MonoX509.X509Certificate cert = new MonoX509.X509Certificate(serverCertificate.GetRawCertData()); // Add server certificate to the certificate collection this.ServerSettings.Certificates = new MonoX509.X509CertificateCollection(); this.ServerSettings.Certificates.Add(cert); this.ServerSettings.UpdateCertificateRSA(); // Add requested certificate types this.ServerSettings.CertificateTypes = new ClientCertificateType[1]; this.ServerSettings.CertificateTypes[0] = ClientCertificateType.RSA; // Add certificate authorities this.ServerSettings.DistinguisedNames = new string[0]; }
public static void EnableSecurityProtocol(SecurityProtocolType type = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12 | SecurityProtocolType.Ssl3) { ServicePointManager.SecurityProtocol |= type; }
private static void ValidateSecurityProtocol(SecurityProtocolType value) { SecurityProtocolType allowed = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; if ((value & ~allowed) != 0) { throw new NotSupportedException(SR.net_securityprotocolnotsupported); } }
static ServicePointManager() { servicePoints = new HybridDictionary(); policy = new DefaultCertificatePolicy(); defaultConnectionLimit = 2; maxServicePointIdleTime = 900000; maxServicePoints = 0; _checkCRL = false; _securityProtocol = (SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls); expectContinue = true; }
/// <summary> /// Only add one of these to your application to make sure clients will be reused whenever possible. /// This will return an existing client, if the same timeout has been used before. /// Otherwise, this will create a new client with the given timeout, because the timeout can only be set before the first request is sent. /// </summary> public AspNetCoreClients(SecurityProtocolType security) : this(timeout => new HttpClient() { Timeout = timeout }, new Once(() => { ServicePointManager.SecurityProtocol = security; }) ) { }
public OAuthAuthentication(MscMcomConfig iMcomConfig, ICerteficateReader certeficateReader, SecurityProtocolType securityProtocolType) { this.clientId = iMcomConfig.ConsumerKey; this.password = iMcomConfig.KeyPassword; this.filePath = iMcomConfig.CertPath; this.xmlStringPrivateKey = certeficateReader.GetPrivateKey(filePath, password); this.encoder = new UTF8Encoding(); ServicePointManager.SecurityProtocol = securityProtocolType; }
public ClientContext( SslClientStream stream, SecurityProtocolType securityProtocolType, string targetHost, X509CertificateCollection clientCertificates) : base(securityProtocolType) { this.sslStream = stream; this.ClientSettings.Certificates = clientCertificates; this.ClientSettings.TargetHost = targetHost; }
public static void SetSecurityProtocol() { var securityProtocol = ConfigurationManager.AppSettings["SecurityProtocol"].Convert2Int32(); SecurityProtocolType security = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; if (securityProtocol > 0) { security = (SecurityProtocolType)securityProtocol; } ServicePointManager.SecurityProtocol = security; }
/// <summary> /// Returns certificate validation to its original state. Has no effect unless <see cref="Platform.IsFullFramework"/> /// </summary> /// <param name="validateCertificates">Whether or not certificates should be validated</param> /// <param name="protocolType"><see cref="SecurityProtocolType"/></param> /// <param name="prevValidator">Pre-existing certificate validation callback</param> public static void RestoreCertificateValidation( bool validateCertificates, SecurityProtocolType protocolType, RemoteCertificateValidationCallback prevValidator) { if (Platform.IsFullFramework && !validateCertificates) { ServicePointManager.SecurityProtocol = protocolType; ServicePointManager.ServerCertificateValidationCallback = prevValidator; } }
private static void ValidateSecurityProtocol(SecurityProtocolType value) { // Do not allow Ssl2 (and others) as explicit SSL version request SecurityProtocolType allowed = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; if ((value & ~allowed) != 0) { throw new NotSupportedException(SR.GetString(SR.net_securityprotocolnotsupported)); } }
public Context(SecurityProtocolType securityProtocolType) { this.SecurityProtocol = securityProtocolType; this.compressionMethod = SecurityCompressionType.None; this.serverSettings = new TlsServerSettings(); this.clientSettings = new TlsClientSettings(); this.handshakeMessages = new TlsStream(); this.sessionId = null; this.handshakeState = HandshakeState.None; this.random = RandomNumberGenerator.Create(); }
public string ETowerApiCalling(string url, string shipmentRequestjson, string type) { try { string response = string.Empty; WebClient client = new WebClient(); client.UseDefaultCredentials = true; client.Credentials = CredentialCache.DefaultCredentials; ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3; SslProtocols _Tls12 = (SslProtocols)0x00000C00; SecurityProtocolType Tls12 = (SecurityProtocolType)_Tls12; ServicePointManager.SecurityProtocol = Tls12; #region DateHeader var CaTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Canada Central Standard Time"); var date = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second, DateTime.Now.Millisecond); var dateTimeZone = TimeZoneInfo.ConvertTimeToUtc(date, TimeZoneInfo.Local); var gmtTime = dateTimeZone.ToString("ddd, dd MMM yyyy HH':'mm':'ss 'GMT'"); string Authorization = string.Empty; #endregion #region Authorization var key = Encoding.UTF8.GetBytes("zjz4BKuTZ5spTY62QQtKyQ"); if (type == "Shipment") { var shipUrl = "POST\n" + gmtTime + "\nhttp://www.etowertech.com/services/shipper/orders"; Authorization = HMACSHA1("zjz4BKuTZ5spTY62QQtKyQ", shipUrl); } else if (type == "Label") { Authorization = string.Empty; var labelUrl = "POST\n" + gmtTime + "\nhttp://www.etowertech.com/services/shipper/labels"; Authorization = HMACSHA1("zjz4BKuTZ5spTY62QQtKyQ", labelUrl); } #endregion //Wed, 05 Dec 2018 06:05:58 GMT client.Headers[HttpRequestHeader.ContentType] = "application/json"; client.Headers["X-WallTech-Date"] = gmtTime; client.Headers["Authorization"] = "WallTech pclKaPYZz9Ie4N6QFpnnU5:" + Authorization.Trim(); response = client.UploadString(url, "POST", shipmentRequestjson); return(response); } catch (Exception ex) { throw ex; } }
/// <summary> /// Default constructor /// </summary> public HttpRequestConfiguration() { Method = "GET"; Credrntials = CredentialCache.DefaultNetworkCredentials; AuthLevel = AuthenticationLevel.None; ImpersonationLevel = TokenImpersonationLevel.None; KeepAlive = false; UserAgent = "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:31.0) Gecko/20100101 Firefox/31.0"; SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls; }
public async Task <SecurityResult> GetPermissionsAsync(string token) { if (string.IsNullOrEmpty(token)) { return(new SecurityResult(HttpStatusCode.Unauthorized, AUTHORIZATION_HEADER_INVALID)); } string checkPermissionsUri = _options.CloudFoundryApi + "/v2/apps/" + _options.ApplicationId + "/permissions"; var request = new HttpRequestMessage(HttpMethod.Get, checkPermissionsUri); AuthenticationHeaderValue auth = new AuthenticationHeaderValue("bearer", token); request.Headers.Authorization = auth; SecurityProtocolType prevProtocols = default(SecurityProtocolType); RemoteCertificateValidationCallback prevValidator = null; try { _logger.LogDebug("GetPermissions({0}, {1})", checkPermissionsUri, token); // If certificate validation is disabled, inject a callback to handle properly HttpClientHelper.ConfigureCertificateValidation( _options.ValidateCertificates, out prevProtocols, out prevValidator); using (var client = HttpClientHelper.GetHttpClient(_options.ValidateCertificates, DEFAULT_GETPERMISSIONS_TIMEOUT)) { using (HttpResponseMessage response = await client.SendAsync(request)) { if (response.StatusCode != HttpStatusCode.OK) { _logger?.LogInformation( "Cloud Foundry returned status: {HttpStatus} while obtaining permissions from: {PermissionsUri}", response.StatusCode, checkPermissionsUri); return(response.StatusCode == HttpStatusCode.Forbidden ? new SecurityResult(HttpStatusCode.Forbidden, ACCESS_DENIED_MESSAGE) : new SecurityResult(HttpStatusCode.ServiceUnavailable, CLOUDFOUNDRY_NOT_REACHABLE_MESSAGE)); } return(new SecurityResult(await GetPermissions(response))); } } } catch (Exception e) { _logger?.LogError("Cloud Foundry returned exception: {SecurityException} while obtaining permissions from: {PermissionsUri}", e, checkPermissionsUri); return(new SecurityResult(HttpStatusCode.ServiceUnavailable, CLOUDFOUNDRY_NOT_REACHABLE_MESSAGE)); } finally { HttpClientHelper.RestoreCertificateValidation(_options.ValidateCertificates, prevProtocols, prevValidator); } }
public static void SecurityProtocol_Ssl3_NotSupported() { const int ssl2Client = 0x00000008; const int ssl2Server = 0x00000004; const SecurityProtocolType ssl2 = (SecurityProtocolType)(ssl2Client | ssl2Server); #pragma warning disable 0618 // Ssl2, Ssl3 are deprecated. Assert.Throws <NotSupportedException>(() => ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3); Assert.Throws <NotSupportedException>(() => ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | ssl2); #pragma warning restore }
protected virtual void ConfigureCertificateValidatation(out SecurityProtocolType protocolType, out RemoteCertificateValidationCallback prevValidator) { prevValidator = null; protocolType = (SecurityProtocolType)0; if (!_settings.ValidateCertificates) { protocolType = ServicePointManager.SecurityProtocol; ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; prevValidator = ServicePointManager.ServerCertificateValidationCallback; ServicePointManager.ServerCertificateValidationCallback = (sender, cert, chain, sslPolicyErrors) => true; } }
public static async Task <JwtSecurityToken> ValidateToken( string token, string issuer, IConfigurationManager <OpenIdConnectConfiguration> configurationManager, string audience, CancellationToken ct = default(CancellationToken)) { if (string.IsNullOrEmpty(token)) { throw new ArgumentNullException(nameof(token)); } if (string.IsNullOrEmpty(issuer)) { throw new ArgumentNullException(nameof(issuer)); } try { const SslProtocols _Tls12 = (SslProtocols)0x00000C00; const SecurityProtocolType Tls12 = (SecurityProtocolType)_Tls12; ServicePointManager.SecurityProtocol = Tls12; var discoveryDocument = await configurationManager.GetConfigurationAsync(ct); var signingKeys = discoveryDocument.SigningKeys; var validationParameters = new TokenValidationParameters { RequireExpirationTime = true, RequireSignedTokens = true, ValidateIssuer = true, ValidIssuer = issuer, ValidateIssuerSigningKey = true, IssuerSigningKeys = signingKeys, ValidateLifetime = true, ValidateAudience = true, ValidAudience = audience, // Allow for some drift in server time // (a lower value is better; we recommend two minutes or less) ClockSkew = TimeSpan.FromMinutes(2), // See additional validation for aud below }; var principal = new JwtSecurityTokenHandler() .ValidateToken(token, validationParameters, out var rawValidatedToken); return((JwtSecurityToken)rawValidatedToken); } catch (Exception e) { throw e; } //catch (System.IdentityModel.Tokens.SecurityTokenValidationException) {return null;} }
public SslServerStream( Stream stream, System.Security.Cryptography.X509Certificates.X509Certificate serverCertificate, bool clientCertificateRequired, bool requestClientCertificate, bool ownsStream, SecurityProtocolType securityProtocolType) : base(stream, ownsStream) { this.context = (Context) new ServerContext(this, securityProtocolType, serverCertificate, clientCertificateRequired, requestClientCertificate); this.protocol = (RecordProtocol) new ServerRecordProtocol(this.innerStream, (ServerContext)this.context); }
public SecureTLSDumbfuckery() { _oldSecurityProtocol = ServicePointManager.SecurityProtocol; ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12 | SecurityProtocolType.Ssl3; _oldExpect100Continue = ServicePointManager.Expect100Continue; ServicePointManager.Expect100Continue = true; }
public ServerContext( SslServerStream stream, SecurityProtocolType securityProtocolType, X509Certificate serverCertificate, bool clientCertificateRequired, bool requestClientCertificate) : base(securityProtocolType) { this.sslStream = stream; this.clientCertificateRequired = clientCertificateRequired; this.request_client_certificate = requestClientCertificate; // Convert the System.Security cert to a Mono Cert MonoX509.X509Certificate cert = new MonoX509.X509Certificate(serverCertificate.GetRawCertData()); // Add server certificate to the certificate collection this.ServerSettings.Certificates = new MonoX509.X509CertificateCollection(); this.ServerSettings.Certificates.Add(cert); this.ServerSettings.UpdateCertificateRSA(); // Build the chain for the certificate and if the chain is correct, add all certificates // (except the root certificate [FIRST ONE] ... the client is supposed to know that one, // otherwise the whole concept of a trusted chain doesn't work out ... MonoX509.X509Chain chain = new MonoX509.X509Chain(MonoX509.X509StoreManager.IntermediateCACertificates); if (chain.Build(cert)) { for (int j = chain.Chain.Count - 1; j > 0; j--) { ServerSettings.Certificates.Add(chain.Chain [j]); } } // Add requested certificate types ServerSettings.CertificateTypes = new ClientCertificateType [ServerSettings.Certificates.Count]; for (int j = 0; j < this.ServerSettings.CertificateTypes.Length; j++) { ServerSettings.CertificateTypes [j] = ClientCertificateType.RSA; } // Add certificate authorities MonoX509.X509CertificateCollection trusted = MonoX509.X509StoreManager.TrustedRootCertificates; string[] list = new string [trusted.Count]; int i = 0; foreach (MonoX509.X509Certificate root in trusted) { list [i++] = root.IssuerName; } this.ServerSettings.DistinguisedNames = list; }
public static string GetAppName(int id) { string appName = "Unknown App"; string requestUrl = string.Format(CultureInfo.InvariantCulture, "https://store.steampowered.com/api/appdetails?appids={0}", id); var requestContents = string.Empty; const SslProtocols _Tls12 = (SslProtocols)0x00000C00; const SecurityProtocolType Tls12 = (SecurityProtocolType)_Tls12; ServicePointManager.SecurityProtocol = Tls12; var webRequest = (HttpWebRequest)WebRequest.Create(requestUrl); webRequest.Method = "GET"; WebResponse response = null; try { response = (HttpWebResponse)webRequest.GetResponse(); } catch (System.Net.WebException ex) { Logger.Instance.Error("Failed to retrieve app name, defaulting to Unknown App"); Logger.Instance.Exception(ex); return(appName); } using (StreamReader streamReader = new StreamReader(response.GetResponseStream())) { requestContents = streamReader.ReadToEnd(); } try { dynamic jsonContents = JObject.Parse(requestContents); appName = jsonContents[id.ToString()]["data"]["name"]; } catch (JsonReaderException jsonEx) { Logger.Instance.Error("Failed to read app name"); Logger.Instance.Exception(jsonEx); } catch (Exception ex) { Logger.Instance.Exception(ex); } return(appName); }
public void Tls12SupportShouldBeAddedWithoutAffectingExistingProtocols() { ServicePointManager.SecurityProtocol = Ssl3 | Tls | Tls11; var connectionManager = ConnectionManager.Instance; SecurityProtocolType actual = ServicePointManager.SecurityProtocol; Assert.IsTrue(actual.HasFlag(Ssl3), "SSL3 support got removed."); Assert.IsTrue(actual.HasFlag(Tls), "TLSv1.0 support got removed."); Assert.IsTrue(actual.HasFlag(Tls11), "TLSv1.1 support got removed."); Assert.IsTrue(actual.HasFlag(Tls12), "TLSv1.2 support not added."); }
public void ChangeProtocol(short protocol) { SecurityProtocolType protocol1 = this.DecodeProtocolCode(protocol); if ((protocol1 & this.SecurityProtocolFlags) != protocol1 && (this.SecurityProtocolFlags & SecurityProtocolType.Default) != SecurityProtocolType.Default) { throw new TlsException(AlertDescription.ProtocolVersion, "Incorrect protocol version received from server"); } this.SecurityProtocol = protocol1; this.SupportedCiphers.Clear(); this.SupportedCiphers = (CipherSuiteCollection)null; this.SupportedCiphers = CipherSuiteFactory.GetSupportedCiphers(protocol1); }
/// <summary> /// Initializes a new instance of the <see cref="RedmineManager" /> class. /// Most of the time, the API requires authentication. To enable the API-style authentication, you have to check Enable /// REST API in Administration -> Settings -> Authentication. Then, authentication can be done in 2 different /// ways: /// using your regular login/password via HTTP Basic authentication. /// using your API key which is a handy way to avoid putting a password in a script. The API key may be attached to /// each request in one of the following way: /// passed in as a "key" parameter /// passed in as a username with a random password via HTTP Basic authentication /// passed in as a "X-Redmine-API-Key" HTTP header (added in Redmine 1.1.0) /// You can find your API key on your account page ( /my/account ) when logged in, on the right-hand pane of the /// default layout. /// </summary> /// <param name="host">The host.</param> /// <param name="login">The login.</param> /// <param name="password">The password.</param> /// <param name="mimeFormat">The MIME format.</param> /// <param name="verifyServerCert">if set to <c>true</c> [verify server cert].</param> /// <param name="proxy">The proxy.</param> /// <param name="securityProtocolType">Use this parameter to specify a SecurityProtcolType. Note: it is recommended to leave this parameter at its default value as this setting also affects the calling application process.</param> /// <param name="timeout">The webclient timeout. Default is 100 seconds.</param> public RedmineManager(string host, string login, string password, MimeFormat mimeFormat = MimeFormat.Xml, bool verifyServerCert = true, IWebProxy proxy = null, SecurityProtocolType securityProtocolType = default, TimeSpan?timeout = null) : this(host, mimeFormat, verifyServerCert, proxy, securityProtocolType, timeout : timeout) { cache = new CredentialCache { { new Uri(host), "Basic", new NetworkCredential(login, password) } }; var token = Convert.ToBase64String(Encoding.UTF8.GetBytes(string.Format(CultureInfo.InvariantCulture, "{0}:{1}", login, password))); basicAuthorization = string.Format(CultureInfo.InvariantCulture, "Basic {0}", token); }
public void TestIssue156(string url, SecurityProtocolType sptFail, SecurityProtocolType sptSucceed) { var spDefault = ServicePointManager.SecurityProtocol; SharpMap.Layers.WmsLayer wmsLayer = null; ServicePointManager.SecurityProtocol = sptFail; Assert.That(() => wmsLayer = new SharpMap.Layers.WmsLayer("WMSFAIL", url), Throws.InstanceOf <System.ApplicationException>()); ServicePointManager.SecurityProtocol = sptSucceed; Assert.That(() => wmsLayer = new SharpMap.Layers.WmsLayer("WMSSUCCED", url), Throws.Nothing); Assert.That(wmsLayer, Is.Not.Null, "wmsLayer null"); ServicePointManager.SecurityProtocol = spDefault; }
public NasaSecureHttpRequest(String httpAddr, SecurityProtocolType protocolType, CookieContainer secureCookieContainer) { if (httpAddr != null && httpAddr != String.Empty) { HttpAddr = httpAddr; SecureProtocolType = protocolType; SecureCookieContainer = secureCookieContainer; } else { NasaRequestStatus = NASA_STATUS.NASA_REQUEST_UNSUCCESSFUL; } }
private static void ValidateSecurityProtocol(SecurityProtocolType value) { const SecurityProtocolType Allowed = #pragma warning disable CA5364 // Do Not Use Deprecated Security Protocols SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | #pragma warning restore CA5364 SecurityProtocolType.Tls12 | SecurityProtocolType.Tls13; if ((value & ~Allowed) != 0) { throw new NotSupportedException(SR.net_securityprotocolnotsupported); } }
private static void Update(InstallerInfo installerInfo) { if (null == installerInfo) { throw new ArgumentNullException("installerInfo"); } if (!IsConnectedToInternet) { throw new UpdateNoInternetException(); } string tempPath = Path.GetTempPath(); string msiPath = Path.Combine(tempPath, "MzingaSetup.msi"); if (File.Exists(msiPath)) { File.Delete(msiPath); } using (WebClient client = new WebClient()) { client.Headers["User-Agent"] = _userAgent; SecurityProtocolType oldType = ServicePointManager.SecurityProtocol; ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; // Fix since Github only supports TLS1.2 client.DownloadFile(installerInfo.Url, msiPath); ServicePointManager.SecurityProtocol = oldType; } string cmdFile = Path.Combine(tempPath, "UpdateMzinga.cmd"); using (StreamWriter sw = new StreamWriter(new FileStream(cmdFile, FileMode.Create))) { sw.WriteLine("msiexec /i \"{0}\" /qb", msiPath); } AppVM.DoOnUIThread(() => { Process p = new Process { StartInfo = new ProcessStartInfo("cmd.exe", string.Format("/c {0}", cmdFile)) { CreateNoWindow = true } }; p.Start(); System.Windows.Application.Current.Shutdown(); }); }
private static List <UrlError> CheckParallel([NotNull] IEnumerable <string> urls, int threadCount) { Assert.ArgumentNotNull(urls, nameof(urls)); Assert.ArgumentCondition(threadCount > 0, "Unexpected thread count: {0}", threadCount); var checkers = new List <UrlChecker>(threadCount); checkers.AddRange(CollectionUtils.Partition(urls, threadCount) .Select(chunk => new UrlChecker(chunk))); SecurityProtocolType securityProtocols = ServicePointManager.SecurityProtocol; try { // try setting value corresponding to: Ssl3 | Tls | Tls11 | Tls12 // Ssl: 48 // Tls: 192 // Tls11: 768 // Tls12: 3072 // Note: Tls11 and Tls12 require either .Net 4.5, or the installation of TLS support package for .Net 3.5.1 // (https://support.microsoft.com/en-us/help/3154518/support-for-tls-system-default-versions-included-in-the--net-framework) // Note: enum values Tls11 and Tls12 are not defined in .Net 3.5, so try setting the integer value ServicePointManager.SecurityProtocol = (SecurityProtocolType)4080; } catch (Exception) { // shouldn't have been changed, but to be sure: reset value ServicePointManager.SecurityProtocol = securityProtocols; } try { CheckParallel(checkers); } finally { ServicePointManager.SecurityProtocol = securityProtocols; } var result = new List <UrlError>(); foreach (UrlChecker checker in checkers) { result.AddRange(checker.Result); } return(result); }
private void processProtocol(short protocol) { SecurityProtocolType securityProtocolType = base.Context.DecodeProtocolCode(protocol); if ((securityProtocolType & base.Context.SecurityProtocolFlags) == securityProtocolType || (base.Context.SecurityProtocolFlags & SecurityProtocolType.Default) == SecurityProtocolType.Default) { base.Context.SecurityProtocol = securityProtocolType; base.Context.SupportedCiphers.Clear(); base.Context.SupportedCiphers = null; base.Context.SupportedCiphers = CipherSuiteFactory.GetSupportedCiphers(securityProtocolType); return; } throw new TlsException(AlertDescription.ProtocolVersion, "Incorrect protocol version received from server"); }
protected void btnLogin_Click(object sender, EventArgs e) { if (!Request.IsAuthenticated) { const SslProtocols _Tls12 = (SslProtocols)0x00000C00; const SecurityProtocolType Tls12 = (SecurityProtocolType)_Tls12; ServicePointManager.SecurityProtocol = Tls12; HttpContext.Current.GetOwinContext().Authentication.Challenge( new AuthenticationProperties { RedirectUri = "/" }, OpenIdConnectAuthenticationDefaults.AuthenticationType); } }
public void ServicePointManager_CheckAllowedProtocols_SystemDefault_Allowed() { SecurityProtocolType orig = ServicePointManager.SecurityProtocol; try { ServicePointManager.SecurityProtocol = SecurityProtocolType.SystemDefault; Assert.Equal(orig, ServicePointManager.SecurityProtocol); } finally { ServicePointManager.SecurityProtocol = orig; } }
public CipherSuiteCollection (SecurityProtocolType protocol) { switch (protocol) { case SecurityProtocolType.Default: case SecurityProtocolType.Tls: case SecurityProtocolType.Ssl3: this.protocol = protocol; break; case SecurityProtocolType.Ssl2: default: throw new NotSupportedException ("Unsupported security protocol type."); } }
public ServerContext( SslServerStream stream, SecurityProtocolType securityProtocolType, X509Certificate serverCertificate, bool clientCertificateRequired, bool requestClientCertificate) : base(securityProtocolType) { this.sslStream = stream; this.clientCertificateRequired = clientCertificateRequired; this.request_client_certificate = requestClientCertificate; // Convert the System.Security cert to a Mono Cert MonoX509.X509Certificate cert = new MonoX509.X509Certificate(serverCertificate.GetRawCertData()); // Add server certificate to the certificate collection this.ServerSettings.Certificates = new MonoX509.X509CertificateCollection(); this.ServerSettings.Certificates.Add(cert); this.ServerSettings.UpdateCertificateRSA(); if (CertificateValidationHelper.SupportsX509Chain) { // Build the chain for the certificate and if the chain is correct, add all certificates // (except the root certificate [FIRST ONE] ... the client is supposed to know that one, // otherwise the whole concept of a trusted chain doesn't work out ... MonoX509.X509Chain chain = new MonoX509.X509Chain (MonoX509.X509StoreManager.IntermediateCACertificates); if (chain.Build (cert)) { for (int j = chain.Chain.Count - 1; j > 0; j--) ServerSettings.Certificates.Add (chain.Chain [j]); } } // Add requested certificate types ServerSettings.CertificateTypes = new ClientCertificateType [ServerSettings.Certificates.Count]; for (int j = 0; j < this.ServerSettings.CertificateTypes.Length; j++) ServerSettings.CertificateTypes [j] = ClientCertificateType.RSA; if (CertificateValidationHelper.SupportsX509Chain) { // Add certificate authorities MonoX509.X509CertificateCollection trusted = MonoX509.X509StoreManager.TrustedRootCertificates; string[] list = new string [trusted.Count]; int i = 0; foreach (MonoX509.X509Certificate root in trusted) { list [i++] = root.IssuerName; } this.ServerSettings.DistinguisedNames = list; } }
public static CipherSuiteCollection GetSupportedCiphers (bool server, SecurityProtocolType protocol) { CipherSuiteCollection suites; switch (protocol) { case SecurityProtocolType.Default: case SecurityProtocolType.Tls: suites = CipherSuiteFactory.GetTls1SupportedCiphers (); break; case SecurityProtocolType.Ssl3: suites = CipherSuiteFactory.GetSsl3SupportedCiphers (); break; case SecurityProtocolType.Ssl2: default: throw new NotSupportedException ("Unsupported security protocol type"); } IEnumerable<string> list = null; #if INSIDE_SYSTEM // if SSL/TLS support is built-in System.dll (e.g. monotouch) then we can access ServicePointManager // extension directly var cb = server ? ServicePointManager.ServerCipherSuitesCallback : ServicePointManager.ClientCipherSuitesCallback; if (cb == null) return suites; // e.g. no callback was set list = cb ((System.Net.SecurityProtocolType) (int) protocol, suites.GetNames ()); #elif !BOOTSTRAP_BASIC // Mono.Security must work on MS.NET so it cannot depend on any Mono-specific extensions PropertyInfo pi = null; if (server) { if (server_callback == null) server_callback = spm.GetProperty ("ServerCipherSuitesCallback", BindingFlags.Static | BindingFlags.Public); pi = server_callback; } else { if (client_callback == null) client_callback = spm.GetProperty ("ClientCipherSuitesCallback", BindingFlags.Static | BindingFlags.Public); pi = client_callback; } if (pi == null) return suites; // e.g. MS runtime - return every supported suites var cb = (Delegate) pi.GetGetMethod ().Invoke (null, null); if (cb == null) return suites; // e.g. no callback was set - return every supported suites list = (IEnumerable<string>) cb.DynamicInvoke (new object[] { (System.Net.SecurityProtocolType) (int) protocol, suites.GetNames () }); #else // TODO: right now the callback is only available when using System.Net.* types for SSL/TLS return suites; #endif CipherSuiteCollection allowed = new CipherSuiteCollection (protocol); if (list != null) { foreach (var name in list) { // add any supported (ignore unknowns) ciphers requested by the callback var cipher = suites [name]; if (cipher != null) allowed.Add (cipher); } } return allowed; }
public SslServerStream( Stream stream, X509Certificate serverCertificate, bool clientCertificateRequired, bool requestClientCertificate, bool ownsStream, SecurityProtocolType securityProtocolType) : base(stream, ownsStream) { this.context = new ServerContext( this, securityProtocolType, serverCertificate, clientCertificateRequired, requestClientCertificate); this.protocol = new ServerRecordProtocol(innerStream, (ServerContext)this.context); }
public CipherSuiteCollection(SecurityProtocolType protocol) : base() { this.protocol = protocol; this.cipherSuites = new ArrayList(); }
private System.Version DefaultProtocolVersion = System.Net.HttpVersion.Version11; //for some reason this one is not allowed to be declared as a const... #endregion Fields #region Constructors public CartWebClientConfig(XElement configXml = null) { //Set defaults SessionTimeout = DefaultSessionTimeout; ResponseTimeout = DefaultResponseTimeout; RetryDelay = DefaultRetryDelay; MaxTries = DefaultMaxTries; //BufferSize = DefaultBufferSize; SecurityProtocol = DefaultSecurityProtocol; ProtocolVersion = DefaultProtocolVersion; KeepAlive = false; Expect100Continue = false; AllowUnsafeHeaderParsing = false; ConnectionLimit = DefaultConnectionLimit; //configXml will override defaults if (configXml != null) Xml = configXml; }
public SslClientStream( Stream stream, string targetHost, bool ownsStream, SecurityProtocolType securityProtocolType, X509CertificateCollection clientCertificates) { if (stream == null) { throw new ArgumentNullException("stream is null."); } if (!stream.CanRead || !stream.CanWrite) { throw new ArgumentNullException("stream is not both readable and writable."); } if (targetHost == null || targetHost.Length == 0) { throw new ArgumentNullException("targetHost is null or an empty string."); } this.context = new ClientContext( this, securityProtocolType, targetHost, clientCertificates); this.inputBuffer = new MemoryStream(); this.innerStream = stream; this.ownsStream = ownsStream; this.negotiate = new object (); this.read = new object (); this.write = new object (); this.protocol = new ClientRecordProtocol(innerStream, context); }
private static void EnsureStrongCryptoSettingsInitialized() { if (disableStrongCryptoInitialized) { return; } lock (disableStrongCryptoLock) { if (disableStrongCryptoInitialized) { return; } bool disableStrongCryptoInternal = true; try { string strongCryptoKey = String.Format(CultureInfo.InvariantCulture, strongCryptoKeyVersionedPattern, Environment.Version.ToString(3)); // We read reflected keys on WOW64. using (RegistryKey key = Registry.LocalMachine.OpenSubKey(strongCryptoKey)) { try { object schUseStrongCryptoKeyValue = key.GetValue(strongCryptoValueName, null); // Setting the value to 1 will enable the MSRC behavior. // All other values are ignored. if ((schUseStrongCryptoKeyValue != null) && (key.GetValueKind(strongCryptoValueName) == RegistryValueKind.DWord)) { disableStrongCryptoInternal = ((int)schUseStrongCryptoKeyValue) != 1; } } catch (UnauthorizedAccessException) { } catch (IOException) { } } } catch (SecurityException) { } catch (ObjectDisposedException) { } if (disableStrongCryptoInternal) { // Revert the SecurityProtocol selection to the legacy combination. s_SecurityProtocolType = SecurityProtocolType.Tls | SecurityProtocolType.Ssl3; } else { s_SecurityProtocolType = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls; // Attempt to read this from the AppSettings config section string appSetting = ConfigurationManager.AppSettings[secureProtocolAppSetting]; SecurityProtocolType value; try { value = (SecurityProtocolType)Enum.Parse(typeof(SecurityProtocolType), appSetting); ValidateSecurityProtocol(value); s_SecurityProtocolType = value; } catch (ArgumentNullException) { } catch (ArgumentException) { } catch (NotSupportedException) { } } disableStrongCrypto = disableStrongCryptoInternal; disableStrongCryptoInitialized = true; } }
private static void EnsureStrongCryptoSettingsInitialized() { if (disableStrongCryptoInitialized) { return; } lock (disableStrongCryptoLock) { if (disableStrongCryptoInitialized) { return; } try { bool disableStrongCryptoInternal = false; int schUseStrongCryptoKeyValue = 0; if (LocalAppContextSwitches.DontEnableSchUseStrongCrypto) { //.Net 4.5.2 and below will default to false unless the registry key is specifically set to 1. schUseStrongCryptoKeyValue = RegistryConfiguration.GlobalConfigReadInt(strongCryptoValueName, 0); disableStrongCryptoInternal = schUseStrongCryptoKeyValue != 1; } else { // .Net 4.6 and above will default to true unless the registry key is specifically set to 0. schUseStrongCryptoKeyValue = RegistryConfiguration.GlobalConfigReadInt(strongCryptoValueName, 1); disableStrongCryptoInternal = schUseStrongCryptoKeyValue == 0; } if (disableStrongCryptoInternal) { // Revert the SecurityProtocol selection to the legacy combination. s_SecurityProtocolType = SecurityProtocolType.Tls | SecurityProtocolType.Ssl3; } else { s_SecurityProtocolType = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls; string appSetting = RegistryConfiguration.AppConfigReadString(secureProtocolAppSetting, null); SecurityProtocolType value; try { value = (SecurityProtocolType)Enum.Parse(typeof(SecurityProtocolType), appSetting); ValidateSecurityProtocol(value); s_SecurityProtocolType = value; } // Ignore all potential exceptions caused by Enum.Parse. catch (ArgumentNullException) { } catch (ArgumentException) { } catch (NotSupportedException) { } catch (OverflowException) { } } disableStrongCrypto = disableStrongCryptoInternal; disableStrongCryptoInitialized = true; } catch (Exception e) { if (e is ThreadAbortException || e is StackOverflowException || e is OutOfMemoryException) { throw; } } } }
public SslServerStream( Stream stream, X509Certificate serverCertificate, bool clientCertificateRequired, bool ownsStream, SecurityProtocolType securityProtocolType) : this (stream, serverCertificate, clientCertificateRequired, false, ownsStream, securityProtocolType) { }
public SslServerStream( Stream stream, X509Certificate serverCertificate, bool clientCertificateRequired, bool ownsStream, SecurityProtocolType securityProtocolType) { if (stream == null) { throw new ArgumentNullException("stream is null."); } if (!stream.CanRead || !stream.CanWrite) { throw new ArgumentNullException("stream is not both readable and writable."); } this.context = new ServerContext( this, securityProtocolType, serverCertificate, clientCertificateRequired); this.inputBuffer = new BufferedStream(new MemoryStream()); this.innerStream = stream; this.ownsStream = ownsStream; this.read = new object (); this.write = new object (); this.protocol = new ServerRecordProtocol(innerStream, context); }
public void SetUp() { DefaultSecurityProtocol = ServicePointManager.SecurityProtocol; }
public SslClientStream( Stream stream, string targetHost, bool ownsStream, SecurityProtocolType securityProtocolType, X509CertificateCollection clientCertificates): base(stream, ownsStream) { if (targetHost == null || targetHost.Length == 0) { throw new ArgumentNullException("targetHost is null or an empty string."); } this.context = new ClientContext( this, securityProtocolType, targetHost, clientCertificates); this.protocol = new ClientRecordProtocol(innerStream, (ClientContext)this.context); }
private void ProcessCipherSpecV2Buffer (SecurityProtocolType protocol, byte[] buffer) { TlsStream codes = new TlsStream(buffer); string prefix = (protocol == SecurityProtocolType.Ssl3) ? "SSL_" : "TLS_"; while (codes.Position < codes.Length) { byte check = codes.ReadByte(); if (check == 0) { // SSL/TLS cipher spec short code = codes.ReadInt16(); int index = this.Context.SupportedCiphers.IndexOf(code); if (index != -1) { this.Context.Negotiating.Cipher = this.Context.SupportedCiphers[index]; break; } } else { byte[] tmp = new byte[2]; codes.Read(tmp, 0, tmp.Length); int tmpCode = ((check & 0xff) << 16) | ((tmp[0] & 0xff) << 8) | (tmp[1] & 0xff); CipherSuite cipher = this.MapV2CipherCode(prefix, tmpCode); if (cipher != null) { this.Context.Negotiating.Cipher = cipher; break; } } } if (this.Context.Negotiating == null) { throw new TlsException(AlertDescription.InsuficientSecurity, "Insuficient Security"); } }
public SslClientStream( Stream stream, string targetHost, bool ownsStream, SecurityProtocolType securityProtocolType) : this( stream, targetHost, ownsStream, securityProtocolType, new X509CertificateCollection()) { }