Exemple #1
0
        public TargetTestBoard()
        {
            TestBoard = null;
            foreach (var dev in SignTest.Enumerate())
            {
                try
                {
                    TestBoard = new SignTest(dev);
                    break;
                }
                catch { }
            }
            if (TestBoard == null)
            {
                throw new Exception("Unable to attach to a Sign Test board.");
            }


            SignComponent[] c = new SignComponent[1];
            c[0] = new SignComponent()
            {
                X = 0, Y = 0, Width = 32, Height = 32
            };
            CurrentConfig = new SignConfiguration(c);

            // Initialize test board.

            TestBoard.SetMode(SignTest.DeviceMode.On);
            TestBoard.SetMode(SignTest.DeviceMode.FpgaActive);
        }
Exemple #2
0
        public async Task SignAsync_WhenChainBuildingFails_ThrowsAsync()
        {
            var package = new SimpleTestPackageContext();

            using (var packageStream = await package.CreateAsStreamAsync())
                using (var test = SignTest.Create(
                           _fixture.GetExpiredCertificate(),
                           HashAlgorithmName.SHA256,
                           packageStream.ToArray(),
                           new X509SignatureProvider(timestampProvider: null)))
                {
                    var exception = await Assert.ThrowsAsync <SignatureException>(
                        () => SigningUtility.SignAsync(test.Options, test.Request, CancellationToken.None));

                    Assert.Equal(NuGetLogCode.NU3018, exception.Code);
                    Assert.Equal("Certificate chain validation failed.", exception.Message);

                    Assert.Equal(1, test.Logger.Errors);
                    Assert.Equal(1, test.Logger.Warnings);
                    Assert.Contains(test.Logger.LogMessages, message =>
                                    message.Code == NuGetLogCode.NU3018 &&
                                    message.Level == LogLevel.Error &&
                                    message.Message == "A required certificate is not within its validity period when verifying against the current system clock or the timestamp in the signed file.");
                    Assert.Contains(test.Logger.LogMessages, message =>
                                    message.Code == NuGetLogCode.NU3018 &&
                                    message.Level == LogLevel.Warning &&
                                    message.Message == "A certificate chain processed, but terminated in a root certificate which is not trusted by the trust provider.");
                }
        }
Exemple #3
0
 public async Task SignAsync_WhenCancellationTokenIsCancelled_ThrowsAsync()
 {
     using (var test = SignTest.Create(new X509Certificate2(), HashAlgorithmName.SHA256))
     {
         await Assert.ThrowsAsync <OperationCanceledException>(
             () => SigningUtility.SignAsync(test.Options, test.Request, new CancellationToken(canceled: true)));
     }
 }
Exemple #4
0
        protected override void EndProcessing()
        {
            var hypo = TestingHelper.GetOneSampleHypothesis(Alternate);

            var test = new SignTest(_data.ToArray(), HypothesizedMedian, hypo)
            {
                Size = Size
            };

            WriteObject(test);
        }
 public async Task SignAsync_WhenCancellationTokenIsCancelled_Throws()
 {
     using (var test = SignTest.Create(new X509Certificate2(), HashAlgorithmName.SHA256))
     {
         await Assert.ThrowsAsync <OperationCanceledException>(
             () => test.Signer.SignAsync(
                 test.Request,
                 Mock.Of <ILogger>(),
                 new CancellationToken(canceled: true)));
     }
 }
        public async Task SignAsync_WhenLoggerIsNull_Throws()
        {
            using (var test = SignTest.Create(new X509Certificate2(), HashAlgorithmName.SHA256))
            {
                var exception = await Assert.ThrowsAsync <ArgumentNullException>(
                    () => test.Signer.SignAsync(
                        test.Request,
                        logger: null,
                        token: CancellationToken.None));

                Assert.Equal("logger", exception.ParamName);
            }
        }
Exemple #7
0
        public async Task SignAsync_WhenPackageIsZip64_ThrowsAsync()
        {
            using (var test = SignTest.Create(
                       _fixture.GetDefaultCertificate(),
                       HashAlgorithmName.SHA256,
                       SigningTestUtility.GetResourceBytes("CentralDirectoryHeaderWithZip64ExtraField.zip")))
            {
                var exception = await Assert.ThrowsAsync <SignatureException>(
                    () => SigningUtility.SignAsync(test.Options, test.Request, CancellationToken.None));

                Assert.Equal(NuGetLogCode.NU3006, exception.Code);
                Assert.Equal("Signed Zip64 packages are not supported.", exception.Message);
            }
        }
Exemple #8
0
        public async Task SignAsync_WhenCertificatePublicKeyLengthIsUnsupported_ThrowsAsync()
        {
            using (var certificate = SigningTestUtility.GenerateCertificate(
                       "test",
                       generator => { },
                       publicKeyLength: 1024))
                using (var test = SignTest.Create(certificate, HashAlgorithmName.SHA256))
                {
                    var exception = await Assert.ThrowsAsync <SignatureException>(
                        () => SigningUtility.SignAsync(test.Options, test.Request, CancellationToken.None));

                    Assert.Equal(NuGetLogCode.NU3014, exception.Code);
                    Assert.Contains("The signing certificate does not meet a minimum public key length requirement.", exception.Message);
                }
        }
        public async Task SignAsync_WhenCertificateSignatureAlgorithmIsUnsupported_ThrowsAsync()
        {
            using (var certificate = SigningTestUtility.GenerateCertificate(
                       "test",
                       generator => { },
                       "SHA256WITHRSAANDMGF1"))
                using (var test = SignTest.Create(certificate, HashAlgorithmName.SHA256))
                {
                    var exception = await Assert.ThrowsAsync <SignatureException>(
                        () => SigningUtility.SignAsync(test.Options, test.Request, CancellationToken.None));

                    Assert.Equal(NuGetLogCode.NU3013, exception.Code);
                    Assert.Contains("The signing certificate has an unsupported signature algorithm.", exception.Message);
                }
        }
Exemple #10
0
        public void SignTestConstructorTest()
        {
            // Example from http://probabilityandstats.wordpress.com/2010/02/28/the-sign-test-more-examples/

            double[] sample =
            {
                1,   1,  2,  2,  3,  3,  4,  5,  5,  6, 7, 7, 8, 10,
                20, 22, 25, 27, 33, 40, 42, 50, 55, 75, 80
            };

            SignTest target = new SignTest(sample, hypothesizedMedian: 30);

            Assert.AreEqual(OneSampleHypothesis.ValueIsDifferentFromHypothesis, target.Hypothesis);
            Assert.AreEqual(0.043285, target.PValue, 1e-4);
            Assert.IsTrue(target.Significant);
        }
Exemple #11
0
        public void SignTestConstructorTest()
        {
            // Example from http://www.unm.edu/~marcusj/1Samplesign.pdf

            double[] sample =
            {
                1,   1,  2,  2,  3,  3,  4,  5,  5,  6, 7, 7, 8, 10,
                20, 22, 25, 27, 33, 40, 42, 50, 55, 75, 80
            };

            SignTest target = new SignTest(sample, hypothesizedMedian: 30);

            // Wolfram Alpha gives 0.02896
            // GNU R gives 0.04329

            Assert.AreEqual(OneSampleHypothesis.ValueIsDifferentFromHypothesis, target.Hypothesis);
            Assert.AreEqual(0.043285, target.PValue, 1e-4);
            Assert.IsTrue(target.Significant);
        }
        public async Task SignAsync_WhenChainBuildingFails_Throws()
        {
            using (var packageStream = new SimpleTestPackageContext().CreateAsStream())
                using (var test = SignTest.Create(
                           _fixture.GetDefaultCertificate(),
                           HashAlgorithmName.SHA256,
                           packageStream.ToArray(),
                           new X509SignatureProvider(timestampProvider: null)))
                {
                    var exception = await Assert.ThrowsAsync <SignatureException>(
                        () => test.Signer.SignAsync(
                            test.Request,
                            Mock.Of <ILogger>(),
                            CancellationToken.None));

                    Assert.Equal(NuGetLogCode.NU3018, exception.AsLogMessage().Code);
                    Assert.Equal("Certificate chain validation failed with error: UntrustedRoot", exception.Message);
                }
        }
        public async Task SignAsync_WithUntrustedSelfSignedCertificate_SucceedsAsync()
        {
            using (var packageStream = new SimpleTestPackageContext().CreateAsStream())
                using (var test = SignTest.Create(
                           _fixture.GetDefaultCertificate(),
                           HashAlgorithmName.SHA256,
                           packageStream.ToArray(),
                           new X509SignatureProvider(timestampProvider: null)))
                {
                    await SigningUtility.SignAsync(test.Options, test.Request, CancellationToken.None);

                    Assert.True(await SignedArchiveTestUtility.IsSignedAsync(test.Options.OutputPackageStream));

                    Assert.Equal(0, test.Logger.Errors);
                    Assert.Equal(1, test.Logger.Warnings);
                    Assert.Equal(1, test.Logger.Messages.Count());
                    Assert.True(test.Logger.Messages.Contains("A certificate chain processed, but terminated in a root certificate which is not trusted by the trust provider."));
                }
        }
Exemple #14
0
        public async Task SignAsync_WhenPackageEntryCountWouldRequireZip64_FailsAsync()
        {
            const ushort desiredFileCount = 0xFFFF - 1;

            var package = new SimpleTestPackageContext();

            var requiredFileCount = desiredFileCount - package.Files.Count;

            for (var i = 0; i < requiredFileCount - 1 /*nuspec*/; ++i)
            {
                package.AddFile(i.ToString());
            }

            using (var packageStream = await package.CreateAsStreamAsync())
            {
                using (var zipArchive = new ZipArchive(packageStream, ZipArchiveMode.Read, leaveOpen: true))
                {
                    // Sanity check before testing.
                    Assert.Equal(desiredFileCount, zipArchive.Entries.Count());
                }

                packageStream.Position = 0;

                using (var test = SignTest.Create(
                           _fixture.GetDefaultCertificate(),
                           HashAlgorithmName.SHA256,
                           packageStream.ToArray(),
                           new X509SignatureProvider(timestampProvider: null)))
                {
                    var exception = await Assert.ThrowsAsync <SignatureException>(
                        () => SigningUtility.SignAsync(test.Options, test.Request, CancellationToken.None));

                    Assert.Equal(NuGetLogCode.NU3039, exception.Code);
                    Assert.Equal("The package cannot be signed as it would require the Zip64 format.", exception.Message);

                    Assert.Equal(0, test.Options.OutputPackageStream.Length);
                    Assert.Equal(0, test.Logger.Errors);
                    Assert.Equal(1, test.Logger.Warnings);
                    Assert.Equal(1, test.Logger.Messages.Count());
                    Assert.True(test.Logger.Messages.Contains("A certificate chain processed, but terminated in a root certificate which is not trusted by the trust provider."));
                }
            }
        }
        public async Task SignAsync_WithUntrustedSelfSignedCertificate_SucceedsAsync()
        {
            var package = new SimpleTestPackageContext();

            using (var packageStream = await package.CreateAsStreamAsync())
                using (var test = SignTest.Create(
                           _fixture.GetDefaultCertificate(),
                           HashAlgorithmName.SHA256,
                           packageStream.ToArray(),
                           new X509SignatureProvider(timestampProvider: null)))
                {
                    await SigningUtility.SignAsync(test.Options, test.Request, CancellationToken.None);

                    Assert.True(await SignedArchiveTestUtility.IsSignedAsync(test.Options.OutputPackageStream));

                    Assert.Equal(0, test.Logger.Errors);
                    Assert.Equal(1, test.Logger.Warnings);
                    Assert.Equal(1, test.Logger.Messages.Count());
                    SigningTestUtility.AssertUntrustedRoot(test.Logger.LogMessages, LogLevel.Warning);
                }
        }
        public async Task SignAsync_WhenChainBuildingFails_ThrowsAsync()
        {
            var package = new SimpleTestPackageContext();

            using (var packageStream = await package.CreateAsStreamAsync())
                using (var test = SignTest.Create(
                           _fixture.GetExpiredCertificate(),
                           HashAlgorithmName.SHA256,
                           packageStream.ToArray(),
                           new X509SignatureProvider(timestampProvider: null)))
                {
                    var exception = await Assert.ThrowsAsync <SignatureException>(
                        () => SigningUtility.SignAsync(test.Options, test.Request, CancellationToken.None));

                    Assert.Equal(NuGetLogCode.NU3018, exception.Code);
                    Assert.Equal("Certificate chain validation failed.", exception.Message);

                    Assert.Equal(1, test.Logger.Errors);
                    Assert.Equal(1, test.Logger.Warnings);
                    SigningTestUtility.AssertNotTimeValid(test.Logger.LogMessages, LogLevel.Error);
                    SigningTestUtility.AssertUntrustedRoot(test.Logger.LogMessages, LogLevel.Warning);
                }
        }
Exemple #17
0
        public void SignTestConstructorTest2()
        {
            // This example has been adapted from the Wikipedia's page about
            // the Z-Test, available from: http://en.wikipedia.org/wiki/Z-test

            // We would like to check whether a sample of 20
            // students with a median score of 96 points ...

            double[] sample =
            {
                106, 115, 96, 88, 91,  88, 81, 104, 99, 68,
                104, 100, 77, 98, 96, 104, 82,  94, 72, 96
            };

            // ... could have happened just by chance inside a
            // population with an hypothesized median of 100 points.

            double hypothesizedMedian = 100;

            // So we start by creating the test:
            SignTest test = new SignTest(sample, hypothesizedMedian,
                                         OneSampleHypothesis.ValueIsSmallerThanHypothesis);

            // Now, we can check whether this result would be
            // unlikely under a standard significance level:

            bool significant = test.Significant; // false (so the event was likely)

            // We can also check the test statistic and its P-Value
            double statistic = test.Statistic; // 5
            double pvalue    = test.PValue;    // 0.99039

            Assert.AreEqual(96, sample.Median());
            Assert.AreEqual(statistic, 5);
            Assert.AreEqual(pvalue, 0.99039459228515625);
        }
Exemple #18
0
        public void Run()
        {
            Dev = new SignTest(SignTest.Enumerate().First());
            Reset();
            while (true)
            {
                if (System.Diagnostics.Debugger.IsAttached)
                {
                    // Run without exception handling in the debugger.
                    Loop();
                }
                else
                {
                    try
                    {
                        Loop();
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine();
                        Console.WriteLine("Exception!");
                        Console.WriteLine(ex.ToString());

                        try
                        {
                            Dev.SetLed(false, true);
                        }
                        catch
                        {
                        }

                        Thread.Sleep(2000);
                        Console.WriteLine("Restarting...");
                        Reset();
                    }
                }

                // Check for some control characters
                if (Console.KeyAvailable)
                {
                    ConsoleKeyInfo k = Console.ReadKey(true);

                    switch (char.ToLower(k.KeyChar))
                    {
                    case '?':
                    case 'h':
                        WriteText("Special keys: 'x' Exit, 'r' Reprogram test board, <space> reprogram current board.");
                        break;

                    case 'x':
                        // Clean up and exit
                        WriteText("'x' pressed, exiting.");
                        Reset();
                        return;

                    case 'r':
                        WriteText("'r' pressed, putting test board into reprogramming mode.");
                        Reset();
                        Dev.Reprogram();
                        return;

                    case ' ':
                        WriteText("<Space> pressed, resetting test system state.");
                        Reset();
                        break;

                    case 'f':
                        WriteText("'f' pressed, restarting FPGA");
                        try
                        {
                            Dev.SetMode(SignTest.DeviceMode.FpgaActive);     // Restarts FPGA.
                        }
                        catch (Exception ex)
                        {
                            WriteText(ex.ToString());
                        }
                        break;

                    case 'c':
                        WriteText("Going into a cycle of power on/off");
                        int    count      = 0;
                        string statusText = "";
                        while (true)
                        {
                            if (count == 0)
                            {
                                statusText = "Power On";
                                Dev.SetLed(true, false);
                                Dev.SetMode(SignTest.DeviceMode.On);
                                try
                                {
                                    Dev.SetMode(SignTest.DeviceMode.FpgaActive);
                                }
                                catch { }
                            }
                            if (count == 40)
                            {
                                statusText = "Power Off";
                                Dev.SetLed(false, false);
                                Dev.SetMode(SignTest.DeviceMode.Off);
                            }
                            count++;
                            if (count == 80)
                            {
                                count = 0;
                            }
                            UpdateStatus(statusText);
                            Thread.Sleep(100);
                        }
                    }
                }


                Thread.Sleep(100);
            }
        }
Exemple #19
0
        /// <summary>
        /// 签章相关API
        /// </summary>
        /// <param name="client"></param>
        static void checkSign(SignClient client)
        {
            SignTest test = new SignTest(client);

            test.runAllTest();
        }