public DerivedKeySecurityToken (string id, string algorithm, SecurityKeyIdentifierClause reference, SymmetricSecurityKey referencedKey, string name, int? generation, int? offset, int? length, string label, byte [] nonce) { algorithm = algorithm ?? SecurityAlgorithms.Psha1KeyDerivation; this.id = id; this.algorithm = algorithm; this.reference = reference; this.generation = generation; this.offset = offset; this.length = length; this.nonce = nonce; this.name = name; this.label = label; SecurityKey key = new InMemorySymmetricSecurityKey ( referencedKey.GenerateDerivedKey ( algorithm, Encoding.UTF8.GetBytes (label ?? Constants.WsscDefaultLabel), nonce, (length ?? 32) * 8, offset ?? 0)); keys = new ReadOnlyCollection<SecurityKey> ( new SecurityKey [] {key}); }
/// <summary> /// Initializes a new instance of the <see cref="SymmetricSignatureProvider"/> class that uses an <see cref="SymmetricSecurityKey"/> to create and / or verify signatures over a array of bytes. /// </summary> /// <param name="key">The <see cref="SymmetricSecurityKey"/> used for signing.</param> /// <param name="algorithm">The signature algorithm to use.</param> /// <exception cref="ArgumentNullException">'key' is null.</exception> /// <exception cref="ArgumentNullException">'algorithm' is null.</exception> /// <exception cref="ArgumentException">'algorithm' contains only whitespace.</exception> /// <exception cref="ArgumentOutOfRangeException">'<see cref="SymmetricSecurityKey"/>.KeySize' is smaller than <see cref="SignatureProviderFactory.MinimumSymmetricKeySizeInBits"/>.</exception> /// <exception cref="InvalidOperationException"><see cref="SymmetricSecurityKey.GetKeyedHashAlgorithm"/> throws.</exception> /// <exception cref="InvalidOperationException"><see cref="SymmetricSecurityKey.GetKeyedHashAlgorithm"/> returns null.</exception> /// <exception cref="InvalidOperationException"><see cref="SymmetricSecurityKey.GetSymmetricKey"/> throws.</exception> public SymmetricSignatureProvider(SymmetricSecurityKey key, string algorithm) { if (key == null) { throw new ArgumentNullException("key"); } if (null == algorithm) { throw new ArgumentNullException(algorithm); } if (string.IsNullOrWhiteSpace(algorithm)) { throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, ErrorMessages.IDX10002, "algorithm")); } if (key.KeySize < SignatureProviderFactory.MinimumSymmetricKeySizeInBits) { throw new ArgumentOutOfRangeException("key.KeySize", key.KeySize, string.Format(CultureInfo.InvariantCulture, ErrorMessages.IDX10603, key.GetType(), SignatureProviderFactory.MinimumSymmetricKeySizeInBits)); } try { this.keyedHash = key.GetKeyedHashAlgorithm(algorithm); } catch (Exception ex) { if (DiagnosticUtility.IsFatal(ex)) { throw; } throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, ErrorMessages.IDX10632, algorithm, key, ex), ex); } if (this.keyedHash == null) { throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, ErrorMessages.IDX10633, algorithm, key)); } try { this.keyedHash.Key = key.GetSymmetricKey(); } catch (Exception ex) { if (DiagnosticUtility.IsFatal(ex)) { throw; } throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, ErrorMessages.IDX10634, algorithm, key, ex), ex); } }
public FaultingSymmetricSecurityKey(SymmetricSecurityKey key, Exception throwMe, SymmetricAlgorithm algorithm = null, KeyedHashAlgorithm keyedHash = null, byte[] keyBytes = null) { _throwMe = throwMe; _key = key; _keyedHash = keyedHash; _agorithm = algorithm; _keyBytes = keyBytes; }
private void SymmetricSignatureProvider_ConstructorVariation(string testcase, SymmetricSecurityKey key, string algorithm, ExpectedException expectedException) { Console.WriteLine(string.Format("Testcase: '{0}'", testcase)); SymmetricSignatureProvider provider = null; try { if (testcase.StartsWith("Signing")) { provider = new SymmetricSignatureProvider(key, algorithm); } else { provider = new SymmetricSignatureProvider(key, algorithm); } expectedException.ProcessNoException(); } catch (Exception ex) { expectedException.ProcessException(ex); } }
/// <summary> /// Initializes a new instance of the <see cref="SessionSecurityToken"/> class. /// </summary> /// <param name="claimsPrincipal"><see cref="ClaimsPrincipal"/> associated with this session.</param> /// <param name="contextId">Context Identifier that identifies the session</param> /// <param name="context">Optional context information associated with the session.</param> /// <param name="endpointId">The endpoint to which this token is bound. String.Empty would create a unscoped token.</param> /// <param name="validFrom">DateTime specifying the time the token becomes valid.</param> /// <param name="validTo">DateTime specifying the time the token becomes invalid.</param> /// <param name="key">Optional symmetric session key.</param> /// <exception cref="ArgumentNullException">The input parameter 'claimsPrincipal' is null.</exception> /// <exception cref="ArgumentNullException">The input parameter 'contextId' is null.</exception> /// <exception cref="ArgumentOutOfRangeException">validFrom is greater than or equal to validTo.</exception> /// <exception cref="ArgumentOutOfRangeException">validTo is less than current time.</exception> /// <remarks> /// If no key is supplied, a 128bit key is generated. KeyEffectiveTime is set to validFrom, KeyExpirationTime is set to validTo. /// A key generation identifier is created. /// </remarks> public SessionSecurityToken(ClaimsPrincipal claimsPrincipal, SysUniqueId contextId, string context, string endpointId, DateTime? validFrom, DateTime? validTo, SymmetricSecurityKey key) : this(claimsPrincipal, contextId, System.IdentityModel.UniqueId.CreateUniqueId(), context, key == null ? null : key.GetSymmetricKey(), endpointId, validFrom, validTo, null, validFrom, validTo, null, null) { }
internal void Initialize(SafeFreeCredentials credentialsHandle, ChannelBinding channelBinding, ExtendedProtectionPolicy extendedProtectionPolicy) { if (!this.isAuthenticated) { bool flag = false; SafeDeleteContext refContext = null; SafeCloseHandle token = null; byte[] request = this.request; try { if (credentialsHandle == null) { credentialsHandle = SspiWrapper.AcquireDefaultCredential("Kerberos", CredentialUse.Inbound, new string[0]); flag = true; } SspiContextFlags inFlags = SspiContextFlags.AllocateMemory | SspiContextFlags.Confidentiality | SspiContextFlags.SequenceDetect | SspiContextFlags.ReplayDetect; ExtendedProtectionPolicyHelper helper = new ExtendedProtectionPolicyHelper(channelBinding, extendedProtectionPolicy); if (((helper.PolicyEnforcement == PolicyEnforcement.Always) && (helper.ChannelBinding == null)) && (helper.ProtectionScenario != ProtectionScenario.TrustedProxy)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(System.IdentityModel.SR.GetString("SecurityChannelBindingMissing"))); } if (helper.PolicyEnforcement == PolicyEnforcement.WhenSupported) { inFlags |= SspiContextFlags.ChannelBindingAllowMissingBindings; } if (helper.ProtectionScenario == ProtectionScenario.TrustedProxy) { inFlags |= SspiContextFlags.ChannelBindingProxyBindings; } SspiContextFlags zero = SspiContextFlags.Zero; SecurityBuffer outputBuffer = new SecurityBuffer(0, BufferType.Token); List <SecurityBuffer> list = new List <SecurityBuffer>(2) { new SecurityBuffer(request, 2) }; if (helper.ShouldAddChannelBindingToASC()) { list.Add(new SecurityBuffer(helper.ChannelBinding)); } SecurityBuffer[] inputBuffers = null; if (list.Count > 0) { inputBuffers = list.ToArray(); } int error = SspiWrapper.AcceptSecurityContext(credentialsHandle, ref refContext, inFlags, Endianness.Native, inputBuffers, outputBuffer, ref zero); switch (error) { case 0: break; case 0x90312: throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(System.IdentityModel.SR.GetString("KerberosMultilegsNotSupported"), new Win32Exception(error))); case -2146893056: throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(System.IdentityModel.SR.GetString("KerberosApReqInvalidOrOutOfMemory"), new Win32Exception(error))); default: throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(System.IdentityModel.SR.GetString("FailAcceptSecurityContext"), new Win32Exception(error))); } LifeSpan span = (LifeSpan)SspiWrapper.QueryContextAttributes(refContext, ContextAttribute.Lifespan); DateTime effectiveTimeUtc = span.EffectiveTimeUtc; DateTime expiryTimeUtc = span.ExpiryTimeUtc; SecuritySessionKeyClass class2 = (SecuritySessionKeyClass)SspiWrapper.QueryContextAttributes(refContext, ContextAttribute.SessionKey); this.symmetricSecurityKey = new InMemorySymmetricSecurityKey(class2.SessionKey); error = SspiWrapper.QuerySecurityContextToken(refContext, out token); if (error != 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(error)); } System.Security.Principal.WindowsIdentity windowsIdentity = new System.Security.Principal.WindowsIdentity(token.DangerousGetHandle(), "Kerberos"); base.Initialize(this.id, "Kerberos", effectiveTimeUtc, expiryTimeUtc, windowsIdentity, false); this.isAuthenticated = true; } finally { if (token != null) { token.Close(); } if (refContext != null) { refContext.Close(); } if (flag && (credentialsHandle != null)) { credentialsHandle.Close(); } } } }
/// <summary> /// Initializes a new instance of the <see cref="SessionSecurityToken"/> class. /// </summary> /// <param name="claimsPrincipal"><see cref="ClaimsPrincipal"/> associated with this session.</param> /// <param name="contextId">Optional context identifier associated with this token. If null a new identifier will be generated.</param> /// <param name="context">Optional context information associated with the session.</param> /// <param name="endpointId">The endpoint to which this token is bound. String.Empty would create a unscoped token.</param> /// <param name="lifetime">The lifetime of the session token. ValidFrom will be set to DateTime.UtcNow, ValidTo will be set to ValidFrom + lifetime.</param> /// <param name="key">Optional symmetric session key.</param> /// <exception cref="InvalidOperationException">The value of lifetime <= TimeSpan.Zero."</exception> public SessionSecurityToken(ClaimsPrincipal claimsPrincipal, SysUniqueId contextId, string context, string endpointId, TimeSpan lifetime, SymmetricSecurityKey key) : this(claimsPrincipal, contextId, context, endpointId, DateTime.UtcNow, lifetime, key) { }
/// <summary> /// Initializes a new instance of the <see cref="SessionSecurityToken"/> class. /// </summary> /// <param name="claimsPrincipal"><see cref="ClaimsPrincipal"/> associated with this session.</param> /// <param name="contextId">Optional context identifier associated with this token. If null a new identifier will be generated.</param> /// <param name="context">Optional context information associated with the session.</param> /// <param name="endpointId">The endpoint to which this token is bound. String.Empty would create a unscoped token.</param> /// <param name="validFrom">DateTime specifying the time the token becomes valid.</param> /// <param name="lifetime">The lifetime of the session token. ValidTo will be set to ValidFrom + lifetime.</param> /// <param name="key">Optional symmetric session key.</param> /// <exception cref="InvalidOperationException">The value of lifetime <= TimeSpan.Zero."</exception> public SessionSecurityToken(ClaimsPrincipal claimsPrincipal, SysUniqueId contextId, string context, string endpointId, DateTime validFrom, TimeSpan lifetime, SymmetricSecurityKey key) : this(claimsPrincipal, contextId, context, endpointId, validFrom, DateTimeUtil.AddNonNegative(validFrom, lifetime), key) { }
public SessionSecurityToken (ClaimsPrincipal claimsPrincipal, UniqueId contextId, string context, string endpointId, DateTime? validFrom, DateTime? validTo, SymmetricSecurityKey key) { ClaimsPrincipal = claimsPrincipal; ContextId = contextId; Context = context; EndpointId = endpointId; validFrom = (validFrom.HasValue) ? validFrom.Value.ToUniversalTime () : DateTime.UtcNow; validTo = (validTo.HasValue) ? validTo.Value.ToUniversalTime () : ValidFrom + SessionSecurityTokenHandler.DefaultTokenLifetime; securityKeys = new ReadOnlyCollection<SecurityKey> (new SecurityKey[] { new InMemorySymmetricSecurityKey ((key == null) ? null : key.GetSymmetricKey ()) }); }
public SessionSecurityToken (ClaimsPrincipal claimsPrincipal, UniqueId contextId, string context, string endpointId, DateTime validFrom, TimeSpan lifetime, SymmetricSecurityKey key) : this (claimsPrincipal, contextId, context, endpointId, validFrom, validFrom + lifetime, key) { }
// This method gets called by the runtime. Use this method to add services to the container public void ConfigureServices(IServiceCollection services) { // Add framework services. services.AddAuthentication(); SecurityKey signingKey; //RSACryptoServiceProvider randomRSA = new RSACryptoServiceProvider(2048); //RSAParameters keyParams = randomRSA.ExportParameters(true); //signingKey = new RsaSecurityKey(keyParams); //services.AddSingleton(new SigningCredentials(signingKey, SecurityAlgorithms.RsaSha256)); signingKey = new SymmetricSecurityKey(System.Text.Encoding.ASCII.GetBytes(ServiceConfiguration.SigningKey)); // This could be changed every hour or so signingKey.CryptoProviderFactory = new MonoFriendlyCryptoProviderFactory(_LoggerFactory.CreateLogger<MonoFriendlyCryptoProviderFactory>()); services.AddSingleton(new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256)); services.AddAuthorization(auth => { auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder() .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme) .RequireAuthenticatedUser().Build()); }); services.Configure<JwtBearerOptions>(options => { options.SecurityTokenValidators.Clear(); options.SecurityTokenValidators.Add(new OrganisationSecurityTokenHandler()); options.TokenValidationParameters.IssuerSigningKey = signingKey; // Basic settings - signing key to validate with, audience and issuer. options.TokenValidationParameters.ValidateAudience = false; options.TokenValidationParameters.ValidateIssuer = false; //options.TokenValidationParameters.ValidAudience = TOKEN_AUDIENCE; //options.TokenValidationParameters.ValidIssuer = TOKEN_ISSUER; // When receiving a token, check that we've signed it. options.TokenValidationParameters.ValidateLifetime = true; // Where external tokens are used, some leeway here could be useful. options.TokenValidationParameters.ClockSkew = TimeSpan.FromMinutes(0); options.AutomaticAuthenticate = true; #if DEBUG options.RequireHttpsMetadata = false; // not in prod #else options.RequireHttpsMetadata = true; #endif }); services.AddMvc(); services.Configure<Microsoft.AspNetCore.Mvc.MvcOptions>(options => { options.RespectBrowserAcceptHeader = true; options.InputFormatters.Clear(); options.InputFormatters.Add(new MediaTypeJsonInputFormatter(_LoggerFactory.CreateLogger<MediaTypeJsonInputFormatter>())); options.InputFormatters.Add(new MediaTypeXmlSerializerInputFormatter()); options.OutputFormatters.Clear(); options.OutputFormatters.Add(new MediaTypeJsonOutputFormatter()); options.OutputFormatters.Add(new MediaTypeXmlSerializerOutputFormatter()); // Register filter globally options.Filters.Add(new ExceptionResultFilterAttribute(_LoggerFactory.CreateLogger<ExceptionResultFilterAttribute>())); }); #if DEBUG services.AddCors(); var policy = new Microsoft.AspNetCore.Cors.Infrastructure.CorsPolicy(); policy.Headers.Add("*"); policy.Methods.Add("*"); policy.Origins.Add("*"); policy.SupportsCredentials = true; services.Configure<Microsoft.AspNetCore.Cors.Infrastructure.CorsOptions>(x => x.AddPolicy("allowEveryThingPolicy", policy)); #endif }
// Ensure acceptable decrypting symmetric key. // 1) if derived key, validate derived key against DefaultEncryptionKeyDerivationLength and validate // source key against DefaultSymmetricKeyLength // 2) if not derived key, validate key against DefaultSymmetricKeyLength internal void EnsureAcceptableDecryptionSymmetricKeySize(SymmetricSecurityKey securityKey, SecurityToken token) { int keySize; DerivedKeySecurityToken dkt = token as DerivedKeySecurityToken; if (dkt != null) { token = dkt.TokenToDerive; keySize = ((SymmetricSecurityKey)token.SecurityKeys[0]).KeySize; // doing special case for derived key token signing length since // the sending side doesn't honor the algorithm suite. It used the DefaultSignatureKeyDerivationLength instead if (dkt.SecurityKeys[0].KeySize < this.DefaultEncryptionKeyDerivationLength) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException( SR.GetString(SR.TokenDoesNotMeetKeySizeRequirements, this, dkt, dkt.SecurityKeys[0].KeySize))); } } else { keySize = securityKey.KeySize; } if (!IsSymmetricKeyLengthSupported(keySize)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException( SR.GetString(SR.TokenDoesNotMeetKeySizeRequirements, this, token, keySize))); } }
private void GenerateRsaKeys() { var key = "IxrAjDoa2FqElO7IhrSrUJELhUckePEPVpaePlS_Xaw"; var keyByte = TextEncodings.Base64Url.Decode(key); var symmetricSecurityKey = new SymmetricSecurityKey(keyByte); using (var rsa = new RSACryptoServiceProvider(2048)) { _key = new RsaSecurityKey(rsa.ExportParameters(true)); _signingCredentials = new SigningCredentials( symmetricSecurityKey, SecurityAlgorithms.HmacSha256Signature, SecurityAlgorithms.Sha256Digest, "secret"); rsa.PersistKeyInCsp = false; } }