internal X509Certificate2 GetApplicationCertificateFromStore()
        {
            HealthVaultPlatformTrace.LogCertLoading(
                "Opening cert store (read-only): {0}",
                _storeLocation.ToString());

            RSACng rsaProvider = null;
            string thumbprint  = null;

            X509Certificate2 result = null;
            X509Store        store  = new X509Store(_storeLocation);

            store.Open(OpenFlags.ReadOnly);

            try
            {
                HealthVaultPlatformTrace.LogCertLoading(
                    "Looking for matching cert with subject: {0}",
                    _certSubject);

                foreach (X509Certificate2 cert in store.Certificates)
                {
                    if (string.Equals(
                            cert.Subject,
                            _certSubject,
                            StringComparison.OrdinalIgnoreCase))
                    {
                        HealthVaultPlatformTrace.LogCertLoading(
                            "Found matching cert subject with thumbprint: {0}",
                            cert.Thumbprint);

                        thumbprint = cert.Thumbprint;

                        HealthVaultPlatformTrace.LogCertLoading("Looking for private key");
                        rsaProvider = (RSACng)cert.GetRSAPrivateKey();
                        HealthVaultPlatformTrace.LogCertLoading("Private key found");

                        result = cert;
                        break;
                    }
                }
            }
            catch (CryptographicException e)
            {
                HealthVaultPlatformTrace.LogCertLoading(
                    "Failed to retrieve private key for certificate: {0}",
                    e.ToString());
            }
            finally
            {
                store.Dispose();
            }

            if (rsaProvider == null || string.IsNullOrEmpty(thumbprint))
            {
                throw new SecurityException("CertificateNotFound");
            }

            return(result);
        }
Example #2
0
        /// <summary>
        /// Loads the specified HV item-types assembly.  If not found or fails to load, returns null.
        /// </summary>
        private static Assembly GetItemTypesAssembly(string name)
        {
            // otherwise, try loading it by name
            Assembly coreAssemblyName = typeof(ItemTypeManager).GetTypeInfo().Assembly;

            var itemTypesAssemblyName = new AssemblyName
            {
                Name        = name,
                Version     = coreAssemblyName.GetName().Version,
                CultureName = coreAssemblyName.GetName().CultureName
            };

            itemTypesAssemblyName.SetPublicKeyToken(coreAssemblyName.GetName().GetPublicKeyToken());

            HealthVaultPlatformTrace.Log(
                TraceEventType.Information,
                "Looking for ItemTypes assembly '{0}': {1}",
                name,
                itemTypesAssemblyName.FullName);

            try
            {
                return(Assembly.Load(itemTypesAssemblyName));
            }
            catch (FileNotFoundException e)
            {
                // assembly not found
                HealthVaultPlatformTrace.Log(
                    TraceEventType.Information,
                    "ItemTypes assembly '{0}' loading skipped.  It was not found: {1}",
                    name,
                    e.Message);

                return(null);
            }
            catch (IOException e)
            {
                // assembly found, but failed to load
                HealthVaultPlatformTrace.Log(
                    TraceEventType.Warning,
                    "ItemTypes assembly '{0}' loading skipped.  It was found, but failed to load: {1}",
                    name,
                    e.Message);

                return(null);
            }
            catch (BadImageFormatException e)
            {
                // assembly found, but not valid
                HealthVaultPlatformTrace.Log(
                    TraceEventType.Warning,
                    "ItemTypes assembly '{0}' loading skipped.  It was found, but was not valid: {1}",
                    name,
                    e.Message);

                return(null);
            }
        }
        private async Task <HealthServiceResponseData> SendRequestAsync(string requestXml, Guid?correlationId = null)
        {
            try
            {
                Debug.WriteLine($"Sent message: {requestXml}");

                byte[] requestXmlBytes = Encoding.UTF8.GetBytes(requestXml);

                CancellationTokenSource cancellationTokenSource = null;
                HttpResponseMessage     response;
                try
                {
                    cancellationTokenSource = new CancellationTokenSource(Configuration.RequestTimeoutDuration);

                    response = await _webRequestClient.SendAsync(
                        ServiceInstance.HealthServiceUrl,
                        requestXmlBytes,
                        requestXml.Length,
                        new Dictionary <string, string> {
                        { CorrelationIdContextKey, correlationId.GetValueOrDefault(Guid.NewGuid()).ToString() }
                    },
                        (CancellationToken)cancellationTokenSource?.Token).ConfigureAwait(false);
                }
                finally
                {
                    cancellationTokenSource?.Dispose();
                }

                // Platform returns a platform request id with the responses. This allows
                // developers to have additional information if necessary for debugging/logging purposes.
                Guid responseId;
                if (response.Headers != null &&
                    response.Headers.Contains(ResponseIdContextKey) &&
                    Guid.TryParse(response.Headers.GetValues(ResponseIdContextKey)?.FirstOrDefault(), out responseId))
                {
                    // TODO: Provide a plug in for applications to plug in their telemetry
                    if (HealthVaultPlatformTrace.LoggingEnabled)
                    {
                        HealthVaultPlatformTrace.Log(TraceEventType.Information, "Response Id: {0}", responseId);
                    }
                }

                HealthServiceResponseData responseData = await _healthServiceResponseParser.ParseResponseAsync(response).ConfigureAwait(false);

                return(responseData);
            }
            catch (XmlException xmlException)
            {
                throw new HealthServiceException(
                          Resources.InvalidResponseFromXMLRequest,
                          xmlException);
            }
        }
        private string GetApplicationCertificateSubject()
        {
            string result = _configuration.CertSubject;

            if (result == null)
            {
                result = "WildcatApp-" + _applicationId;

                HealthVaultPlatformTrace.LogCertLoading(
                    "Using default cert subject: {0}",
                    result);
            }
            else
            {
                HealthVaultPlatformTrace.LogCertLoading(
                    "Using custom cert subject: {0}",
                    result);
            }

            return(result);
        }
        private X509Certificate2 GetApplicationCertificateFromFile(string certFilename)
        {
            HealthVaultPlatformTrace.LogCertLoading(
                "Attempting to load certificate from file: {0}",
                certFilename);

            certFilename = Environment.ExpandEnvironmentVariables(certFilename);

            if (!File.Exists(certFilename))
            {
                HealthVaultPlatformTrace.LogCertLoading(
                    "Cert file not found: {0}",
                    certFilename);

                throw new ArgumentException("CertificateFileNotFound");
            }

            string password = _configuration.ApplicationCertificatePassword;

            X509Certificate2 cert;

            try
            {
                HealthVaultPlatformTrace.LogCertLoading(
                    "Loading certificate from file {0}",
                    string.IsNullOrEmpty(password) ? "without a password" : "with a password");

                cert = new X509Certificate2(certFilename, password, X509KeyStorageFlags.MachineKeySet);
            }
            catch (CryptographicException e)
            {
                HealthVaultPlatformTrace.LogCertLoading(
                    "Failed to load certificate: {0}",
                    e.ToString());

                throw new ArgumentException("ErrorLoadingCertificateFile", e);
            }

            HealthVaultPlatformTrace.LogCertLoading("Looking for private key");

            if (!cert.HasPrivateKey)
            {
                HealthVaultPlatformTrace.LogCertLoading(
                    "Certificate did not contain a private key.");

                throw new ArgumentException("CertificateMissingPrivateKey");
            }

            HealthVaultPlatformTrace.LogCertLoading(
                "Found cert with thumbprint: {0}",
                cert.Thumbprint);

            var thumbprint  = cert.Thumbprint;
            var rsaProvider = (RSACryptoServiceProvider)cert.GetRSAPrivateKey();

            HealthVaultPlatformTrace.LogCertLoading("Private key found");

            if (rsaProvider == null || string.IsNullOrEmpty(thumbprint))
            {
                throw new ArgumentException("CertificateNotFound");
            }

            return(cert);
        }