public CertificateEntryLookupEntry(VerificationTarget target, SignaturePlacement placement, CertificateItem certificate, ICollection <string> owners = null)
 {
     Target      = target;
     Placement   = placement;
     Certificate = certificate ?? throw new ArgumentNullException(nameof(certificate));
     Owners      = owners;
 }
Example #2
0
        public void CertificateItem_Equals_WithDifferentFingerprint_ReturnsFalse()
        {
            var certificate1 = new CertificateItem("abcdefg", Common.HashAlgorithmName.SHA512);
            var certificate2 = new CertificateItem("stuvxyz", Common.HashAlgorithmName.SHA512);

            certificate1.Equals(certificate2).Should().BeFalse();
        }
Example #3
0
        public void CertificateItem_ParsedCorrectly()
        {
            // Arrange
            var config          = @"
<configuration>
    <SectionName>
        <certificate fingerprint=""abcdefg"" hashAlgorithm=""SHA256"" allowUntrustedRoot=""true"" />
    </SectionName>
</configuration>";
            var nugetConfigPath = "NuGet.Config";

            using (var mockBaseDirectory = TestDirectory.Create())
            {
                SettingsTestUtils.CreateConfigurationFile(nugetConfigPath, mockBaseDirectory, config);

                // Act and Assert
                var settingsFile = new SettingsFile(mockBaseDirectory);
                var section      = settingsFile.GetSection("SectionName");
                section.Should().NotBeNull();

                section.Items.Count.Should().Be(1);
                var item = section.Items.First() as CertificateItem;

                var expectedItem = new CertificateItem("abcdefg", Common.HashAlgorithmName.SHA256, allowUntrustedRoot: true);
                SettingsTestUtils.DeepEquals(item, expectedItem).Should().BeTrue();
            }
        }
Example #4
0
        public void CertificateItem_Equals_WithSameFingerprint_ReturnsTrue()
        {
            var certificate1 = new CertificateItem("abcdefg", Common.HashAlgorithmName.SHA512);
            var certificate2 = new CertificateItem("abcdefg", Common.HashAlgorithmName.SHA256);

            certificate1.Equals(certificate2).Should().BeTrue();
        }
        /// <summary>
        /// netsh 실행 (add urlacl, add sslcert)
        /// </summary>
        /// <param name="item"></param>
        private static void NetshReg(CertificateItem item)
        {
            try
            {
                string sUrlAcl  = "";
                string sSslCert = "";
                sUrlAcl  = string.Format(@"http add urlacl url={0} user={1}\{2}", item.Url, Environment.UserDomainName, Environment.UserName);
                sSslCert = string.Format("http add sslcert ipport = 0.0.0.0:{0} certhash = c081f6fce7ebd93aea6556b37a14980850087534 appid = \"{{4225a41c-4b33-4353-ab2b-3790924f73f7}}\"", item.Port);

                // URL 예약등록
                ProcessStartInfo psi = new ProcessStartInfo("netsh", sUrlAcl);
                psi.Verb            = "runas";
                psi.CreateNoWindow  = true;
                psi.WindowStyle     = ProcessWindowStyle.Hidden;
                psi.UseShellExecute = true;
                Process.Start(psi).WaitForExit();

                // SSL 바인딩등록
                psi                 = new ProcessStartInfo("netsh", sSslCert);
                psi.Verb            = "runas";
                psi.CreateNoWindow  = true;
                psi.WindowStyle     = ProcessWindowStyle.Hidden;
                psi.UseShellExecute = true;
                Process.Start(psi).WaitForExit();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Example #6
0
        public static CertificateItem GetX509Certificate()
        {
            CertificateItem item = new CertificateItem();

            if (Mode.Equals("R", StringComparison.CurrentCultureIgnoreCase)) //운영서버
            {
                item.Url      = "https://+:50001/ScanLauncher/";
                item.Port     = "50001";
                item.PfxPath  = string.Format("{0}\\CourtCert.pfx", System.IO.Directory.GetCurrentDirectory());
                item.CertName = "CN=localhost";
                item.Password = "******";
            }
            else if (Mode.Equals("T", StringComparison.CurrentCultureIgnoreCase)) //개발서버
            {
                item.Url      = "https://+:50002/ScanLauncher/";
                item.Port     = "50002";
                item.PfxPath  = string.Format("{0}\\CourtCert.pfx", System.IO.Directory.GetCurrentDirectory());
                item.CertName = "CN=localhost";
                item.Password = "******";
            }
            else if (Mode.Equals("SS", StringComparison.CurrentCultureIgnoreCase)) //임시개발서버(https)
            {
                item.Url      = "https://+:50004/ScanLauncher/";
                item.Port     = "50004";
                item.PfxPath  = string.Format("{0}\\CourtCert.pfx", System.IO.Directory.GetCurrentDirectory());
                item.CertName = "CN=localhost";
                item.Password = "******";
            }

            return(item);
        }
Example #7
0
		public void RewriteConfig() {
			SetConfigField("CertificateStore", CertificateStore.ToString());
			SetConfigField("CertificateItem", CertificateItem.ToString());
			SetConfigField("WindowHeight", WindowHeight.ToString());
			SetConfigField("WindowWidth", WindowWidth.ToString());
			SetConfigField("WindowLeft", WindowLeft.ToString());
			SetConfigField("WindowTop", WindowTop.ToString());
			saveChangesToConfig();
		}
        /// <summary>
        /// https 인증서 등록
        /// </summary>
        public static void Create(CertificateItem item)
        {
            try
            {
                // Get the certifcate to use to encrypt the key.
                X509Certificate2 cert = GetCertificateFromStore(item.CertName);

                // 법무부에 동일한 loclahost 명의 인증서파일이 존재하므로 검사하지않고 그냥 등록
                // 접속 안될때 : Explorer -> 인터넷옵션 -> 로컬 인트라넷 -> 사이트 -> 3가지항목 체크 해제 확인
                // 접속 안될때 : 신롸할수없는 사이트 추가, 호환성보기 설정 추가
                // 접속 안될때 : telnet 확인
                //if (cert == null)
                {
                    if (FileHelper.ExistsFile(item.PfxPath) == false)
                    {
                        throw new Exception("인증서 파일이 존재 하지 않습니다.");
                    }

                    X509Certificate2 x509 = new X509Certificate2(item.PfxPath, item.Password);

                    // 신뢰할수있는 루트인증기관 등록
                    X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
                    store.Open(OpenFlags.ReadWrite);
                    store.Add(x509);
                    store.Close();

                    // 신뢰할수있는 루트인증기관 등록
                    store = new X509Store(StoreName.Root, StoreLocation.LocalMachine);
                    store.Open(OpenFlags.ReadWrite);
                    store.Add(x509);
                    store.Close();

                    // 신뢰할수있는 게시자 등록
                    store = new X509Store(StoreName.TrustedPublisher, StoreLocation.LocalMachine);
                    store.Open(OpenFlags.ReadWrite);
                    store.Add(x509);
                    store.Close();

                    ServicePointManager.Expect100Continue = true;
                    ServicePointManager.SecurityProtocol  = SecurityProtocolType.Tls12;
                    ServicePointManager.ServerCertificateValidationCallback = delegate { return(true); };
                }

                // netsh 실행 (add urlacl, add sslcert)
                NetshReg(item);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Example #9
0
        /// <summary>
        /// Updates the certificate list of a trusted signer by adding the given certificate.
        /// If the signer does not exists it creates a new one.
        /// </summary>
        /// <remarks>This method defaults to adding a trusted author if the signer doesn't exist.</remarks>
        /// <param name="name">Name of the trusted author.</param>
        /// <param name="fingerprint">Fingerprint to be added to the certificate entry.</param>
        /// <param name="hashAlgorithm">Hash algorithm used to calculate <paramref name="fingerprint"/>.</param>
        /// <param name="allowUntrustedRoot">Specifies if allowUntrustedRoot should be set to true in the certificate entry.</param>
        public void AddOrUpdateTrustedSigner(string name, string fingerprint, HashAlgorithmName hashAlgorithm, bool allowUntrustedRoot)
        {
            if (string.IsNullOrEmpty(name))
            {
                throw new ArgumentException(Strings.ArgumentCannotBeNullOrEmpty, nameof(name));
            }

            if (string.IsNullOrEmpty(fingerprint))
            {
                throw new ArgumentException(Strings.ArgumentCannotBeNullOrEmpty, nameof(fingerprint));
            }

            if (!Enum.IsDefined(typeof(HashAlgorithmName), hashAlgorithm) || hashAlgorithm == HashAlgorithmName.Unknown)
            {
                throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Strings.UnsupportedHashAlgorithm, hashAlgorithm.ToString()));
            }

            var certificateToAdd          = new CertificateItem(fingerprint, hashAlgorithm, allowUntrustedRoot);
            TrustedSignerItem signerToAdd = null;

            var signers = _trustedSignersProvider.GetTrustedSigners();

            foreach (var existingSigner in signers)
            {
                if (string.Equals(existingSigner.Name, name, StringComparison.Ordinal))
                {
                    signerToAdd = existingSigner;

                    break;
                }
            }

            string logMessage = null;

            if (signerToAdd == null)
            {
                signerToAdd = new AuthorItem(name, certificateToAdd);
                logMessage  = Strings.SuccessfullyAddedTrustedAuthor;
            }
            else
            {
                signerToAdd.Certificates.Add(certificateToAdd);
                logMessage = Strings.SuccessfullUpdatedTrustedSigner;
            }

            _trustedSignersProvider.AddOrUpdateTrustedSigner(signerToAdd);

            _logger.Log(LogLevel.Information, string.Format(CultureInfo.CurrentCulture, logMessage, name));
        }
        internal CertificateIdentityItem(CertificateItem certItem, VaultUriHelper vaultUriHelper)
        {
            if (certItem == null)
                throw new ArgumentNullException("certItem");
            if (certItem.Attributes == null)
                throw new ArgumentException(KeyVaultProperties.Resources.InvalidKeyAttributes);
            if (certItem.Identifier == null)
                throw new ArgumentException(KeyVaultProperties.Resources.InvalidKeyIdentifier);

            SetObjectIdentifier(vaultUriHelper, certItem.Identifier);

            Enabled = certItem.Attributes.Enabled;
            Expires = certItem.Attributes.Expires;
            NotBefore = certItem.Attributes.NotBefore;
            Created = certItem.Attributes.Created;
            Updated = certItem.Attributes.Updated;
            Tags = (certItem.Tags == null) ? null : certItem.Tags.ConvertToHashtable();
        }
        public static bool TagsFilter(this CertificateItem certificate, string issuer, string endpoint)
        {
            var tags = certificate.Tags;

            if (tags == null)
            {
                return(false);
            }

            if (!tags.TryGetValue("Issuer", out var tagIssuer) || tagIssuer != issuer)
            {
                return(false);
            }

            if (!tags.TryGetValue("Endpoint", out var tagEndpoint) || tagEndpoint != endpoint)
            {
                return(false);
            }

            return(true);
        }
        public HttpListenerHelper(IReadOnlyCollection <string> prefixes, Func <Common.BaseForm, HttpListenerRequest, string> method)
        {
            if (!HttpListener.IsSupported)
            {
                throw new NotSupportedException("Need Windows XP SP2, Server 2003 or later.");
            }

            if (prefixes == null || prefixes.Count == 0)
            {
                throw new ArgumentException("URI prefixes are required");
            }

            if (method == null)
            {
                throw new ArgumentException("responder method required.");
            }

            //https 환경설정 정보
            CertificateItem cfitem = ApplicationConfig.GetX509Certificate();

            //운영 모드 시 https 설정
            if (string.IsNullOrEmpty(cfitem.Url) == false)
            {
                X509CertificateHelper.Create(cfitem);

                _listener.Prefixes.Add(cfitem.Url);
                _listener.AuthenticationSchemes = AuthenticationSchemes.Anonymous;
            }
            else
            {
                foreach (var item in prefixes)
                {
                    _listener.Prefixes.Add(item);
                }
            }

            _responderMethod = method;
            _listener.Start();
        }
Example #13
0
        public void CertificateItem_ElementName_IsCorrect()
        {
            var certificateItem = new CertificateItem("abcdefg", Common.HashAlgorithmName.SHA512);

            certificateItem.ElementName.Should().Be("certificate");
        }
Example #14
0
 public CertificateVersion(int index, CertificateItem certificateItem) : base(index, certificateItem.Attributes.Created, certificateItem.Attributes.Updated, Microsoft.Vault.Library.Utils.GetChangedBy(certificateItem.Tags), certificateItem.Identifier)
 {
     CertificateItem = certificateItem;
 }
Example #15
0
		private bool checkConfig(XDocument cfg) {
			string binConfigPath = cfg.Root?.Element("CfgBinPath")?.Value;
			string certFilePath = cfg.Root?.Element("CertificateFilePath")?.Value;

			StoreLocation storeLocation;
			StoreLocation.TryParse(cfg.Root?.Element("CertificateStore")?.Value, true, out storeLocation);
			if(storeLocation != 0) {
				CertificateStore = storeLocation;
			} else {
				CertificateStore = StoreLocation.CurrentUser;
				SetConfigField("CertificateStore", CertificateStore.ToString());
			}

			#region [set window position and size]

			string lastHeightStr = cfg.Root?.Element("WindowHeight")?.Value;
			string lastWidthStr = cfg.Root?.Element("WindowWidth")?.Value;
			string lastLeftStr = cfg.Root?.Element("WindowLeft")?.Value;
			string lastTopStr = cfg.Root?.Element("WindowTop")?.Value;

			if(!string.IsNullOrEmpty(lastHeightStr)) {
				WindowHeight = Int32.Parse(lastHeightStr);
			} else {
				WindowHeight = 780;
				SetConfigField("WindowHeight", WindowHeight.ToString());
			}

			if(!string.IsNullOrEmpty(lastWidthStr)) {
				WindowWidth = Int32.Parse(lastWidthStr);
			} else {
				WindowWidth = 590;
				SetConfigField("WindowWidth", WindowWidth.ToString());
			}

			if(!string.IsNullOrEmpty(lastLeftStr)) {
				WindowLeft = Int32.Parse(lastLeftStr);
			} else {
				WindowLeft = 100;
				SetConfigField("WindowLeft", WindowLeft.ToString());
			}

			if(!string.IsNullOrEmpty(lastTopStr)) {
				WindowTop = Int32.Parse(lastTopStr);
			} else {
				WindowTop = 20;
				SetConfigField("WindowTop", WindowTop.ToString());
			}
			#endregion

			string lastCertificateStr = cfg.Root?.Element("CertificateItem")?.Value;
			if(!string.IsNullOrEmpty(lastCertificateStr)) {
				CertificateItem = Int32.Parse(lastCertificateStr);
			} else {
				CertificateItem = 0;
				SetConfigField("CertificateItem", CertificateItem.ToString());
			}

			string interopCertificateThumb = cfg.Root?.Element("InteropCertificateThumbprint")?.Value;
			if (string.IsNullOrEmpty(interopCertificateThumb)) {
//				Thread.Sleep(1000);
				SetErrorMessage("Не указан сертификат подписи для взаимодействия");
					bool certSelected = SelectInteropCertificate();
					if (!certSelected) {

						MessageBox.Show(
							"Не указан сертификат подписи для взаимодействия.\nУкажите сертификат подписи, используя соответствующий пункт меню «Настройка» программы.",
							"Ошибка загрузки начальной конфигурации.", MessageBoxButton.OK,
							MessageBoxImage.Error);

						return false;
					} else {
						StoreLocation.TryParse(cfg.Root?.Element("InteropCertificateStore")?.Value,
												true,
												out _interopCertificateStoreLocation);
					}
			} else {
				_interopCertificateThumbprint = interopCertificateThumb;
				StoreLocation.TryParse(cfg.Root?.Element("InteropCertificateStore")?.Value, true, out _interopCertificateStoreLocation);
			}

			saveChangesToConfig();

			//signed (and siphered) binary config
			if(string.IsNullOrEmpty(binConfigPath)) {
				SetErrorMessage("Личный конфигурационный файл не найден");
				bool privateConfigSelected = LoadPrivateConfig();
				if (!privateConfigSelected) {

					MessageBox.Show("Личный конфигурационный файл не найден.\nСкачайте новый личный конфигурационный файл с корпоративного портала.",
									"Ошибка загрузки начальной конфигурации.", MessageBoxButton.OK, MessageBoxImage.Error);

					return false;
				}
			} else {
				//means htere is a config
				//check it's signature, but first load our certificate
				if(string.IsNullOrEmpty(certFilePath)) {
					MessageBox.Show("Файл сертификата сервера не найден.\nСкачайте файл сертификата сервера с корпоративного портала.",
								"Ошибка загрузки начальной конфигурации.", MessageBoxButton.OK, MessageBoxImage.Error);
					SetErrorMessage("Файл сертификата сервера не найден");
					bool serverCertifcateSelected = LoadServerCertificate();
					if (!serverCertifcateSelected) {
						return false;
					}
				} else {
					//means certificate && config present
					//check cert expiration date
					X509Certificate2 cert = new X509Certificate2();
					try {
						cert.Import(certFilePath);
						if (cert.NotAfter > DateTime.Now) {
							//cert ok
							//check config signature
							string configContents = Util.DecryptConfig(binConfigPath,ProgramFolder);
							if (string.IsNullOrEmpty(configContents)) {
								MessageBox.Show("Личный конфигурационный файл поврежден.\nСкачайте новый личный конфигурационный файл с корпоративного портала.",
									"Ошибка загрузки начальной конфигурации.", MessageBoxButton.OK, MessageBoxImage.Error);
								SetErrorMessage("Личный конфигурационный файл поврежден");
								return false;
							}
							XmlDocument xdocConfig = new XmlDocument();     // this stuff is for

							try {
								xdocConfig.LoadXml(configContents); // check signature further
							} catch (Exception e) {
								MessageBox.Show(
									$"Личный конфигурационный файл поврежден.\nСкачайте новый личный конфигурационный файл с корпоративного портала.\n\n{e.Message}",
									"Ошибка загрузки начальной конфигурации.", MessageBoxButton.OK, MessageBoxImage.Error);
								SetErrorMessage("Личный конфигурационный файл поврежден");
								return false;
							}

							XDocument privateConfig = XDocument.Parse(configContents);
							try {
								#if !DEBUG
								if (SignatureProcessor.VerifySignature(SignatureProcessor.SignatureType.Smev3SidebysideDetached, xdocConfig, cert)) {
								#endif
								#if DEBUG
								if(SignatureProcessor.VerifySignature(SignatureProcessor.SignatureType.Smev3SidebysideDetached, xdocConfig)) {
								#endif
									//config signature OK - loading contents
									if (privateConfig.Root?.Attribute("version").Value == ProgramVersion) {
										//means config version corresponds to a program version

										_ourCertificate = cert;
										_serverUri = new Uri(privateConfig.Root?.Element("Server").Element("GetFileUri")?.Value ?? "");
										_serverSignatureCertificateThumbprint = privateConfig.Root?.Element("Server").Element("CertificateThumbprint")?.Value ?? "";
										_serverHttpsCertificateThumbprint =
											privateConfig.Root?.Element("Server").Element("SSLCertificateThumbprint")?.Value ?? "";
										ClearError("Конфигурационный файл успешно загружен");
									} else {
										//means version in config is not right one
										MessageBox.Show(
											$"Текущая версия программы <{ProgramVersion}> устарела.\nСкачайте новую версию с корпоративного портала.",
											"Программа устарела.", MessageBoxButton.OK, MessageBoxImage.Error);
										SetErrorMessage($"Установленная версия программы <{ProgramVersion}> устарела");
										return false;
									}
								} else {
									//signature incorrect
									Debug.WriteLine("Invalid Signature");
									MessageBox.Show(
										"Личный конфигурационный файл поврежден.\nСкачайте новый личный конфигурационный файл с корпоративного портала.",
										"Ошибка загрузки начальной конфигурации.", MessageBoxButton.OK, MessageBoxImage.Error);
									SetErrorMessage("Личный конфигурационный файл поврежден");
									return false;
								}
							} catch (Exception e) {
								MessageBox.Show(
										$"Личный конфигурационный файл поврежден.\nСкачайте новый личный конфигурационный файл с корпоративного портала.\n\n{e.Message}",
										"Ошибка загрузки начальной конфигурации.", MessageBoxButton.OK, MessageBoxImage.Error);
								SetErrorMessage("Личный конфигурационный файл поврежден");
								return false;
							}

						} else {
							//cert expired
							MessageBox.Show("Файл сертификата сервера просрочен.\nСкачайте новый файл сертификата сервера с корпоративного портала.",
								"Ошибка загрузки начальной конфигурации.", MessageBoxButton.OK, MessageBoxImage.Error);
							SetErrorMessage("Файл сертификата сервера просрочен");
							return false;
						}
					} catch (Exception e) {
						//certificate corrupted
						MessageBox.Show($"Ошибка загрузки сертификата сервера. Файл поврежден.\nСкачайте новый файл сертификата сервера с корпоративного портала.\n\n{e.Message}",
								"Ошибка загрузки начальной конфигурации.", MessageBoxButton.OK, MessageBoxImage.Error);
						SetErrorMessage("Ошибка загрузки сертификата сервера");
						return false;
					}
				}
			}
			return true;
		}
 private static string GetCertLookupKey(CertificateItem certificate)
 {
     return($"{certificate.HashAlgorithm.ToString()}-{certificate.Fingerprint}");
 }
 public ListViewItemCertificate(ISession session, CertificateItem c) : this(session, c.Identifier, c.Attributes, Utils.ByteArrayToHex(c.X509Thumbprint), c.Tags)
 {
 }
 private static bool CertificateItem_DeepEquals(CertificateItem item1, CertificateItem item2)
 {
     return(ItemBase_DeepEquals(item1, item2));
 }