Exemplo n.º 1
0
        public void HAGetConfigTwoResultsTest3()
        {
            // Test getting extender configuration with 2 successful sub-service responses

            IKsiService haService = GetHAService(
                new List <PduPayload>()
            {
                GetExtenderConfigResponsePayload(null, null, null, null),
            },
                new List <PduPayload>()
            {
                GetExtenderConfigResponsePayload(4, new List <string>()
                {
                    "uri-2"
                }, 1136073600, 2136073600)
            });

            ExtenderConfig config = haService.GetExtenderConfig();

            Assert.AreEqual(4, config.MaxRequests, "Unexpected max requests value");
            Assert.AreEqual(1, config.ParentsUris.Count, "Unexpected parent uri count");
            Assert.AreEqual("uri-2", config.ParentsUris[0], "Unexpected parent uri value at position 0");
            Assert.AreEqual(1136073600, config.CalendarFirstTime, "Unexpected calendar first time value");
            Assert.AreEqual(2136073600, config.CalendarLastTime, "Unexpected calendar last time value");
        }
        public void HAGetConfigResultsOutOfLimitTest()
        {
            // Test getting aggregator configuration with 2 successful sub-service responses
            // Some values are out of bounds

            IKsiService haService = GetHAService(
                new List <PduPayload>()
            {
                GetAggregatorConfigResponsePayload(1, 2, 99, 4, new List <string>()
                {
                    "uri-1"
                })
            },
                new List <PduPayload>()
            {
                GetAggregatorConfigResponsePayload(21, null, 20001, 16001, null)
            });

            AggregatorConfig config = haService.GetAggregatorConfig();

            Assert.AreEqual(1, config.MaxLevel, "Unexpected max level value");
            Assert.AreEqual(2, config.AggregationAlgorithm, "Unexpected algorithm value");
            Assert.IsNull(config.AggregationPeriod, "Unexpected aggregation period value");
            Assert.AreEqual(4, config.MaxRequests, "Unexpected max requests value");
            Assert.AreEqual(1, config.ParentsUris.Count, "Unexpected parent uri count");
            Assert.AreEqual("uri-1", config.ParentsUris[0], "Unexpected parent uri value at position 0");
        }
Exemplo n.º 3
0
        public void HAGetConfigResultsOutOfLimitTest()
        {
            // Test getting extender configuration with 2 successful sub-service responses
            // Some values are out of bounds

            IKsiService haService = GetHAService(
                new List <PduPayload>()
            {
                GetExtenderConfigResponsePayload(4, new List <string>()
                {
                    "uri-1"
                }, 1136073601, 1136073600)
            },
                new List <PduPayload>()
            {
                GetExtenderConfigResponsePayload(16001, null, 1136073599, 1136073598)
            });

            ExtenderConfig config = haService.GetExtenderConfig();

            Assert.AreEqual(4, config.MaxRequests, "Unexpected max requests value");
            Assert.AreEqual(1, config.ParentsUris.Count, "Unexpected parent uri count");
            Assert.AreEqual("uri-1", config.ParentsUris[0], "Unexpected parent uri value at position 0");
            Assert.AreEqual(1136073601, config.CalendarFirstTime, "Unexpected calendar first time value");
            Assert.IsNull(config.CalendarLastTime, "Unexpected calendar last time value");
        }
        public void HAGetConfigTwoResultsTest4()
        {
            // Test getting aggregator configuration with 2 successful sub-service responses

            IKsiService haService = GetHAService(
                new List <PduPayload>()
            {
                GetAggregatorConfigResponsePayload(1, 2, 100, 4, new List <string>()
                {
                    "uri-1"
                }),
            },
                new List <PduPayload>()
            {
                GetAggregatorConfigResponsePayload(null, null, null, null, null)
            });

            AggregatorConfig config = haService.GetAggregatorConfig();

            Assert.AreEqual(1, config.MaxLevel, "Unexpected max level value");
            Assert.AreEqual(2, config.AggregationAlgorithm, "Unexpected algorithm value");
            Assert.AreEqual(100, config.AggregationPeriod, "Unexpected aggregation period value");
            Assert.AreEqual(4, config.MaxRequests, "Unexpected max requests value");
            Assert.AreEqual(1, config.ParentsUris.Count, "Unexpected parent uri count");
            Assert.AreEqual("uri-1", config.ParentsUris[0], "Unexpected parent uri value at position 0");
        }
 /// <summary>
 /// End sub-service signing request.
 /// </summary>
 /// <param name="service">sub-service</param>
 /// <param name="asyncResult">async result</param>
 protected override object SubServiceEndRequest(IKsiService service, IAsyncResult asyncResult)
 {
     if (_returnResponsePayload)
     {
         return(service.GetSignResponsePayload(asyncResult));
     }
     return(service.EndSign(asyncResult));
 }
Exemplo n.º 6
0
        /// <summary>
        ///     Create new KSI instance.
        /// </summary>
        /// <param name="ksiService">KSI service</param>
        /// <param name="ksiSignatureFactoryForExtending">Signature factory to be used for creating an extended signature</param>
        public Ksi(IKsiService ksiService, IKsiSignatureFactory ksiSignatureFactoryForExtending = null)
        {
            if (ksiService == null)
            {
                throw new ArgumentNullException(nameof(ksiService));
            }

            _ksiService = ksiService;
            _ksiSignatureFactoryForExtending = ksiSignatureFactoryForExtending ?? new KsiSignatureFactory();
        }
Exemplo n.º 7
0
        public void EndSignArgumentNullTest()
        {
            IKsiService service = GetStaticKsiService(new byte[] { 0 });

            ArgumentNullException ex = Assert.Throws <ArgumentNullException>(delegate
            {
                service.EndSign(null);
            });

            Assert.AreEqual("asyncResult", ex.ParamName);
        }
Exemplo n.º 8
0
        public void EndSignInvalidAsyncResultTest()
        {
            IKsiService service = GetStaticKsiService(new byte[] { 0 });

            KsiServiceException ex = Assert.Throws <KsiServiceException>(delegate
            {
                service.EndSign(new TestAsyncResult());
            });

            Assert.That(ex.Message.StartsWith("Invalid asyncResult type:"), "Unexpected exception message: " + ex.Message);
        }
Exemplo n.º 9
0
        private void RunSubService(HAAsyncResult haAsyncResult, int serviceIndex)
        {
            IKsiService service = GetService(serviceIndex);

            try
            {
                IAsyncResult asyncResult = SubServiceBeginRequest(service);
                if (!asyncResult.AsyncWaitHandle.WaitOne(_requestTimeout))
                {
                    throw new HAKsiServiceException("Sub-service request timed out.");
                }

                if (_endCallWaitHandle != null)
                {
                    // We need to wait HA service end call (eg. EndSign)
                    // Mark HA async request as complete
                    haAsyncResult.SetComplete();

                    // Wait for HA service end call.
                    if (!_endCallWaitHandle.WaitOne(_requestTimeout))
                    {
                        throw new HAKsiServiceException("Wait end call timed out.");
                    }
                }

                object subServiceEndRequest = SubServiceEndRequest(service, asyncResult);

                lock (_resultTlvLock)
                {
                    _resultTlvs.Add(subServiceEndRequest);
                }

                _subServiceFirstResultsWaitHandle?.Set();

                if (haAsyncResult.IsCompleted)
                {
                    return;
                }

                if (!_returnAllResponses)
                {
                    haAsyncResult.SetComplete();
                    return;
                }
            }
            catch (Exception ex)
            {
                HandleException(ex, service);
            }

            CheckComplete(haAsyncResult);
        }
Exemplo n.º 10
0
        public void EndSignWithoutSigningServiceProtocol()
        {
            IKsiService serviceBegin = GetStaticKsiService(File.ReadAllBytes(Path.Combine(TestSetup.LocalPath, Resources.KsiService_AggregationResponsePdu_RequestId_1584727637)),
                                                           1584727637);
            IAsyncResult asyncResult = serviceBegin.BeginSign(new DataHash(Base16.Decode("0111A700B0C8066C47ECBA05ED37BC14DCADB238552D86C659342D1D7E87B8772D")), null, null);
            KsiService   serviceEnd  = new KsiService(null, null, null, null, null, null);

            KsiServiceException ex = Assert.Throws <KsiServiceException>(delegate
            {
                serviceEnd.EndSign(asyncResult);
            });

            Assert.That(ex.Message.StartsWith("Signing service protocol is missing from service"), "Unexpected exception message: " + ex.Message);
        }
Exemplo n.º 11
0
        /// <summary>
        /// Create high availability KSI service
        /// </summary>
        /// <param name="signingServices">List of signing services. Max 3 allowed.</param>
        /// <param name="extendingServices">List of extending services. Max 3 allowed.</param>
        /// <param name="publicationsFileService">Publications file service</param>
        /// <param name="requestTimeout">request timeout in milliseconds</param>
        public HAKsiService(IList <IKsiService> signingServices,
                            IList <IKsiService> extendingServices,
                            IKsiService publicationsFileService,
                            uint?requestTimeout = null)
        {
            if (signingServices != null)
            {
                if (signingServices.Count > 3)
                {
                    throw new HAKsiServiceException("Cannot use more than 3 signing services.");
                }

                SigningServices = new ReadOnlyCollection <IKsiService>(signingServices);

                foreach (IKsiService service in SigningServices)
                {
                    service.AggregatorConfigChanged += SigningService_AggregatorConfigChanged;
                }
            }
            else
            {
                SigningServices = new ReadOnlyCollection <IKsiService>(new List <IKsiService>());
            }

            if (extendingServices != null)
            {
                if (extendingServices.Count > 3)
                {
                    throw new HAKsiServiceException("Cannot use more than 3 extending services.");
                }

                ExtendingServices = new ReadOnlyCollection <IKsiService>(extendingServices);

                foreach (IKsiService service in ExtendingServices)
                {
                    service.ExtenderConfigChanged += ExtendingService_ExtenderConfigChanged;
                }
            }
            else
            {
                ExtendingServices = new ReadOnlyCollection <IKsiService>(new List <IKsiService>());
            }

            PublicationsFileService = publicationsFileService;

            if (requestTimeout.HasValue)
            {
                _requestTimeout = requestTimeout.Value;
            }
        }
Exemplo n.º 12
0
 /// <summary>
 ///  Create new block signer instance
 /// </summary>
 /// <param name="ksiService">KSI service</param>
 /// <param name="useBlindingMasks">If true then blinding masks are used when aggregating</param>
 /// <param name="randomSeed">Random seed for for blinding masks</param>
 /// <param name="hashAlgorithm">Hash algorithm to be used when creating aggregation hash chains. If null then defult is used.</param>
 /// <param name="signatureFactory">KSI signature factory for creating uni-signatures.</param>
 /// <param name="maxTreeHeight">Max allowed aggregation tree height</param>
 public BlockSigner(IKsiService ksiService, bool useBlindingMasks, byte[] randomSeed, HashAlgorithm hashAlgorithm = null, IKsiSignatureFactory signatureFactory = null,
                    uint?maxTreeHeight = null)
     : this(ksiService, hashAlgorithm, signatureFactory, maxTreeHeight)
 {
     if (useBlindingMasks)
     {
         if (randomSeed == null)
         {
             throw new BlockSigningException("Random seed cannot be null when using blinding masks.");
         }
         _previousHash     = new byte[_hashAlgorithm.Length + 1];
         _useBlindingMasks = true;
         _randomSeed       = randomSeed;
     }
 }
Exemplo n.º 13
0
        private void HandleException(Exception ex, IKsiService service)
        {
            string message = "Using sub-service failed.";

            if (service != null)
            {
                message += " " + SubServiceToString(service);
            }

            if (ex != null)
            {
                message += Environment.NewLine + ex;
            }

            Logger.Warn(message, ex);
            SubServiceErrors.Add(new HAKsiSubServiceException(service, message, ex));
        }
Exemplo n.º 14
0
        public void HAGetConfigSingleResultAllNullsTest()
        {
            // Test getting extender configuration with 1 successful sub-service response
            // All the values are empty

            IKsiService haService = GetHAService(
                new List <PduPayload>()
            {
                GetExtenderConfigResponsePayload(null, null, null, null),
            });

            ExtenderConfig config = haService.GetExtenderConfig();

            Assert.IsNull(config.MaxRequests, "Unexpected max requests value");
            Assert.AreEqual(0, config.ParentsUris.Count, "Unexpected parent uri list");
            Assert.IsNull(config.CalendarFirstTime, "Unexpected calendar first time value");
            Assert.IsNull(config.CalendarLastTime, "Unexpected calendar last time value");
        }
        public void HAGetConfigSingleResultAllNullsTest()
        {
            // Test getting aggregator configuration with 1 successful sub-service response
            // All the values are empty

            IKsiService haService = GetHAService(
                new List <PduPayload>()
            {
                GetAggregatorConfigResponsePayload(null, null, null, null, null),
            });

            AggregatorConfig config = haService.GetAggregatorConfig();

            Assert.IsNull(config.MaxLevel, "Unexpected max level value");
            Assert.IsNull(config.AggregationAlgorithm, "Unexpected algorithm value");
            Assert.IsNull(config.AggregationPeriod, "Unexpected aggregation period value");
            Assert.IsNull(config.MaxRequests, "Unexpected max requests value");
            Assert.AreEqual(0, config.ParentsUris.Count, "Unexpected parent uri list");
        }
Exemplo n.º 16
0
        static KsiSamples()
        {
            // The end point URL of the Aggregation service, needed for signing, e.g. http://host.net:8080/gt-signingservice.
            string signingServiceUrl = Settings.Default.HttpSigningServiceUrl;

            // The end point URL of the Extender service, needed for extending signature, e.g. *http://host.net:8081/gt-extendingservice
            string extendingServiceUrl = Settings.Default.HttpExtendingServiceUrl;

            // The publications file URL, needed for signature verification, e.g. http://verify.guardtime.com/ksi-publications.bin
            string publicationsFileUrl = Settings.Default.HttpPublicationsFileUrl;

            // The credentials to access the KSI signing service
            ServiceCredentials signingServiceCredentials =
                new ServiceCredentials(Settings.Default.HttpSigningServiceUser, Settings.Default.HttpSigningServicePass);

            // The credentials to access the KSI extending service
            ServiceCredentials extendingServiceCredentials =
                new ServiceCredentials(Settings.Default.HttpExtendingServiceUser, Settings.Default.HttpExtendingServicePass);

            HttpKsiServiceProtocol ksiServiceProtocol = new HttpKsiServiceProtocol(signingServiceUrl,
                                                                                   extendingServiceUrl, publicationsFileUrl);

            // Certificate selector, used to filter which certificates are trusted when verifying the RSA signature.
            // We only trust certificates, that have issued to the particular e-mail address
            CertificateSubjectRdnSelector = new CertificateSubjectRdnSelector("[email protected]");

            // This is the KSI context which holds the references to the Aggregation service, Extender
            // service and other configuration data to perform the various operations.
            KsiService =
                new KsiService(
                    ksiServiceProtocol,
                    signingServiceCredentials,
                    ksiServiceProtocol,
                    extendingServiceCredentials,
                    ksiServiceProtocol,
                    new PublicationsFileFactory(new PkiTrustStoreProvider(new X509Store(StoreName.Root), CertificateSubjectRdnSelector)));

            Ksi = new KSI.Ksi(GetKsiService());

            // Set crypto provider to be used. Currently MicrosoftCryptoProvider and BouncyCastleCryptoProvider are available.
            KsiProvider.SetCryptoProvider(new MicrosoftCryptoProvider());
        }
Exemplo n.º 17
0
        /// <summary>
        /// Create new block signer instance
        /// </summary>
        /// <param name="ksiService">KSI service</param>
        /// <param name="hashAlgorithm">Hash algorithm to be used when creating aggregation hash chains. If null then defult is used.</param>
        /// <param name="signatureFactory">Signature factory for creating uni-signatures.</param>
        /// <param name="maxTreeHeight">Max allowed aggregation tree height</param>
        public BlockSigner(IKsiService ksiService, HashAlgorithm hashAlgorithm = null, IKsiSignatureFactory signatureFactory = null,
                           uint?maxTreeHeight = null)
        {
            if (ksiService == null)
            {
                throw new ArgumentNullException(nameof(ksiService));
            }

            _hashAlgorithm = hashAlgorithm ?? HashAlgorithm.Default;

            if (_hashAlgorithm.HasDeprecatedSinceDate)
            {
                throw new HashingException(string.Format("Hash algorithm {0} is deprecated since {1} and can not be used.", _hashAlgorithm.Name,
                                                         _hashAlgorithm.DeprecatedSinceDate?.ToString(Constants.DateFormat)));
            }

            _ksiService       = ksiService;
            _signatureFactory = signatureFactory ?? new KsiSignatureFactory();
            _treeBuilder      = new TreeBuilder(_hashAlgorithm, maxTreeHeight);
        }
Exemplo n.º 18
0
        public void HAExtenderConfigRequestWithSingleServiceTest()
        {
            // Test getting extender configuration with single sub-service
            IKsiService haService = GetHAService(
                new List <PduPayload>()
            {
                GetExtenderConfigResponsePayload(4, new List <string>()
                {
                    "uri-1"
                }, 1136073600, 2136073600)
            });

            haService.GetExtenderConfig();

            ExtenderConfig config = haService.GetExtenderConfig();

            Assert.AreEqual(4, config.MaxRequests, "Unexpected max requests value");
            Assert.AreEqual(1, config.ParentsUris.Count, "Unexpected parent uri count");
            Assert.AreEqual("uri-1", config.ParentsUris[0], "Unexpected parent uri value at position 0");
            Assert.AreEqual(1136073600, config.CalendarFirstTime, "Unexpected calendar first time value");
            Assert.AreEqual(2136073600, config.CalendarLastTime, "Unexpected calendar last time value");
        }
Exemplo n.º 19
0
 /// <summary>
 /// Begin sub-service request.
 /// </summary>
 /// <param name="service">sub-service</param>
 /// <returns></returns>
 protected abstract IAsyncResult SubServiceBeginRequest(IKsiService service);
Exemplo n.º 20
0
 /// <summary>
 /// Returns a string that represents the given sub-service.
 /// </summary>
 /// <param name="service">sub-service</param>
 /// <returns></returns>
 protected abstract string SubServiceToString(IKsiService service);
Exemplo n.º 21
0
 /// <summary>
 /// End sub-service request.
 /// </summary>
 /// <param name="service">sub-service</param>
 /// <param name="asyncResult">async result</param>
 /// <returns></returns>
 protected abstract object SubServiceEndRequest(IKsiService service, IAsyncResult asyncResult);
        /// <summary>
        /// Create aggregator configuration changed event arguments class instance.
        /// </summary>
        /// <param name="exception">Exception thrown while processing aggregator configuration request</param>
        /// <param name="ksiService">KsiService that made the aggregator configuration request</param>
        public AggregatorConfigChangedEventArgs(KsiException exception, IKsiService ksiService)

        {
            Exception  = exception;
            KsiService = ksiService;
        }
 /// <summary>
 /// Create aggregator configuration changed event arguments class instance.
 /// </summary>
 /// <param name="aggregatorConfig">New aggregator configuration</param>
 /// <param name="ksiService">KsiService that made the aggregator configuration request</param>
 public AggregatorConfigChangedEventArgs(AggregatorConfig aggregatorConfig, IKsiService ksiService = null)
 {
     AggregatorConfig = aggregatorConfig;
     KsiService       = ksiService;
 }
Exemplo n.º 24
0
 /// <summary>
 /// End sub-service extending request.
 /// </summary>
 /// <param name="service">sub-service</param>
 /// <param name="asyncResult">async result</param>
 protected override object SubServiceEndRequest(IKsiService service, IAsyncResult asyncResult)
 {
     return(service.EndExtend(asyncResult));
 }
Exemplo n.º 25
0
 /// <summary>
 /// Returns a string that represents the given extending sub-service.
 /// </summary>
 /// <param name="service">sub-service</param>
 protected override string SubServiceToString(IKsiService service)
 {
     return("Extending service: " + service.ExtenderAddress);
 }
Exemplo n.º 26
0
 /// <summary>
 /// Begin sub-service extending request.
 /// </summary>
 /// <param name="service">sub-service</param>
 protected override IAsyncResult SubServiceBeginRequest(IKsiService service)
 {
     return(_publicationTime.HasValue ? service.BeginExtend(_aggregationTime, _publicationTime.Value, null, null) : service.BeginExtend(_aggregationTime, null, null));
 }
 /// <summary>
 ///     Create new HA KSI sub-service exception.
 /// </summary>
 /// <param name="thrownBySubService">Sub-service that threw the exception</param>
 /// <param name="message">Exception message</param>
 /// <param name="innerExceptions">Inner exceptions</param>
 public HAKsiSubServiceException(IKsiService thrownBySubService, string message, Exception innerExceptions = null) : base(message, innerExceptions)
 {
     ThrownBySubService = thrownBySubService;
 }
Exemplo n.º 28
0
 /// <summary>
 /// Returns a string that represents the given signing sub-service.
 /// </summary>
 /// <param name="service">sub-service</param>
 protected override string SubServiceToString(IKsiService service)
 {
     return("Signing service: " + service.AggregatorAddress);
 }
Exemplo n.º 29
0
 /// <summary>
 /// End sub-service aggregator configuration request.
 /// </summary>
 /// <param name="service">sub-service</param>
 /// <param name="asyncResult">async result</param>
 protected override object SubServiceEndRequest(IKsiService service, IAsyncResult asyncResult)
 {
     return(service.EndGetAggregatorConfig(asyncResult));
 }
Exemplo n.º 30
0
 /// <summary>
 /// Begin sub-service aggregator configuration request.
 /// </summary>
 /// <param name="service">sub-service</param>
 protected override IAsyncResult SubServiceBeginRequest(IKsiService service)
 {
     return(service.BeginGetAggregatorConfig(null, null));
 }