예제 #1
0
        public List <Claim> GenerateRefreshClaims(uvw_Issuer issuer, uvw_User user)
        {
            var expire = _context.Set <uvw_Setting>().Where(x => x.IssuerId == issuer.Id && x.AudienceId == null && x.UserId == null &&
                                                            x.ConfigKey == SettingsConstants.RefreshExpire).Single();

            var claims = new List <Claim>();

            //add lowest common denominators...
            claims.Add(new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()));

            //nonce to enhance entropy
            claims.Add(new Claim(JwtRegisteredClaimNames.Nonce, AlphaNumeric.CreateString(8), ClaimValueTypes.String));

            //not before timestamp
            claims.Add(new Claim(JwtRegisteredClaimNames.Nbf,
                                 new DateTimeOffset(Clock.UtcDateTime).ToUnixTimeSeconds().ToString(), ClaimValueTypes.Integer64));

            //issued at timestamp
            claims.Add(new Claim(JwtRegisteredClaimNames.Iat,
                                 new DateTimeOffset(Clock.UtcDateTime).ToUnixTimeSeconds().ToString(), ClaimValueTypes.Integer64));

            //expire on timestamp
            claims.Add(new Claim(JwtRegisteredClaimNames.Exp,
                                 new DateTimeOffset(Clock.UtcDateTime).AddSeconds(uint.Parse(expire.ConfigValue)).ToUnixTimeSeconds().ToString(), ClaimValueTypes.Integer64));

            return(claims);
        }
예제 #2
0
        public override int Run(string[] remainingArguments)
        {
            try
            {
                var license = _uow.Settings.Get(QueryExpressionFactory.GetQueryExpression <tbl_Setting>()
                                                .Where(x => x.ConfigKey == "RebexLicense").ToLambda()).OrderBy(x => x.Created)
                              .Last();

                Rebex.Licensing.Key = license.ConfigValue;

                AsymmetricKeyAlgorithm.Register(Curve25519.Create);
                AsymmetricKeyAlgorithm.Register(Ed25519.Create);
                AsymmetricKeyAlgorithm.Register(EllipticCurveAlgorithm.Create);

                if (string.IsNullOrEmpty(_secretCurrent))
                {
                    Console.Out.Write("  *** Enter current secret to encrypt passwords *** : ");
                    _secretCurrent = StandardInput.GetHiddenInput();
                }

                if (string.IsNullOrEmpty(_secretNew))
                {
                    Console.Out.Write("  *** Enter new secret to encrypt passwords *** : ");
                    _secretNew = StandardInput.GetHiddenInput();
                }
                else
                {
                    _secretNew = AlphaNumeric.CreateString(32);
                    Console.Out.WriteLine($"  *** The new secret to encrypt passwords is *** : {_secretNew}");
                }

                var keys  = _uow.PrivateKeys.Get().ToList();
                var creds = _uow.Credentials.Get().ToList();

                Console.Out.WriteLine();
                Console.Out.WriteLine("  *** Current private key pass ciphertexts *** ");
                ConsoleHelper.StdOutKeyPairSecrets(keys);

                Console.Out.WriteLine();
                Console.Out.WriteLine("  *** Current credential password ciphertexts *** ");
                ConsoleHelper.StdOutCredentialSecrets(creds);

                keys  = KeyHelper.EditPrivKeySecrets(_uow, keys, _secretCurrent, _secretNew).ToList();
                creds = UserHelper.EditCredentialSecrets(_uow, creds, _secretCurrent, _secretNew).ToList();

                Console.Out.WriteLine();
                Console.Out.WriteLine("  *** New private key pass ciphertexts *** ");
                ConsoleHelper.StdOutKeyPairSecrets(keys);

                Console.Out.WriteLine();
                Console.Out.WriteLine("  *** New credential password ciphertexts *** ");
                ConsoleHelper.StdOutCredentialSecrets(creds);

                return(StandardOutput.FondFarewell());
            }
            catch (Exception ex)
            {
                return(StandardOutput.AngryFarewell(ex));
            }
        }
예제 #3
0
        public void CreateClaims()
        {
            if (foundIssuer == null)
            {
                CreateIssuers();
            }

            /*
             * create test claims
             */

            foundClaim = _uow.Claims.Get(QueryExpressionFactory.GetQueryExpression <tbl_Claim>()
                                         .Where(x => x.Type == TestDefaultConstants.ClaimName).ToLambda())
                         .SingleOrDefault();

            if (foundClaim == null)
            {
                foundClaim = _uow.Claims.Create(
                    _map.Map <tbl_Claim>(new ClaimV1()
                {
                    IssuerId    = foundIssuer.Id,
                    Subject     = TestDefaultConstants.ClaimSubject,
                    Type        = TestDefaultConstants.ClaimName,
                    Value       = AlphaNumeric.CreateString(8),
                    ValueType   = TestDefaultConstants.ClaimValueType,
                    IsDeletable = true,
                }));

                _uow.Commit();
            }
        }
예제 #4
0
        public void CreateAudienceRefreshes()
        {
            if (foundIssuer == null)
            {
                CreateIssuers();
            }

            if (foundAudience == null)
            {
                CreateAudiences();
            }

            /*
             * create test refreshes
             */

            _uow.Refreshes.Create(
                _map.Map <tbl_Refresh>(new RefreshV1()
            {
                IssuerId     = foundIssuer.Id,
                AudienceId   = foundAudience.Id,
                RefreshType  = ConsumerType.Client.ToString(),
                RefreshValue = AlphaNumeric.CreateString(8),
                ValidFromUtc = DateTime.UtcNow,
                ValidToUtc   = DateTime.UtcNow.AddSeconds(60),
            }));

            _uow.Commit();
        }
예제 #5
0
        public void Repo_Claims_CreateV1_Success()
        {
            var data = new TestDataFactory(UoW);

            data.Destroy();
            data.CreateClaims();

            var issuer = UoW.Issuers.Get(QueryExpressionFactory.GetQueryExpression <uvw_Issuer>()
                                         .Where(x => x.Name == TestDefaultConstants.IssuerName).ToLambda())
                         .Single();

            var result = UoW.Claims.Create(
                Mapper.Map <uvw_Claim>(new ClaimV1()
            {
                IssuerId    = issuer.Id,
                Subject     = TestDefaultConstants.ClaimSubject,
                Type        = TestDefaultConstants.ClaimName,
                Value       = AlphaNumeric.CreateString(8),
                ValueType   = TestDefaultConstants.ClaimValueType,
                IsDeletable = false,
            }));

            UoW.Commit();

            result.Should().BeAssignableTo <uvw_Claim>();
        }
예제 #6
0
        public override int Run(string[] remainingArguments)
        {
            try
            {
                if (!string.IsNullOrEmpty(_privKeyPass))
                {
                    Console.Out.Write("  *** Enter password for the private key *** : ");
                    _privKeyPass = StandardInput.GetHiddenInput();
                }
                else
                {
                    _privKeyPass = AlphaNumeric.CreateString(32);
                    Console.Out.WriteLine($"  *** The password for the private key *** : {_privKeyPass}");
                }

                var privKey = KeyHelper.CreatePrivKey(_conf, _uow, _keyAlgo, _privKeySize, _privKeyPass, SignatureHashAlgorithm.SHA256);

                var pubKey = _uow.PublicKeys.Get(QueryExpressionFactory.GetQueryExpression <tbl_PublicKey>()
                                                 .Where(x => x.PrivateKeyId == privKey.Id).ToLambda())
                             .Single();

                Console.Out.WriteLine($"{privKey.KeyValue}");
                Console.Out.WriteLine($"{pubKey.KeyValue}");

                return(StandardOutput.FondFarewell());
            }
            catch (Exception ex)
            {
                return(StandardOutput.AngryFarewell(ex));
            }
        }
예제 #7
0
        public List <Claim> GenerateAccessClaims(tbl_Issuer issuer, tbl_Audience audience)
        {
            var expire = _context.Set <tbl_Setting>().Where(x => x.IssuerId == issuer.Id && x.AudienceId == null && x.UserId == null &&
                                                            x.ConfigKey == SettingsConstants.AccessExpire).Single();

            var claims = new List <Claim>();

            //add lowest common denominators...
            claims.Add(new Claim(ClaimTypes.NameIdentifier, audience.Id.ToString()));

            var roles = _context.Set <tbl_Role>()
                        .Where(x => x.tbl_AudienceRoles.Any(y => y.AudienceId == audience.Id)).ToList();

            foreach (var role in roles.OrderBy(x => x.Name))
            {
                claims.Add(new Claim(ClaimTypes.Role, role.Name));
            }

            //nonce to enhance entropy
            claims.Add(new Claim(JwtRegisteredClaimNames.Nonce, AlphaNumeric.CreateString(8), ClaimValueTypes.String));

            //not before timestamp
            claims.Add(new Claim(JwtRegisteredClaimNames.Nbf,
                                 new DateTimeOffset(Clock.UtcDateTime).ToUnixTimeSeconds().ToString(), ClaimValueTypes.Integer64));

            //issued at timestamp
            claims.Add(new Claim(JwtRegisteredClaimNames.Iat,
                                 new DateTimeOffset(Clock.UtcDateTime).ToUnixTimeSeconds().ToString(), ClaimValueTypes.Integer64));

            //expire on timestamp
            claims.Add(new Claim(JwtRegisteredClaimNames.Exp,
                                 new DateTimeOffset(Clock.UtcDateTime).AddSeconds(uint.Parse(expire.ConfigValue)).ToUnixTimeSeconds().ToString(), ClaimValueTypes.Integer64));

            return(claims);
        }
예제 #8
0
        public List<Claim> GenerateAccessClaims(tbl_Issuer issuer, tbl_User user)
        {
            var expire = _context.Set<tbl_Setting>().Where(x => x.IssuerId == issuer.Id && x.AudienceId == null && x.UserId == null
                && x.ConfigKey == SettingsConstants.AccessExpire).Single();

            var legacyClaims = _context.Set<tbl_Setting>().Where(x => x.IssuerId == null && x.AudienceId == null && x.UserId == null
                && x.ConfigKey == SettingsConstants.GlobalLegacyClaims).Single();

            var claims = new List<Claim>();

            //add lowest common denominators...
            claims.Add(new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()));

            if (!string.IsNullOrEmpty(user.EmailAddress))
                claims.Add(new Claim(ClaimTypes.Email, user.EmailAddress));

            if (!string.IsNullOrEmpty(user.PhoneNumber))
                claims.Add(new Claim(ClaimTypes.MobilePhone, user.PhoneNumber));

            claims.Add(new Claim(ClaimTypes.GivenName, user.FirstName));
            claims.Add(new Claim(ClaimTypes.Surname, user.LastName));

            var userRoles = _context.Set<tbl_Role>()
                .Where(x => x.tbl_UserRoles.Any(y => y.UserId == user.Id)).ToList();

            foreach (var role in userRoles.OrderBy(x => x.Name))
            {
                claims.Add(new Claim(ClaimTypes.Role, role.Name));

                //check compatibility is enabled. pack claim(s) with old name and new name.
                if (bool.Parse(legacyClaims.ConfigValue))
                    claims.Add(new Claim("role", role.Name, ClaimTypes.Role));
            }

            var userClaims = _context.Set<tbl_Claim>()
                .Where(x => x.tbl_UserClaims.Any(y => y.UserId == user.Id)).ToList();

            foreach (var claim in userClaims.OrderBy(x => x.Type))
                claims.Add(new Claim(claim.Type, claim.Value, claim.ValueType));

            //nonce to enhance entropy
            claims.Add(new Claim(JwtRegisteredClaimNames.Nonce, AlphaNumeric.CreateString(8), ClaimValueTypes.String));

            //not before timestamp
            claims.Add(new Claim(JwtRegisteredClaimNames.Nbf,
                new DateTimeOffset(Clock.UtcDateTime).ToUnixTimeSeconds().ToString(), ClaimValueTypes.Integer64));

            //issued at timestamp
            claims.Add(new Claim(JwtRegisteredClaimNames.Iat,
                new DateTimeOffset(Clock.UtcDateTime).ToUnixTimeSeconds().ToString(), ClaimValueTypes.Integer64));

            //expire on timestamp
            claims.Add(new Claim(JwtRegisteredClaimNames.Exp,
                new DateTimeOffset(Clock.UtcDateTime).AddSeconds(uint.Parse(expire.ConfigValue)).ToUnixTimeSeconds().ToString(), ClaimValueTypes.Integer64));

            return claims;
        }
예제 #9
0
        public void CreateUserStates()
        {
            if (foundIssuer == null)
            {
                CreateIssuers();
            }

            if (foundAudience == null)
            {
                CreateAudiences();
            }

            if (foundUser == null)
            {
                CreateUsers();
            }

            /*
             * create test states
             */

            _uow.States.Create(
                _map.Map <tbl_State>(new StateV1()
            {
                IssuerId     = foundIssuer.Id,
                AudienceId   = foundAudience.Id,
                UserId       = foundUser.Id,
                StateValue   = AlphaNumeric.CreateString(32),
                StateType    = ConsumerType.Device.ToString(),
                StateConsume = true,
                ValidFromUtc = DateTime.UtcNow,
                ValidToUtc   = DateTime.UtcNow.AddSeconds(60),
            }));

            _uow.States.Create(
                _map.Map <tbl_State>(new StateV1()
            {
                IssuerId     = foundIssuer.Id,
                AudienceId   = foundAudience.Id,
                UserId       = foundUser.Id,
                StateValue   = AlphaNumeric.CreateString(32),
                StateType    = ConsumerType.User.ToString(),
                StateConsume = false,
                ValidFromUtc = DateTime.UtcNow,
                ValidToUtc   = DateTime.UtcNow.AddSeconds(60),
            }));

            _uow.Commit();
        }
예제 #10
0
        public void CreateUsers()
        {
            /*
             * create test users
             */

            foundUser = _uow.Users.Get(QueryExpressionFactory.GetQueryExpression <tbl_User>()
                                       .Where(x => x.UserName == TestDefaultConstants.UserName).ToLambda())
                        .SingleOrDefault();

            if (foundUser == null)
            {
                foundUser = _uow.Users.Create(
                    _map.Map <tbl_User>(new UserV1()
                {
                    UserName     = TestDefaultConstants.UserName,
                    Email        = TestDefaultConstants.UserName,
                    PhoneNumber  = NumberAs.CreateString(11),
                    FirstName    = "First-" + AlphaNumeric.CreateString(4),
                    LastName     = "Last-" + AlphaNumeric.CreateString(4),
                    IsHumanBeing = true,
                    IsLockedOut  = false,
                    IsDeletable  = true,
                }), TestDefaultConstants.UserPassCurrent);

                _uow.Commit();

                _uow.AuthActivity.Create(
                    _map.Map <tbl_AuthActivity>(new AuthActivityV1()
                {
                    UserId       = foundUser.Id,
                    LoginType    = GrantFlowType.ResourceOwnerPasswordV2.ToString(),
                    LoginOutcome = GrantFlowResultType.Success.ToString(),
                }));

                _uow.Users.SetConfirmedEmail(foundUser, true);
                _uow.Users.SetConfirmedPhoneNumber(foundUser, true);
                _uow.Users.SetConfirmedPassword(foundUser, true);

                _uow.Commit();
            }
        }
예제 #11
0
        public void CreateLogins()
        {
            /*
             * create test logins
             */

            foundLogin = _uow.Logins.Get(QueryExpressionFactory.GetQueryExpression <tbl_Login>()
                                         .Where(x => x.Name == TestDefaultConstants.LoginName).ToLambda())
                         .SingleOrDefault();

            if (foundLogin == null)
            {
                foundLogin = _uow.Logins.Create(
                    _map.Map <tbl_Login>(new LoginV1()
                {
                    Name        = TestDefaultConstants.LoginName,
                    LoginKey    = AlphaNumeric.CreateString(16),
                    IsDeletable = true,
                }));

                _uow.Commit();
            }
        }
예제 #12
0
        public void CreateMOTDs()
        {
            var sets = 2;

            for (int i = 0; i < sets; i++)
            {
                _uow.MOTDs.Create(
                    _map.Map <tbl_MOTD>(new MOTDTssV1()
                {
                    globalId   = Guid.NewGuid(),
                    author     = TestDefaultConstants.MOTDAuthor,
                    quote      = "Quote-" + Base64.CreateString(4),
                    length     = 666.ToString(),
                    id         = AlphaNumeric.CreateString(8),
                    date       = DateTime.UtcNow.ToString(),
                    category   = "Test Category",
                    title      = "Test Title",
                    background = "Test Background",
                    tags       = "tag1,tag2,tag3".Split(',', StringSplitOptions.None).ToList(),
                }));
            }

            _uow.Commit();
        }
예제 #13
0
        public void Repo_EmailQueue_CreateV1_Success()
        {
            var data = new TestDataFactory(UoW);

            data.Destroy();
            data.CreateEmails();

            var user = UoW.Users.Get(QueryExpressionFactory.GetQueryExpression <tbl_User>()
                                     .Where(x => x.UserName == TestDefaultConstants.UserName).ToLambda())
                       .First();

            var result = UoW.EmailQueue.Create(
                Mapper.Map <tbl_EmailQueue>(new EmailV1()
            {
                FromEmail = user.EmailAddress,
                ToEmail   = user.EmailAddress,
                Subject   = "Subject-" + AlphaNumeric.CreateString(4),
                Body      = "Body" + AlphaNumeric.CreateString(4),
            }));

            UoW.Commit();

            result.Should().BeAssignableTo <tbl_EmailQueue>();
        }
예제 #14
0
        public void Repo_States_CreateV1_Success()
        {
            var data = new TestDataFactory(UoW);

            data.Destroy();
            data.CreateUserStates();

            var issuer = UoW.Issuers.Get(QueryExpressionFactory.GetQueryExpression <tbl_Issuer>()
                                         .Where(x => x.Name == TestDefaultConstants.IssuerName).ToLambda())
                         .Single();

            var audience = UoW.Audiences.Get(QueryExpressionFactory.GetQueryExpression <tbl_Audience>()
                                             .Where(x => x.Name == TestDefaultConstants.AudienceName).ToLambda())
                           .Single();

            var user = UoW.Users.Get(QueryExpressionFactory.GetQueryExpression <tbl_User>()
                                     .Where(x => x.UserName == TestDefaultConstants.UserName).ToLambda())
                       .Single();

            var result = UoW.States.Create(
                Mapper.Map <tbl_State>(new StateV1()
            {
                IssuerId     = issuer.Id,
                AudienceId   = audience.Id,
                UserId       = user.Id,
                StateValue   = AlphaNumeric.CreateString(32),
                StateType    = ConsumerType.Device.ToString(),
                StateConsume = false,
                ValidFromUtc = DateTime.UtcNow,
                ValidToUtc   = DateTime.UtcNow.AddSeconds(60),
            }));

            UoW.Commit();

            result.Should().BeAssignableTo <tbl_State>();
        }
예제 #15
0
        public IActionResult AuthCodeV2_Ask([FromQuery] AuthCodeAskV2 input)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            //clean out cruft from encoding...
            input.issuer       = HttpUtility.UrlDecode(input.issuer);
            input.client       = HttpUtility.UrlDecode(input.client);
            input.user         = HttpUtility.UrlDecode(input.user);
            input.redirect_uri = HttpUtility.UrlDecode(input.redirect_uri);
            input.scope        = HttpUtility.UrlDecode(input.scope);

            Guid       issuerID;
            tbl_Issuer issuer;

            //check if identifier is guid. resolve to guid if not.
            if (Guid.TryParse(input.issuer, out issuerID))
            {
                issuer = uow.Issuers.Get(x => x.Id == issuerID).SingleOrDefault();
            }
            else
            {
                issuer = uow.Issuers.Get(x => x.Name == input.issuer).SingleOrDefault();
            }

            if (issuer == null)
            {
                ModelState.AddModelError(MessageType.IssuerNotFound.ToString(), $"Issuer:{input.issuer}");
                return(NotFound(ModelState));
            }

            Guid         audienceID;
            tbl_Audience audience;

            //check if identifier is guid. resolve to guid if not.
            if (Guid.TryParse(input.client, out audienceID))
            {
                audience = uow.Audiences.Get(x => x.Id == audienceID, x => x.Include(u => u.tbl_Urls)).SingleOrDefault();
            }
            else
            {
                audience = uow.Audiences.Get(x => x.Name == input.client, x => x.Include(u => u.tbl_Urls)).SingleOrDefault();
            }

            if (audience == null)
            {
                ModelState.AddModelError(MessageType.AudienceNotFound.ToString(), $"Audience:{input.client}");
                return(NotFound(ModelState));
            }

            Guid     userID;
            tbl_User user;

            //check if identifier is guid. resolve to guid if not.
            if (Guid.TryParse(input.user, out userID))
            {
                user = uow.Users.Get(x => x.Id == userID).SingleOrDefault();
            }
            else
            {
                user = uow.Users.Get(x => x.UserName == input.user).SingleOrDefault();
            }

            if (user == null)
            {
                ModelState.AddModelError(MessageType.UserNotFound.ToString(), $"User:{input.user}");
                return(NotFound(ModelState));
            }
            //check that user is confirmed...
            //check that user is not locked...
            else if (uow.Users.IsLockedOut(user) ||
                     !user.EmailConfirmed ||
                     !user.PasswordConfirmed)
            {
                ModelState.AddModelError(MessageType.UserInvalid.ToString(), $"User:{user.Id}");
                return(BadRequest(ModelState));
            }

            var authorize = new Uri(string.Format("{0}/{1}/{2}", conf["IdentityMeUrls:BaseUiUrl"], conf["IdentityMeUrls:BaseUiPath"], "authorize"));
            var redirect  = new Uri(input.redirect_uri);

            //check if there is redirect url defined for client. if not then use base url for identity ui.
            if (audience.tbl_Urls.Any(x => x.UrlHost == null && x.UrlPath == redirect.AbsolutePath))
            {
                redirect = new Uri(string.Format("{0}/{1}/{2}", conf["IdentityMeUrls:BaseUiUrl"], conf["IdentityMeUrls:BaseUiPath"], "authorize-callback"));
            }
            else if (audience.tbl_Urls.Any(x => new Uri(x.UrlHost + x.UrlPath).AbsoluteUri == redirect.AbsoluteUri))
            {
            }
            else
            {
                ModelState.AddModelError(MessageType.UriInvalid.ToString(), $"Uri:{input.redirect_uri}");
                return(BadRequest(ModelState));
            }

            var expire = uow.Settings.Get(x => x.IssuerId == issuer.Id && x.AudienceId == null && x.UserId == null &&
                                          x.ConfigKey == SettingsConstants.TotpExpire).Single();

            var state = uow.States.Create(
                map.Map <tbl_State>(new StateV1()
            {
                IssuerId     = issuer.Id,
                AudienceId   = audience.Id,
                UserId       = user.Id,
                StateValue   = AlphaNumeric.CreateString(32),
                StateType    = ConsumerType.User.ToString(),
                StateConsume = false,
                ValidFromUtc = DateTime.UtcNow,
                ValidToUtc   = DateTime.UtcNow.AddSeconds(uint.Parse(expire.ConfigValue)),
            }));

            uow.Commit();

            return(RedirectPermanent(
                       UrlFactory.GenerateAuthCodeV2(authorize, redirect, issuer.Id.ToString(), audience.Id.ToString(), user.Id.ToString(), state.StateValue).AbsoluteUri));
        }
예제 #16
0
파일: Daemon.cs 프로젝트: bhbk/fm3na7zy
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            await Task.Run(() =>
            {
                try
                {
                    AsymmetricKeyAlgorithm.Register(Curve25519.Create);
                    AsymmetricKeyAlgorithm.Register(Ed25519.Create);
                    AsymmetricKeyAlgorithm.Register(EllipticCurveAlgorithm.Create);

                    using (var scope = _factory.CreateScope())
                    {
                        var conf = scope.ServiceProvider.GetRequiredService <IConfiguration>();
                        var uow  = scope.ServiceProvider.GetRequiredService <IUnitOfWork>();

                        if (!Enum.TryParse <LogLevel>(conf["Rebex:LogLevel"], true, out _level))
                        {
                            throw new InvalidCastException();
                        }

                        var license = uow.Settings.Get(QueryExpressionFactory.GetQueryExpression <tbl_Setting>()
                                                       .Where(x => x.ConfigKey == "RebexLicense").ToLambda()).OrderBy(x => x.Created)
                                      .Last();

                        Rebex.Licensing.Key = license.ConfigValue;

                        KeyHelper.CheckPrivKey(conf, uow, SshHostKeyAlgorithm.DSS, 1024, AlphaNumeric.CreateString(32), SignatureHashAlgorithm.SHA256);
                        KeyHelper.CheckPrivKey(conf, uow, SshHostKeyAlgorithm.RSA, 4096, AlphaNumeric.CreateString(32), SignatureHashAlgorithm.SHA256);
                        KeyHelper.CheckPrivKey(conf, uow, SshHostKeyAlgorithm.ECDsaNistP256, 256, AlphaNumeric.CreateString(32), SignatureHashAlgorithm.SHA256);
                        KeyHelper.CheckPrivKey(conf, uow, SshHostKeyAlgorithm.ECDsaNistP384, 384, AlphaNumeric.CreateString(32), SignatureHashAlgorithm.SHA256);
                        KeyHelper.CheckPrivKey(conf, uow, SshHostKeyAlgorithm.ECDsaNistP521, 521, AlphaNumeric.CreateString(32), SignatureHashAlgorithm.SHA256);
                        KeyHelper.CheckPrivKey(conf, uow, SshHostKeyAlgorithm.ED25519, 256, AlphaNumeric.CreateString(32), SignatureHashAlgorithm.SHA256);

                        var secret = conf["Databases:AuroraSecret"];

                        var dsaStr     = SshHostKeyAlgorithm.DSS.ToString();
                        var dsaPrivKey = uow.PrivateKeys.Get(QueryExpressionFactory.GetQueryExpression <tbl_PrivateKey>()
                                                             .Where(x => x.KeyAlgo == dsaStr && x.IdentityId == null).ToLambda()).OrderBy(x => x.Created)
                                         .Single();

                        var dsaBytes = Encoding.ASCII.GetBytes(dsaPrivKey.KeyValue);
                        _server.Keys.Add(new SshPrivateKey(dsaBytes, AES.DecryptString(dsaPrivKey.KeyPass, secret)));

                        var rsaStr     = SshHostKeyAlgorithm.RSA.ToString();
                        var rsaPrivKey = uow.PrivateKeys.Get(QueryExpressionFactory.GetQueryExpression <tbl_PrivateKey>()
                                                             .Where(x => x.KeyAlgo == rsaStr && x.IdentityId == null).ToLambda()).OrderBy(x => x.Created)
                                         .Single();

                        var rsaBytes = Encoding.ASCII.GetBytes(rsaPrivKey.KeyValue);
                        _server.Keys.Add(new SshPrivateKey(rsaBytes, AES.DecryptString(rsaPrivKey.KeyPass, secret)));

                        var ecdsa256Str     = SshHostKeyAlgorithm.ECDsaNistP256.ToString();
                        var ecdsa256PrivKey = uow.PrivateKeys.Get(QueryExpressionFactory.GetQueryExpression <tbl_PrivateKey>()
                                                                  .Where(x => x.KeyAlgo == ecdsa256Str && x.IdentityId == null).ToLambda()).OrderBy(x => x.Created)
                                              .Single();

                        var ecdsa256Bytes = Encoding.ASCII.GetBytes(ecdsa256PrivKey.KeyValue);
                        _server.Keys.Add(new SshPrivateKey(ecdsa256Bytes, AES.DecryptString(ecdsa256PrivKey.KeyPass, secret)));

                        var ecdsa384Str     = SshHostKeyAlgorithm.ECDsaNistP384.ToString();
                        var ecdsa384PrivKey = uow.PrivateKeys.Get(QueryExpressionFactory.GetQueryExpression <tbl_PrivateKey>()
                                                                  .Where(x => x.KeyAlgo == ecdsa384Str && x.IdentityId == null).ToLambda()).OrderBy(x => x.Created)
                                              .Single();

                        var ecdsa384Bytes = Encoding.ASCII.GetBytes(ecdsa384PrivKey.KeyValue);
                        _server.Keys.Add(new SshPrivateKey(ecdsa384Bytes, AES.DecryptString(ecdsa384PrivKey.KeyPass, secret)));

                        var ecdsa521Str     = SshHostKeyAlgorithm.ECDsaNistP521.ToString();
                        var ecdsa521PrivKey = uow.PrivateKeys.Get(QueryExpressionFactory.GetQueryExpression <tbl_PrivateKey>()
                                                                  .Where(x => x.KeyAlgo == ecdsa521Str && x.IdentityId == null).ToLambda()).OrderBy(x => x.Created)
                                              .Single();

                        var ecdsa521Bytes = Encoding.ASCII.GetBytes(ecdsa521PrivKey.KeyValue);
                        _server.Keys.Add(new SshPrivateKey(ecdsa521Bytes, AES.DecryptString(ecdsa521PrivKey.KeyPass, secret)));

                        var ed25519Str     = SshHostKeyAlgorithm.ED25519.ToString();
                        var ed25519PrivKey = uow.PrivateKeys.Get(QueryExpressionFactory.GetQueryExpression <tbl_PrivateKey>()
                                                                 .Where(x => x.KeyAlgo == ed25519Str && x.IdentityId == null).ToLambda()).OrderBy(x => x.Created)
                                             .Single();

                        var ed25519Bytes = Encoding.ASCII.GetBytes(ed25519PrivKey.KeyValue);
                        _server.Keys.Add(new SshPrivateKey(ed25519Bytes, AES.DecryptString(ed25519PrivKey.KeyPass, secret)));

                        _binding = conf.GetSection("Daemons:SftpService:Bindings").GetChildren().Select(x => x.Value);
                    }

                    foreach (var binding in _binding)
                    {
                        var pair = binding.Split("|");

                        _server.Bind(new IPEndPoint(IPAddress.Parse(pair[0]), int.Parse(pair[1])), FileServerProtocol.Sftp);
#if DEBUG
                        _server.Bind(new IPEndPoint(IPAddress.Parse(pair[0]), int.Parse(pair[1])), FileServerProtocol.Shell);
#endif
                    }

                    _server.LogWriter = new ConsoleLogWriter(_level);
                    _server.Settings.AllowedAuthenticationMethods        = AuthenticationMethods.PublicKey | AuthenticationMethods.Password;
                    _server.Settings.SshParameters.EncryptionAlgorithms  = SshEncryptionAlgorithm.Any;
                    _server.Settings.SshParameters.EncryptionModes       = SshEncryptionMode.Any;
                    _server.Settings.SshParameters.KeyExchangeAlgorithms = SshKeyExchangeAlgorithm.Any;
                    _server.Settings.SshParameters.HostKeyAlgorithms     = SshHostKeyAlgorithm.Any;
                    _server.Settings.SshParameters.MacAlgorithms         = SshMacAlgorithm.Any;
                    _server.Authentication    += FsUser_Authentication;
                    _server.Connecting        += FsUser_Connecting;
                    _server.Disconnected      += FsUser_Disconnected;
                    _server.FileDownloaded    += FsUser_FileDownloaded;
                    _server.FileUploaded      += FsUser_FileUploaded;
                    _server.PreAuthentication += FsUser_PreAuthentication;
                    _server.Start();
                }
                catch (Exception ex)
                {
                    Log.Error(ex.ToString());
                }
            }, cancellationToken);
        }
예제 #17
0
        public void Create()
        {
            if (_uow.InstanceType == InstanceContext.DeployedOrLocal)
            {
                throw new InvalidOperationException();
            }

            /*
             * create key pairs for daemons
             */
            KeyHelper.CheckPrivKey(_conf, _uow, SshHostKeyAlgorithm.DSS, 1024, AlphaNumeric.CreateString(32), SignatureHashAlgorithm.SHA256);
            KeyHelper.CheckPrivKey(_conf, _uow, SshHostKeyAlgorithm.RSA, 4096, AlphaNumeric.CreateString(32), SignatureHashAlgorithm.SHA256);
            KeyHelper.CheckPrivKey(_conf, _uow, SshHostKeyAlgorithm.ECDsaNistP256, 256, AlphaNumeric.CreateString(32), SignatureHashAlgorithm.SHA256);
            KeyHelper.CheckPrivKey(_conf, _uow, SshHostKeyAlgorithm.ECDsaNistP384, 384, AlphaNumeric.CreateString(32), SignatureHashAlgorithm.SHA256);
            KeyHelper.CheckPrivKey(_conf, _uow, SshHostKeyAlgorithm.ECDsaNistP521, 521, AlphaNumeric.CreateString(32), SignatureHashAlgorithm.SHA256);
            KeyHelper.CheckPrivKey(_conf, _uow, SshHostKeyAlgorithm.ED25519, 256, AlphaNumeric.CreateString(32), SignatureHashAlgorithm.SHA256);

            /*
             * create composite test users
             */
            var foundCompositeUser = _uow.Users.Get(QueryExpressionFactory.GetQueryExpression <tbl_User>()
                                                    .Where(x => x.IdentityAlias == Constants.TestCompositeUser).ToLambda())
                                     .SingleOrDefault();

            if (foundCompositeUser == null)
            {
                foundCompositeUser = _uow.Users.Create(
                    new tbl_User()
                {
                    IdentityId       = Guid.NewGuid(),
                    IdentityAlias    = Constants.TestCompositeUser,
                    RequirePassword  = true,
                    RequirePublicKey = false,
                    FileSystemType   = FileSystemTypes.Composite.ToString(),
                    Created          = DateTime.Now,
                    Enabled          = true,
                    Deletable        = true,
                });

                _uow.Commit();

                KeyHelper.CreatePrivKey(_conf, _uow, foundCompositeUser, SshHostKeyAlgorithm.RSA, 2048,
                                        AlphaNumeric.CreateString(32), SignatureHashAlgorithm.SHA256, Dns.GetHostName());
            }

            /*
             * create memory test users
             */
            var foundMemoryUser = _uow.Users.Get(QueryExpressionFactory.GetQueryExpression <tbl_User>()
                                                 .Where(x => x.IdentityAlias == Constants.TestMemoryUser).ToLambda())
                                  .SingleOrDefault();

            if (foundMemoryUser == null)
            {
                foundMemoryUser = _uow.Users.Create(
                    new tbl_User()
                {
                    IdentityId       = Guid.NewGuid(),
                    IdentityAlias    = Constants.TestMemoryUser,
                    RequirePassword  = true,
                    RequirePublicKey = false,
                    FileSystemType   = FileSystemTypes.Memory.ToString(),
                    Created          = DateTime.Now,
                    Enabled          = true,
                    Deletable        = true,
                });

                _uow.Commit();

                KeyHelper.CreatePrivKey(_conf, _uow, foundMemoryUser, SshHostKeyAlgorithm.RSA, 2048,
                                        AlphaNumeric.CreateString(32), SignatureHashAlgorithm.SHA256, Dns.GetHostName());
            }

            /*
             * create smb test users
             */
            var foundSmbUser = _uow.Users.Get(QueryExpressionFactory.GetQueryExpression <tbl_User>()
                                              .Where(x => x.IdentityAlias == Constants.TestSmbUser).ToLambda())
                               .SingleOrDefault();

            if (foundSmbUser == null)
            {
                foundSmbUser = _uow.Users.Create(
                    new tbl_User()
                {
                    IdentityId       = Guid.NewGuid(),
                    IdentityAlias    = Constants.TestSmbUser,
                    RequirePassword  = true,
                    RequirePublicKey = false,
                    FileSystemType   = FileSystemTypes.SMB.ToString(),
                    Created          = DateTime.Now,
                    Enabled          = true,
                    Deletable        = true,
                });

                _uow.Commit();

                KeyHelper.CreatePrivKey(_conf, _uow, foundSmbUser, SshHostKeyAlgorithm.RSA, 2048,
                                        AlphaNumeric.CreateString(32), SignatureHashAlgorithm.SHA256, Dns.GetHostName());
            }
        }