Beispiel #1
0
        public static IList <User> MockUsers()
        {
            string prefix = SecurityUtil.CreateRandomString(6) + "测试用户";

            IList <User> list = new List <User>();

            for (int i = 0; i < 1000; ++i)
            {
                User user = new User()
                {
                    Guid          = SecurityUtil.CreateUniqueToken(),
                    SecurityStamp = SecurityUtil.CreateUniqueToken(),
                    UserName      = $"{prefix}_{SecurityUtil.CreateUniqueToken()}",
                    Mobile        = $"1{SecurityUtil.CreateRandomNumbericString(10)}",
                    IsActivated   = true,
                    UserType      = "TestUsers"
                };

                list.Add(user);
            }

            return(list);
        }
Beispiel #2
0
        public void ToDetailPage(string info)
        {
            string id   = info.Split(';')[0];
            string type = info.Split(';')[1];

            switch (type)
            {
            case "Leave":
                Response.Redirect("../LeaveRequestPages/LeaveRequestDetail.aspx?LeaveRequestID=" + SecurityUtil.DECEncrypt(id), false);
                break;

            case "Out":
                Response.Redirect("../OutApplicationPages/OutApplicationDetail.aspx?PKID=" + SecurityUtil.DECEncrypt(id), false);
                break;

            case "OverWork":
                Response.Redirect("../OverWorkPages/OverWorkDetail.aspx?PKID=" + SecurityUtil.DECEncrypt(id), false);
                break;

            default:
                break;
            }
        }
Beispiel #3
0
 /// <exception cref="System.IO.IOException"/>
 public override void Initialize(URI name, Configuration conf)
 {
     base.Initialize(name, conf);
     SetConf(conf);
     this.connectionFactory = URLConnectionFactory.NewDefaultURLConnectionFactory(conf
                                                                                  );
     this.ugi              = UserGroupInformation.GetCurrentUser();
     this.nnUri            = GetNamenodeUri(name);
     this.tokenServiceName = SecurityUtil.BuildTokenService(nnUri);
     try
     {
         this.hftpURI = new URI(name.GetScheme(), name.GetAuthority(), null, null, null);
     }
     catch (URISyntaxException e)
     {
         throw new ArgumentException(e);
     }
     InitTokenAspect();
     if (UserGroupInformation.IsSecurityEnabled())
     {
         tokenAspect.InitDelegationToken(ugi);
     }
 }
Beispiel #4
0
        /// <summary>
        /// 设置保留价
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="price"></param>
        public void SetReservePrice(int userId, decimal price)
        {
            if (price < this.StartPrice)
            {
                throw new SetReservePriceException("保留价不得低于起始价");
            }
            if (this.Status != TradeStatus.Normal)
            {
                throw new SetReservePriceException("当前状态不允许录入保留价");
            }
            var hours = AppSettings.GetValue("HowManyHoursCanSetReservePriceBeforeTradeEndTime", 1);

            if ((this.TradeEndTime - DateTime.Now).TotalHours < 1)
            {
                throw new SetReservePriceException(string.Format("交易结束前{0}个小时不允许录入保留价", hours));
            }
            if (!string.IsNullOrEmpty(this.ReservePrice))
            {
                throw new SetReservePriceException("已有保留价,不能再次录入");
            }
            this.ReservePrice = price.ToString();
            this.ReservePrice = SecurityUtil.EncryptTriDes(this.ReservePrice, ENCRYPT_KEY);
        }
        void Obj_AfterQuery(object sender, QueryObject.QueryEventArgs e)
        {
            if (e.Result == null)
            {
                return;
            }

            string typefullname = e.Type.FullName;

            string key = typefullname + ".query:" + SecurityUtil.MD5_Hash(e.Sql);

            string root_key = JCache.GetRootCacheKey(typefullname);

            List <string> sub_keys = JCache.Get <List <string> >(root_key) ?? new List <string>();

            if (!sub_keys.Contains(key))
            {
                sub_keys.Add(key);
            }

            JCache.Insert(root_key, sub_keys);
            JCache.Insert(key, e.Result);
        }
Beispiel #6
0
        public void TestSQLite_Changes_Test()
        {
            string connectString = $"Data Source=sqlite_test2.db";

            using SqliteConnection conn = new SqliteConnection(connectString);
            conn.Open();

            string guid = SecurityUtil.CreateUniqueToken();

            string insertCommandText = $"insert into tb_publisher(`Name`, `LastTime`, `Guid`, `Version`) values('SSFS', 100, '{guid}', 1)";

            using SqliteCommand insertCommand = new SqliteCommand(insertCommandText, conn);

            insertCommand.ExecuteScalar();


            string commandText = $"update `tb_publisher` set  `Name`='{new Random().NextDouble()}', `Version`=2 WHERE `Guid`='{guid}' ;";

            using SqliteCommand mySqlCommand1 = new SqliteCommand(commandText, conn);

            int rt1 = mySqlCommand1.ExecuteNonQuery();

            using SqliteCommand rowCountCommand1 = new SqliteCommand("select changes()", conn);

            long?rowCount1 = (long?)rowCountCommand1.ExecuteScalar();

            using SqliteCommand mySqlCommand2 = new SqliteCommand(commandText, conn);

            int rt2 = mySqlCommand1.ExecuteNonQuery();

            using SqliteCommand rowCountCommand2 = new SqliteCommand("select changes()", conn);

            long?rowCount2 = (long?)rowCountCommand2.ExecuteScalar();

            Assert.Equal(rt1, rt2);
            Assert.Equal(rowCount1, rowCount2);
        }
Beispiel #7
0
        /// <summary>
        ///     ユーザ情報を取得する
        /// </summary>
        private UserModel Authenticate(LoginModel login)
        {
            UserModel user = null;

            using (this._context)
            {
                var userData =
                    (
                        from users in this._context.Users
                        where
                        users.IsDeleted == false &&
                        users.UserId == login.Username &&
                        users.IsConfirmed == true
                        select users
                    ).FirstOrDefault();

                if (userData != null)
                {
                    // 入力されたパスワードとDBのパスワードを検証
                    var salt         = Convert.FromBase64String(userData.Salt);
                    var loginHash    = SecurityUtil.GeneratePasswordHash(login.Password, salt, this._config.Security.ByteSize, this._config.Security.Iteration);
                    var passwordText = Convert.ToBase64String(loginHash);

                    if (passwordText == userData.Hash)
                    {
                        // UserModelの構築
                        user = new UserModel()
                        {
                            UserName    = userData.UserId,
                            MailAddress = userData.MailAddress
                        };
                    }
                }
            }

            return(user);
        }
        public static Dictionary <Type, List <EntityInfo> > BeforeSaveEntitiesHandler(Dictionary <Type, List <EntityInfo> > entities)
        {
            var userName     = SecurityUtil.GetUserName();
            var entityErrors = new List <EFEntityError>();

            foreach (var type in entities.Keys)
            {
                CheckCanUpdate(type);

                foreach (var entityInfo in entities[type])
                {
                    // TODO check site permissions on save
                    if (entityInfo.EntityState == Breeze.ContextProvider.EntityState.Added)
                    {
                        //if (!_permissionsRepository.UserCanAddEntity(entities, entityInfo, userId))
                        //    entityErrors.Add(new EFEntityError(entityInfo, "Unauthorized", "User does not have permission to add this entity.", ""));
                    }
                    if (entityInfo.EntityState == Breeze.ContextProvider.EntityState.Modified)
                    {
                        //if (!_permissionsRepository.UserCanEditEntity(entityInfo, userId))
                        //    entityErrors.Add(new EFEntityError(entityInfo, "Unauthorized", "User does not have permission to edit this entity.", ""));
                    }
                    if (entityInfo.EntityState == Breeze.ContextProvider.EntityState.Deleted)
                    {
                        //if (!_permissionsRepository.UserCanDeleteEntity(entityInfo, userId))
                        //    entityErrors.Add(new EFEntityError(entityInfo, "Unauthorized", "User does not have permission to delete this entity.", ""));
                    }

                    SetAuditFields(entityInfo, userName);
                }
            }
            if (entityErrors.Count > 0)
            {
                throw new EntityErrorsException(entityErrors);
            }
            return(entities);
        }
Beispiel #9
0
        public override IEnumerable <CommandDTOBase?> Execute(string[] args)
        {
            if (!SecurityUtil.IsHighIntegrity() && !ThisRunTime.ISRemote())
            {
                WriteError("Unable to collect. Must be an administrator.");
                yield break;
            }

            WriteVerbose($"Searching process creation logs (EID 4688) for sensitive data.");
            WriteVerbose($"Format: Date(Local time),User,Command line.\n");

            // Get our "sensitive" cmdline regexes from a common helper function.
            var processCmdLineRegex = MiscUtil.GetProcessCmdLineRegex();

            var query     = $"*[System/EventID=4688]";
            var logReader = ThisRunTime.GetEventLogReader("Security", query);

            for (var eventDetail = logReader.ReadEvent(); eventDetail != null; eventDetail = logReader.ReadEvent())
            {
                var user        = eventDetail.Properties[1].Value.ToString().Trim();
                var commandLine = eventDetail.Properties[8].Value.ToString().Trim();

                foreach (var reg in processCmdLineRegex)
                {
                    var m = reg.Match(commandLine);
                    if (m.Success)
                    {
                        yield return(new ProcessCreationEventDTO(
                                         eventDetail.TimeCreated?.ToUniversalTime(),
                                         eventDetail.Id,
                                         user,
                                         commandLine
                                         ));
                    }
                }
            }
        }
Beispiel #10
0
        /// <summary>
        /// 激活用户信息验证
        /// </summary>
        /// <param name="key">激活参数串</param>
        public string ActiveUserInfo(string key)
        {
            var email     = "";
            var paramInfo = HttpUtility.UrlDecode(SecurityUtil.DESDecode(key));

            if (!string.IsNullOrEmpty(paramInfo))
            {
                paramInfo = paramInfo.Substring(paramInfo.IndexOf('=') + 1);
                var verifyId = paramInfo.Substring(0, paramInfo.IndexOf('&'));
                paramInfo = paramInfo.Substring(paramInfo.IndexOf('=') + 1);
                var activeCode = paramInfo.Substring(0, paramInfo.IndexOf('&'));
                email = paramInfo.Substring(paramInfo.IndexOf('=') + 1);

                var message = "激活用户";
                CheckVerifyCode(activeCode, email, verifyId, message);

                // 更新开发者数据表数据
                var condit = new ConditionCollection()
                {
                    new Condition("mobile", email)
                };

                var developer = GetRepository <McpDeveloperInfo>().GetModel(condit);

                developer.IsActived       = (int)IsActived.Active;
                developer.ActivedDatetime = CommonUtil.GetDBDateTime();

                this.GetRepository <McpDeveloperInfo>().Update(developer);

                return(email);
            }
            else
            {
                throw new MessageException("连接地址有误,请于管理员联系");
            }
        }
Beispiel #11
0
        private bool IsFieldValueValid()
        {
            string currPwd = txtCurrentPwd.Text.Trim().ToLower();

            if (string.IsNullOrEmpty(currPwd))
            {
                txtCurrentPwd.Focus();
                MsgBox.Warn("请重新填写您的当前密码。");
                return(false);
            }

            currPwd = SecurityUtil.MD5Encrypt(currPwd);
            if (!currPwd.Equals(GlobeSettings.LoginedUser.UserPwd))
            {
                txtCurrentPwd.Focus();
                MsgBox.Warn("当前密码填写不正确,请重新填写您的当前密码。");
                return(false);
            }

            if (txtNewPwd.Text.Trim().Length == 0)
            {
                txtNewPwd.Focus();
                MsgBox.Warn("密码不允许为空字符,请填写新密码。");
                return(false);
            }

            if (!txtNewPwd.Text.Trim().Equals(txtPwdAgain.Text.Trim(), StringComparison.OrdinalIgnoreCase))
            {
                txtNewPwd.Text = txtPwdAgain.Text = string.Empty;
                txtNewPwd.Focus();
                MsgBox.Warn("新密码与确认密码填写不一致,请重新输入。");
                return(false);
            }

            return(true);
        }
Beispiel #12
0
        /// <summary>Creates configuration for starting a secure cluster.</summary>
        /// <param name="dataTransferProtection">supported QOPs</param>
        /// <returns>configuration for starting a secure cluster</returns>
        /// <exception cref="System.Exception">if there is any failure</exception>
        protected internal virtual HdfsConfiguration CreateSecureConfig(string dataTransferProtection
                                                                        )
        {
            HdfsConfiguration conf = new HdfsConfiguration();

            SecurityUtil.SetAuthenticationMethod(UserGroupInformation.AuthenticationMethod.Kerberos
                                                 , conf);
            conf.Set(DFSConfigKeys.DfsNamenodeKerberosPrincipalKey, hdfsPrincipal);
            conf.Set(DFSConfigKeys.DfsNamenodeKeytabFileKey, keytab);
            conf.Set(DFSConfigKeys.DfsDatanodeKerberosPrincipalKey, hdfsPrincipal);
            conf.Set(DFSConfigKeys.DfsDatanodeKeytabFileKey, keytab);
            conf.Set(DFSConfigKeys.DfsWebAuthenticationKerberosPrincipalKey, spnegoPrincipal);
            conf.SetBoolean(DFSConfigKeys.DfsBlockAccessTokenEnableKey, true);
            conf.Set(DFSConfigKeys.DfsDataTransferProtectionKey, dataTransferProtection);
            conf.Set(DFSConfigKeys.DfsHttpPolicyKey, HttpConfig.Policy.HttpsOnly.ToString());
            conf.Set(DFSConfigKeys.DfsNamenodeHttpsAddressKey, "localhost:0");
            conf.Set(DFSConfigKeys.DfsDatanodeHttpsAddressKey, "localhost:0");
            conf.SetInt(CommonConfigurationKeys.IpcClientConnectMaxRetriesOnSaslKey, 10);
            string keystoresDir = baseDir.GetAbsolutePath();
            string sslConfDir   = KeyStoreTestUtil.GetClasspathDir(this.GetType());

            KeyStoreTestUtil.SetupSSLConfig(keystoresDir, sslConfDir, conf, false);
            return(conf);
        }
Beispiel #13
0
        public virtual void TestProxyWithToken()
        {
            Configuration conf = new Configuration(masterConf);

            TestSaslRPC.TestTokenSecretManager sm = new TestSaslRPC.TestTokenSecretManager();
            SecurityUtil.SetAuthenticationMethod(UserGroupInformation.AuthenticationMethod.Kerberos
                                                 , conf);
            UserGroupInformation.SetConfiguration(conf);
            Server server = new RPC.Builder(conf).SetProtocol(typeof(TestDoAsEffectiveUser.TestProtocol
                                                                     )).SetInstance(new TestDoAsEffectiveUser.TestImpl(this)).SetBindAddress(Address)
                            .SetPort(0).SetNumHandlers(5).SetVerbose(true).SetSecretManager(sm).Build();

            server.Start();
            UserGroupInformation current = UserGroupInformation.CreateRemoteUser(RealUserName
                                                                                 );
            IPEndPoint addr = NetUtils.GetConnectAddress(server);

            TestSaslRPC.TestTokenIdentifier tokenId = new TestSaslRPC.TestTokenIdentifier(new
                                                                                          Org.Apache.Hadoop.IO.Text(current.GetUserName()), new Org.Apache.Hadoop.IO.Text(
                                                                                              "SomeSuperUser"));
            Org.Apache.Hadoop.Security.Token.Token <TestSaslRPC.TestTokenIdentifier> token = new
                                                                                             Org.Apache.Hadoop.Security.Token.Token <TestSaslRPC.TestTokenIdentifier>(tokenId,
                                                                                                                                                                      sm);
            SecurityUtil.SetTokenService(token, addr);
            UserGroupInformation proxyUserUgi = UserGroupInformation.CreateProxyUserForTesting
                                                    (ProxyUserName, current, GroupNames);

            proxyUserUgi.AddToken(token);
            RefreshConf(conf);
            string retVal = proxyUserUgi.DoAs(new _PrivilegedExceptionAction_457(this, addr,
                                                                                 conf, server));

            //The user returned by server must be the one in the token.
            Assert.Equal(RealUserName + " (auth:TOKEN) via SomeSuperUser (auth:SIMPLE)"
                         , retVal);
        }
Beispiel #14
0
        /// <summary>
        /// 校验登录用户并记录信息
        /// </summary>
        /// <param name="info">登录用户信息</param>
        private void CheckLoginUser(McpAdminInfo info, LoginViewModel model)
        {
            if (info == null)
            {
                throw new MessageException("此帐号不存在!");
            }

            if (!info.AdminPwd.Equals(SecurityUtil.ConvertToMD5(model.Pwd.Trim())))
            {
                throw new MessageException("密码不正确!");
            }

            switch (info.StatusCode)
            {
            case (int)StatusCodeType.Disabled:
                throw new MessageException(UserStatusType.Disabled.GetRemark());

            case (int)StatusCodeType.Deleted:
                throw new MessageException(UserStatusType.Deleted.GetRemark());

            default: break;
            }
            ;
        }
Beispiel #15
0
    /// <summary>
    /// 封装数据包。
    /// </summary>
    /// <param name="data"></param>
    /// <returns></returns>
    private byte[] makeData(byte[] data)
    {
        bool isCompress = false;

        if (data.Length > 200)
        {
            isCompress = true;
            data       = ZlibHelper.CompressBytes(data);
        }
        data = SecurityUtil.Xor(data);               //加密
        ushort crc     = Crc16.CalculateCrc16(data); //校验码。
        ushort bodyLen = (ushort)(data.Length + 3);  //包体长度

        MyMemoryStream m = new MyMemoryStream();

        m.WriteUShort(bodyLen);
        m.WriteBool(isCompress);
        m.WriteUShort(crc);
        m.Write(data, 0, data.Length);
        data = m.ToArray();
        m.Close();

        return(data);
    }
        public MyResult <object> UpdatePwd(BackstageUserAdd model)
        {
            MyResult        result         = new MyResult();
            BackstageCookie backUser       = GetUserCook();
            BackstageUser   backstageModel = this.First <BackstageUser>(t => t.Id == backUser.Id);

            if (backstageModel == null)
            {
                return(result.SetStatus(ErrorCode.NotFound, "登录名称不存在!"));
            }
            string pwd = SecurityUtil.MD5(model.OldPassword);

            if (pwd.Equals(backstageModel.Password))
            {
                string pwdNew = SecurityUtil.MD5(model.ConfirmPassword);
                backstageModel.Password = pwdNew;
            }
            else
            {
                return(result.SetStatus(ErrorCode.NotFound, "您输入的密码不正确!"));
            }
            this.Update(backstageModel, true);
            return(result);
        }
Beispiel #17
0
    /// <summary>
    /// 制作一个数据包,该数据包是符合传给服务器的格式的(包头+包体)
    /// 当前工程的格式是包头:包体长度,包体:压缩标志+CRC校验码+加密的真正数据(异或算法)(协议编码+协议内容)
    /// 把private改为public,配合本机模式本地测试用
    /// </summary>
    /// <param name="data">真实数据</param>
    /// <returns></returns>
    public byte[] MakeDataPkg(byte[] data)
    {
        byte[] returnBuffer = null;
        data = SecurityUtil.XorAlgorithm(data);           //1、加密
        bool isCompress = data.Length > mCompressMinSize; //2、压缩

        if (isCompress)
        {
            //开始压缩
            data = ZlibHelper.CompressBytes(data);
        }
        ushort crc16 = Crc16.CalculateCrc16(data);  //3、CRC校验

        using (MemoryStreamUtil stream = new MemoryStreamUtil())
        {
            stream.WriteUShort((ushort)(data.Length + 3)); //写包头,+3是因为多了一个bool,一个ushort,一共3字节
            stream.WriteBool(isCompress);                  //写压缩标志
            stream.WriteUShort(crc16);                     //写CRC
            stream.Write(data, 0, data.Length);            //写加密后的真实数据
            returnBuffer = stream.ToArray();
        }
        Debug.Log("数据包构建完毕!");
        return(returnBuffer);
    }
        /// <exception cref="System.IO.IOException"/>
        protected internal virtual bool IsValidRequestor(HttpServletRequest request, Configuration
                                                         conf)
        {
            string remotePrincipal = request.GetUserPrincipal().GetName();
            string remoteShortName = request.GetRemoteUser();

            if (remotePrincipal == null)
            {
                // This really shouldn't happen...
                Log.Warn("Received null remoteUser while authorizing access to " + "GetJournalEditServlet"
                         );
                return(false);
            }
            if (Log.IsDebugEnabled())
            {
                Log.Debug("Validating request made by " + remotePrincipal + " / " + remoteShortName
                          + ". This user is: " + UserGroupInformation.GetLoginUser());
            }
            ICollection <string> validRequestors = new HashSet <string>();

            Sharpen.Collections.AddAll(validRequestors, DFSUtil.GetAllNnPrincipals(conf));
            try
            {
                validRequestors.AddItem(SecurityUtil.GetServerPrincipal(conf.Get(DFSConfigKeys.DfsSecondaryNamenodeKerberosPrincipalKey
                                                                                 ), SecondaryNameNode.GetHttpAddress(conf).GetHostName()));
            }
            catch (Exception e)
            {
                // Don't halt if SecondaryNameNode principal could not be added.
                Log.Debug("SecondaryNameNode principal could not be added", e);
                string msg = string.Format("SecondaryNameNode principal not considered, %s = %s, %s = %s"
                                           , DFSConfigKeys.DfsSecondaryNamenodeKerberosPrincipalKey, conf.Get(DFSConfigKeys
                                                                                                              .DfsSecondaryNamenodeKerberosPrincipalKey), DFSConfigKeys.DfsNamenodeSecondaryHttpAddressKey
                                           , conf.Get(DFSConfigKeys.DfsNamenodeSecondaryHttpAddressKey, DFSConfigKeys.DfsNamenodeSecondaryHttpAddressDefault
                                                      ));
                Log.Warn(msg);
            }
            // Check the full principal name of all the configured valid requestors.
            foreach (string v in validRequestors)
            {
                if (Log.IsDebugEnabled())
                {
                    Log.Debug("isValidRequestor is comparing to valid requestor: " + v);
                }
                if (v != null && v.Equals(remotePrincipal))
                {
                    if (Log.IsDebugEnabled())
                    {
                        Log.Debug("isValidRequestor is allowing: " + remotePrincipal);
                    }
                    return(true);
                }
            }
            // Additionally, we compare the short name of the requestor to this JN's
            // username, because we want to allow requests from other JNs during
            // recovery, but we can't enumerate the full list of JNs.
            if (remoteShortName.Equals(UserGroupInformation.GetLoginUser().GetShortUserName()
                                       ))
            {
                if (Log.IsDebugEnabled())
                {
                    Log.Debug("isValidRequestor is allowing other JN principal: " + remotePrincipal);
                }
                return(true);
            }
            if (Log.IsDebugEnabled())
            {
                Log.Debug("isValidRequestor is rejecting: " + remotePrincipal);
            }
            return(false);
        }
Beispiel #19
0
        public static void SetupData()
        {
            var    encryption = new EncryptionHelper();
            string salt       = SecurityUtil.GenerateSalt();

            // Create some users
            for (var i = 1; i <= 5; i++)
            {
                var user = new AppUser
                {
                    Id       = 1,
                    Username = "******" + i.ToString(),
                    Password = encryption.EncodePassword("123456", 1, salt)
                };

                Users.Add(user);
            }

            // create an admin user
            var admin = new AppUser
            {
                Id       = 99,
                Username = "******",
                Password = encryption.EncodePassword("123456", 1, salt),
                IsAdmin  = true
            };

            Users.Add(admin);


            int sectionCount = 10;

            Random rndDuration = new Random();

            for (var i = 1; i <= 20; i++)
            {
                var post = new Post
                {
                    CreatedBy   = "Author " + i.ToString(),
                    Title       = "Help Topic  " + i.ToString(),
                    Url         = "<a target='_blank' href='https://leanpub.com/qlikview-recipes'>Book webpage</a>",
                    Id          = i,
                    ImageUrl    = "/uploads/posts/" + (i % 2 == 0 ? "1.png" : "2.png"),
                    PublishedOn = DateTime.Now.AddDays(-i),
                    ReadingTime = rndDuration.Next(1, 12),
                    Description = "The content of the help goes here.  Be as detailed as possible. "

                                  //Tag = Tags.ElementAt(rndDuration.Next(1, Tags.Count))
                };

                var genCount = rndDuration.Next(1, Tags.Count);

                for (var g = 0; g < genCount; g++)
                {
                    post.Tags.Add(Tags[g]);
                    //Tags[g].Books.Add(post);
                }

                if (i % 2 == 0)
                {
                    sectionCount = 20;              // random section count
                }
                for (var j = 1; j <= sectionCount; j++)
                {
                    var u       = Users[j % 5];
                    var section = new Section
                    {
                        Title    = "Section of " + post.Title,
                        Body     = "An excellent post, " + post.Title,
                        PostId   = post.Id,
                        Id       = i * j,
                        Username = u.Username,
                        User     = u
                    };

                    Random rnd    = new Random();
                    var    rating = new Rating
                    {
                        PostId   = post.Id,
                        Username = u.Username,
                        Value    = rnd.Next(0, 5)
                    };

                    post.Sections.Add(section);
                    post.Ratings.Add(rating);

                    Ratings.Add(rating);
                    Sections.Add(section);
                }

                Posts.Add(post);
            }
        }
        public virtual void TestTokenCompatibilityFor203()
        {
            Configuration  conf = new Configuration();
            HftpFileSystem fs   = new HftpFileSystem();

            Org.Apache.Hadoop.Security.Token.Token <object> token = new Org.Apache.Hadoop.Security.Token.Token
                                                                    <TokenIdentifier>(new byte[0], new byte[0], DelegationTokenIdentifier.HdfsDelegationKind
                                                                                      , new Text("127.0.0.1:8020"));
            Credentials cred = new Credentials();

            cred.AddToken(HftpFileSystem.TokenKind, token);
            ByteArrayOutputStream os = new ByteArrayOutputStream();

            cred.Write(new DataOutputStream(os));
            HttpURLConnection conn = Org.Mockito.Mockito.Mock <HttpURLConnection>();

            Org.Mockito.Mockito.DoReturn(new ByteArrayInputStream(os.ToByteArray())).When(conn
                                                                                          ).GetInputStream();
            Org.Mockito.Mockito.DoReturn(HttpURLConnection.HttpOk).When(conn).GetResponseCode
                ();
            URLConnectionFactory factory = Org.Mockito.Mockito.Mock <URLConnectionFactory>();

            Org.Mockito.Mockito.DoReturn(conn).When(factory).OpenConnection(Org.Mockito.Mockito
                                                                            .Any <Uri>(), Matchers.AnyBoolean());
            URI uri = new URI("hftp://127.0.0.1:8020");

            fs.Initialize(uri, conf);
            fs.connectionFactory = factory;
            UserGroupInformation ugi = UserGroupInformation.CreateUserForTesting("foo", new string
                                                                                 [] { "bar" });
            TokenAspect <HftpFileSystem> tokenAspect = new TokenAspect <HftpFileSystem>(fs, SecurityUtil
                                                                                        .BuildTokenService(uri), HftpFileSystem.TokenKind);

            tokenAspect.InitDelegationToken(ugi);
            tokenAspect.EnsureTokenInitialized();
            NUnit.Framework.Assert.AreSame(HftpFileSystem.TokenKind, fs.GetRenewToken().GetKind
                                               ());
            Org.Apache.Hadoop.Security.Token.Token <object> tok = (Org.Apache.Hadoop.Security.Token.Token
                                                                   <object>)Whitebox.GetInternalState(fs, "delegationToken");
            NUnit.Framework.Assert.AreNotSame("Not making a copy of the remote token", token,
                                              tok);
            NUnit.Framework.Assert.AreEqual(token.GetKind(), tok.GetKind());
        }
Beispiel #21
0
        public ActionResult Pay(string orderNo, decimal money)
        {
            string password  = SettingManager.GetSettingValue(AppSettings.YsPay.KeyPassword);
            string priKey    = Server.MapPath("/flyfoxglf.pfx");
            string pubKey    = Server.MapPath("/businessgate.cer");
            string returnKey = Server.MapPath("/businessgate.cer");

            string method = "ysepay.online.wap.directpay.createbyuser";

            string server_url = "https://openapi.ysepay.com/gateway.do";


            string partner_id = SettingManager.GetSettingValue(AppSettings.YsPay.PartnerId);
            string timestamp  = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            string charset    = "utf-8";
            string sign_type  = "RSA";
            string notify_url = Request.Url.Scheme + "://" + Request.Url.Host + ":" + Request.Url.Port + "/YsPay/PayNotify";
            string return_url = Request.Url.Scheme + "://" + Request.Url.Host + ":" + Request.Url.Port + "/YsPay/PayReturn";
            string version    = "3.0";

            string out_trade_no       = orderNo;
            string subject            = "物业缴费";
            string total_amount       = money.ToString("F2");
            string seller_id          = SettingManager.GetSettingValue(AppSettings.YsPay.PartnerId);
            string seller_name        = SettingManager.GetSettingValue(AppSettings.YsPay.SellerName);
            string timeout_express    = "6m";
            string pay_mode           = "internetbank";
            string bank_type          = "1031000";
            string bank_account_type  = "personal";
            string support_card_type  = "debit";
            string extend_params      = "";
            string business_code      = "01000010";
            string extra_common_param = "23";

            Dictionary <string, string> dic = new Dictionary <string, string>();

            dic.Add("method", method);
            dic.Add("partner_id", partner_id);
            dic.Add("timestamp", timestamp);
            dic.Add("charset", charset);
            dic.Add("sign_type", sign_type);
            dic.Add("notify_url", notify_url);
            dic.Add("return_url", return_url);
            dic.Add("version", version);

            dic.Add("out_trade_no", out_trade_no);
            dic.Add("subject", subject);
            dic.Add("total_amount", total_amount);
            dic.Add("seller_id", seller_id);
            dic.Add("seller_name", seller_name);
            dic.Add("timeout_express", timeout_express);
            dic.Add("extend_params", extend_params);
            dic.Add("business_code", business_code);
            dic.Add("extra_common_param", extra_common_param);
            dic.Add("remark", "");

            dic = Common.SortDictionary(dic);
            string unsign     = Common.CreateString(dic);
            string privatekey = SecurityUtil.loadKey(priKey, password, true);
            string sign       = SecurityUtil.RSASignString(unsign, privatekey);

            dic.Add("sign", sign);

            string paras = Common.CreateLinkString(dic);

            StringBuilder Html = new StringBuilder();

            Html.Append("<form id='yssubmit' name='yssubmit' action='" + server_url + "' method='post'>");

            foreach (KeyValuePair <string, string> temp in dic)
            {
                Html.Append("<input type='hidden' name='" + temp.Key + "' value='" + temp.Value + "'/>");
            }

            Html.Append("<input type='submit' value='确认' style='display:none;'></form>");
            Html.Append("<script>document.forms['yssubmit'].submit();</script>");

            return(Content(Html.ToString(), "text/html"));
        }
Beispiel #22
0
    protected override void OnUpdate()
    {
        base.OnUpdate();

        if (m_IsConnectedOk)
        {
            m_IsConnectedOk = false;
            if (OnConnectOK != null)
            {
                OnConnectOK();
            }
            AppDebug.Log("连接成功");
        }

        #region 从队列中获取数据
        while (true)
        {
            if (m_ReceiveCount <= 5)
            {
                m_ReceiveCount++;
                lock (m_ReceiveQueue)
                {
                    if (m_ReceiveQueue.Count > 0)
                    {
                        //得到队列中的数据包
                        byte[] buffer = m_ReceiveQueue.Dequeue();

                        //异或之后的数组
                        byte[] bufferNew = new byte[buffer.Length - 3];

                        bool   isCompress = false;
                        ushort crc        = 0;

                        using (MMO_MemoryStream ms = new MMO_MemoryStream(buffer))
                        {
                            isCompress = ms.ReadBool();
                            crc        = ms.ReadUShort();
                            ms.Read(bufferNew, 0, bufferNew.Length);
                        }

                        //先crc
                        int newCrc = Crc16.CalculateCrc16(bufferNew);

                        if (newCrc == crc)
                        {
                            //异或 得到原始数据
                            bufferNew = SecurityUtil.Xor(bufferNew);

                            if (isCompress)
                            {
                                bufferNew = ZlibHelper.DeCompressBytes(bufferNew);
                            }

                            ushort protoCode    = 0;
                            byte[] protoContent = new byte[bufferNew.Length - 2];
                            using (MMO_MemoryStream ms = new MMO_MemoryStream(bufferNew))
                            {
                                //协议编号
                                protoCode = ms.ReadUShort();
                                ms.Read(protoContent, 0, protoContent.Length);

                                SocketDispatcher.Instance.Dispatch(protoCode, protoContent);
                            }
                        }
                        else
                        {
                            break;
                        }
                    }
                    else
                    {
                        break;
                    }
                }
            }
            else
            {
                m_ReceiveCount = 0;
                break;
            }
        }
        #endregion
    }
 protected void Update_Command(object sender, CommandEventArgs e)
 {
     Response.Redirect(
         "../OverWorkPages/UpdateOverWork.aspx?PKID=" +
         SecurityUtil.DECEncrypt(e.CommandArgument.ToString()), false);
 }
Beispiel #24
0
 /// <exception cref="System.IO.IOException"/>
 protected internal virtual void DoSecureLogin()
 {
     SecurityUtil.Login(GetConfig(), YarnConfiguration.NmKeytab, YarnConfiguration.NmPrincipal
                        );
 }
Beispiel #25
0
        public virtual void TestMasterKeyRollOver()
        {
            conf.SetLong(YarnConfiguration.RmAmrmTokenMasterKeyRollingIntervalSecs, rolling_interval_sec
                         );
            conf.SetLong(YarnConfiguration.RmAmExpiryIntervalMs, am_expire_ms);
            TestAMAuthorization.MyContainerManager containerManager = new TestAMAuthorization.MyContainerManager
                                                                          ();
            TestAMAuthorization.MockRMWithAMS rm = new TestAMAuthorization.MockRMWithAMS(conf
                                                                                         , containerManager);
            rm.Start();
            long                      startTime             = Runtime.CurrentTimeMillis();
            Configuration             conf                  = rm.GetConfig();
            YarnRPC                   rpc                   = YarnRPC.Create(conf);
            ApplicationMasterProtocol rmClient              = null;
            AMRMTokenSecretManager    appTokenSecretManager = rm.GetRMContext().GetAMRMTokenSecretManager
                                                                  ();
            MasterKeyData oldKey = appTokenSecretManager.GetMasterKey();

            NUnit.Framework.Assert.IsNotNull(oldKey);
            try
            {
                MockNM nm1 = rm.RegisterNode("localhost:1234", 5120);
                RMApp  app = rm.SubmitApp(1024);
                nm1.NodeHeartbeat(true);
                int waitCount = 0;
                while (containerManager.containerTokens == null && waitCount++ < maxWaitAttempts)
                {
                    Log.Info("Waiting for AM Launch to happen..");
                    Sharpen.Thread.Sleep(1000);
                }
                NUnit.Framework.Assert.IsNotNull(containerManager.containerTokens);
                RMAppAttempt         attempt = app.GetCurrentAppAttempt();
                ApplicationAttemptId applicationAttemptId = attempt.GetAppAttemptId();
                // Create a client to the RM.
                UserGroupInformation currentUser = UserGroupInformation.CreateRemoteUser(applicationAttemptId
                                                                                         .ToString());
                Credentials credentials   = containerManager.GetContainerCredentials();
                IPEndPoint  rmBindAddress = rm.GetApplicationMasterService().GetBindAddress();
                Org.Apache.Hadoop.Security.Token.Token <TokenIdentifier> amRMToken = TestAMAuthorization.MockRMWithAMS
                                                                                     .SetupAndReturnAMRMToken(rmBindAddress, credentials.GetAllTokens());
                currentUser.AddToken(amRMToken);
                rmClient = CreateRMClient(rm, conf, rpc, currentUser);
                RegisterApplicationMasterRequest request = Org.Apache.Hadoop.Yarn.Util.Records.NewRecord
                                                           <RegisterApplicationMasterRequest>();
                rmClient.RegisterApplicationMaster(request);
                // One allocate call.
                AllocateRequest allocateRequest = Org.Apache.Hadoop.Yarn.Util.Records.NewRecord <AllocateRequest
                                                                                                 >();
                NUnit.Framework.Assert.IsTrue(rmClient.Allocate(allocateRequest).GetAMCommand() ==
                                              null);
                // Wait for enough time and make sure the roll_over happens
                // At mean time, the old AMRMToken should continue to work
                while (Runtime.CurrentTimeMillis() - startTime < rolling_interval_sec * 1000)
                {
                    rmClient.Allocate(allocateRequest);
                    Sharpen.Thread.Sleep(500);
                }
                MasterKeyData newKey = appTokenSecretManager.GetMasterKey();
                NUnit.Framework.Assert.IsNotNull(newKey);
                NUnit.Framework.Assert.IsFalse("Master key should have changed!", oldKey.Equals(newKey
                                                                                                ));
                // Another allocate call with old AMRMToken. Should continue to work.
                rpc.StopProxy(rmClient, conf);
                // To avoid using cached client
                rmClient = CreateRMClient(rm, conf, rpc, currentUser);
                NUnit.Framework.Assert.IsTrue(rmClient.Allocate(allocateRequest).GetAMCommand() ==
                                              null);
                waitCount = 0;
                while (waitCount++ <= maxWaitAttempts)
                {
                    if (appTokenSecretManager.GetCurrnetMasterKeyData() != oldKey)
                    {
                        break;
                    }
                    try
                    {
                        rmClient.Allocate(allocateRequest);
                    }
                    catch (Exception)
                    {
                        break;
                    }
                    Sharpen.Thread.Sleep(200);
                }
                // active the nextMasterKey, and replace the currentMasterKey
                NUnit.Framework.Assert.IsTrue(appTokenSecretManager.GetCurrnetMasterKeyData().Equals
                                                  (newKey));
                NUnit.Framework.Assert.IsTrue(appTokenSecretManager.GetMasterKey().Equals(newKey)
                                              );
                NUnit.Framework.Assert.IsTrue(appTokenSecretManager.GetNextMasterKeyData() == null
                                              );
                // Create a new Token
                Org.Apache.Hadoop.Security.Token.Token <AMRMTokenIdentifier> newToken = appTokenSecretManager
                                                                                        .CreateAndGetAMRMToken(applicationAttemptId);
                SecurityUtil.SetTokenService(newToken, rmBindAddress);
                currentUser.AddToken(newToken);
                // Another allocate call. Should continue to work.
                rpc.StopProxy(rmClient, conf);
                // To avoid using cached client
                rmClient        = CreateRMClient(rm, conf, rpc, currentUser);
                allocateRequest = Org.Apache.Hadoop.Yarn.Util.Records.NewRecord <AllocateRequest>(
                    );
                NUnit.Framework.Assert.IsTrue(rmClient.Allocate(allocateRequest).GetAMCommand() ==
                                              null);
                // Should not work by using the old AMRMToken.
                rpc.StopProxy(rmClient, conf);
                // To avoid using cached client
                try
                {
                    currentUser.AddToken(amRMToken);
                    rmClient        = CreateRMClient(rm, conf, rpc, currentUser);
                    allocateRequest = Org.Apache.Hadoop.Yarn.Util.Records.NewRecord <AllocateRequest>(
                        );
                    NUnit.Framework.Assert.IsTrue(rmClient.Allocate(allocateRequest).GetAMCommand() ==
                                                  null);
                    NUnit.Framework.Assert.Fail("The old Token should not work");
                }
                catch (Exception)
                {
                }
            }
            finally
            {
                // expect exception
                rm.Stop();
                if (rmClient != null)
                {
                    rpc.StopProxy(rmClient, conf);
                }
            }
        }
Beispiel #26
0
    /// <summary>
    /// 模拟要点:解客户端数据包,同时向正式代码模拟发送服务端数据包
    /// 41课以后包体结构更复杂,包体=协议编号+协议内容
    /// 43课以后数据包完全体为:包体=压缩标志+CRC校验码+异或算法后的真实数据(协议编号+协议内容)
    /// </summary>
    /// <param name="dataPkg">本地向服务器传什么数据</param>
    /// <param name="isDIYReturnMsg">是否由客户端决定服务器返回什么数据,默认为false,就是由服务端通过逻辑处理后返回一个伪真实的数据,如果为true,就是一个由客户端决定的纯伪造的数据</param>
    /// <param name="returnPkg">希望服务器向本地传什么数据</param>
    public void ServerOperator(byte[] dataPkg, bool isDIYReturnPkg = false)
    {
        if (isDIYReturnPkg == true)  //向客户端返回的是客户端指定的数据包,不必再做下列处理
        {
            return;
        }
        mReceiveStream.Position = mReceiveStream.Length;
        mReceiveStream.Write(dataPkg, 0, dataPkg.Length);        //数据写进内存,等待操作
        mReceiveStream.Position = 0;
        int currentMsgLen  = mReceiveStream.ReadUShort();        //包体长度
        int currentFullLen = 2 + currentMsgLen;                  //包头+包体长度

        if (mReceiveStream.Length >= currentFullLen)             //接收的数据包大于一个完整包的长度,表示至少有一个完整包传过来了
        {
            byte[] buffer = new byte[currentMsgLen];             //此buffer为数据包,包体内容
            mReceiveStream.Position = 2;                         //把包头去掉,剩下包体
            mReceiveStream.Read(buffer, 0, currentMsgLen);       //把数据读到buffer中
            #region 43课以后完整版数据包增加以下内容
            ushort CRC            = 0;                           //CRC校验码
            bool   isCompress     = false;                       //压缩标志
            byte[] realDataBuffer = new byte[buffer.Length - 3]; //刨除CRC和压缩标志,真正数据部分
            using (MemoryStreamUtil stream = new MemoryStreamUtil(buffer))
            {
                isCompress = stream.ReadBool();   //获取压缩标志
                CRC        = stream.ReadUShort(); //获取CRC校验码
                stream.Read(realDataBuffer, 0, realDataBuffer.Length);
            }
            ushort newCRC = Crc16.CalculateCrc16(realDataBuffer); //开始校验CRC
            if (CRC == newCRC)                                    //校验通过
            {
                if (isCompress)
                {
                    realDataBuffer = ZlibHelper.DeCompressBytes(realDataBuffer); //解压
                }
                realDataBuffer = SecurityUtil.XorAlgorithm(realDataBuffer);      //解密,此时realDataBuffer是可以操作的数据
            }
            else
            {
                Debug.Log("server:CRC verify failed!");
                return;
            }

            #endregion
            #region 41课以后服务器增加以下内容
            ushort protoCode    = 0;
            byte[] protoContent = new byte[realDataBuffer.Length - 2];  //可操作数据buffer减去协议编号部分
            #endregion
            using (MemoryStreamUtil stream = new MemoryStreamUtil(realDataBuffer))
            {
                protoCode = stream.ReadUShort();
                stream.Read(protoContent, 0, protoContent.Length);
                SocketDispatcher.Instance.Dispatch(protoCode, protoContent);
                //EventDispatcherS.Instance.Dispatch(protoCode, null, protoContent);
            }
            //41课以后使用网络协议,增加此部分判断逻辑
            //43课以后使用观察者模式
            //此处作为模拟器不使用观察者模式,采用模拟数据的方式简易处理

            /*
             * if (protoCode == Leo_ProtoCodeDefine.RoleOperation_Login)
             * {
             *  Leo_ProtoTest test = Leo_ProtoTest.ToObject(protoContent);
             *  Debug.Log("服务器解析协议成功,协议编号:" + protoCode);
             *  Debug.Log("ID:" + test.ID);
             *  Debug.Log("name:" + test.name);
             *  Leo_ProtoTest testReturn = new Leo_ProtoTest();
             *  testReturn.protoCode = Leo_ProtoCodeDefine.RoleOperation_Login;
             *  testReturn.ID = 2002;
             *  testReturn.name = "return";
             *  testReturn.price = 2.22f;
             *  byte[] returnBuffer = Leo_SocketManager.Instance.MakeDataPkg(testReturn.ToArray()); //模拟服务器向客户端返回一条协议数据
             * }
             * */
            //Leo_SocketDispatcher.Instance.Dispatch(protoCode, protoContent);
        }
        else
        {
            Debug.Log("服务器解析数据包错误!");
        }
        //2020-06-25新增,一次接收结束后把stream里的内容清空,保证下次接收的内容是新的
        mReceiveStream.Position = 0;
        mReceiveStream.SetLength(0);
    }
Beispiel #27
0
 protected void Approve_Command(object sender, CommandEventArgs e)
 {
     Response.Redirect("ApproveTrainApplication.aspx?TrainApplicationID=" + SecurityUtil.DECEncrypt(e.CommandArgument.ToString()));
     //_ShowWindowForConfirmOperation(e.CommandArgument.ToString());
 }
Beispiel #28
0
 protected void grd_RowCommand(object sender, GridViewCommandEventArgs e)
 {
     switch (e.CommandName)
     {
     case "HiddenPostButtonCommand":
         Response.Redirect("DetailTrainApplication.aspx?TrainApplicationID=" + SecurityUtil.DECEncrypt(e.CommandArgument.ToString()));
         return;
     }
 }
Beispiel #29
0
        public override IEnumerable <CommandDTOBase?> Execute(string[] args)
        {
            // lists installed servics that don't have "Microsoft Corporation" as the company name in their file info
            //      or all services if "-full" is passed

            WriteHost(Runtime.FilterResults ? "Non Microsoft Services (via WMI)\n" : "All Services (via WMI)\n");

            var wmiData = new ManagementObjectSearcher(@"root\cimv2", "SELECT * FROM win32_service");
            var data    = wmiData.Get();

            foreach (ManagementObject result in data)
            {
                var    serviceName    = result["Name"] == null ? null : (string)result["Name"];
                string serviceDll     = null;
                string serviceCommand = null;
                string binaryPath     = null;
                var    isDotNet       = false;
                string companyName    = null;
                string binaryPathSDDL = null;
                string serviceSDDL    = null;

                serviceCommand = GetServiceCommand(result);
                serviceDll     = GetServiceDll(serviceName);

                binaryPath = GetServiceBinaryPath(serviceCommand);

                // ServiceDll could be null if access to the Parameters key is denied
                //  - Examples: The lmhosts service on Win10 as an unprivileged user
                if (binaryPath.ToLower().EndsWith("\\svchost.exe") && serviceDll != null)
                {
                    binaryPath = serviceDll;
                }

                if (!string.IsNullOrEmpty(binaryPath) && File.Exists(binaryPath))
                {
                    companyName = GetCompanyName(binaryPath);

                    if (Runtime.FilterResults)
                    {
                        if (string.IsNullOrEmpty(companyName) || (companyName != null && Regex.IsMatch(companyName, @"^Microsoft.*", RegexOptions.IgnoreCase)))
                        {
                            continue;
                        }
                    }

                    isDotNet = FileUtil.IsDotNetAssembly(binaryPath);

                    binaryPathSDDL = File.GetAccessControl(binaryPath).GetSecurityDescriptorSddlForm(System.Security.AccessControl.AccessControlSections.All);
                }

                try
                {
                    var info = SecurityUtil.GetSecurityInfos(serviceName, Interop.Advapi32.SE_OBJECT_TYPE.SE_SERVICE);
                    serviceSDDL = info.SDDL;
                }
                catch
                {
                    // eat it
                }

                yield return(new ServicesDTO()
                {
                    Name = serviceName,
                    DisplayName = (string)result["DisplayName"],
                    Description = (string)result["Description"],
                    User = (string)result["StartName"],
                    State = (string)result["State"],
                    StartMode = (string)result["StartMode"],
                    ServiceCommand = serviceCommand,
                    BinaryPath = binaryPath,
                    BinaryPathSDDL = binaryPathSDDL,
                    ServiceDll = serviceDll,
                    ServiceSDDL = serviceSDDL,
                    CompanyName = companyName,
                    IsDotNet = isDotNet
                });
            }

            // yield return null;
        }
 private void List_Command(object sender, EventArgs e)
 {
     Response.Redirect("EmployeeSalaryHistoryList.aspx?EmployeeID=" + SecurityUtil.DECEncrypt(EmployeeSalaryHistoryDetailView1.EmployeeID), false);
 }