Пример #1
0
        public void op_SubtractionTest()
        {
            LargeInteger int1     = new LargeInteger("-4788888888888888888888888888888888");
            LargeInteger int2     = new LargeInteger("2");
            LargeInteger expected = new LargeInteger("-4788888888888888888888888888888890");
            LargeInteger actual;

            actual = (int1 - int2);
            Assert.AreEqual(expected.ToString(), actual.ToString());
        }
Пример #2
0
        public void op_MultiplyTest()
        {
            LargeInteger int1     = new LargeInteger("-4788888888888888888888888888888888");
            LargeInteger int2     = new LargeInteger("37888888888888888888887777777777777777777776666666666666");
            LargeInteger expected = new LargeInteger("-181445679012345679012340358024691324345679007024691358022486419753086419753087407407407408");
            LargeInteger actual;

            actual = (int1 * int2);
            Assert.AreEqual(expected.ToString(), actual.ToString());
        }
Пример #3
0
        public void op_AdditionSpecialTest()
        {
            LargeInteger int1     = new LargeInteger("-0");
            LargeInteger int2     = new LargeInteger("-000000");
            LargeInteger expected = new LargeInteger("0"); //
            LargeInteger actual;

            actual = (int1 + int2);
            Assert.AreEqual(expected.ToString(), actual.ToString());
        }
Пример #4
0
        internal static IADsLargeInteger Int64ToLargeInteger(long val)
        {
            var largeInt = new LargeInteger
            {
                HighPart = (int)(val >> 32),
                LowPart  = (int)val
            };

            return(largeInt);
        }
        //Commented out by Rupa D - because of use of Single Sign On
        /// <summary>
        /// ESC49330, ESC49331, ESC49321 - Jun Lee
        /// Check if the User's password is expired on the Webapps Active Directory
        /// To expire external user’s password properly,
        /// two critical data are necessary: PasswordExpirationDate and PasswordNeedToBeChanged.
        /// If Today is greater than PasswordExpirationDate or PasswordNeedToBeChanged is true,
        /// current user's password is expired.
        /// </summary>
        /// <param name="parentDE">DirectoryEntry</param>
        /// <param name="UserName">string</param>
        /// <returns>bool</returns>
        public static bool IsUserExpired(DirectoryEntry parentDE, string UserName)
        {
            bool isExpired = false;

            try
            {
                // Search and Get User object from Active Directory
                DirectorySearcher ds = new DirectorySearcher(parentDE);
                ds.ReferralChasing = ReferralChasingOption.All;
                ds.SearchScope     = SearchScope.Subtree;
                ds.Filter          = "(&(objectClass=user)(objectClass=person)(sAMAccountName=" + UserName.Trim() + "))";

                ds.PropertiesToLoad.Add("sAMAccountName");      //1. WEBAPPS Account
                ds.PropertiesToLoad.Add("MemberOf");            //Membership
                ds.PropertiesToLoad.Add("pwdLastSet");          //Password Last Set

                SearchResult myUsers = ds.FindOne();


                if (myUsers.Properties.Contains("pwdLastSet"))
                {
                    // Do work with data returned for address entry
                    DirectoryEntry deUser        = myUsers.GetDirectoryEntry();
                    LargeInteger   acctPwdChange = deUser.Properties["pwdLastSet"].Value as LargeInteger;


                    long dateAcctPwdChange = (((long)(acctPwdChange.HighPart) << 32) + (long)acctPwdChange.LowPart);

                    if (dateAcctPwdChange == 0)
                    {
                        isExpired = true;
                    }
                    else if (dateAcctPwdChange > 0)
                    {
                        // Get max password age in current domain: WebApps
                        int maxPasswordAge = GetMaxPasswordAge().Days;

                        // Convert FileTime to DateTime and get what today's date is.
                        // Add maxPwdAgeDays to dtAcctPwdChange
                        DateTime passwordExpirationDate = DateTime.FromFileTime(dateAcctPwdChange).AddDays(maxPasswordAge);

                        // Test the expiration condtion
                        if (DateTime.Now > passwordExpirationDate)
                        {
                            isExpired = true;
                        }
                    }
                }
            }
            catch (Exception exp)
            {
                GSA.R7BD.Utility.EventLog.AddWebErrors("Utility", "PasswordExpiration.cs", "IsUserExpired", exp.Message);
            }
            return(isExpired);
        }
Пример #6
0
 internal static extern SecStatusCode AcceptSecurityContext(
     [In] SecHandle phCredential,
     [In] SecHandle phContext,
     SecBufferDesc pInput,
     AcceptContextReqFlags fContextReq,
     SecDataRep TargetDataRep,
     [In, Out] SecHandle phNewContext,
     [In, Out] SecBufferDesc pOutput,
     out AcceptContextRetFlags pfContextAttr,
     [Out] LargeInteger ptsExpiry
     );
Пример #7
0
 internal static extern SecStatusCode AcquireCredentialsHandle(
     string pszPrincipal,
     string pszPackage,
     SecPkgCredFlags fCredentialUse,
     OptionalLuid pvLogonId,
     SafeBuffer pAuthData,
     IntPtr pGetKeyFn,
     IntPtr pvGetKeyArgument,
     [Out] SecHandle phCredential,
     [Out] LargeInteger ptsExpiry
     );
 public static extern NtStatus NtAlpcConnectPortEx(
     out SafeKernelObjectHandle PortHandle,
     [In] ObjectAttributes ConnectionPortObjectAttributes,
     [In] ObjectAttributes ClientPortObjectAttributes,
     [In] AlpcPortAttributes PortAttributes,
     AlpcMessageFlags Flags,
     [In] SafeBuffer ServerSecurityRequirements, // SECURITY_DESCRIPTOR
     [In, Out] SafeAlpcPortMessageBuffer ConnectionMessage,
     [In, Out] OptionalLength BufferLength,
     [In, Out] SafeAlpcMessageAttributesBuffer OutMessageAttributes,
     [In, Out] SafeAlpcMessageAttributesBuffer InMessageAttributes,
     [In] LargeInteger Timeout);
Пример #9
0
        public LargeInteger GetBalance(byte[] publicKey)
        {
            LargeInteger ret     = null;
            var          balance = balanceCoder.Get(publicKey);

            if (balance != null)
            {
                ret = new LargeInteger(balance);
            }

            return(ret);
        }
Пример #10
0
 internal Native(BasicLimitInformation managed)
 {
     PerProcessUserTimeLimit = new LargeInteger(managed.PerProcessUserTimeLimit.Ticks);
     PerJobUserTimeLimit     = new LargeInteger(managed.PerJobUserTimeLimit.Ticks);
     LimitFlags            = managed.LimitFlags;
     MinimumWorkingSetSize = managed.MinimumWorkingSetSize;
     MaximumWorkingSetSize = managed.MaximumWorkingSetSize;
     ActiveProcessLimit    = managed.ActiveProcessLimit;
     Affinity        = managed.Affinity;
     PriorityClass   = managed.PriorityClass;
     SchedulingClass = managed.SchedulingClass;
 }
Пример #11
0
        private void Deserialize(byte[] rlp)
        {
            var data = RLP.Decode(rlp);

            Nonce       = ByteManipulator.GetUInt32(data[0] ?? new byte[] { 0 });
            Ammount     = new LargeInteger(data[1] ?? new byte[] { 0 });
            Fee         = new LargeInteger(data[2] ?? new byte[] { 0 });
            Source      = ByteManipulator.BigEndianTruncate(data[3], 33) ?? new byte[33];
            Destination = ByteManipulator.BigEndianTruncate(data[4], 33) ?? new byte[33];
            Signature   = ByteManipulator.BigEndianTruncate(data[5], 64) ?? new byte[64];
            Network     = data[6] ?? new byte[] { 0 };
        }
Пример #12
0
        public static double?GetStandardBalance(HttpProvider httpProvider, byte[] destination)
        {
            LargeInteger smallUnitsBalance = GetSmallUnitsBalance(httpProvider, mainWindow.ActiveWallet.PublicKey);

            double?ret = null;

            if (smallUnitsBalance != null)
            {
                ret = SendTransactionWindow.GetStandardUnits(smallUnitsBalance);
            }

            return(ret);
        }
 public static extern NtStatus NtAlpcConnectPort(
     out SafeKernelObjectHandle PortHandle,
     [In] UnicodeString PortName,
     [In] ObjectAttributes ObjectAttributes,
     [In] AlpcPortAttributes PortAttributes,
     AlpcMessageFlags Flags,
     [In] SafeSidBufferHandle RequiredServerSid,
     [In, Out] SafeAlpcPortMessageBuffer ConnectionMessage,
     [In, Out] OptionalLength BufferLength,
     [In, Out] SafeAlpcMessageAttributesBuffer OutMessageAttributes,
     [In, Out] SafeAlpcMessageAttributesBuffer InMessageAttributes,
     [In] LargeInteger Timeout
     );
        internal static SecStatusCode InitializeSecurityContext(
            CredentialHandle credential,
            SecHandle context,
            string target_name,
            InitializeContextReqFlags req_attributes,
            SecDataRep data_rep,
            IList <SecurityBuffer> input,
            SecHandle new_context,
            IList <SecurityBuffer> output,
            out InitializeContextRetFlags ret_attributes,
            LargeInteger expiry,
            bool throw_on_error)
        {
            using (DisposableList list = new DisposableList())
            {
                var input_buffers  = input?.ToBufferList(list);
                var output_buffers = output?.ToBufferList(list);

                var in_buffer_desc  = input_buffers.ToDesc(list);
                var out_buffer_desc = output_buffers.ToDesc(list);

                var result = SecurityNativeMethods.InitializeSecurityContext(credential.CredHandle,
                                                                             context, target_name, req_attributes, 0, data_rep, in_buffer_desc, 0,
                                                                             new_context, out_buffer_desc, out ret_attributes, expiry).CheckResult(throw_on_error);
                if (!result.IsSuccess())
                {
                    return(result);
                }

                try
                {
                    if (result == SecStatusCode.SEC_I_COMPLETE_NEEDED || result == SecStatusCode.SEC_I_COMPLETE_AND_CONTINUE)
                    {
                        var comp_result = SecurityNativeMethods.CompleteAuthToken(new_context, out_buffer_desc).CheckResult(throw_on_error);
                        if (!comp_result.IsSuccess())
                        {
                            return(comp_result);
                        }
                    }
                }
                finally
                {
                    if (result.IsSuccess())
                    {
                        output?.UpdateBuffers(out_buffer_desc);
                    }
                }

                return(result);
            }
        }
        private bool GenClientContext(AuthenticationToken token)
        {
            using (DisposableList list = new DisposableList())
            {
                SecStatusCode result = 0;

                SecBuffer     out_sec_buffer  = list.AddResource(new SecBuffer(SecBufferType.Token, 64 * 1024));
                SecBufferDesc out_buffer_desc = list.AddResource(new SecBufferDesc(out_sec_buffer));

                InitializeContextRetFlags flags;
                LargeInteger expiry = new LargeInteger();
                if (token != null)
                {
                    List <SecBuffer> buffers = new List <SecBuffer>();
                    buffers.Add(list.AddResource(new SecBuffer(SecBufferType.Token, token.ToArray())));
                    if (_channel_binding != null)
                    {
                        buffers.Add(list.AddResource(SecBuffer.CreateForChannelBinding(_channel_binding)));
                    }
                    SecBufferDesc in_buffer_desc = list.AddResource(new SecBufferDesc(buffers.ToArray()));
                    result = SecurityNativeMethods.InitializeSecurityContext(_creds.CredHandle, _context, _target, _req_attributes, 0,
                                                                             _data_rep, in_buffer_desc, 0, _context, out_buffer_desc, out flags, expiry).CheckResult();
                    Flags = flags;
                }
                else
                {
                    SecBufferDesc    in_buffer_desc = null;
                    List <SecBuffer> buffers        = new List <SecBuffer>();
                    if (_channel_binding != null)
                    {
                        buffers.Add(list.AddResource(SecBuffer.CreateForChannelBinding(_channel_binding)));
                        in_buffer_desc = list.AddResource(new SecBufferDesc(buffers.ToArray()));
                    }

                    result = SecurityNativeMethods.InitializeSecurityContext(_creds.CredHandle, null, _target,
                                                                             _req_attributes, 0, _data_rep, in_buffer_desc, 0, _context,
                                                                             out_buffer_desc, out flags, expiry).CheckResult();
                }

                Expiry = expiry.QuadPart;
                Flags  = flags;
                if (result == SecStatusCode.CompleteNeeded || result == SecStatusCode.CompleteAndContinue)
                {
                    SecurityNativeMethods.CompleteAuthToken(_context, out_buffer_desc).CheckResult();
                }

                Token = AuthenticationToken.Parse(_creds.PackageName, _token_count++, true, out_buffer_desc.ToArray()[0].ToArray());
                return(!(result == SecStatusCode.ContinueNeeded || result == SecStatusCode.CompleteAndContinue));
            }
        }
Пример #16
0
 internal static extern SecStatusCode InitializeSecurityContext(
     [In] SecHandle phCredential,
     [In] SecHandle phContext,
     string pszTargetName,
     InitializeContextReqFlags fContextReq,
     int Reserved1,
     SecDataRep TargetDataRep,
     SecBufferDesc pInput,
     int Reserved2,
     [Out] SecHandle phNewContext,
     [In, Out] SecBufferDesc pOutput,
     out InitializeContextRetFlags pfContextAttr,
     [Out] LargeInteger ptsExpiry
     );
Пример #17
0
        public LargeInteger GetBalance(byte[] publicKey)
        {
            LargeInteger ret = 0;

            if ((publicKey == null) || (publicKey.Length > 33))
            {
                ret = null;
            }
            else
            {
                ret = balanceLedger.GetBalance(publicKey);
            }

            return(ret);
        }
Пример #18
0
        public void DateTimeFromLargeIntegerShouldReturnNullIfIntegerNoSet()
        {
            // Fixture setup
            var integer = new LargeInteger
            {
                HighPart = int.MaxValue,
                LowPart  = -1
            };

            // Exercise system
            var actual = DateTimeFromLargeInteger(integer);

            // Verify outcome
            actual.Should().BeNull();
        }
Пример #19
0
        public void UpdateParameters()
        {
            nonce     = 0;
            timestamp = (uint)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds;

            lock (GateKeeper.TransactionPoolLock)
            {
                lock (GateKeeper.BalanceLedgerLock)
                {
                    transactions = _transactionPool.GetMineableTransactions();

                    if (transactions.Count > 100)
                    {
                        transactions = transactions.Take(100).ToList();
                    }
                }
            }

            lock (GateKeeper.ChainManagerLock)
            {
                var topBlock = _chainManager.GetBlock(_chainManager.Height);

                if (topBlock.Height > lastBlockHeight)
                {
                    numberOfAttempts = 0;
                    lastBlockHeight  = topBlock.Height;
                }

                height            = topBlock.Height + 1;
                previousBlockHash = topBlock.GetHash();

                lastBlockTimeStamp = topBlock.Timestamp;

                if (height == 1)
                {
                    difficulty = Block.LowestDifficulty;
                }
                else if (height % Program.DifficultyRecalibration == 1)
                {
                    var recalibrationBlock = _chainManager.GetBlock(height - Program.DifficultyRecalibration);
                    difficulty = ChainManager.CalculateDifficulty(recalibrationBlock, timestamp);
                }
                else
                {
                    difficulty = topBlock.Difficulty;
                }
            }
        }
Пример #20
0
        public void ToDateTime_Should_ReturnExpectedResult()
        {
            // Arrange
            var expected = new DateTime(2015, 10, 15, 10, 32, 00, DateTimeKind.Utc);
            var date     = new LargeInteger()
            {
                HighPart = 30476084,
                LowPart  = -1185116160
            };

            // Act
            var actual = AdDateTime.ToDateTime(date);

            // Assert
            Assert.Equal(expected.ToString("s"), actual.ToString("s"));
        }
        public static Transaction CreateTransaction(Wallet sender, Wallet recipient, LargeInteger value, uint nonce)
        {
            var ret = new Transaction()
            {
                Ammount     = value,
                Destination = recipient.PublicKey,
                Network     = Program.Network,
                Fee         = 20,
                Nonce       = nonce,
                Source      = sender.PublicKey
            };

            ret.Sign(sender.PrivateKey);

            return(ret);
        }
Пример #22
0
        public void ToDateTime_Should_ReturnMaxDate_When_ProvidedWithLargeIntegerThatIsAllOnes()
        {
            // Arrange
            var expected = DateTime.MaxValue;
            var date     = new LargeInteger()
            {
                HighPart = 2147483647,
                LowPart  = -1
            };

            // Act
            var actual = AdDateTime.ToDateTime(date);

            // Assert
            Assert.Equal(expected.ToString("s"), actual.ToString("s"));
        }
        private protected FirewallNetEvent(IFwNetEvent net_event)
        {
            Type = net_event.Type;
            var header = net_event.Header;

            Flags          = header.flags;
            Timestamp      = new LargeInteger(header.timeStamp.ToInt64()).ToDateTime();
            IPProtocol     = (ProtocolType)header.ipProtocol;
            LocalEndpoint  = FirewallUtils.GetEndpoint(header.ipVersion, header.localAddrV4, header.localAddrV6, header.localPort);
            RemoteEndpoint = FirewallUtils.GetEndpoint(header.ipVersion, header.remoteAddrV4, header.remoteAddrV6, header.remotePort);
            ScopeId        = header.scopeId;
            AppId          = Encoding.Unicode.GetString(header.appId.ToArray()).TrimEnd('\0');
            UserId         = Sid.Parse(header.userId, false).GetResultOrDefault();
            AddressFamily  = header.addressFamily;
            PackageSid     = Sid.Parse(header.packageSid, false).GetResultOrDefault();
        }
Пример #24
0
        public async Task <Block> MineRound()
        {
            var block = new Block()
            {
                Difficulty        = difficulty,
                Height            = height,
                MinerAddress      = minerAddress,
                PreviousBlockHash = previousBlockHash,
                Timestamp         = timestamp,
                Transactions      = transactions
            };

            var difficultyBytes = difficulty.GetBytes();

            for (int i = 0; i < hashesPerRound; i++)
            {
                block.Nonce = nonce.GetBytes();

                numberOfAttempts = numberOfAttempts + 1;

                if (ArrayManipulator.IsGreater(ByteManipulator.BigEndianTruncate(difficultyBytes, 32), block.GetHash(), difficultyBytes.Length)) //new block found
                {
                    lock (GateKeeper.ChainManagerLock)
                    {
                        _chainManager.ProcessBlocks(new List <Block>()
                        {
                            block
                        });
                    }
                    lock (GateKeeper.TransactionPoolLock)
                    {
                        lock (GateKeeper.BalanceLedgerLock)
                        {
                            _transactionPool.Clean();
                        }
                    }

                    BlockTime = block.Timestamp - lastBlockTimeStamp;

                    return(block);
                }

                nonce = nonce + 1;
            }

            return(null);
        }
Пример #25
0
        public static void ForcePasswordSet(this  DirectoryEntry de, bool enabled)
        {
            var newLI = new LargeInteger();

            if (enabled)
            {
                newLI.HighPart = 0;
                newLI.LowPart  = 0;
            }
            else
            {
                newLI.HighPart = -1;
                newLI.LowPart  = -1;
            }

            de.Properties["pwdLastSet"].Value = newLI;
        }
Пример #26
0
        public static LargeInteger GetSmallUnitsBalance(HttpProvider httpProvider, byte[] destination)
        {
            LargeInteger ret        = null;
            var          balanceHex = httpProvider.PeerPost <string, string>(HexConverter.ToPrefixString(destination), @"http://127.0.0.1:8125/transaction/balance").Result;

            if (balanceHex != null)
            {
                var balanceBytes = HexConverter.ToBytes(balanceHex);

                if (balanceBytes != null)
                {
                    ret = new LargeInteger(balanceBytes);
                }
            }

            return(ret);
        }
Пример #27
0
        // gets a long from a LargeInteger (COM object)
        static internal ulong GetLongFromLargeInteger(LargeInteger largeInteger)
        {
            ulong lHigh = 0;
            ulong lLow  = 0;

            unchecked
            {
                lHigh = (uint)largeInteger.HighPart;
                lLow  = (uint)largeInteger.LowPart;
            }

            ulong retVal = (ulong)lHigh;

            retVal = (retVal << 32);
            retVal = retVal + (ulong)lLow;
            return(retVal);
        }
Пример #28
0
        public Block(byte[] rlp)
        {
            if (rlp.Length > Program.BlockSizeLimit)
            {
                throw new Exception("Invalid block");
            }

            var decoded = RLP.Decode(rlp);

            if (decoded.Count == 7 && decoded[1] != null)
            {
                Height     = (int)(decoded[0] != null ? ByteManipulator.GetUInt32(decoded[0]) : 0);
                Timestamp  = ByteManipulator.GetUInt32(decoded[1]);
                Difficulty = new LargeInteger(decoded[2] ?? new byte[32]);
                Nonce      = decoded[3] != null?ByteManipulator.BigEndianTruncate(decoded[3], 32) : new byte[32];

                MinerAddress = decoded[4] != null?ByteManipulator.BigEndianTruncate(decoded[4], 33) : new byte[33];

                PreviousBlockHash = decoded[5] != null?ByteManipulator.BigEndianTruncate(decoded[5], 32) : new byte[32];

                var decodedTransactions = RLP.Decode(decoded[6]);

                Transactions = new List <Transaction>();

                if (decodedTransactions != null)
                {
                    foreach (var rlpTransaction in decodedTransactions)
                    {
                        var tx = new Transaction(rlpTransaction);
                        if (tx.Verify())
                        {
                            Transactions.Add(tx);
                        }
                        else
                        {
                            throw new Exception("Invalid block");
                        }
                    }
                }
            }
            else
            {
                throw new Exception("Invalid block");
            }
        }
Пример #29
0
        public bool SingleVerify()
        {
            var ret = new LargeInteger(GetHash()) < Difficulty;

            if (ret)
            {
                foreach (var transaction in Transactions)
                {
                    if (!transaction.Verify())
                    {
                        ret = false;
                        break;
                    }
                }
            }

            return(ret);
        }
Пример #30
0
        /// <summary>
        /// Query the value of the secret.
        /// </summary>
        /// <param name="throw_on_error">True to throw on error.</param>
        /// <returns>The value of the secret.</returns>
        public NtResult <LsaSecretValue> Query(bool throw_on_error)
        {
            LargeInteger current_value_set_time = new LargeInteger();
            LargeInteger old_value_set_time     = new LargeInteger();
            var          status = SecurityNativeMethods.LsaQuerySecret(Handle, out SafeLsaMemoryBuffer current_value,
                                                                       current_value_set_time, out SafeLsaMemoryBuffer old_value, old_value_set_time);

            if (!status.IsSuccess())
            {
                return(status.CreateResultFromError <LsaSecretValue>(throw_on_error));
            }
            using (current_value)
            {
                using (old_value)
                {
                    return(new LsaSecretValue(current_value, current_value_set_time, old_value, old_value_set_time).CreateResult());
                }
            }
        }
Пример #31
0
 private static extern bool GetFileSizeEx(SafeFileHandle handle, out LargeInteger size);
Пример #32
0
        /// <summary>
        /// Reads a KSYSTEM_TIME value atomically.
        /// </summary>
        /// <param name="time">A pointer to a KSYSTEM_TIME value.</param>
        /// <returns>A 64-bit time value.</returns>
        private unsafe static LargeInteger QueryKSystemTime(KSystemTime* time)
        {
            LargeInteger localTime = new LargeInteger();

            // If we're on 32-bit, we need to use a special 
            // method to read the time atomically. On 64-bit, 
            // we can simply read the time.

            if (OSVersion.Architecture == OSArch.I386)
            {
                localTime.QuadPart = 0;

                while (true)
                {
                    localTime.HighPart = time->High1Time;
                    localTime.LowPart = time->LowPart;

                    // Check if someone started changing the time 
                    // while we were reading the two values.
                    if (localTime.HighPart == time->High2Time)
                        break;

                    System.Threading.Thread.SpinWait(1);
                }
            }
            else
            {
                localTime.QuadPart = time->QuadPart;
            }

            return localTime;
        }
Пример #33
0
        // gets a long from a LargeInteger (COM object)
        internal static ulong GetLongFromLargeInteger(LargeInteger largeInteger)
        {
            ulong lHigh = 0;
            ulong lLow = 0;
            unchecked
            {
                lHigh = (uint)largeInteger.HighPart;
                lLow = (uint)largeInteger.LowPart;
            }

            ulong retVal = (ulong) lHigh;
            retVal = (retVal << 32);
            retVal = retVal + (ulong)lLow;
            return retVal;
        }