Beispiel #1
0
 /// <summary>
 /// Initializes a new instance of the <see cref="CookieBasedSessions"/> class.
 /// </summary>
 /// <param name="encryptionProvider">The encryption provider.</param>
 /// <param name="passPhrase">The encryption pass phrase.</param>
 /// <param name="salt">The encryption salt.</param>
 /// <param name="sessionObjectFormatter">Session object formatter to use</param>
 public CookieBasedSessions(IEncryptionProvider encryptionProvider, string passPhrase, string salt, ISessionObjectFormatter sessionObjectFormatter)
 {
     this.encryptionProvider = encryptionProvider;
     this.passPhrase = passPhrase;
     this.salt = CreateSalt(salt);
     this.formatter = sessionObjectFormatter;
 }
Beispiel #2
0
        public static string DecryptSigned(
            IEncryptionProvider encryptionProvider,
            IHmacProvider signatureProvider,
            string input)
        {
            try
            {
                var signatureLength = Base64Helpers.GetBase64Length(signatureProvider.HmacLength);

                var encryptedInput = input.Substring(signatureLength);
                var signature = input.Substring(0, signatureLength);

                var signatureBytes = Convert.FromBase64String(signature);
                var newSignatureBytes = signatureProvider.GenerateHmac(encryptedInput);
                var signatureIsValid = HmacComparer.Compare(
                    signatureBytes,
                    newSignatureBytes,
                    signatureProvider.HmacLength);

                var decryptedId = encryptionProvider.Decrypt(encryptedInput);

                return signatureIsValid ? decryptedId : String.Empty;
            }
            catch
            {
                return String.Empty;
            }
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="CookieBasedSessions"/> class.
 /// </summary>
 /// <param name="encryptionProvider">The encryption provider.</param>
 /// <param name="hmacProvider">The hmac provider</param>
 /// <param name="objectSerializer">Session object serializer to use</param>
 public CookieBasedSessions(IEncryptionProvider encryptionProvider, IHmacProvider hmacProvider, IObjectSerializer objectSerializer)
 {
     this.currentConfiguration = new CookieBasedSessionsConfiguration
     {
         Serializer = objectSerializer,
         CryptographyConfiguration = new CryptographyConfiguration(encryptionProvider, hmacProvider)
     };
 }
Beispiel #4
0
        /// <summary>
        /// Initialise and add cookie based session hooks to the application pipeine
        /// </summary>
        /// <param name="applicationPipelines">Application pipelines</param>
        /// <param name="encryptionProvider">Encryption provider for encrypting cookies</param>
        /// <param name="passPhrase">Encryption pass phrase</param>
        /// <param name="salt">Encryption salt</param>
        /// <returns>Formatter selector for choosing a non-default formatter</returns>
        public static IFormatterSelector Enable(IApplicationPipelines applicationPipelines, IEncryptionProvider encryptionProvider, string passPhrase, string salt)
        {
            var sessionStore = new CookieBasedSessions(encryptionProvider, passPhrase, salt, new DefaultSessionObjectFormatter());

            applicationPipelines.BeforeRequest.AddItemToEndOfPipeline(ctx => LoadSession(ctx, sessionStore));
            applicationPipelines.AfterRequest.AddItemToEndOfPipeline(ctx => SaveSession(ctx, sessionStore));

            return sessionStore;
        }
        public CookieBasedSessionsFixture()
        {
            this.fakeEncryptionProvider = A.Fake<IEncryptionProvider>();
            this.fakeHmacProvider = A.Fake<IHmacProvider>();
            this.cookieStore = new CookieBasedSessions(this.fakeEncryptionProvider, this.fakeHmacProvider, new Fakes.FakeSessionObjectFormatter());

            this.rijndaelEncryptionProvider = new RijndaelEncryptionProvider(new PassphraseKeyGenerator("password"));
            this.defaultHmacProvider = new DefaultHmacProvider(new PassphraseKeyGenerator("anotherpassword"));
        }
        public CookieBasedSessionsFixture()
        {
            this.fakeEncryptionProvider = A.Fake<IEncryptionProvider>();
            this.fakeHmacProvider = A.Fake<IHmacProvider>();
            this.cookieStore = new CookieBasedSessions(this.fakeEncryptionProvider, this.fakeHmacProvider, new Fakes.FakeObjectSerializer());

            this.rijndaelEncryptionProvider = new RijndaelEncryptionProvider(new PassphraseKeyGenerator("password", new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }, 1000));
            this.defaultHmacProvider = new DefaultHmacProvider(new PassphraseKeyGenerator("anotherpassword", new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }, 1000));
        }
        public SQLiteEncryptedBlobCache(string databaseFile, IEncryptionProvider encryptionProvider = null, IScheduler scheduler = null) : base(databaseFile, scheduler)
        {
            this.encryption = encryptionProvider ?? Locator.Current.GetService<IEncryptionProvider>();

            if (this.encryption == null)
            {
                throw new Exception("No IEncryptionProvider available. This should never happen, your DependencyResolver is broken");
            }
        }
 /// <summary>
 ///   Initializes a new instance of the <see cref="BySessionIdCookieIdentificationMethod" /> class.
 /// </summary>
 public BySessionIdCookieIdentificationMethod(CryptographyConfiguration cryptoConfig) {
   if (cryptoConfig == null) throw new ArgumentNullException("cryptoConfig");
   _encryptionProvider = cryptoConfig.EncryptionProvider;
   _hmacProvider = cryptoConfig.HmacProvider;
   _sessionIdentificationDataProvider = new SessionIdentificationDataProvider(cryptoConfig.HmacProvider);
   _hmacValidator = new HmacValidator(cryptoConfig.HmacProvider);
   _sessionIdFactory = new SessionIdFactory();
   _cookieFactory = new CookieFactory();
   CookieName = DefaultCookieName;
 }
 /// <summary>
 ///   Initializes a new instance of the <see cref="ByQueryStringParamIdentificationMethod" /> class.
 /// </summary>
 public ByQueryStringParamIdentificationMethod(CryptographyConfiguration cryptoConfig) {
   if (cryptoConfig == null) throw new ArgumentNullException("cryptoConfig");
   _encryptionProvider = cryptoConfig.EncryptionProvider;
   _hmacProvider = cryptoConfig.HmacProvider;
   _sessionIdentificationDataProvider = new SessionIdentificationDataProvider(cryptoConfig.HmacProvider);
   _hmacValidator = new HmacValidator(cryptoConfig.HmacProvider);
   _sessionIdFactory = new SessionIdFactory();
   _responseManipulatorForSession = new ResponseManipulatorForSession();
   ParameterName = DefaultParameterName;
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="RedisBasedSessions"/> class.
        /// </summary>
        /// <param name="encryptionProvider">The encryption provider.</param>
        /// <param name="hmacProvider">The hmac provider</param>
        /// <param name="objectSerializer">Session object serializer to use</param>
        public RedisBasedSessions(IEncryptionProvider encryptionProvider, IHmacProvider hmacProvider, IObjectSerializer objectSerializer)
        {
            _currentConfiguration = new RedisBasedSessionsConfiguration
            {
                Serializer = objectSerializer,
                CryptographyConfiguration = new CryptographyConfiguration(encryptionProvider, hmacProvider)
            };

            if (_redis == null)
                _redis = ConnectionMultiplexer.Connect(_currentConfiguration.ConnectionString);

            _db = _redis.GetDatabase();
        }
        public EncryptedBlobCache(
            string cacheDirectory = null,
            IEncryptionProvider encryptionProvider = null,
            IFilesystemProvider filesystemProvider = null, 
            IScheduler scheduler = null,
            Action<AsyncSubject<byte[]>> invalidatedCallback = null) 
            : base(cacheDirectory, filesystemProvider, scheduler, invalidatedCallback)
        {
            this.encryption = encryptionProvider ?? Locator.Current.GetService<IEncryptionProvider>();

            if (this.encryption == null)
            {
                throw new Exception("No IEncryptionProvider available. This should never happen, your DependencyResolver is broken");
            }
        }
 public ByQueryStringParamIdentificationMethodFixture() {
   _fakeEncryptionProvider = A.Fake<IEncryptionProvider>();
   _fakeHmacProvider = A.Fake<IHmacProvider>();
   _validConfiguration = new InProcSessionsConfiguration();
   _fakeSessionIdentificationDataProvider = A.Fake<ISessionIdentificationDataProvider>();
   _fakeHmacValidator = A.Fake<IHmacValidator>();
   _fakeSessionIdFactory = A.Fake<ISessionIdFactory>();
   _fakeResponseManipulatorForSession = A.Fake<IResponseManipulatorForSession>();
   _byQueryStringParamIdentificationMethod = new ByQueryStringParamIdentificationMethod(
     _fakeEncryptionProvider,
     _fakeHmacProvider,
     _fakeSessionIdentificationDataProvider,
     _fakeHmacValidator,
     _fakeSessionIdFactory,
     _fakeResponseManipulatorForSession);
   _parameterName = "TheNameOfTheParameter";
   _byQueryStringParamIdentificationMethod.ParameterName = _parameterName;
 }
Beispiel #13
0
 public static ActionResult Data(this Controller controller, object data, string contentType = null, Encoding encoding = null, IEncryptionProvider encryptor = null)
 {
     string type = controller.Request.QueryString["type"];
     if (string.IsNullOrEmpty(type))
     {
         type = "json";
     }
     switch (type.ToLower())
     {
         case "json":
         default:
             //return new JsonResult() { Data = data, ContentType = contentType, ContentEncoding = encoding, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
             var jsonSerializer = IocInstance.Container.Resolve<Core.Serialization.IJsonSerializer>();
             return new DAF.Web.Mvc.Results.JsonResult(jsonSerializer, encryptor) { Data = data, ContentType = contentType, ContentEncoding = encoding };
         case "xml":
             return new XmlResult() { Data = data, ContentType = contentType, ContentEncoding = encoding };
     }
 }
 public BySessionIdCookieIdentificationMethodFixture() {
   _fakeEncryptionProvider = A.Fake<IEncryptionProvider>();
   _fakeHmacProvider = A.Fake<IHmacProvider>();
   _validConfiguration = new InProcSessionsConfiguration();
   _fakeSessionIdentificationDataProvider = A.Fake<ISessionIdentificationDataProvider>();
   _fakeHmacValidator = A.Fake<IHmacValidator>();
   _fakeSessionIdFactory = A.Fake<ISessionIdFactory>();
   _fakeCookieFactory = A.Fake<ICookieFactory>();
   _bySessionIdCookieIdentificationMethod = new BySessionIdCookieIdentificationMethod(
     _fakeEncryptionProvider,
     _fakeHmacProvider,
     _fakeSessionIdentificationDataProvider,
     _fakeHmacValidator,
     _fakeSessionIdFactory,
     _fakeCookieFactory);
   _cookieName = "TheNameOfTheCookie";
   _bySessionIdCookieIdentificationMethod.CookieName = _cookieName;
 }
 /// <summary>
 ///   Initializes a new instance of the <see cref="ByQueryStringParamIdentificationMethod" /> class.
 /// </summary>
 internal ByQueryStringParamIdentificationMethod(
   IEncryptionProvider encryptionProvider,
   IHmacProvider hmacProvider,
   ISessionIdentificationDataProvider sessionIdentificationDataProvider,
   IHmacValidator hmacValidator,
   ISessionIdFactory sessionIdFactory,
   IResponseManipulatorForSession responseManipulatorForSession) {
   if (encryptionProvider == null) throw new ArgumentNullException("encryptionProvider");
   if (hmacProvider == null) throw new ArgumentNullException("hmacProvider");
   if (sessionIdentificationDataProvider == null) throw new ArgumentNullException("configuration");
   if (hmacValidator == null) throw new ArgumentNullException("configuration");
   if (sessionIdFactory == null) throw new ArgumentNullException("configuration");
   if (responseManipulatorForSession == null) throw new ArgumentNullException("responseManipulatorForSession");
   _encryptionProvider = encryptionProvider;
   _hmacProvider = hmacProvider;
   _sessionIdentificationDataProvider = sessionIdentificationDataProvider;
   _hmacValidator = hmacValidator;
   _sessionIdFactory = sessionIdFactory;
   _responseManipulatorForSession = responseManipulatorForSession;
   ParameterName = DefaultParameterName;
 }
 /// <summary>
 ///   Initializes a new instance of the <see cref="BySessionIdCookieIdentificationMethod" /> class.
 /// </summary>
 internal BySessionIdCookieIdentificationMethod(
   IEncryptionProvider encryptionProvider,
   IHmacProvider hmacProvider,
   ISessionIdentificationDataProvider sessionIdentificationDataProvider,
   IHmacValidator hmacValidator,
   ISessionIdFactory sessionIdFactory,
   ICookieFactory cookieFactory) {
   if (encryptionProvider == null) throw new ArgumentNullException("encryptionProvider");
   if (hmacProvider == null) throw new ArgumentNullException("hmacProvider");
   if (sessionIdentificationDataProvider == null) throw new ArgumentNullException("sessionIdentificationDataProvider");
   if (hmacValidator == null) throw new ArgumentNullException("hmacValidator");
   if (sessionIdFactory == null) throw new ArgumentNullException("sessionIdFactory");
   if (cookieFactory == null) throw new ArgumentNullException("cookieFactory");
   _encryptionProvider = encryptionProvider;
   _hmacProvider = hmacProvider;
   _sessionIdentificationDataProvider = sessionIdentificationDataProvider;
   _hmacValidator = hmacValidator;
   _sessionIdFactory = sessionIdFactory;
   _cookieFactory = cookieFactory;
   CookieName = DefaultCookieName;
 }
Beispiel #17
0
 public EncryptedStore(IKeyValueStore <TK, string> entityStore, IEncryptionProvider encryptionProvider)
 {
     this.entityStore        = Preconditions.CheckNotNull(entityStore, nameof(entityStore));
     this.EncryptionProvider = Preconditions.CheckNotNull(encryptionProvider, nameof(encryptionProvider));
 }
 /// <summary>
 /// Creates a new instance of the CryptographyConfiguration class
 /// </summary>
 /// <param name="encryptionProvider">Encryption provider</param>
 /// <param name="hmacProvider">HMAC provider</param>
 public CryptographyConfiguration(IEncryptionProvider encryptionProvider, IHmacProvider hmacProvider)
 {
     this.EncryptionProvider = encryptionProvider;
     this.HmacProvider = hmacProvider;
 }
 public static string Decrypt(IEncryptionProvider encryptionProvider, string value)
 {
     return encryptionProvider.Decrypt(value);
 }
Beispiel #20
0
 public JsonResult(IJsonSerializer jsonSerializer, IEncryptionProvider encryptor)
 {
     this.jsonSerializer = jsonSerializer;
     this.encryptor = encryptor;
 }
 public FileBackupConfigSource(string path, IConfigSource underlying, ISerde <DeploymentConfigInfo> serde, IEncryptionProvider encryptionProvider)
 {
     this.configFilePath     = Preconditions.CheckNonWhiteSpace(path, nameof(path));
     this.underlying         = Preconditions.CheckNotNull(underlying, nameof(underlying));
     this.serde              = Preconditions.CheckNotNull(serde, nameof(serde));
     this.encryptionProvider = Preconditions.CheckNotNull(encryptionProvider, nameof(IEncryptionProvider));
     Events.Created(this.configFilePath);
 }
 public PasswordProvider(IMsMcsAdmPwdProvider msMcsAdmPwdProvider, ILithnetAdminPasswordProvider lithnetProvider, IEncryptionProvider encryptionProvider, ICertificateProvider certificateProvider, ILogger <PasswordProvider> logger)
 {
     this.msLapsProvider      = msMcsAdmPwdProvider;
     this.lithnetProvider     = lithnetProvider;
     this.encryptionProvider  = encryptionProvider;
     this.certificateProvider = certificateProvider;
     this.logger = logger;
 }
 public AccountPasswordValidator(IEncryptionProvider encryptionProvider)
 {
     _encryptionProvider = encryptionProvider;
 }
        public void Encrypt(
            Stream reader,
            Stream writer,
            ReadOnlySpan <byte> privateKey   = default,
            ReadOnlySpan <byte> symmetricKey = default,
            IEncryptionProvider symmetricKeyEncryptionProvider = null)
        {
            Check.ArgNotNull(reader, nameof(reader));
            Check.ArgNotNull(writer, nameof(writer));

            byte[]           symmetricKeyRental = null;
            byte[]           ivRental           = null;
            byte[]           headerRental       = null;
            byte[]           signingKeyRental   = null;
            byte[]           buffer             = null;
            ArrayPool <byte> pool = ArrayPool <byte> .Shared;

            try
            {
                buffer = pool.Rent(4096);
                using (var header = this.GenerateHeader(this.options, symmetricKey, privateKey, null, symmetricKeyEncryptionProvider))
                {
                    symmetricKeyRental = pool.Rent(header.SymmetricKey.Memory.Length);
                    ivRental           = pool.Rent(header.IvSize);
                    header.SymmetricKey.Memory.CopyTo(symmetricKeyRental);
                    header.IV.Memory.CopyTo(ivRental);
                    this.algorithm ??= CreateSymmetricAlgorithm(this.options);

                    using (var encryptor = this.algorithm.CreateEncryptor(symmetricKeyRental, ivRental))
                    {
                        var cs = new CryptoStream(writer, encryptor, CryptoStreamMode.Write);
                        using (var bw = new BinaryWriter(writer, Utf8Options.NoBom, true))
                        {
                            bw.Write(new byte[header.HeaderSize]);
                            bw.Flush();
                        }

                        long bytesLeft = reader.Length;

                        while (bytesLeft > 0)
                        {
                            int read = reader.Read(buffer, 0, buffer.Length);
                            bytesLeft -= read;
                            cs.Write(buffer, 0, read);
                        }

                        cs.Flush();
                        cs.FlushFinalBlock();
                        writer.Flush();
                    }

                    headerRental = pool.Rent(header.HeaderSize);
                    header.Bytes.Memory.CopyTo(headerRental);

                    if (!this.options.SkipSigning && header.SigningKey != null && !header.SigningKey.Memory.IsEmpty)
                    {
                        signingKeyRental = pool.Rent(header.SigningKey.Memory.Length);
                        header.SigningKey.CopyTo(signingKeyRental);
                        using (var signer = CreateSigningAlgorithm(this.options))
                        {
                            signer.Key = signingKeyRental;

                            writer.Seek(header.HeaderSize, SeekOrigin.Begin);
                            var hash = signer.ComputeHash(writer);

                            Array.Copy(hash, 0, headerRental, header.Position, hash.Length);
                            hash.Clear();
                        }
                    }

                    writer.Seek(0, SeekOrigin.Begin);
                    using (var bw = new BinaryWriter(writer, Utf8Options.NoBom, true))
                    {
                        bw.Write(headerRental, 0, header.HeaderSize);
                        writer.Flush();
                        writer.Seek(0, SeekOrigin.End);
                    }
                }
            }
            finally
            {
                if (buffer != null)
                {
                    pool.Return(buffer, true);
                }

                if (symmetricKeyRental != null)
                {
                    pool.Return(symmetricKeyRental, true);
                }

                if (ivRental != null)
                {
                    pool.Return(ivRental, true);
                }

                if (headerRental != null)
                {
                    pool.Return(headerRental, true);
                }

                if (signingKeyRental != null)
                {
                    pool.Return(signingKeyRental, true);
                }
            }
        }
        /// <summary>
        /// Encrypts the data and returns the encrypted bytes.
        /// </summary>
        /// <param name="blob">The data to encrypt.</param>
        /// <param name="privateKey">
        ///  A password or phrase used to generate the key for the symmetric algorithm.
        /// </param>
        /// <param name="symmetricKey">
        ///  The key for the symmetric algorithm. If used, the private key is ignored
        ///  and the symmetric key is stored with the message.
        /// </param>
        /// <param name="symmetricKeyEncryptionProvider">
        ///  The encryption provider used to encrypt/decrypt the symmetric key when it is
        ///  stored with the message.
        /// </param>
        /// <returns>Encrypted bytes.</returns>
        public ReadOnlySpan <byte> Encrypt(
            ReadOnlySpan <byte> blob,
            ReadOnlySpan <byte> privateKey   = default,
            ReadOnlySpan <byte> symmetricKey = default,
            IEncryptionProvider symmetricKeyEncryptionProvider = null)
        {
            if (blob == null)
            {
                throw new ArgumentNullException(nameof(blob));
            }

            byte[]           symmetricKeyRental = null;
            byte[]           ivRental           = null;
            byte[]           headerRental       = null;
            byte[]           signingKeyRental   = null;
            ArrayPool <byte> pool = ArrayPool <byte> .Shared;

            try
            {
                using (var header = this.GenerateHeader(this.options, symmetricKey, privateKey, null, symmetricKeyEncryptionProvider))
                {
                    byte[] encryptedBlob = null;
                    symmetricKeyRental = pool.Rent(header.SymmetricKey.Memory.Length);
                    ivRental           = pool.Rent(header.IvSize);
                    header.SymmetricKey.Memory.CopyTo(symmetricKeyRental);
                    header.IV.Memory.CopyTo(ivRental);

                    this.algorithm = this.algorithm ?? CreateSymmetricAlgorithm(this.options);
                    using (var encryptor = this.algorithm.CreateEncryptor(symmetricKeyRental, ivRental))
                        using (var ms = new MemoryStream())
                            using (var cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
                            {
#if NET461 || NET451
                                var next = ArrayPool <byte> .Shared.Rent(blob.Length);

                                blob.CopyTo(next);
                                cs.Write(next, 0, next.Length);
                                next.Clear();
                                ArrayPool <byte> .Shared.Return(next);
#else
                                cs.Write(blob);
#endif
                                cs.Flush();
                                cs.FlushFinalBlock();
                                ms.Flush();
                                encryptedBlob = ms.ToArray();
                            }

                    headerRental = pool.Rent(header.HeaderSize);
                    header.Bytes.Memory.CopyTo(headerRental);

                    if (!this.options.SkipSigning && header.SigningKey != null && !header.SigningKey.Memory.IsEmpty)
                    {
                        signingKeyRental      = pool.Rent(header.SigningKey.Memory.Length);
                        this.signingAlgorithm = this.signingAlgorithm ?? CreateSigningAlgorithm(this.options);

                        header.SigningKey.Memory.CopyTo(signingKeyRental);
                        this.signingAlgorithm.Key = signingKeyRental;
                        var hash = this.signingAlgorithm.ComputeHash(encryptedBlob);

                        Array.Copy(hash, 0, headerRental, header.Position, hash.Length);

                        hash.Clear();
                        hash = null;
                    }

                    using (var ms = new MemoryStream())
                    {
                        using (var writer = new BinaryWriter(ms, Utf8Options.NoBom, true))
                        {
                            writer.Write(headerRental, 0, header.HeaderSize);
                        }

#if NET461 || NET451
                        ms.Write(encryptedBlob, 0, encryptedBlob.Length);
#else
                        ms.Write(encryptedBlob.AsMemory());
#endif
                        encryptedBlob.Clear();
                        ms.Flush();
                        return(ms.ToArray());
                    }
                }
            }
            finally
            {
                if (symmetricKeyRental != null)
                {
                    pool.Return(symmetricKeyRental, true);
                }

                if (ivRental != null)
                {
                    pool.Return(ivRental, true);
                }

                if (headerRental != null)
                {
                    pool.Return(headerRental, true);
                }

                if (signingKeyRental != null)
                {
                    pool.Return(signingKeyRental, true);
                }
            }
        }
        public void Decrypt(
            Stream reader,
            Stream writer,
            ReadOnlySpan <byte> privateKey = default,
            IEncryptionProvider symmetricKeyEncryptionProvider = null)
        {
            Check.ArgNotNull(reader, nameof(reader));
            Check.ArgNotNull(writer, nameof(writer));

            var pool = ArrayPool <byte> .Shared;

            byte[] rental             = null;
            byte[] signerKeyRental    = null;
            byte[] symmetricKeyRental = null;
            byte[] ivRental           = null;
            byte[] buffer             = null;
            try
            {
                buffer = pool.Rent(4096);
                using (var header = this.ReadHeader(reader, this.options, privateKey, symmetricKeyEncryptionProvider))
                {
                    long position = reader.Position;
                    this.algorithm = this.algorithm ?? CreateSymmetricAlgorithm(this.options);

                    if (header.Hash != null)
                    {
                        using (var signer = CreateSigningAlgorithm(this.options))
                        {
                            signerKeyRental = pool.Rent(header.SigningKey.Memory.Length);
                            header.SigningKey.CopyTo(signerKeyRental);
                            signer.Key = signerKeyRental;
                            var h1 = header.Hash;

                            long bytesRead = reader.Length - header.HeaderSize;
                            reader.Seek(header.HeaderSize, SeekOrigin.Begin);
                            var h2 = signer.ComputeHash(reader);

                            if (!h1.Memory.Span.SlowEquals(h2))
                            {
                                return;
                            }
                        }
                    }

                    reader.Seek(header.HeaderSize, SeekOrigin.Begin);

                    symmetricKeyRental = pool.Rent(header.SymmetricKey.Memory.Length);
                    ivRental           = pool.Rent(header.IvSize);

                    header.SymmetricKey.CopyTo(symmetricKeyRental);
                    header.IV.CopyTo(ivRental);
                    using (var decryptor = this.algorithm.CreateDecryptor(symmetricKeyRental, ivRental))
                    {
                        // TODO: create a sudo stream that breaks a dispose call.
                        var cs = new CryptoStream(writer, decryptor, CryptoStreamMode.Write);

                        long bytesRead = reader.Length - header.HeaderSize;
                        while (bytesRead > 0)
                        {
                            int read = reader.Read(buffer, 0, buffer.Length);
                            bytesRead -= read;
                            cs.Write(buffer, 0, read);
                        }

                        cs.Flush();
                        cs.FlushFinalBlock();
                        writer.Flush();
                    }
                }
            }
            finally
            {
                if (buffer != null)
                {
                    pool.Return(buffer, true);
                }

                if (rental != null)
                {
                    pool.Return(rental, true);
                }

                if (symmetricKeyRental != null)
                {
                    pool.Return(symmetricKeyRental, true);
                }

                if (ivRental != null)
                {
                    pool.Return(ivRental, true);
                }

                if (signerKeyRental != null)
                {
                    pool.Return(signerKeyRental, true);
                }
            }
        }
 public Login(IMapperProvider mapperProvider, IEncryptionProvider encryptionProvider, IAccountService accountService)
 {
     _mapperProvider     = mapperProvider;
     _accountService     = accountService;
     _encryptionProvider = encryptionProvider;
 }
Beispiel #28
0
 public ConsumerDataflow <TState> SetEncryptionProvider(IEncryptionProvider provider)
 {
     Guard.AgainstNull(provider, nameof(provider));
     _encryptionProvider = provider;
     return(this);
 }
Beispiel #29
0
        protected override void Load(ContainerBuilder builder)
        {
            // ISerde<Diff>
            builder.Register(
                c => new DiffSerde(
                    new Dictionary <string, Type>
            {
                { DockerType, typeof(DockerModule) }
            }))
            .As <ISerde <Diff> >()
            .SingleInstance();

            // ISerde<ModuleSet>
            builder.Register(
                c => new ModuleSetSerde(
                    new Dictionary <string, Type>
            {
                { DockerType, typeof(DockerModule) }
            }))
            .As <ISerde <ModuleSet> >()
            .SingleInstance();

            // ISerde<DeploymentConfig>
            builder.Register(
                c =>
            {
                ISerde <DeploymentConfig> serde = new TypeSpecificSerDe <DeploymentConfig>(DeploymentConfigTypeMapping);
                return(serde);
            })
            .As <ISerde <DeploymentConfig> >()
            .SingleInstance();

            // ISerde<DeploymentConfigInfo>
            builder.Register(
                c =>
            {
                ISerde <DeploymentConfigInfo> serde = new TypeSpecificSerDe <DeploymentConfigInfo>(DeploymentConfigTypeMapping);
                return(serde);
            })
            .As <ISerde <DeploymentConfigInfo> >()
            .SingleInstance();

            // Detect system environment
            builder.Register(c => new SystemEnvironment())
            .As <ISystemEnvironment>()
            .SingleInstance();

            // IRocksDbOptionsProvider
            // For EdgeAgent, we don't need high performance from RocksDb, so always turn off optimizeForPerformance
            builder.Register(c => new RocksDbOptionsProvider(c.Resolve <ISystemEnvironment>(), false))
            .As <IRocksDbOptionsProvider>()
            .SingleInstance();

            // IDbStore
            builder.Register(
                c =>
            {
                var loggerFactory = c.Resolve <ILoggerFactory>();
                ILogger logger    = loggerFactory.CreateLogger(typeof(AgentModule));

                if (this.usePersistentStorage)
                {
                    // Create partition for mma
                    var partitionsList = new List <string> {
                        "moduleState", "deploymentConfig"
                    };
                    try
                    {
                        IDbStoreProvider dbStoreprovider = DbStoreProvider.Create(
                            c.Resolve <IRocksDbOptionsProvider>(),
                            this.storagePath,
                            partitionsList);
                        logger.LogInformation($"Created persistent store at {this.storagePath}");
                        return(dbStoreprovider);
                    }
                    catch (Exception ex) when(!ExceptionEx.IsFatal(ex))
                    {
                        logger.LogError(ex, "Error creating RocksDB store. Falling back to in-memory store.");
                        return(new InMemoryDbStoreProvider());
                    }
                }
                else
                {
                    logger.LogInformation($"Using in-memory store");
                    return(new InMemoryDbStoreProvider());
                }
            })
            .As <IDbStoreProvider>()
            .SingleInstance();

            // IStoreProvider
            builder.Register(c => new StoreProvider(c.Resolve <IDbStoreProvider>()))
            .As <IStoreProvider>()
            .SingleInstance();

            // IEntityStore<string, ModuleState>
            builder.Register(c => c.Resolve <IStoreProvider>().GetEntityStore <string, ModuleState>("moduleState"))
            .As <IEntityStore <string, ModuleState> >()
            .SingleInstance();

            // IEntityStore<string, DeploymentConfigInfo>
            builder.Register(c => c.Resolve <IStoreProvider>().GetEntityStore <string, string>("deploymentConfig"))
            .As <IEntityStore <string, string> >()
            .SingleInstance();

            // IRestartManager
            builder.Register(c => new RestartPolicyManager(this.maxRestartCount, this.coolOffTimeUnitInSeconds))
            .As <IRestartPolicyManager>()
            .SingleInstance();

            // IPlanner
            builder.Register(
                async c => new HealthRestartPlanner(
                    await c.Resolve <Task <ICommandFactory> >(),
                    c.Resolve <IEntityStore <string, ModuleState> >(),
                    this.intensiveCareTime,
                    c.Resolve <IRestartPolicyManager>()) as IPlanner)
            .As <Task <IPlanner> >()
            .SingleInstance();

            // IPlanRunner
            builder.Register(c => new OrderedRetryPlanRunner(this.maxRestartCount, this.coolOffTimeUnitInSeconds, SystemTime.Instance))
            .As <IPlanRunner>()
            .SingleInstance();

            // IEncryptionDecryptionProvider
            builder.Register(
                async c =>
            {
                IEncryptionProvider provider = await this.workloadUri.Map(
                    async uri =>
                {
                    IEncryptionProvider encryptionProvider = await EncryptionProvider.CreateAsync(
                        this.storagePath,
                        uri,
                        Constants.EdgeletWorkloadApiVersion,
                        this.moduleId,
                        this.moduleGenerationId.Expect(() => new InvalidOperationException("Missing generation ID")),
                        Constants.EdgeletInitializationVectorFileName);
                    return(encryptionProvider);
                }).GetOrElse(() => Task.FromResult <IEncryptionProvider>(NullEncryptionProvider.Instance));

                return(provider);
            })
            .As <Task <IEncryptionProvider> >()
            .SingleInstance();

            // Task<Agent>
            builder.Register(
                async c =>
            {
                var configSource                   = c.Resolve <Task <IConfigSource> >();
                var environmentProvider            = c.Resolve <Task <IEnvironmentProvider> >();
                var planner                        = c.Resolve <Task <IPlanner> >();
                var planRunner                     = c.Resolve <IPlanRunner>();
                var reporter                       = c.Resolve <IReporter>();
                var moduleIdentityLifecycleManager = c.Resolve <IModuleIdentityLifecycleManager>();
                var deploymentConfigInfoSerde      = c.Resolve <ISerde <DeploymentConfigInfo> >();
                var deploymentConfigInfoStore      = c.Resolve <IEntityStore <string, string> >();
                var encryptionProvider             = c.Resolve <Task <IEncryptionProvider> >();
                return(await Agent.Create(
                           await configSource,
                           await planner,
                           planRunner,
                           reporter,
                           moduleIdentityLifecycleManager,
                           await environmentProvider,
                           deploymentConfigInfoStore,
                           deploymentConfigInfoSerde,
                           await encryptionProvider));
            })
            .As <Task <Agent> >()
            .SingleInstance();

            base.Load(builder);
        }
        public ConnectionModule(IMapper mapper, IUserStore userStore, IConnectionValidator connectionValidator, IEncryptionProvider encryptionProvider, IWorkflowInfoService workflowStoreService, IWorkflowStoreFactory workflowStoreFactory)
            : base()
        {
            _mapper               = mapper;
            _userStore            = userStore;
            _connectionValidator  = connectionValidator;
            _encryptionProvider   = encryptionProvider;
            _workflowInfoService  = workflowStoreService;
            _workflowStoreFactory = workflowStoreFactory;

            // lists all connections for the current user
            Get[Actions.Connection.List] = (x) =>
            {
                //this.RequiresAnyClaim(Claims.AllClaims);
                return(this.List());
            };
            // deletes a connection for the current user
            Post[Actions.Connection.Delete] = (x) =>
            {
                this.RequiresClaims(Claims.ConnectionDelete);
                return(DeleteConnection());
            };
            Post[Actions.Connection.Info] = (x) =>
            {
                return(Info());
            };
            // saves a connection for the current user
            Post[Actions.Connection.Save] = (x) =>
            {
                this.RequiresClaims(Claims.ConnectionAdd);
                return(Save());
            };
            // tests a new connection for the current user
            Post[Actions.Connection.Test] = (x) =>
            {
                //this.RequiresAnyClaim(Claims.ConnectionAdd);
                return(Test());
            };
        }
Beispiel #31
0
        protected override void Load(ContainerBuilder builder)
        {
            // ILogsUploader
            builder.Register(c => new AzureBlobLogsUploader(this.iotHubHostName, this.deviceId))
            .As <ILogsUploader>()
            .SingleInstance();

            // Task<ILogsProvider>
            builder.Register(
                async c =>
            {
                var logsProcessor = new LogsProcessor(new LogMessageParser(this.iotHubHostName, this.deviceId));
                IRuntimeInfoProvider runtimeInfoProvider = await c.Resolve <Task <IRuntimeInfoProvider> >();
                return(new LogsProvider(runtimeInfoProvider, logsProcessor) as ILogsProvider);
            })
            .As <Task <ILogsProvider> >()
            .SingleInstance();

            // Task<IStreamRequestListener>
            builder.Register(
                async c =>
            {
                if (this.enableStreams)
                {
                    ILogsProvider logsProvider       = await c.Resolve <Task <ILogsProvider> >();
                    var streamRequestHandlerProvider = new StreamRequestHandlerProvider(logsProvider);
                    return(new StreamRequestListener(streamRequestHandlerProvider) as IStreamRequestListener);
                }
                else
                {
                    return(new NullStreamRequestListener() as IStreamRequestListener);
                }
            })
            .As <Task <IStreamRequestListener> >()
            .SingleInstance();

            // Task<IRequestManager>
            builder.Register(
                async c =>
            {
                var logsUploader            = c.Resolve <ILogsUploader>();
                var runtimeInfoProviderTask = c.Resolve <Task <IRuntimeInfoProvider> >();
                var logsProviderTask        = c.Resolve <Task <ILogsProvider> >();
                IRuntimeInfoProvider runtimeInfoProvider = await runtimeInfoProviderTask;
                ILogsProvider logsProvider = await logsProviderTask;
                var requestHandlers        = new List <IRequestHandler>
                {
                    new PingRequestHandler(),
                    new LogsUploadRequestHandler(logsUploader, logsProvider, runtimeInfoProvider)
                };
                return(new RequestManager(requestHandlers, this.requestTimeout) as IRequestManager);
            })
            .As <Task <IRequestManager> >()
            .SingleInstance();

            // Task<IEdgeAgentConnection>
            builder.Register(
                async c =>
            {
                var serde = c.Resolve <ISerde <DeploymentConfig> >();
                var deviceClientprovider      = c.Resolve <IModuleClientProvider>();
                var streamRequestListenerTask = c.Resolve <Task <IStreamRequestListener> >();
                var requestManagerTask        = c.Resolve <Task <IRequestManager> >();
                IStreamRequestListener streamRequestListener = await streamRequestListenerTask;
                IRequestManager requestManager           = await requestManagerTask;
                IEdgeAgentConnection edgeAgentConnection = new EdgeAgentConnection(deviceClientprovider, serde, requestManager, streamRequestListener, this.configRefreshFrequency);
                return(edgeAgentConnection);
            })
            .As <Task <IEdgeAgentConnection> >()
            .SingleInstance();

            // Task<IConfigSource>
            builder.Register(
                async c =>
            {
                var serde = c.Resolve <ISerde <DeploymentConfigInfo> >();
                var edgeAgentConnectionTask              = c.Resolve <Task <IEdgeAgentConnection> >();
                IEncryptionProvider encryptionProvider   = await c.Resolve <Task <IEncryptionProvider> >();
                IEdgeAgentConnection edgeAgentConnection = await edgeAgentConnectionTask;
                var twinConfigSource             = new TwinConfigSource(edgeAgentConnection, this.configuration);
                IConfigSource backupConfigSource = new FileBackupConfigSource(this.backupConfigFilePath, twinConfigSource, serde, encryptionProvider);
                return(backupConfigSource);
            })
            .As <Task <IConfigSource> >()
            .SingleInstance();

            // Task<IReporter>
            builder.Register(
                async c =>
            {
                var runtimeInfoDeserializerTypes = new Dictionary <string, Type>
                {
                    [DockerType]        = typeof(DockerReportedRuntimeInfo),
                    [Constants.Unknown] = typeof(UnknownRuntimeInfo)
                };

                var edgeAgentDeserializerTypes = new Dictionary <string, Type>
                {
                    [DockerType]        = typeof(EdgeAgentDockerRuntimeModule),
                    [Constants.Unknown] = typeof(UnknownEdgeAgentModule)
                };

                var edgeHubDeserializerTypes = new Dictionary <string, Type>
                {
                    [DockerType]        = typeof(EdgeHubDockerRuntimeModule),
                    [Constants.Unknown] = typeof(UnknownEdgeHubModule)
                };

                var moduleDeserializerTypes = new Dictionary <string, Type>
                {
                    [DockerType] = typeof(DockerRuntimeModule)
                };

                var deserializerTypesMap = new Dictionary <Type, IDictionary <string, Type> >
                {
                    { typeof(IRuntimeInfo), runtimeInfoDeserializerTypes },
                    { typeof(IEdgeAgentModule), edgeAgentDeserializerTypes },
                    { typeof(IEdgeHubModule), edgeHubDeserializerTypes },
                    { typeof(IModule), moduleDeserializerTypes }
                };

                var edgeAgentConnectionTask = c.Resolve <Task <IEdgeAgentConnection> >();
                IEdgeAgentConnection edgeAgentConnection = await edgeAgentConnectionTask;

                return(new IoTHubReporter(
                           edgeAgentConnection,
                           new TypeSpecificSerDe <AgentState>(deserializerTypesMap),
                           this.versionInfo) as IReporter);
            })
            .As <Task <IReporter> >()
            .SingleInstance();

            base.Load(builder);
        }
Beispiel #32
0
        protected override void Load(ContainerBuilder builder)
        {
            // IMessageConverter<IRoutingMessage>
            builder.Register(c => new RoutingMessageConverter())
            .As <Core.IMessageConverter <IRoutingMessage> >()
            .SingleInstance();

            // IRoutingPerfCounter
            builder.Register(
                c =>
            {
                Routing.PerfCounter = NullRoutingPerfCounter.Instance;
                return(Routing.PerfCounter);
            })
            .As <IRoutingPerfCounter>()
            .AutoActivate()
            .SingleInstance();

            // IRoutingUserAnalyticsLogger
            builder.Register(
                c =>
            {
                Routing.UserAnalyticsLogger = NullUserAnalyticsLogger.Instance;
                return(Routing.UserAnalyticsLogger);
            })
            .As <IRoutingUserAnalyticsLogger>()
            .AutoActivate()
            .SingleInstance();

            // IRoutingUserMetricLogger
            builder.Register(
                c =>
            {
                Routing.UserMetricLogger = NullRoutingUserMetricLogger.Instance;
                return(Routing.UserMetricLogger);
            })
            .As <IRoutingUserMetricLogger>()
            .AutoActivate()
            .SingleInstance();

            // IMessageConverter<Message>
            builder.Register(c => new DeviceClientMessageConverter())
            .As <Core.IMessageConverter <Message> >()
            .SingleInstance();

            // IMessageConverter<Twin>
            builder.Register(c => new TwinMessageConverter())
            .As <Core.IMessageConverter <Twin> >()
            .SingleInstance();

            // IMessageConverter<TwinCollection>
            builder.Register(c => new TwinCollectionMessageConverter())
            .As <Core.IMessageConverter <TwinCollection> >()
            .SingleInstance();

            // IMessageConverterProvider
            builder.Register(
                c => new MessageConverterProvider(new Dictionary <Type, IMessageConverter>()
            {
                { typeof(Message), c.Resolve <Core.IMessageConverter <Message> >() },
                { typeof(Twin), c.Resolve <Core.IMessageConverter <Twin> >() },
                { typeof(TwinCollection), c.Resolve <Core.IMessageConverter <TwinCollection> >() }
            }))
            .As <Core.IMessageConverterProvider>()
            .SingleInstance();

            // IDeviceConnectivityManager
            builder.Register(
                c =>
            {
                IDeviceConnectivityManager deviceConnectivityManager = new DeviceConnectivityManager(this.connectivityCheckFrequency, TimeSpan.FromMinutes(2));
                return(deviceConnectivityManager);
            })
            .As <IDeviceConnectivityManager>()
            .SingleInstance();

            // IDeviceClientProvider
            builder.Register(c =>
            {
                IClientProvider underlyingClientProvider        = new ClientProvider();
                IClientProvider connectivityAwareClientProvider = new ConnectivityAwareClientProvider(underlyingClientProvider, c.Resolve <IDeviceConnectivityManager>());
                return(connectivityAwareClientProvider);
            })
            .As <IClientProvider>()
            .SingleInstance();

            // ICloudConnectionProvider
            builder.Register(c => new CloudConnectionProvider(c.Resolve <Core.IMessageConverterProvider>(), this.connectionPoolSize, c.Resolve <IClientProvider>(), this.upstreamProtocol))
            .As <ICloudConnectionProvider>()
            .SingleInstance();

            if (this.isStoreAndForwardEnabled || this.cacheTokens)
            {
                // Detect system environment
                builder.Register(c => new SystemEnvironment())
                .As <ISystemEnvironment>()
                .SingleInstance();

                // DataBase options
                builder.Register(c => new Storage.RocksDb.RocksDbOptionsProvider(c.Resolve <ISystemEnvironment>(), this.optimizeForPerformance))
                .As <Storage.RocksDb.IRocksDbOptionsProvider>()
                .SingleInstance();

                // IDbStore
                builder.Register(
                    c =>
                {
                    var loggerFactory = c.Resolve <ILoggerFactory>();
                    ILogger logger    = loggerFactory.CreateLogger(typeof(RoutingModule));

                    if (this.usePersistentStorage)
                    {
                        // Create partitions for messages and twins
                        var partitionsList = new List <string> {
                            Core.Constants.MessageStorePartitionKey, Core.Constants.TwinStorePartitionKey, Core.Constants.CheckpointStorePartitionKey
                        };
                        try
                        {
                            IDbStoreProvider dbStoreprovider = Storage.RocksDb.DbStoreProvider.Create(c.Resolve <Storage.RocksDb.IRocksDbOptionsProvider>(),
                                                                                                      this.storagePath, partitionsList);
                            logger.LogInformation($"Created persistent store at {this.storagePath}");
                            return(dbStoreprovider);
                        }
                        catch (Exception ex) when(!ExceptionEx.IsFatal(ex))
                        {
                            logger.LogError(ex, "Error creating RocksDB store. Falling back to in-memory store.");
                            return(new InMemoryDbStoreProvider());
                        }
                    }
                    else
                    {
                        logger.LogInformation($"Using in-memory store");
                        return(new InMemoryDbStoreProvider());
                    }
                })
                .As <IDbStoreProvider>()
                .SingleInstance();
            }

            // Task<ICredentialsStore>
            builder.Register(async c =>
            {
                if (this.cacheTokens)
                {
                    var dbStoreProvider = c.Resolve <IDbStoreProvider>();
                    IEncryptionProvider encryptionProvider = await this.workloadUri.Map(
                        async uri => await EncryptionProvider.CreateAsync(
                            this.storagePath,
                            new Uri(uri),
                            Service.Constants.WorkloadApiVersion,
                            this.edgeModuleId,
                            this.edgeModuleGenerationId.Expect(() => new InvalidOperationException("Missing generation ID")),
                            Service.Constants.InitializationVectorFileName) as IEncryptionProvider)
                                                             .GetOrElse(() => Task.FromResult <IEncryptionProvider>(NullEncryptionProvider.Instance));
                    IStoreProvider storeProvider = new StoreProvider(dbStoreProvider);
                    IEntityStore <string, string> tokenCredentialsEntityStore = storeProvider.GetEntityStore <string, string>("tokenCredentials");
                    return(new TokenCredentialsStore(tokenCredentialsEntityStore, encryptionProvider));
                }
                else
                {
                    return(new NullCredentialsStore() as ICredentialsStore);
                }
            })
            .As <Task <ICredentialsStore> >()
            .SingleInstance();

            // IConnectionManager
            builder.Register(c => new ConnectionManager(c.Resolve <ICloudConnectionProvider>(), this.maxConnectedClients))
            .As <IConnectionManager>()
            .SingleInstance();

            // IEndpointFactory
            builder.Register(c => new EndpointFactory(c.Resolve <IConnectionManager>(), c.Resolve <Core.IMessageConverter <IRoutingMessage> >(), this.edgeDeviceId))
            .As <IEndpointFactory>()
            .SingleInstance();

            // RouteFactory
            builder.Register(c => new EdgeRouteFactory(c.Resolve <IEndpointFactory>()))
            .As <RouteFactory>()
            .SingleInstance();

            // RouterConfig
            builder.Register(c => new RouterConfig(Enumerable.Empty <Route>()))
            .As <RouterConfig>()
            .SingleInstance();

            if (!this.isStoreAndForwardEnabled)
            {
                // EndpointExecutorConfig
                builder.Register(
                    c =>
                {
                    RetryStrategy defaultRetryStrategy = new FixedInterval(0, TimeSpan.FromSeconds(1));
                    TimeSpan defaultRevivePeriod       = TimeSpan.FromHours(1);
                    TimeSpan defaultTimeout            = TimeSpan.FromSeconds(60);
                    return(new EndpointExecutorConfig(defaultTimeout, defaultRetryStrategy, defaultRevivePeriod, true));
                })
                .As <EndpointExecutorConfig>()
                .SingleInstance();

                // IEndpointExecutorFactory
                builder.Register(c => new SyncEndpointExecutorFactory(c.Resolve <EndpointExecutorConfig>()))
                .As <IEndpointExecutorFactory>()
                .SingleInstance();

                // Task<Router>
                builder.Register(
                    async c =>
                {
                    var endpointExecutorFactory = c.Resolve <IEndpointExecutorFactory>();
                    var routerConfig            = c.Resolve <RouterConfig>();
                    Router router = await Router.CreateAsync(Guid.NewGuid().ToString(), this.iotHubName, routerConfig, endpointExecutorFactory);
                    return(router);
                })
                .As <Task <Router> >()
                .SingleInstance();

                // ITwinManager
                builder.Register(c => TwinManager.CreateTwinManager(c.Resolve <IConnectionManager>(), c.Resolve <IMessageConverterProvider>(), Option.None <IStoreProvider>()))
                .As <ITwinManager>()
                .SingleInstance();
            }
            else
            {
                // EndpointExecutorConfig
                builder.Register(
                    c =>
                {
                    // Endpoint executor config values -
                    // ExponentialBackoff - minBackoff = 1s, maxBackoff = 60s, delta (used to add randomness to backoff) - 1s (default)
                    // Num of retries = int.MaxValue(we want to keep retrying till the message is sent)
                    // Revive period - period for which the endpoint should be considered dead if it doesn't respond - 1 min (we want to try continuously till the message expires)
                    // Timeout - time for which we want for the ack from the endpoint = 30s
                    // TODO - Should the number of retries be tied to the Store and Forward ttl? Not
                    // doing that right now as that value can be changed at runtime, but these settings
                    // cannot. Need to make the number of retries dynamically configurable for that.

                    TimeSpan minWait            = TimeSpan.FromSeconds(1);
                    TimeSpan maxWait            = TimeSpan.FromSeconds(60);
                    TimeSpan delta              = TimeSpan.FromSeconds(1);
                    int retries                 = int.MaxValue;
                    RetryStrategy retryStrategy = new ExponentialBackoff(retries, minWait, maxWait, delta);
                    TimeSpan timeout            = TimeSpan.FromSeconds(30);
                    TimeSpan revivePeriod       = TimeSpan.FromSeconds(30);
                    return(new EndpointExecutorConfig(timeout, retryStrategy, revivePeriod));
                })
                .As <EndpointExecutorConfig>()
                .SingleInstance();

                // ICheckpointStore
                builder.Register(c => CheckpointStore.Create(c.Resolve <IDbStoreProvider>()))
                .As <ICheckpointStore>()
                .SingleInstance();

                // IMessageStore
                builder.Register(
                    c =>
                {
                    var checkpointStore          = c.Resolve <ICheckpointStore>();
                    var dbStoreProvider          = c.Resolve <IDbStoreProvider>();
                    IStoreProvider storeProvider = new StoreProvider(dbStoreProvider);
                    IMessageStore messageStore   = new MessageStore(storeProvider, checkpointStore, TimeSpan.MaxValue);
                    return(messageStore);
                })
                .As <IMessageStore>()
                .SingleInstance();

                // IEndpointExecutorFactory
                builder.Register(
                    c =>
                {
                    var endpointExecutorConfig = c.Resolve <EndpointExecutorConfig>();
                    var messageStore           = c.Resolve <IMessageStore>();
                    IEndpointExecutorFactory endpointExecutorFactory = new StoringAsyncEndpointExecutorFactory(endpointExecutorConfig, new AsyncEndpointExecutorOptions(10, TimeSpan.FromSeconds(10)), messageStore);
                    return(endpointExecutorFactory);
                })
                .As <IEndpointExecutorFactory>()
                .SingleInstance();

                // Task<Router>
                builder.Register(
                    async c =>
                {
                    var checkpointStore         = c.Resolve <ICheckpointStore>();
                    var routerConfig            = c.Resolve <RouterConfig>();
                    var endpointExecutorFactory = c.Resolve <IEndpointExecutorFactory>();
                    return(await Router.CreateAsync(Guid.NewGuid().ToString(), this.iotHubName, routerConfig, endpointExecutorFactory, checkpointStore));
                })
                .As <Task <Router> >()
                .SingleInstance();

                // ITwinManager
                builder.Register(c => TwinManager.CreateTwinManager(c.Resolve <IConnectionManager>(), c.Resolve <IMessageConverterProvider>(), Option.Some <IStoreProvider>(new StoreProvider(c.Resolve <IDbStoreProvider>()))))
                .As <ITwinManager>()
                .SingleInstance();
            }

            // IClientCredentials "EdgeHubCredentials"
            builder.Register(
                c =>
            {
                var identityFactory = c.Resolve <IClientCredentialsFactory>();
                IClientCredentials edgeHubCredentials = this.connectionString.Map(cs => identityFactory.GetWithConnectionString(cs)).GetOrElse(
                    () => identityFactory.GetWithIotEdged(this.edgeDeviceId, this.edgeModuleId));
                return(edgeHubCredentials);
            })
            .Named <IClientCredentials>("EdgeHubCredentials")
            .SingleInstance();

            // Task<ICloudProxy> "EdgeHubCloudProxy"
            builder.Register(
                async c =>
            {
                var edgeHubCredentials          = c.ResolveNamed <IClientCredentials>("EdgeHubCredentials");
                var connectionManager           = c.Resolve <IConnectionManager>();
                Try <ICloudProxy> cloudProxyTry = await connectionManager.CreateCloudConnectionAsync(edgeHubCredentials);
                if (!cloudProxyTry.Success)
                {
                    throw new EdgeHubConnectionException("Edge hub is unable to connect to IoT Hub", cloudProxyTry.Exception);
                }

                ICloudProxy cloudProxy = cloudProxyTry.Value;
                return(cloudProxy);
            })
            .Named <Task <ICloudProxy> >("EdgeHubCloudProxy")
            .SingleInstance();

            // IInvokeMethodHandler
            builder.Register(c => new InvokeMethodHandler(c.Resolve <IConnectionManager>()))
            .As <IInvokeMethodHandler>()
            .SingleInstance();

            // Task<IEdgeHub>
            builder.Register(
                async c =>
            {
                Router router = await c.Resolve <Task <Router> >();
                IEdgeHub hub  = new RoutingEdgeHub(router, c.Resolve <Core.IMessageConverter <IRoutingMessage> >(), c.Resolve <IConnectionManager>(),
                                                   c.Resolve <ITwinManager>(), this.edgeDeviceId, c.Resolve <IInvokeMethodHandler>());
                return(hub);
            })
            .As <Task <IEdgeHub> >()
            .SingleInstance();

            // Task<ConfigUpdater>
            builder.Register(
                async c =>
            {
                IMessageStore messageStore = this.isStoreAndForwardEnabled ? c.Resolve <IMessageStore>() : null;
                Router router     = await c.Resolve <Task <Router> >();
                var configUpdater = new ConfigUpdater(router, messageStore);
                return(configUpdater);
            })
            .As <Task <ConfigUpdater> >()
            .SingleInstance();

            // Task<IConfigSource>
            builder.Register(
                async c =>
            {
                var routeFactory = c.Resolve <RouteFactory>();

                if (this.useTwinConfig)
                {
                    var connectionManager              = c.Resolve <IConnectionManager>();
                    var edgeHubCredentials             = c.ResolveNamed <IClientCredentials>("EdgeHubCredentials");
                    var twinCollectionMessageConverter = c.Resolve <Core.IMessageConverter <TwinCollection> >();
                    var twinMessageConverter           = c.Resolve <Core.IMessageConverter <Twin> >();
                    var twinManager                 = c.Resolve <ITwinManager>();
                    ICloudProxy cloudProxy          = await c.ResolveNamed <Task <ICloudProxy> >("EdgeHubCloudProxy");
                    IEdgeHub edgeHub                = await c.Resolve <Task <IEdgeHub> >();
                    IConfigSource edgeHubConnection = await EdgeHubConnection.Create(
                        edgeHubCredentials,
                        edgeHub,
                        twinManager,
                        connectionManager,
                        cloudProxy,
                        routeFactory,
                        twinCollectionMessageConverter,
                        twinMessageConverter,
                        this.versionInfo
                        );
                    return(edgeHubConnection);
                }
                else
                {
                    return(new LocalConfigSource(routeFactory, this.routes, this.storeAndForwardConfiguration));
                }
            })
            .As <Task <IConfigSource> >()
            .SingleInstance();

            // Task<IConnectionProvider>
            builder.Register(
                async c =>
            {
                IEdgeHub edgeHub = await c.Resolve <Task <IEdgeHub> >();
                IConnectionProvider connectionProvider = new ConnectionProvider(c.Resolve <IConnectionManager>(), edgeHub);
                return(connectionProvider);
            })
            .As <Task <IConnectionProvider> >()
            .SingleInstance();

            base.Load(builder);
        }
Beispiel #33
0
 /// <summary>
 /// Initializes a new instance of the <see cref="CookieBasedSessions"/> class.
 /// </summary>
 /// <param name="encryptionProvider">The encryption provider.</param>
 /// <param name="hmacProvider">The hmac provider</param>
 /// <param name="objectSerializer">Session object serializer to use</param>
 public CookieBasedSessions(IEncryptionProvider encryptionProvider, IHmacProvider hmacProvider, IObjectSerializer objectSerializer)
 {
     this.encryptionProvider = encryptionProvider;
     this.hmacProvider = hmacProvider;
     this.serializer = objectSerializer;
 }
Beispiel #34
0
 /// <summary>
 /// Creates a new instance of the CryptographyConfiguration class
 /// </summary>
 /// <param name="encryptionProvider">Encryption provider</param>
 /// <param name="hmacProvider">HMAC provider</param>
 public CryptographyConfiguration(IEncryptionProvider encryptionProvider, IHmacProvider hmacProvider)
 {
     this.EncryptionProvider = encryptionProvider;
     this.HmacProvider       = hmacProvider;
 }
Beispiel #35
0
 public GetCustomer(ICustomerService customerService, IMapperProvider mapperProvider, IEncryptionProvider encryptionProvider)
     : base(mapperProvider, encryptionProvider)
 {
     _customerService = customerService;
 }
Beispiel #36
0
 public UserDbContext(DbContextOptions options) : base(options)
 {
     _encryptionInfo = AesProvider.GenerateKey(AesKeySize.AES128Bits);
     _provider       = new AesProvider(_encryptionInfo.Key, _encryptionInfo.IV);
 }
Beispiel #37
0
 public void SetIVAndKey(byte[] iv, byte[] key)
 {
     this.encryptionIV  = iv;
     this.encryptionKey = iv;
     this.provider      = new AesProvider(this.encryptionKey, this.encryptionIV);
 }
 public CookieBasedSessionsFixture()
 {
     this.encryptionProvider = A.Fake<IEncryptionProvider>();
     this.cookieStore = new Nancy.Session.CookieBasedSessions(this.encryptionProvider, "the passphrase", "the salt", new Fakes.FakeSessionObjectFormatter());
 }
Beispiel #39
0
 /// <summary>
 /// Initializes a new instance of the <see cref="CookieBasedSessions"/> class.
 /// </summary>
 /// <param name="encryptionProvider">The encryption provider.</param>
 /// <param name="hmacProvider">The hmac provider</param>
 /// <param name="objectSerializer">Session object serializer to use</param>
 public CookieBasedSessions(IEncryptionProvider encryptionProvider, IHmacProvider hmacProvider, IObjectSerializer objectSerializer)
 {
     this.encryptionProvider = encryptionProvider;
     this.hmacProvider       = hmacProvider;
     this.serializer         = objectSerializer;
 }
Beispiel #40
0
 public RedisCacheProvider(IEnvironmentProvider environmentProvider, IEncryptionProvider encryptionProvider, IOptions <Configuration.Options> options) : this(environmentProvider, encryptionProvider, options.Value)
 {
 }
Beispiel #41
0
        /// <summary>
        /// Decrypts encrypted data and returns the decrypted bytes.
        /// </summary>
        /// <param name="reader">The data stream to read from.</param>
        /// <param name="writer">The data stream to write to.</param>
        /// <param name="privateKey">
        /// A password or phrase used to generate the key for the symmetric alogrithm. If the symetric
        /// key is stored with the message, the key for the symmetric algorithm is used instead.
        /// </param>
        /// <param name="symmetricKeyEncryptionProvider">
        ///  The encryption provider used to decrypt the symmetric key when it is
        ///  stored with the message.
        /// </param>
        public void Decrypt(
            Stream reader,
            Stream writer,
            ReadOnlySpan <byte> privateKey = default,
            IEncryptionProvider symmetricKeyEncryptionProvider = null)
        {
            Check.NotNull(nameof(reader), reader);
            Check.NotNull(nameof(writer), writer);

            var pool = ArrayPool <byte> .Shared;

            byte[] rental             = null;
            byte[] signerKeyRental    = null;
            byte[] symmetricKeyRental = null;
            byte[] ivRental           = null;
            byte[] buffer             = null;
            try
            {
                buffer = pool.Rent(4096);
                using (var header = this.ReadHeader(reader, this.options, privateKey, symmetricKeyEncryptionProvider))
                {
                    long position = reader.Position;
                    this.algorithm = this.algorithm ?? CreateSymmetricAlgorithm(this.options);

                    if (header.Hash != null)
                    {
                        signerKeyRental = pool.Rent(header.SigningKey.Memory.Length);
                        using (var signer = CreateSigningAlgorithm(this.options))
                        {
                            header.SigningKey.Memory.CopyTo(signerKeyRental);
                            signer.Key = signerKeyRental;
                            var h1 = header.Hash;

                            long bytesRead = reader.Length - reader.Position + 1;
                            var  hash      = new byte[signer.OutputBlockSize];
                            while (bytesRead > 0)
                            {
                                int read = reader.Read(buffer, 0, buffer.Length);
                                bytesRead -= read;
                                signer.TransformBlock(buffer, 0, read, buffer, 0);
                            }

                            signer.TransformFinalBlock(Array.Empty <byte>(), 0, 0);
                            var h2 = signer.Hash;

                            if (!h1.Memory.Span.SlowEquals(h2))
                            {
                                return;
                            }
                        }
                    }

                    reader.Seek(position, SeekOrigin.Begin);
                    symmetricKeyRental = pool.Rent(header.SymmetricKey.Memory.Length);
                    ivRental           = pool.Rent(header.IV.Memory.Length);
                    header.SymmetricKey.Memory.CopyTo(symmetricKeyRental);
                    header.IV.Memory.CopyTo(ivRental);
                    using (var decryptor = this.algorithm.CreateDecryptor(symmetricKeyRental, ivRental))
                        using (var cs = new CryptoStream(writer, decryptor, CryptoStreamMode.Write))
                            using (var bw = new BinaryWriter(cs))
                            {
                                long bytesRead = reader.Length - (reader.Position - 1);

                                while (bytesRead > 0)
                                {
                                    bytesRead -= reader.Read(buffer, 0, buffer.Length);
                                    bw.Write(buffer);
                                }

                                cs.FlushFinalBlock();
                                writer.Flush();
                            }
                }
            }
            finally
            {
                if (buffer != null)
                {
                    pool.Return(buffer, true);
                }

                if (rental != null)
                {
                    pool.Return(rental, true);
                }

                if (symmetricKeyRental != null)
                {
                    pool.Return(symmetricKeyRental, true);
                }

                if (ivRental != null)
                {
                    pool.Return(ivRental, true);
                }

                if (signerKeyRental != null)
                {
                    pool.Return(signerKeyRental, true);
                }
            }
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="CookieBasedSessions"/> class.
 /// </summary>
 /// <param name="encryptionProvider">The encryption provider.</param>
 /// <param name="hmacProvider">The hmac provider</param>
 /// <param name="sessionObjectFormatter">Session object formatter to use</param>
 public CookieBasedSessions(IEncryptionProvider encryptionProvider, IHmacProvider hmacProvider, ISessionObjectFormatter sessionObjectFormatter)
 {
     this.encryptionProvider = encryptionProvider;
     this.hmacProvider = hmacProvider;
     this.formatter = sessionObjectFormatter;
 }
 public SecurityAccessTokenProvider(IEncryptionProvider encryptionProvider, ISessionProvider sessionProvider, IUserSecurityStorageProvider userSecurityStorageProvider)
 {
     _encryptionProvider = encryptionProvider;
     _sessionProvider = sessionProvider;
     _userSecurityStorageProvider = userSecurityStorageProvider;
 }
 public NoEncryptionProviderFixture()
 {
     this.provider = new NoEncryptionProvider();
 }
        protected override void Load(ContainerBuilder builder)
        {
            // IEdgeAgentConnection
            builder.Register(
                c =>
            {
                var serde = c.Resolve <ISerde <DeploymentConfig> >();
                var deviceClientprovider = c.Resolve <IModuleClientProvider>();
                IEdgeAgentConnection edgeAgentConnection = new EdgeAgentConnection(deviceClientprovider, serde, this.configRefreshFrequency);
                return(edgeAgentConnection);
            })
            .As <IEdgeAgentConnection>()
            .SingleInstance();

            // Task<IConfigSource>
            builder.Register(
                async c =>
            {
                var serde = c.Resolve <ISerde <DeploymentConfigInfo> >();
                var edgeAgentConnection = c.Resolve <IEdgeAgentConnection>();
                IEncryptionProvider encryptionProvider = await c.Resolve <Task <IEncryptionProvider> >();
                var twinConfigSource             = new TwinConfigSource(edgeAgentConnection, this.configuration);
                IConfigSource backupConfigSource = new FileBackupConfigSource(this.backupConfigFilePath, twinConfigSource, serde, encryptionProvider);
                return(backupConfigSource);
            })
            .As <Task <IConfigSource> >()
            .SingleInstance();

            // IReporter
            builder.Register(
                c =>
            {
                var runtimeInfoDeserializerTypes = new Dictionary <string, Type>
                {
                    [DockerType]        = typeof(DockerReportedRuntimeInfo),
                    [Constants.Unknown] = typeof(UnknownRuntimeInfo)
                };

                var edgeAgentDeserializerTypes = new Dictionary <string, Type>
                {
                    [DockerType]        = typeof(EdgeAgentDockerRuntimeModule),
                    [Constants.Unknown] = typeof(UnknownEdgeAgentModule)
                };

                var edgeHubDeserializerTypes = new Dictionary <string, Type>
                {
                    [DockerType]        = typeof(EdgeHubDockerRuntimeModule),
                    [Constants.Unknown] = typeof(UnknownEdgeHubModule)
                };

                var moduleDeserializerTypes = new Dictionary <string, Type>
                {
                    [DockerType] = typeof(DockerRuntimeModule)
                };

                var deserializerTypesMap = new Dictionary <Type, IDictionary <string, Type> >
                {
                    { typeof(IRuntimeInfo), runtimeInfoDeserializerTypes },
                    { typeof(IEdgeAgentModule), edgeAgentDeserializerTypes },
                    { typeof(IEdgeHubModule), edgeHubDeserializerTypes },
                    { typeof(IModule), moduleDeserializerTypes }
                };

                return(new IoTHubReporter(
                           c.Resolve <IEdgeAgentConnection>(),
                           new TypeSpecificSerDe <AgentState>(deserializerTypesMap),
                           this.versionInfo
                           ) as IReporter);
            }
                )
            .As <IReporter>()
            .SingleInstance();

            base.Load(builder);
        }
 public PasswordManager(IEncryptionProvider encryptionProvider)
 {
     _encryptionProvider = encryptionProvider;
 }
 public UpdatableEncryptedStore(IKeyValueStore <TK, string> entityStore, IEncryptionProvider encryptionProvider)
     : base(entityStore, encryptionProvider)
 {
 }
        /// <summary>
        /// Decrypts encrypted data and returns the decrypted bytes.
        /// </summary>
        /// <param name="blob">The data to encrypt.</param>
        /// <param name="privateKey">
        /// A password or phrase used to generate the key for the symmetric algorithm. If the symmetric
        /// key is stored with the message, the key for the symmetric algorithm is used instead.
        /// </param>
        /// <param name="symmetricKeyEncryptionProvider">
        ///  The encryption provider used to decrypt the symmetric key when it is
        ///  stored with the message.
        /// </param>
        /// <returns>Encrypted bytes.</returns>
        public ReadOnlySpan <byte> Decrypt(
            ReadOnlySpan <byte> blob,
            ReadOnlySpan <byte> privateKey = default,
            IEncryptionProvider symmetricKeyEncryptionProvider = null)
        {
            var pool = ArrayPool <byte> .Shared;

            byte[] rental             = null;
            byte[] signerKeyRental    = null;
            byte[] symmetricKeyRental = null;
            byte[] ivRental           = null;

            try
            {
                rental = pool.Rent(blob.Length);
                blob.CopyTo(rental);
                using (var reader = new MemoryStream(rental))
                    using (var header = this.ReadHeader(reader, this.options, privateKey, symmetricKeyEncryptionProvider))
                    {
                        this.algorithm = this.algorithm ?? CreateSymmetricAlgorithm(this.options);
                        var messageSize = blob.Length - header.HeaderSize;
                        var message     = new byte[messageSize];
                        Array.Copy(rental, header.HeaderSize, message, 0, messageSize);

                        if (header.Hash != null)
                        {
                            signerKeyRental = pool.Rent(header.SigningKey.Memory.Length);
                            using (var signer = this.signingAlgorithm ?? CreateSigningAlgorithm(this.options))
                            {
                                header.SigningKey.Memory.CopyTo(signerKeyRental);
                                signer.Key = signerKeyRental;
                                var         h1 = header.Hash;
                                Span <byte> h2 = signer.ComputeHash(message);

                                if (!h1.Memory.Span.SlowEquals(h2))
                                {
                                    h2.Clear();
                                    message.Clear();
                                    return(null);
                                }

                                h2.Clear();
                            }
                        }

                        symmetricKeyRental = ArrayPool <byte> .Shared.Rent(header.SymmetricKey.Memory.Length);

                        ivRental = ArrayPool <byte> .Shared.Rent(header.IvSize);

                        header.SymmetricKey.Memory.CopyTo(symmetricKeyRental);
                        header.IV.Memory.CopyTo(ivRental);
                        using (var decryptor = this.algorithm.CreateDecryptor(symmetricKeyRental, ivRental))
                            using (var ms = new MemoryStream())
                                using (var cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Write))
                                {
#if NET461 || NET451
                                    cs.Write(message, 0, message.Length);
#else
                                    cs.Write(message.AsSpan());
#endif
                                    message.Clear();
                                    cs.Flush();
                                    cs.FlushFinalBlock();
                                    ms.Flush();
                                    return(ms.ToArray());
                                }
                    }
            }
            finally
            {
                if (rental != null)
                {
                    pool.Return(rental, true);
                }

                if (symmetricKeyRental != null)
                {
                    pool.Return(symmetricKeyRental, true);
                }

                if (ivRental != null)
                {
                    pool.Return(ivRental, true);
                }

                if (signerKeyRental != null)
                {
                    pool.Return(signerKeyRental, true);
                }
            }
        }
Beispiel #49
0
 public Saml2TokenHandler(ITokenProviderServiceSettings settings, IEncryptionProvider encryptionProvider)
 {
     Settings           = settings;
     EncryptionProvider = encryptionProvider;
 }
Beispiel #50
0
 public EncryptForm(IEncryptionProvider encryptionProvider, IStorageProvider storageProvider) : this()
 {
     _encryptionProvider = encryptionProvider;
     _storageProvider    = storageProvider;
 }
 public ApiIdentityDbContext(DbContextOptions <ApiIdentityDbContext> dbContext) : base(dbContext)
 {
     this._provider = new AesProvider(this._encryptionKey, this._encryptionIV);
 }
Beispiel #52
0
        public static void SetEncryptionProvider(IEncryptionProvider encryptionProvider)
        {
            encryptionProvider.Ensure("encryptionProvider");

            _encryptionProvider = encryptionProvider;
        }
Beispiel #53
0
 public EncryptionController(IEncryptionProvider provider, ILogger <EncryptionController> logger)
 {
     _encryptionProvider = provider;
     _logger             = logger;
 }
Beispiel #54
0
 public static string Encrypt(
     IEncryptionProvider encryptionProvider,
     string input)
 {
     return encryptionProvider.Encrypt(input);
 }
Beispiel #55
0
 public SimpleEncryptedDatabaseContext(DbContextOptions options, IEncryptionProvider encryptionProvider = null)
     : base(options, encryptionProvider)
 {
 }
Beispiel #56
0
 public SecureCache(string databaseFile, IEncryptionProvider encryptionProvider = null,
     IScheduler scheduler = null) : base(databaseFile, encryptionProvider, scheduler) {}
Beispiel #57
0
 public SecretConverter(IEncryptionProvider provider)
 {
     this.provider = provider ?? throw new ArgumentNullException(nameof(provider));
 }