public static byte[] Encode(Message msg)
        {
            var first4Bytes = new byte[4];

            first4Bytes[0] = msg.Reserved1;
            first4Bytes[1] = msg.Reserved2;
            first4Bytes[2] = msg.Reserved3;
            first4Bytes[3] = (byte)msg.MessageType;

            var bodyLength = 0;//最后再赋值

            var requestId = msg.RequestId;

            var routeDatas = System.Text.Encoding.UTF8.GetBytes(msg.Route ?? string.Empty);

            //8(固定header长度)+4(requestId长度)+4(routeDatas长度)+routeDatas.Length+msg.Data.Length
            bodyLength = 4 + 4 + routeDatas.Length + msg.Data.Length;

            var datas = new byte[bodyLength + 8];

            int offset = 0;

            Write(first4Bytes, datas, ref offset);

            Write(EncoderUtils.EncodeInt32(bodyLength), datas, ref offset);
            Write(EncoderUtils.EncodeInt32(msg.RequestId), datas, ref offset);
            Write(EncoderUtils.EncodeInt32(routeDatas.Length), datas, ref offset);
            Write(routeDatas, datas, ref offset);
            Write(msg.Data, datas, ref offset);

            return(datas);
        }
示例#2
0
        public virtual async Task <bool> Register(UserModel registrationModel)
        {
            if (registrationModel == null || string.IsNullOrEmpty(registrationModel.UserName) || string.IsNullOrEmpty(registrationModel.Password))
            {
                return(false);
            }

            bool registerUserResult = _userDAO.RegisterUser(registrationModel);

            if (!registerUserResult)
            {
                return(false);
            }

            bool addWelcomeBonusResult = AddwelcomeBonus(registrationModel.UserName);

            string token = EncoderUtils.Base64Encode(registrationModel.UserName);

            string registrationMailSubject = "Confirm email";
            string registrationMailBody    = $@"
                Hi! <br/>
                To confirm your email please follow the 
                <a href='{GetCurrentDomain()}/Auth/ConfirmRegistration?token={token}'>link</a> 
                <br/><br/><br/>
                Best regards!";

            if (_appSettings.IgnoreEmails)
            {
                return(await ConfirmRegistration(token));
            }

            await _emailSender.SendEmailAsync(registrationModel.UserName, registrationMailSubject, registrationMailBody);

            return(true);
        }
示例#3
0
        public virtual async Task <bool> PasswordRecovery(UserModel passwordRecoveryModel)
        {
            if (passwordRecoveryModel == null || string.IsNullOrEmpty(passwordRecoveryModel.UserName))
            {
                return(false);
            }

            if (!_userDAO.Exist(passwordRecoveryModel.UserName))
            {
                return(false);
            }
            string token = new Guid().ToString();

            _userDAO.UpdatePasswordToken(passwordRecoveryModel.UserName, token);

            string passwordRecoverySubject = "Password recovery email";
            string passwordRecoveryBody    = $@"
                Hi! <br/>
                You requested password recovery to complete request follow 
                <a href='{_appSettings.BaseUrl}/Auth/recover?token={EncoderUtils.Base64Encode(token)}'>link</a>
                <br/><br/><br/>
                Best regards!";

            await _emailSender.SendEmailAsync(passwordRecoveryModel.UserName, passwordRecoverySubject, passwordRecoveryBody);

            return(true);
        }
示例#4
0
        private void ValidateBrokenAuthSensitivedataExposure(string userName)
        {
            string sessionId   = _httpContextAccessor.HttpContext.Request.Cookies["SessionId"];
            string logedInUser = null;

            CtfChallangeModel missingAuthChallange = _ctfOptions.CtfChallanges
                                                     .Where(x => x.Type == CtfChallengeTypes.MissingAuthentication)
                                                     .Single();

            if (string.IsNullOrEmpty(sessionId))
            {
                _httpContextAccessor.HttpContext.Response.Headers.Add(missingAuthChallange.FlagKey, missingAuthChallange.Flag);
            }
            else
            {
                if (!_userDAO.ValidateSession(sessionId.Split("-")[1]))
                {
                    _httpContextAccessor.HttpContext.Response.Headers.Add(missingAuthChallange.FlagKey, missingAuthChallange.Flag);
                }

                logedInUser = EncoderUtils.Base64Decode(sessionId.Split("-")[0]);
            }

            if (logedInUser != userName)
            {
                CtfChallangeModel sensitiveDataExposureChallenge = _ctfOptions.CtfChallanges
                                                                   .Where(x => x.Type == CtfChallengeTypes.SensitiveDataExposure)
                                                                   .Single();

                _httpContextAccessor.HttpContext.Response.Headers.Add(sensitiveDataExposureChallenge.FlagKey, sensitiveDataExposureChallenge.Flag);
            }
        }
        public override bool AuthorizeAdmin(AuthorizationFilterContext context)
        {
            bool result = base.AuthorizeAdmin(context);

            if (!result)
            {
                return(false);
            }

            string sessionId = context.HttpContext.Request.Cookies["SessionId"];
            string userName  = EncoderUtils.Base64Decode(sessionId.Split("-")[USER_NAME_INDEX]);

            IUserDAO userDAO = context.HttpContext.RequestServices.GetRequiredService <IUserDAO>();

            UserDBModel user = userDAO.GetUser(userName);

            if (user.Role < ADMIN_ROLE)
            {
                CtfOptions ctfOptions = context.HttpContext.RequestServices.GetRequiredService <IOptions <CtfOptions> >().Value;

                CtfChallangeModel ctfChallange = ctfOptions.CtfChallanges
                                                 .Where(x => x.Type == CtfChallengeTypes.ChangeRoleInCookie)
                                                 .Single();

                context.HttpContext.Response.Headers.Add(ctfChallange.FlagKey, ctfChallange.Flag);
            }

            return(true);
        }
示例#6
0
        public virtual Task <UserModel> Login(UserModel loginModel)
        {
            if (loginModel == null || string.IsNullOrEmpty(loginModel.UserName) || string.IsNullOrEmpty(loginModel.Password))
            {
                return(Task.FromResult <UserModel>(null));
            }

            var accessLogModel = new
            {
                Ip       = _httpContextAccessor.HttpContext.Connection.RemoteIpAddress.ToString(),
                Username = loginModel.UserName,
                Password = loginModel.Password
            };

            _accessLogger.Info($"{Newtonsoft.Json.JsonConvert.SerializeObject(accessLogModel)}");

            if (!_userDAO.ValidatePassword(loginModel.UserName, loginModel.Password))
            {
                return(Task.FromResult <UserModel>(null));
            }

            UserDBModel userModel = _userDAO.GetUser(loginModel.UserName);

            Random random = new Random();

            var byteArray = new byte[256];

            random.NextBytes(byteArray);

            string cookie = Sha256HashUtils.ComputeSha256Hash(byteArray);
            string inrole = userModel.Role > 0 ? "1" : "0";

            if (userModel.Role > 50)
            {
                inrole = "100";
            }

            string allCookie = $"{EncoderUtils.Base64Encode(loginModel.UserName)}-{cookie}-{inrole}";

            if (!_userDAO.SaveSession(cookie, DateTime.UtcNow.AddDays(1)))
            {
                return(Task.FromResult <UserModel>(null));
            }

            loginModel.Password = null;
            loginModel.Cookie   = allCookie;
            loginModel.Status   = "ok";

            _httpContextAccessor.HttpContext.Response.Cookies.Append(AUTH_COOKIE, loginModel.Cookie, new CookieOptions
            {
                Expires  = DateTime.Now.AddDays(3),
                HttpOnly = false
            });

            return(Task.FromResult(loginModel));
        }
示例#7
0
            public void save()
            {
                var result = new JiraAuth();

                result.url      = this.url;
                result.username = this.username;
                result.password = EncoderUtils.encode(this.password);

                FileUtils.WriteFile(AppSettings.JiraAuth, JsonConvert.SerializeObject(result));
            }
示例#8
0
        protected virtual IEnumerable <Claim> GetClaims(string cookie)
        {
            Claim[] claims = new[]
            {
                new Claim(CookieConstants.AUTHENTICATED_CALIM_TYPE, "True"),
                new Claim(CookieConstants.USERNAME_CALIM_TYPE, EncoderUtils.Base64Decode(GetUserName(cookie))),
                new Claim(CookieConstants.ROLE_CALIM_TYPE, GetRole(cookie)),
            };

            return(claims);
        }
示例#9
0
        public virtual bool AuthorizeNormal(AuthorizationFilterContext context)
        {
            string sessionId = context.HttpContext.Request.Cookies["SessionId"];

            if (string.IsNullOrEmpty(sessionId))
            {
                return(false);
            }

            string[] sessionParts = sessionId.Split('-');
            if (sessionParts.Length != COOKIE_PARTS)
            {
                return(false);
            }

            bool parseRoleResult = int.TryParse(sessionParts[ROLDE_INDEX], out int role);

            if (!parseRoleResult)
            {
                return(false);
            }

            IUserDAO userDAO = context.HttpContext.RequestServices.GetRequiredService <IUserDAO>();

            if (userDAO.ValidateSession(sessionParts[TOKEN_INDEX]) == false)
            {
                return(false);
            }

            string roleString = NORMAL_ROLE_STRING;

            if (role >= ADMIN_ROLE)
            {
                roleString = ADMIN_ROLE_STRING;
            }

            Claim[] claims = new[]
            {
                new Claim("authenticated", "true"),
                new Claim("userName", EncoderUtils.Base64Decode(sessionParts[USER_NAME_INDEX])),
                new Claim("role", roleString),
            };

            GenericPrincipal tmpUser = new GenericPrincipal(new ClaimsIdentity(claims), Array.Empty <string>());

            context.HttpContext.User = tmpUser;

            return(true);
        }
示例#10
0
            private bool loadFromDB()
            {
                var data = FileUtils.ReadFile(AppSettings.JiraAuth);

                if (String.IsNullOrEmpty(data))
                {
                    // TODO put log here
                    return(false);
                }
                var result = JsonConvert.DeserializeObject <JiraAuth>(data);

                this.url      = result.url;
                this.username = result.username;
                this.password = EncoderUtils.decode(result.password);
                return(this.isValid());
            }
示例#11
0
        public virtual Task <bool> RecoverPasswordValid(string token)
        {
            if (string.IsNullOrEmpty(token))
            {
                return(Task.FromResult(false));
            }

            string userName = EncoderUtils.Base64Decode(token);

            if (!_userDAO.PasswordTokenExists(userName))
            {
                return(Task.FromResult(false));
            }

            return(Task.FromResult(true));
        }
示例#12
0
        public virtual Task <bool> ConfirmRegistration(string token)
        {
            if (string.IsNullOrEmpty(token))
            {
                return(Task.FromResult(false));
            }

            string userName = EncoderUtils.Base64Decode(token);

            bool result = _userDAO.ConfirmToken(userName);

            if (!result)
            {
                return(Task.FromResult(false));
            }

            //_transactionDAO.MakeRandomTransactions(userName);
            return(Task.FromResult(true));
        }
示例#13
0
        public virtual Task <bool> RecoverPassword(UserModel passwordRecoveryModel)
        {
            if (passwordRecoveryModel == null || string.IsNullOrEmpty(passwordRecoveryModel.Token) || string.IsNullOrEmpty(passwordRecoveryModel.Password))
            {
                return(Task.FromResult(false));
            }

            string userName = EncoderUtils.Base64Decode(passwordRecoveryModel.Token);

            if (!_userDAO.PasswordTokenExists(userName))
            {
                return(Task.FromResult(false));
            }

            if (!_userDAO.UpdatePassword(userName, passwordRecoveryModel.Password))
            {
                return(Task.FromResult(false));
            }

            return(Task.FromResult(true));
        }
示例#14
0
        public override string CreateCookie(UserDBModel user, HttpContext context)
        {
            Random random = new Random();

            var byteArray = new byte[256];

            random.NextBytes(byteArray);

            string cookieHash = Sha256HashUtils.ComputeSha256Hash(byteArray);
            string inrole     = user.Role.ToString();

            if (user.Role > ADMIN_ROLE)
            {
                inrole = ADMIN_ROLE_COOKIE_VALUE;
            }

            IUserDAO userDAO           = context.RequestServices.GetRequiredService <IUserDAO>();
            bool     saveSessionResult = userDAO.SaveSession(cookieHash, DateTime.UtcNow.Add(COOKIE_VALID_FOR));

            if (!saveSessionResult)
            {
                return(null);
            }

            string allCookie = string.Format(COOKIE_FORMAT, EncoderUtils.Base64Encode(user.UserName), cookieHash, inrole);

            string encodedCookie = _protector.Protect(allCookie);

            CookieOptions cookieOptions = new CookieOptions
            {
                Expires = DateTime.UtcNow.AddDays(1)
            };

            context.Response.Cookies.Append(COOKIE_KEY, encodedCookie, cookieOptions);

            return(encodedCookie);
        }
示例#15
0
        public virtual async Task <bool> PasswordRecovery(UserModel passwordRecoveryModel)
        {
            if (passwordRecoveryModel == null || string.IsNullOrEmpty(passwordRecoveryModel.UserName))
            {
                return(false);
            }

            if (!_userDAO.Exist(passwordRecoveryModel.UserName))
            {
                return(false);
            }

            string passwordRecoverySubject = "Password recovery email";
            string passwordRecoveryBody    = $@"
                Hi! <br/>
                You requested password recovery to complete request follow 
                <a href='{GetCurrentDomain()}/Auth/recover?token={EncoderUtils.Base64Encode(passwordRecoveryModel.UserName)}'>link</a>
                <br/><br/><br/>
                Best regards!";

            await _emailSender.SendEmailAsync(passwordRecoveryModel.UserName, passwordRecoverySubject, passwordRecoveryBody);

            return(true);
        }
示例#16
0
 public static string MD5(string s, Encoding encoding)
 {
     encoding = encoding ?? Encoding.UTF8;
     return(EncoderUtils.ToMD5String(s, encoding));
 }