using Alkami.Ops.Certificates.Utilities; using Alkami.Ops.Common.Cryptography; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Management.Automation; using System.Security.Cryptography.X509Certificates; namespace Alkami.Ops.Certificates.Cmdlets { [Cmdlet("Get", "UntrackedCertificates")] [OutputType(typeof(string))] public class GetUntrackedCertificates : Cmdlet { [Parameter(Position = 0, Mandatory = false)] public string thumbprintsFilePath { get; set; } = @"C:\Tools\CertificateManagement\TrackedThumbprints\"; private readonly string[] storeTypes = new string[] { "personal", "ia", "root", "trustedpeople" }; /// /// Entry point method. /// protected override void ProcessRecord() { var untrackedJsonFilePath = Path.Combine(thumbprintsFilePath, "untracked.json"); if (!Directory.Exists(thumbprintsFilePath) && !File.Exists(untrackedJsonFilePath)) { Console.WriteLine("No un-tracked certificates at the specified location. Returning."); return; } var untrackedCertDetails = JsonConvert.DeserializeObject>(File.ReadAllText(untrackedJsonFilePath)); var localCerts = new X509Certificate2Collection(); // Get all certs foreach (var storeName in this.storeTypes) { var certStore = Extensions.GetStoreNameByFolderName(storeName); localCerts.AddRange(CertificateHelper.GetAllCertificates(certStore, StoreLocation.LocalMachine)); } var untrackedLocalCerts = new X509Certificate2Collection(); foreach (var untrackedCert in untrackedCertDetails) { // It's possible that certs will be duplicated in multiple stores. Just pull the first. var tempCerts = localCerts.Find(X509FindType.FindByThumbprint, untrackedCert.Key, false); if (tempCerts.Count > 0) { untrackedLocalCerts.Add(tempCerts[0]); } } var untrackedCertList = untrackedLocalCerts.ToList(); WriteObject(untrackedCertList.Select(s => new KeyValuePair(s.Thumbprint, s.GetNameInfo(X509NameType.SimpleName, false)))); } } }