public void SignPackage()
        {
            var dss               = new DigitalSignatureService();
            var templatePackage   = new TemplatePackage(dss);
            var certPass          = GetTestCertPassword();
            X509Certificate2 cert = templatePackage.LoadCert(@"Packaging\TestCert.pfx", certPass);

            var file  = Path.GetFullPath(@".\Packaging\Unsigned\UnsignedPackage.mstx");
            var file2 = Path.GetFullPath(@".\Packaging\ToSign.mstx");

            File.Copy(file, file2);

            using (Package package = Package.Open(file2, FileMode.Open))
            {
                dss.SignPackage(package, cert);
            }

            using (Package package = Package.Open(file2, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                var isSigned         = dss.IsSigned(package);
                var isSignatureValid = dss.VerifySignatures(package);

                Assert.True(isSigned);
                Assert.True(isSignatureValid);
            }

            File.Delete(file2);
        }
        private async Task <bool> ExtractAsync(TemplatesPackageInfo packageInfo, string finalDest, bool verifyPackageSignatures = true, CancellationToken ct = default(CancellationToken))
        {
            try
            {
                _version = packageInfo.Version;
                if (!string.IsNullOrEmpty(packageInfo.LocalPath))
                {
                    var finalDestinationTemp = string.Concat(finalDest, _tmpExtension);

                    await TemplatePackage.ExtractAsync(packageInfo.LocalPath, finalDestinationTemp, verifyPackageSignatures, ReportExtractionProgress, ct);

                    Fs.SafeRenameDirectory(finalDestinationTemp, finalDest);

                    AppHealth.Current.Verbose.TrackAsync($"{StringRes.TemplatesContentExtractedToString} {finalDest}.").FireAndForget();
                    return(true);
                }
                else
                {
                    AppHealth.Current.Error.TrackAsync(StringRes.TemplatesSourceLocalPathEmptyMessage).FireAndForget();
                    return(false);
                }
            }
            catch (Exception ex) when(ex.GetType() != typeof(OperationCanceledException))
            {
                AppHealth.Current.Exception.TrackAsync(ex, StringRes.TemplatesSourceExtractContentMessage).FireAndForget();
                throw;
            }
        }
Exemple #3
0
 public void PackAndSign_CertNotFound()
 {
     Exception ex = Assert.Throws <SignCertNotFoundException>(() =>
     {
         TemplatePackage.PackAndSign(@"Packaging\SampleContent.txt", "SignedContent.package", "CERT_NOT_FOUND", MediaTypeNames.Text.Plain);
     });
 }
        private static void WriteCertificatesInfo(string inputPath, TextWriter output)
        {
            var certsInfo = TemplatePackage.GetCertsInfo(inputPath);

            output.WriteLine();
            output.WriteCommandText($"Found {certsInfo.Count} certificates in the package.");
            foreach (var info in certsInfo)
            {
                output.WriteLine();
                output.WriteCommandText($" Cert Subject: {info.cert.Subject}");
                output.WriteLine();
                output.WriteCommandText($" Cert Issuer: {info.cert.IssuerName.Name}");
                output.WriteLine();
                output.WriteCommandText($" Cert Serial Number: {info.cert.SerialNumber}");
                output.WriteLine();
                output.WriteCommandText($" Cert Chain Status: {info.status.ToString()}");
                output.WriteLine();
                output.WriteCommandText($" Cert PubKey:");
                output.WriteCommandText($" {info.cert.GetPublicKeyString()}");
                output.WriteLine();
                output.WriteCommandText($" Cert Pin:");
                output.WriteCommandText($" {info.pin}");
                output.WriteLine();
                output.WriteCommandText("--");
            }
        }
Exemple #5
0
        public static async Task <int> ExecuteAsync(
            TemplateOptions options,
            IConsole console,
            IAppEnvironment appEnvironment,
            InvocationContext context = null)
        {
            console.Out.WriteLine($"Uninstalling template package '{options.PackageId}'");

            var templateSettingsManager       = new TemplateSettingsManager(appEnvironment);
            TemplatesSettings currentSettings = templateSettingsManager.LoadSettings() ?? new TemplatesSettings();

            var packageManager = new NuGetTemplatePackageManager(appEnvironment);

            if (currentSettings.Packages.Exists(templatePackage => templatePackage.PackageId == options.PackageId))
            {
                TemplatePackage package = currentSettings.Packages.Find(templatePackage => templatePackage.Id == options.PackageId);

                if (package != null)
                {
                    await packageManager.UnnstallAsync(package).ConfigureAwait(false);

                    currentSettings.Packages.Remove(package);

                    if (currentSettings.DefaultTemplate.PackageName == package.PackageId)
                    {
                        currentSettings.DefaultTemplate = new DefaultTemplate();
                    }
                }
            }

            return(ReturnCodes.Ok);
        }
        internal static async Task CreateAsync(string inputPath, string outfile, string certThumbprint, TextWriter output, TextWriter error)
        {
            try
            {
                if (Directory.Exists(inputPath))
                {
                    output.WriteCommandHeader($"Creating template package from folder {inputPath}.");
                    if (!string.IsNullOrWhiteSpace(certThumbprint))
                    {
                        output.WriteCommandText($"The template package will be signed using the cert matching {certThumbprint} as thumbprint.");
                        await TemplatePackage.PackAndSignAsync(inputPath, outfile, certThumbprint, "text/plain").ConfigureAwait(false);

                        output.WriteCommandText($"Templates package file '{outfile}' successfully created.");
                    }
                    else
                    {
                        output.WriteCommandText($"No cert thumbprint provided, the template package will not be signed.");
                        await TemplatePackage.PackAsync(inputPath, outfile, "text/plain").ConfigureAwait(false);
                    }

                    output.WriteCommandText($"Templates package file '{outfile}' successfully created.");
                }
                else
                {
                    error.WriteCommandText($"{inputPath} is not a valid folder to create a Templates Package.");
                }
            }
            catch (Exception ex)
            {
                error.WriteException(ex, "Unexpected exception creating templates package.");
            }
        }
Exemple #7
0
        private async Task EnrichTemplatePackage(TemplatePackage templatePackage)
        {
            IDeserializer    deserializer = new DeserializerBuilder().IgnoreUnmatchedProperties().IgnoreFields().Build();
            MarkdownPipeline pipeline     = new MarkdownPipelineBuilder()
                                            .UseYamlFrontMatter()
                                            .Build();

            foreach (Template template in templatePackage.Templates)
            {
                string filePath = Path.GetFullPath(Path.Combine(templatePackage.InstalltionPath, template.NestedFilePath));
                string content  = await File.ReadAllTextAsync(filePath).ConfigureAwait(false);

                MarkdownDocument     doc       = Markdown.Parse(content, pipeline);
                YamlFrontMatterBlock yamlBlock = doc.Descendants <YamlFrontMatterBlock>().FirstOrDefault();

                if (yamlBlock != null)
                {
                    string yaml = string.Join(Environment.NewLine, yamlBlock.Lines.Lines.Select(stringLine => stringLine.ToString()).Where(value => !string.IsNullOrEmpty(value)));
                    Dictionary <string, dynamic> frontMatter = deserializer.Deserialize <Dictionary <string, dynamic> >(yaml);

                    if (frontMatter.TryGetValue("ContentType", out dynamic contentType))
                    {
                        template.ContentType = contentType;
                    }
                }
            }
        }
Exemple #8
0
 public async Task PackAndSign_CertNotFoundAsync()
 {
     SignCertNotFoundException ex = await Assert.ThrowsAsync <SignCertNotFoundException>(async() =>
     {
         await TemplatePackage.PackAndSignAsync(@"Packaging\SampleContent.txt", "SignedContent.package", "CERT_NOT_FOUND", MediaTypeNames.Text.Plain);
     });
 }
        internal static async Task ExtractAsync(string inputFile, string destinationDir, TextWriter output, TextWriter error)
        {
            try
            {
                if (File.Exists(inputFile))
                {
                    if (destinationDir == ".")
                    {
                        destinationDir = System.Environment.CurrentDirectory;
                    }

                    Fs.EnsureFolder(destinationDir);

                    output.WriteCommandHeader($"Extracting {inputFile} to {destinationDir}...");
                    await TemplatePackage.ExtractAsync(inputFile, destinationDir, true).ConfigureAwait(false);
                }
                else
                {
                    error.WriteCommandText($"{inputFile} is not a valid folder to create a Templates Package.");
                }
            }
            catch (Exception ex)
            {
                error.WriteException(ex, "Unexpected exception extracting templates package.");
            }
        }
 public RemoteTemplatesSource(string platform, string language, string installedPackagePath, IDigitalSignatureService digitalSignatureService)
 {
     Platform             = platform;
     Language             = ProgrammingLanguages.GetShortProgrammingLanguage(language);
     InstalledPackagePath = installedPackagePath;
     _templatePackage     = new TemplatePackage(digitalSignatureService);
     CanGetNewContent     = digitalSignatureService.CanVerifySignatures;
 }
Exemple #11
0
        public async Task <TemplatePackage> InstallLatestAsync(string packageId)
        {
            TemplatePackage template = await this.GetLatestTemplatePackage(packageId, "any", this.appEnvironment.TemplatesPath).ConfigureAwait(false);

            await this.EnrichTemplatePackage(template).ConfigureAwait(false);

            return(template);
        }
        protected override string AcquireMstx()
        {
            var tempFolder = Path.Combine(GetTempFolder(), SourceFolderName);

            Copy($@"..\..\TestData\{SourceFolderName}", tempFolder);

            File.WriteAllText(Path.Combine(tempFolder, "version.txt"), _localVersion, Encoding.UTF8);

            return(TemplatePackage.Pack(tempFolder));
        }
Exemple #13
0
        public void PackAndSign_CertFromFile_RelativeInOutPath()
        {
            var certPass          = GetTestCertPassword();
            X509Certificate2 cert = TemplatePackage.LoadCert(@"Packaging\TestCert.pfx", certPass);

            var inFile  = @"Packaging\SampleContent.txt";
            var outFile = @"Packaging\SignedContent.package";

            TemplatePackage.PackAndSign(inFile, outFile, cert, MediaTypeNames.Text.Plain);
            Assert.True(File.Exists(outFile));
            File.Delete(outFile);
        }
Exemple #14
0
        public void PackAndSign_CertFromFile_AbsouluteInOutPath()
        {
            var certPass          = GetTestCertPassword();
            X509Certificate2 cert = TemplatePackage.LoadCert(@"Packaging\TestCert.pfx", certPass);

            var inFile  = Path.Combine(Environment.CurrentDirectory, @"Packaging\SampleContent.txt");
            var outFile = @"C:\temp\Packaging\SignedContent.package";

            TemplatePackage.PackAndSign(inFile, outFile, cert, MediaTypeNames.Text.Plain);
            Assert.True(File.Exists(outFile));
            File.Delete(outFile);
        }
Exemple #15
0
        public void PackAndSign_WithThumbprint()
        {
            EnsureTestCertificateInStore();

            var inFile  = Path.Combine(Environment.CurrentDirectory, @"Packaging\SampleContent.txt");
            var outFile = @"C:\temp\Packaging\SignedContent.package";

            TemplatePackage.PackAndSign(inFile, outFile, "B584589A382B2AD20B54D2DD1634BB487792A970", MediaTypeNames.Text.Plain);

            Assert.True(File.Exists(outFile));
            File.Delete(outFile);
        }
Exemple #16
0
        protected override string AcquireMstx()
        {
            // Compress Content adding version return TemplatePackage path.
            var tempFolder = Path.Combine(GetTempFolder(), SourceFolderName);

            Copy(Origin, tempFolder);

            Fs.CopyRecursive(@".\TestData\StyleCop", Path.Combine(tempFolder, "Features", "StyleCop"));

            File.WriteAllText(Path.Combine(tempFolder, "version.txt"), LocalTemplatesVersion);

            return(TemplatePackage.Pack(tempFolder));
        }
 private static void Extract(string mstxFilePath, string versionedFolder, bool verifyPackageSignatures = true)
 {
     try
     {
         TemplatePackage.Extract(mstxFilePath, versionedFolder, verifyPackageSignatures);
         AppHealth.Current.Verbose.TrackAsync($"{StringRes.TemplatesContentExtractedToString} {versionedFolder}.").FireAndForget();
     }
     catch (Exception ex)
     {
         AppHealth.Current.Exception.TrackAsync(ex, StringRes.TemplatesSourceExtractContentMessage).FireAndForget();
         throw;
     }
 }
Exemple #18
0
        public async Task ExtractConcurrentReadAsync()
        {
            var inFile  = @"Packaging\MsSigned\Templates.mstx";
            var outDir1 = @"C:\Temp\OutFolder\Concurrent1";
            var outDir2 = @"C:\Temp\OutFolder\Concurrent2";

            Task t1 = Task.Run(async() => await TemplatePackage.ExtractAsync(inFile, outDir1));
            Task t2 = Task.Run(async() => await TemplatePackage.ExtractAsync(inFile, outDir2));

            await Task.WhenAll(t1, t2);

            Directory.Delete(outDir1, true);
            Directory.Delete(outDir2, true);
        }
Exemple #19
0
        private async Task ExtractAsync(string mstxFilePath, string versionedFolder, bool verifyPackageSignatures = true, CancellationToken ct = default(CancellationToken))
        {
            try
            {
                await TemplatePackage.ExtractAsync(mstxFilePath, versionedFolder, verifyPackageSignatures, ReportExtractionProgress, ct);

                AppHealth.Current.Verbose.TrackAsync($"{StringRes.TemplatesContentExtractedToString} {versionedFolder}.").FireAndForget();
            }
            catch (Exception ex) when(ex.GetType() != typeof(OperationCanceledException))
            {
                AppHealth.Current.Exception.TrackAsync(ex, StringRes.TemplatesSourceExtractContentMessage).FireAndForget();
                throw;
            }
        }
Exemple #20
0
        private static void EnsureTestCertificateInStore()
        {
            SecureString ss = GetTestCertPassword();

            if (TemplatePackage.LoadCert("B584589A382B2AD20B54D2DD1634BB487792A970") == null)
            {
                X509Certificate2 c = new X509Certificate2(@"Packaging\TestCert.pfx", ss, X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet);

                X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
                store.Open(OpenFlags.ReadWrite);
                store.Add(c);
                store.Close();
            }
        }
Exemple #21
0
        public static async Task <int> ExecuteAsync(
            TemplateOptions options,
            IConsole console,
            IAppEnvironment appEnvironment,
            InvocationContext context = null)
        {
            console.Out.WriteLine($"Installing template from package '{options.PackageId}'");

            var templateSettingsManager       = new TemplateSettingsManager(appEnvironment);
            TemplatesSettings currentSettings = templateSettingsManager.LoadSettings() ?? new TemplatesSettings();

            var packageManager = new NuGetTemplatePackageManager(appEnvironment);

            if (currentSettings.Packages.Exists(x => x.PackageId == options.PackageId))
            {
                TemplatePackage package = currentSettings.Packages.Find(x => x.Id == options.PackageId);

                if (package != null)
                {
                    await packageManager.UnnstallAsync(package).ConfigureAwait(false);

                    currentSettings.Packages.Remove(package);

                    if (currentSettings.DefaultTemplate.PackageName == package.PackageId)
                    {
                        currentSettings.DefaultTemplate = new DefaultTemplate();
                    }
                }
            }

            TemplatePackage templatePackage =
                await packageManager.InstallLatestAsync(options.PackageId).ConfigureAwait(false);

            if (!currentSettings.Packages.Exists(x => x.Id == templatePackage.Id))
            {
                currentSettings.Packages.Add(templatePackage);
            }

            currentSettings.DefaultTemplate ??= new DefaultTemplate
            {
                ContentType = templatePackage.Templates.First().ContentType,
                PackageName = templatePackage.PackageId,
                PackagePath = templatePackage.InstalltionPath,
            };

            templateSettingsManager.SaveSettings(currentSettings);

            return(ReturnCodes.Ok);
        }
Exemple #22
0
        public void ValidateSignatureTamperedPackage()
        {
            var certPass          = GetTestCertPassword();
            X509Certificate2 cert = TemplatePackage.LoadCert(@"Packaging\TestCert.pfx", certPass);

            var inFile  = @"Packaging\SampleContent.txt";
            var outFile = @"Packaging\ToExtract.package";

            TemplatePackage.PackAndSign(inFile, outFile, cert, MediaTypeNames.Text.Plain);

            ModifyContent(outFile, "SampleContent.txt");

            Assert.False(TemplatePackage.ValidateSignatures(outFile));

            File.Delete(outFile);
        }
Exemple #23
0
        public void ExtractFileCurrentDir()
        {
            var certPass          = GetTestCertPassword();
            X509Certificate2 cert = TemplatePackage.LoadCert(@"Packaging\TestCert.pfx", certPass);

            var inFile        = @"Packaging\SampleContent.txt";
            var outFile       = @"ToExtract.package";
            var extractionDir = string.Empty;

            TemplatePackage.PackAndSign(inFile, outFile, cert, MediaTypeNames.Text.Plain);

            TemplatePackage.Extract(outFile, extractionDir);

            Assert.True(File.Exists(outFile));

            File.Delete(outFile);
        }
Exemple #24
0
        public async Task ExtractFileCurrentDirAsync()
        {
            var certPass          = GetTestCertPassword();
            X509Certificate2 cert = TemplatePackage.LoadCert(@"Packaging\TestCert.pfx", certPass);

            var inFile        = @"Packaging\SampleContent.txt";
            var outFile       = @"ToExtract.package";
            var extractionDir = string.Empty;

            await TemplatePackage.PackAndSignAsync(inFile, outFile, cert, MediaTypeNames.Text.Plain);

            await TemplatePackage.ExtractAsync(outFile, extractionDir, null, CancellationToken.None, true);

            Assert.True(File.Exists(outFile));

            File.Delete(outFile);
        }
Exemple #25
0
        public async Task Pack_FolderWithDefaultNamingAsync()
        {
            int filesInCurrentFolder = new DirectoryInfo(Environment.CurrentDirectory).GetFiles("*", SearchOption.AllDirectories).Count();
            var inFolder             = Environment.CurrentDirectory;
            var outDir     = @"C:\Temp\PackTests";
            var extractDir = Path.Combine(outDir, "Extraction");

            var outFile = await TemplatePackage.PackAsync(inFolder);

            await TemplatePackage.ExtractAsync(outFile, extractDir, null, CancellationToken.None, false);

            int filesInExtractionFolder = new DirectoryInfo(extractDir).GetFiles("*", SearchOption.AllDirectories).Count();

            Assert.Equal(filesInCurrentFolder, filesInExtractionFolder);

            File.Delete(outFile);
            Directory.Delete(outDir, true);
        }
Exemple #26
0
        public void Pack_FolderWithDefaultNaming()
        {
            int filesInCurrentFolder = new DirectoryInfo(Environment.CurrentDirectory).GetFiles("*", SearchOption.AllDirectories).Count();
            var inFolder             = Environment.CurrentDirectory;
            var outDir     = @"C:\Temp\PackTests";
            var extractDir = Path.Combine(outDir, "Extraction");

            var outFile = TemplatePackage.Pack(inFolder);

            TemplatePackage.Extract(outFile, extractDir, false);

            int filesInExtractionFolder = new DirectoryInfo(extractDir).GetFiles("*", SearchOption.AllDirectories).Count();

            Assert.Equal(filesInCurrentFolder, filesInExtractionFolder);

            File.Delete(outFile);
            Directory.Delete(outDir, true);
        }
Exemple #27
0
        public void Pack_Folder()
        {
            int filesInCurrentFolder = new DirectoryInfo(Environment.CurrentDirectory).GetFiles("*", SearchOption.AllDirectories).Count();
            var inFolder             = Environment.CurrentDirectory;
            var outDir     = @"C:\Temp\PackTests";
            var outFile    = Path.Combine(outDir, "JustPacked.mstx");
            var extractDir = Path.Combine(outDir, "Extraction");

            TemplatePackage.Pack(inFolder, outFile, MediaTypeNames.Text.Plain);

            TemplatePackage.Extract(outFile, extractDir, false);

            int filesInExtractionFolder = new DirectoryInfo(extractDir).GetFiles("*", SearchOption.AllDirectories).Count();

            Assert.Equal(filesInCurrentFolder, filesInExtractionFolder);

            Directory.Delete(outDir, true);
        }
Exemple #28
0
        public void ExtractFileAndPacksInCurrentDir()
        {
            var certPass          = GetTestCertPassword();
            X509Certificate2 cert = TemplatePackage.LoadCert(@"Packaging\TestCert.pfx", certPass);

            File.Copy(@"Packaging\SampleContent.txt", Path.Combine(Environment.CurrentDirectory, "NewFile.txt"), true);
            var inFile        = "NewFile.txt";
            var outFile       = @"ToExtract.package";
            var extractionDir = Environment.CurrentDirectory;

            TemplatePackage.PackAndSign(inFile, outFile, cert, MediaTypeNames.Text.Plain);

            TemplatePackage.Extract(outFile, extractionDir);

            Assert.True(Directory.Exists(extractionDir));
            Assert.True(File.Exists(Path.Combine(extractionDir, Path.GetFileName(inFile))));

            File.Delete(outFile);
        }
Exemple #29
0
        public void ExtractAbsoluteDirs()
        {
            var certPass          = GetTestCertPassword();
            X509Certificate2 cert = TemplatePackage.LoadCert(@"Packaging\TestCert.pfx", certPass);

            var inFile        = Path.Combine(Environment.CurrentDirectory, @"Packaging\SampleContent.txt");
            var outFile       = @"C:\Temp\MyPackage\ToExtract.package";
            var extractionDir = @"C:\Temp\NewContent\Extracted";

            TemplatePackage.PackAndSign(inFile, outFile, cert, MediaTypeNames.Text.Plain);

            TemplatePackage.Extract(outFile, extractionDir);

            Assert.True(Directory.Exists(extractionDir));
            Assert.True(File.Exists(Path.Combine(extractionDir, @"Packaging\SampleContent.txt")));

            File.Delete(outFile);
            Directory.Delete(extractionDir, true);
        }
Exemple #30
0
        public void ExtractRelativeDirs()
        {
            var certPass          = GetTestCertPassword();
            X509Certificate2 cert = TemplatePackage.LoadCert(@"Packaging\TestCert.pfx", certPass);

            var inFile        = @"Packaging\SampleContent.txt";
            var outFile       = @"Packaging\ToExtract.package";
            var extractionDir = "NewDirToExtract";

            TemplatePackage.PackAndSign(inFile, outFile, cert, MediaTypeNames.Text.Plain);

            TemplatePackage.Extract(outFile, extractionDir);

            Assert.True(Directory.Exists(extractionDir));
            Assert.True(File.Exists(Path.Combine(extractionDir, inFile)));

            File.Delete(outFile);
            Directory.Delete(extractionDir, true);
        }