Exemple #1
0
 static void Main(string[] args)
 {
     using (var package = new InstallPackage(@"C:\test.msi", DatabaseOpenMode.ReadOnly))
     {
         package.ExtractFiles();
     }
 }
Exemple #2
0
        /// <summary>
        /// Extracts files from an MSI database and rewrites the paths embedded in the source .wixpdb to the output .wixpdb.
        /// </summary>
        private void MeltProduct()
        {
            // print friendly message saying what file is being decompiled
            Console.WriteLine("{0} / {1}", Path.GetFileName(this.inputFile), Path.GetFileName(this.inputPdbFile));

            // extract files from the .msi (unless suppressed) and get the path map of File ids to target paths
            string outputDirectory             = this.exportBasePath ?? Environment.GetEnvironmentVariable("WIX_TEMP");
            IDictionary <string, string> paths = null;

            using (InstallPackage package = new InstallPackage(this.inputFile, DatabaseOpenMode.ReadOnly, null, outputDirectory))
            {
                if (!this.suppressExtraction)
                {
                    package.ExtractFiles();
                }

                paths = package.Files.SourcePaths;
            }

            Pdb   inputPdb     = Pdb.Load(this.inputPdbFile, true, true);
            Table wixFileTable = inputPdb.Output.Tables["WixFile"];

            if (null != wixFileTable)
            {
                foreach (Row row in wixFileTable.Rows)
                {
                    WixFileRow fileRow = row as WixFileRow;
                    if (null != fileRow)
                    {
                        string newPath;
                        if (paths.TryGetValue(fileRow.File, out newPath))
                        {
                            fileRow.Source = Path.Combine(outputDirectory, newPath);
                        }
                    }
                }
            }

            string tempPath = Path.Combine(Environment.GetEnvironmentVariable("WIX_TEMP") ?? Path.GetTempPath(), Path.GetRandomFileName());

            try
            {
                inputPdb.Save(this.outputFile, null, null, tempPath);
            }
            finally
            {
                if (this.tidy)
                {
                    if (!AppCommon.DeleteDirectory(tempPath, this.messageHandler))
                    {
                        Console.WriteLine(MeltStrings.WAR_FailedToDeleteTempDir, tempPath);
                    }
                }
                else
                {
                    Console.WriteLine(MeltStrings.INF_TempDirLocatedAt, tempPath);
                }
            }
        }
        /// <summary>
        /// Extracts the files contained in the msi.
        /// </summary>
        /// <param name="msiFile">The msi file to extract.</param>
        /// <param name="path">The path to extract the files to.</param>
        /// <returns>List of files in MSI.</returns>
        public string[] ExtractFilesInMsi(string msiFile, string path)
        {
            _ = msiFile ?? throw new ArgumentNullException(nameof(msiFile));
            _ = path ?? throw new ArgumentNullException(nameof(path));

            using (var package = new InstallPackage(msiFile, DatabaseOpenMode.ReadOnly, null, path))
            {
                package.ExtractFiles();
            }

            var msiFiles = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories);
            return msiFiles;
        }
        /// <summary>
        /// Extracts files from an MSI database and rewrites the paths embedded in the source .wixpdb to the output .wixpdb.
        /// </summary>
        private void MeltProduct()
        {
            // print friendly message saying what file is being decompiled
            Console.WriteLine("{0} / {1}", Path.GetFileName(this.inputFile), Path.GetFileName(this.inputPdbFile));

            Pdb inputPdb = Pdb.Load(this.inputPdbFile, true);

            // extract files from the .msi (unless suppressed) and get the path map of File ids to target paths
            string outputDirectory             = this.exportBasePath ?? Environment.GetEnvironmentVariable("WIX_TEMP");
            IDictionary <string, string> paths = null;

            using (InstallPackage package = new InstallPackage(this.inputFile, DatabaseOpenMode.ReadOnly, null, outputDirectory))
            {
                // ignore failures as this is a new validation in v3.x
                ValidateMsiMatchesPdb(package, inputPdb);

                if (!this.suppressExtraction)
                {
                    package.ExtractFiles();
                }

                paths = package.Files.SourcePaths;
            }

            Table wixFileTable = inputPdb.Output.Tables["WixFile"];

            if (null != wixFileTable)
            {
                foreach (Row row in wixFileTable.Rows)
                {
                    WixFileRow fileRow = row as WixFileRow;
                    if (null != fileRow)
                    {
                        string newPath;
                        if (paths.TryGetValue(fileRow.File, out newPath))
                        {
                            fileRow.Source = Path.Combine(outputDirectory, newPath);
                        }
                    }
                }
            }

            inputPdb.Save(this.outputFile);
        }
Exemple #5
0
        /// <summary>
        /// Method:         dsExtractAllStreamsEngine
        /// Description:    This  method is used to extract all the data streams and also to extract all files based
        ///                 on the option selected. Interestingly this uses WiX DTF rather than the COM Approach used
        ///                 in the other code file
        /// </summary>
        /// <param name="iFile"></param>
        /// <param name="streamFlag"></param>
        public static void dsExtractAllStreamsEngine(string iFile, int streamFlag)
        {
            InstallPackage winInstaller = new InstallPackage(iFile, DatabaseOpenMode.ReadOnly);

            winInstaller.Message += new InstallPackageMessageHandler(Console.WriteLine);
            string workingDir = System.Environment.GetEnvironmentVariable("TEMP");

            workingDir = (workingDir + "\\" + iFile);
            bool chkAppFolder = System.IO.Directory.Exists(workingDir);

            if (!chkAppFolder)
            {
                System.IO.Directory.CreateDirectory(workingDir);
            }


            if (streamFlag == 1)
            {
                try
                {
                    winInstaller.ExportAll(workingDir);
                    Console.Clear();
                    Program.copyrightBanner();
                    Console.ForegroundColor = ConsoleColor.White;
                    Console.WriteLine("The data streams from the provided MSI Database has been extracted.");
                    Console.WriteLine("\nExtracted Streams are saved here: \n" + workingDir);
                    Console.ResetColor();
                }

                catch (System.ArgumentException ex)
                {
                    Console.Clear();
                    Program.copyrightBanner();
                    Console.ForegroundColor = ConsoleColor.White;
                    Console.WriteLine("The data streams from the provided MSI Database has been extracted.");
                    Console.ForegroundColor = ConsoleColor.White;
                    Console.WriteLine("\nExtracted Streams are saved here: \n" + workingDir);
                    Console.ForegroundColor = ConsoleColor.DarkRed;
                    Console.WriteLine("\nWarning:");
                    Console.ForegroundColor = ConsoleColor.DarkRed;
                    Console.WriteLine("\nSome data streams within the MSI Database contains Illegal Path Characters" +
                                      "\nin its name and hence may not get extracted.", ex.Message);
                    Console.ResetColor();
                }
            }

            else if (streamFlag == 0)
            {
                try
                {
                    Console.Clear();
                    Program.copyrightBanner();
                    Console.ForegroundColor = ConsoleColor.White;
                    Console.WriteLine("The input Windows Installer Database is : " + iFile);
                    Console.WriteLine("\nExtracting the files inside the Windows Installer Database, please wait...");
                    winInstaller.WorkingDirectory = workingDir;
                    TextWriter stdOutput = Console.Out;
                    Console.SetOut(TextWriter.Null);
                    winInstaller.ExtractFiles();
                    Console.SetOut(stdOutput);
                    Console.ForegroundColor = ConsoleColor.White;
                    Console.WriteLine("\nExtracted files can be found at : \n" + workingDir);
                    Console.ResetColor();
                }

                catch (System.Exception ex)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("Error:\nAn error encountered during the extract process, please check parameters." + ex.Message);
                    Console.ResetColor();
                }
            }
        }
Exemple #6
0
    public static int Main(string[] args)
    {
        if (!(args.Length == 2 || args.Length == 3))
        {
            Usage(Console.Out);
            return(-1);
        }

        string msiFile = args[0];

        string option = args[1].ToLowerInvariant();

        if (option.StartsWith("-", StringComparison.Ordinal))
        {
            option = "/" + option.Substring(1);
        }

        string[] fileNames = null;
        if (args.Length == 3)
        {
            fileNames = args[2].Split(',');
        }

        try
        {
            switch (option)
            {
            case "/l":
                using (InstallPackage pkg = new InstallPackage(msiFile, DatabaseOpenMode.ReadOnly))
                {
                    pkg.Message += new InstallPackageMessageHandler(Console.WriteLine);
                    IEnumerable <string> fileKeys = (fileNames != null ? FindFileKeys(pkg, fileNames) : pkg.Files.Keys);

                    foreach (string fileKey in fileKeys)
                    {
                        Console.WriteLine(pkg.Files[fileKey]);
                    }
                }
                break;

            case "/x":
                using (InstallPackage pkg = new InstallPackage(msiFile, DatabaseOpenMode.ReadOnly))
                {
                    pkg.Message += new InstallPackageMessageHandler(Console.WriteLine);
                    ICollection <string> fileKeys = FindFileKeys(pkg, fileNames);

                    pkg.ExtractFiles(fileKeys);
                }
                break;

            case "/u":
                using (InstallPackage pkg = new InstallPackage(msiFile, DatabaseOpenMode.Transact))
                {
                    pkg.Message += new InstallPackageMessageHandler(Console.WriteLine);
                    ICollection <string> fileKeys = FindFileKeys(pkg, fileNames);

                    pkg.UpdateFiles(fileKeys);
                    pkg.Commit();
                }
                break;

            default:
                Usage(Console.Out);
                return(-1);
            }
        }
        catch (InstallerException iex)
        {
            Console.WriteLine("Error: " + iex.Message);
            return(iex.ErrorCode != 0 ? iex.ErrorCode : 1);
        }
        catch (FileNotFoundException fnfex)
        {
            Console.WriteLine(fnfex.Message);
            return(2);
        }
        catch (Exception ex)
        {
            Console.WriteLine("Error: " + ex.Message);
            return(1);
        }
        return(0);
    }
Exemple #7
0
        public override SignatureVerificationResult VerifySignature(string path, string parent, string virtualPath)
        {
            SignatureVerificationResult svr = base.VerifySignature(path, parent, virtualPath);

            if (VerifyRecursive)
            {
                CreateDirectory(svr.TempPath);

                // TODO: Fix for MSIs with external CABs that are not present.
                using (var installPackage = new InstallPackage(svr.FullPath, DatabaseOpenMode.Transact, sourceDir: null, workingDir: svr.TempPath))
                {
                    InstallPathMap files         = installPackage.Files;
                    var            originalFiles = new Dictionary <string, string>();

                    // Flatten the files to avoid path too long errors. We use the File column and extension to create a unique file
                    // and record the original, relative MSI path in the result.
                    foreach (string key in installPackage.Files.Keys)
                    {
                        originalFiles[key] = installPackage.Files[key].TargetPath;
                        string name       = key + Path.GetExtension(installPackage.Files[key].TargetName);
                        string targetPath = Path.Combine(svr.TempPath, name);
                        installPackage.Files[key].TargetName = name;
                        installPackage.Files[key].SourceName = name;
                        installPackage.Files[key].SourcePath = targetPath;
                        installPackage.Files[key].TargetPath = targetPath;
                    }

                    try
                    {
                        Log.WriteMessage(LogVerbosity.Diagnostic, SignCheckResources.DiagExtractingFileContents, svr.TempPath);
                        installPackage.ExtractFiles(installPackage.Files.Keys);

                        foreach (string key in installPackage.Files.Keys)
                        {
                            SignatureVerificationResult packageFileResult = VerifyFile(installPackage.Files[key].TargetPath, svr.Filename, Path.Combine(svr.VirtualPath, originalFiles[key]), containerPath: null);
                            packageFileResult.AddDetail(DetailKeys.File, SignCheckResources.DetailFullName, originalFiles[key]);
                            svr.NestedResults.Add(packageFileResult);
                        }
                    }
                    catch (Exception e)
                    {
                        Log.WriteError(e.Message);
                    }
                }

                // Extract files from the Binary table - this is where items such as custom actions are stored.
                try
                {
                    using (var installDatabase = new Database(svr.FullPath, DatabaseOpenMode.ReadOnly))
                        using (View view = installDatabase.OpenView("SELECT `Name`, `Data` FROM `Binary`"))
                        {
                            view.Execute();

                            foreach (Record record in view)
                            {
                                string binaryFile     = (string)record["Name"];
                                string binaryFilePath = Path.Combine(svr.TempPath, binaryFile);
                                StructuredStorage.SaveStream(record, svr.TempPath);
                                SignatureVerificationResult binaryStreamResult = VerifyFile(binaryFilePath, svr.Filename, Path.Combine(svr.VirtualPath, binaryFile), containerPath: null);
                                binaryStreamResult.AddDetail(DetailKeys.Misc, SignCheckResources.FileExtractedFromBinaryTable);
                                svr.NestedResults.Add(binaryStreamResult);
                                record.Close();
                            }
                        }
                }
                catch (Exception e)
                {
                    Log.WriteError(e.Message);
                }

                DeleteDirectory(svr.TempPath);
            }

            return(svr);
        }