Beispiel #1
0
		public PublicKey Open() {
			var dialog = new OpenFileDialog() {
				Filter = PickFilenameConstants.StrongNameKeyFilter,
				RestoreDirectory = true,
			};
			if (dialog.ShowDialog() != DialogResult.OK)
				return null;
			if (string.IsNullOrEmpty(dialog.FileName))
				return null;

			try {
				var snk = new StrongNameKey(dialog.FileName);
				return new PublicKey(snk.PublicKey);
			}
			catch {
			}

			try {
				var snk = new StrongNamePublicKey(dialog.FileName);
				return new PublicKey(snk.CreatePublicKey());
			}
			catch {
			}

			Shared.App.MsgBox.Instance.Show(string.Format(dnSpy_AsmEditor_Resources.Error_NotSNKFile, dialog.FileName), MsgBoxButton.OK, ownerWindow);
			return null;
		}
Beispiel #2
0
		/// <summary>
		///     Protects the stub using original project settings replace the current output with the protected stub.
		/// </summary>
		/// <param name="context">The working context.</param>
		/// <param name="fileName">The result file name.</param>
		/// <param name="module">The stub module.</param>
		/// <param name="snKey">The strong name key.</param>
		/// <param name="prot">The packer protection that applies to the stub.</param>
		protected void ProtectStub(ConfuserContext context, string fileName, byte[] module, StrongNameKey snKey, Protection prot = null) {
			string tmpDir = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
			string outDir = Path.Combine(tmpDir, Path.GetRandomFileName());
			Directory.CreateDirectory(tmpDir);

			for (int i = 0; i < context.OutputModules.Count; i++) {
				string path = Path.GetFullPath(Path.Combine(tmpDir, context.OutputPaths[i]));
				var dir = Path.GetDirectoryName(path);
				if (!Directory.Exists(dir))
					Directory.CreateDirectory(dir);
				File.WriteAllBytes(path, context.OutputModules[i]);
			}
			File.WriteAllBytes(Path.Combine(tmpDir, fileName), module);

			var proj = new ConfuserProject();
			proj.Seed = context.Project.Seed;
			foreach (Rule rule in context.Project.Rules)
				proj.Rules.Add(rule);
			proj.Add(new ProjectModule {
				Path = fileName
			});
			proj.BaseDirectory = tmpDir;
			proj.OutputDirectory = outDir;
			foreach (var path in context.Project.ProbePaths)
				proj.ProbePaths.Add(path);
			proj.ProbePaths.Add(context.Project.BaseDirectory);

			PluginDiscovery discovery = null;
			if (prot != null) {
				var rule = new Rule {
					Preset = ProtectionPreset.None,
					Inherit = true,
					Pattern = "true"
				};
				rule.Add(new SettingItem<Protection> {
					Id = prot.Id,
					Action = SettingItemAction.Add
				});
				proj.Rules.Add(rule);
				discovery = new PackerDiscovery(prot);
			}

			try {
				ConfuserEngine.Run(new ConfuserParameters {
					Logger = new PackerLogger(context.Logger),
					PluginDiscovery = discovery,
					Marker = new PackerMarker(snKey),
					Project = proj,
					PackerInitiated = true
				}, context.token).Wait();
			}
			catch (AggregateException ex) {
				context.Logger.Error("Failed to protect packer stub.");
				throw new ConfuserException(ex);
			}

			context.OutputModules = new[] { File.ReadAllBytes(Path.Combine(outDir, fileName)) };
			context.OutputPaths = new[] { fileName };
		}
Beispiel #3
0
		/// <summary>
		/// Calculates and returns the strong name signature
		/// </summary>
		/// <param name="snk">Strong name key used for signing</param>
		/// <param name="snSigOffset">Offset (relative to start of PE file) of the strong
		/// name signature.</param>
		/// <returns>The strong name signature</returns>
		public byte[] CalculateSignature(StrongNameKey snk, long snSigOffset) {
			uint snSigSize = (uint)snk.SignatureSize;
			var hashAlg = snk.HashAlgorithm == 0 ? AssemblyHashAlgorithm.SHA1 : snk.HashAlgorithm;
			var hash = StrongNameHashData(hashAlg, snSigOffset, snSigSize);
			var snSig = GetStrongNameSignature(snk, hashAlg, hash);
			if (snSig.Length != snSigSize)
				throw new InvalidOperationException("Invalid strong name signature size");
			return snSig;
		}
Beispiel #4
0
		public PublicKey Open() {
			var dialog = new OpenFileDialog() {
				Filter = PickFilenameConstants.StrongNameKeyFilter,
				RestoreDirectory = true,
			};
			if (dialog.ShowDialog() != DialogResult.OK)
				return null;
			if (string.IsNullOrEmpty(dialog.FileName))
				return null;

			try {
				var snk = new StrongNameKey(dialog.FileName);
				return new PublicKey(snk.PublicKey);
			}
			catch {
			}

			MainWindow.Instance.ShowMessageBox(string.Format("'{0}' is not a strong name key file (snk)", dialog.FileName), MessageBoxButton.OK, ownerWindow);
			return null;
		}
Beispiel #5
0
		/// <summary>
		/// Creates a counter signature, just like
		/// <c>sn -a IdentityPubKey.snk IdentityKey.snk SignaturePubKey.snk</c> can do.
		/// The public key <c>sn</c> prints is <paramref name="signaturePubKey"/>'s value.
		/// </summary>
		/// <param name="identityPubKey">Identity public key</param>
		/// <param name="identityKey">Identity strong name key pair</param>
		/// <param name="signaturePubKey">Signature public key</param>
		/// <returns>The counter signature</returns>
		public static byte[] CreateCounterSignature(StrongNamePublicKey identityPubKey, StrongNameKey identityKey, StrongNamePublicKey signaturePubKey) {
			var hash = AssemblyHash.Hash(signaturePubKey.CreatePublicKey(), identityPubKey.HashAlgorithm);
			using (var rsa = identityKey.CreateRSA()) {
				var rsaFmt = new RSAPKCS1SignatureFormatter(rsa);
				string hashName = identityPubKey.HashAlgorithm.GetName();
				rsaFmt.SetHashAlgorithm(hashName);
				var snSig = rsaFmt.CreateSignature(hash);
				Array.Reverse(snSig);
				return snSig;
			}
		}
Beispiel #6
0
		/// <summary>
		/// Creates a counter signature, just like
		/// <c>sn -a IdentityPubKey.snk IdentityKey.snk SignaturePubKey.snk</c> can do.
		/// The public key <c>sn</c> prints is <paramref name="signaturePubKey"/>'s value.
		/// </summary>
		/// <param name="identityPubKey">Identity public key</param>
		/// <param name="identityKey">Identity strong name key pair</param>
		/// <param name="signaturePubKey">Signature public key</param>
		/// <returns>The counter signature as a hex string</returns>
		public static string CreateCounterSignatureAsString(StrongNamePublicKey identityPubKey, StrongNameKey identityKey, StrongNamePublicKey signaturePubKey) {
			var counterSignature = CreateCounterSignature(identityPubKey, identityKey, signaturePubKey);
			return Utils.ToHex(counterSignature, false);
		}
Beispiel #7
0
 public PackerMarker(StrongNameKey snKey)
 {
     this.snKey = snKey;
 }
Beispiel #8
0
		/// <summary>
		/// Calculates the strong name signature and writes it to the stream. The signature
		/// is also returned.
		/// </summary>
		/// <param name="snk">Strong name key used for signing</param>
		/// <param name="snSigOffset">Offset (relative to the start of the PE file) of the strong
		/// name signature.</param>
		/// <returns>The strong name signature</returns>
		public byte[] WriteSignature(StrongNameKey snk, long snSigOffset) {
			var sign = CalculateSignature(snk, snSigOffset);
			stream.Position = baseOffset + snSigOffset;
			stream.Write(sign, 0, sign.Length);
			return sign;
		}
Beispiel #9
0
		/// <summary>
		/// Returns the strong name signature
		/// </summary>
		/// <param name="snk">Strong name key</param>
		/// <param name="hashAlg">Hash algorithm</param>
		/// <param name="hash">Strong name hash of the .NET PE file</param>
		/// <returns>Strong name signature</returns>
		byte[] GetStrongNameSignature(StrongNameKey snk, AssemblyHashAlgorithm hashAlg, byte[] hash) {
			using (var rsa = snk.CreateRSA()) {
				var rsaFmt = new RSAPKCS1SignatureFormatter(rsa);
				string hashName = hashAlg.GetName() ?? AssemblyHashAlgorithm.SHA1.GetName();
				rsaFmt.SetHashAlgorithm(hashName);
				var snSig = rsaFmt.CreateSignature(hash);
				Array.Reverse(snSig);
				return snSig;
			}
		}
Beispiel #10
0
        /// <summary>
        /// Adds or updates an existing <c>System.Reflection.AssemblySignatureKeyAttribute</c>
        /// attribute. This attribute is used in enhanced strong naming with key migration.
        /// See http://msdn.microsoft.com/en-us/library/hh415055.aspx
        /// </summary>
        /// <param name="identityPubKey">Identity public key</param>
        /// <param name="identityKey">Identity strong name key pair</param>
        /// <param name="signaturePubKey">Signature public key</param>
        public void UpdateOrCreateAssemblySignatureKeyAttribute(StrongNamePublicKey identityPubKey, StrongNameKey identityKey, StrongNamePublicKey signaturePubKey)
        {
            var manifestModule = ManifestModule;

            if (manifestModule == null)
            {
                return;
            }

            // Remove all existing attributes
            var ca = CustomAttributes.ExecuteLocked <CustomAttribute, object, CustomAttribute>(null, (tsList, arg) => {
                CustomAttribute foundCa = null;
                for (int i = 0; i < tsList.Count_NoLock(); i++)
                {
                    var caTmp = tsList.Get_NoLock(i);
                    if (caTmp.TypeFullName != "System.Reflection.AssemblySignatureKeyAttribute")
                    {
                        continue;
                    }
                    tsList.RemoveAt_NoLock(i);
                    i--;
                    if (foundCa == null)
                    {
                        foundCa = caTmp;
                    }
                }
                return(foundCa);
            });

            if (IsValidAssemblySignatureKeyAttribute(ca))
            {
                ca.NamedArguments.Clear();
            }
            else
            {
                ca = CreateAssemblySignatureKeyAttribute();
            }

            var counterSig = StrongNameKey.CreateCounterSignatureAsString(identityPubKey, identityKey, signaturePubKey);

            ca.ConstructorArguments[0] = new CAArgument(manifestModule.CorLibTypes.String, new UTF8String(signaturePubKey.ToString()));
            ca.ConstructorArguments[1] = new CAArgument(manifestModule.CorLibTypes.String, new UTF8String(counterSig));
            CustomAttributes.Add(ca);
        }
Beispiel #11
0
        /// <summary>
        /// Creates a counter signature, just like
        /// <c>sn -a IdentityPubKey.snk IdentityKey.snk SignaturePubKey.snk</c> can do.
        /// The public key <c>sn</c> prints is <paramref name="signaturePubKey"/>'s value.
        /// </summary>
        /// <param name="identityPubKey">Identity public key</param>
        /// <param name="identityKey">Identity strong name key pair</param>
        /// <param name="signaturePubKey">Signature public key</param>
        /// <returns>The counter signature</returns>
        public static byte[] CreateCounterSignature(StrongNamePublicKey identityPubKey, StrongNameKey identityKey, StrongNamePublicKey signaturePubKey)
        {
            var hash = AssemblyHash.Hash(signaturePubKey.CreatePublicKey(), identityPubKey.HashAlgorithm);

            using (var rsa = identityKey.CreateRSA()) {
                var    rsaFmt   = new RSAPKCS1SignatureFormatter(rsa);
                string hashName = identityPubKey.HashAlgorithm.GetName();
                rsaFmt.SetHashAlgorithm(hashName);
                var snSig = rsaFmt.CreateSignature(hash);
                Array.Reverse(snSig);
                return(snSig);
            }
        }
Beispiel #12
0
        /// <summary>
        /// Creates a counter signature, just like
        /// <c>sn -a IdentityPubKey.snk IdentityKey.snk SignaturePubKey.snk</c> can do.
        /// The public key <c>sn</c> prints is <paramref name="signaturePubKey"/>'s value.
        /// </summary>
        /// <param name="identityPubKey">Identity public key</param>
        /// <param name="identityKey">Identity strong name key pair</param>
        /// <param name="signaturePubKey">Signature public key</param>
        /// <returns>The counter signature as a hex string</returns>
        public static string CreateCounterSignatureAsString(StrongNamePublicKey identityPubKey, StrongNameKey identityKey, StrongNamePublicKey signaturePubKey)
        {
            var counterSignature = CreateCounterSignature(identityPubKey, identityKey, signaturePubKey);

            return(Utils.ToHex(counterSignature, false));
        }
Beispiel #13
0
        /// <summary>
        /// Adds or updates an existing <c>System.Reflection.AssemblySignatureKeyAttribute</c>
        /// attribute. This attribute is used in enhanced strong naming with key migration.
        /// See http://msdn.microsoft.com/en-us/library/hh415055.aspx
        /// </summary>
        /// <param name="identityPubKey">Identity public key</param>
        /// <param name="identityKey">Identity strong name key pair</param>
        /// <param name="signaturePubKey">Signature public key</param>
        public void UpdateOrCreateAssemblySignatureKeyAttribute(StrongNamePublicKey identityPubKey, StrongNameKey identityKey, StrongNamePublicKey signaturePubKey)
        {
            if (ManifestModule == null)
            {
                return;
            }

            // Remove all existing attributes
            CustomAttribute ca = null;

            for (int i = 0; i < CustomAttributes.Count; i++)
            {
                var caTmp = CustomAttributes[i];
                if (caTmp.TypeFullName != "System.Reflection.AssemblySignatureKeyAttribute")
                {
                    continue;
                }
                CustomAttributes.RemoveAt(i);
                i--;
                if (ca == null)
                {
                    ca = caTmp;
                }
            }

            if (IsValidAssemblySignatureKeyAttribute(ca))
            {
                ca.NamedArguments.Clear();
            }
            else
            {
                ca = CreateAssemblySignatureKeyAttribute();
            }

            var counterSig = StrongNameKey.CreateCounterSignatureAsString(identityPubKey, identityKey, signaturePubKey);

            ca.ConstructorArguments[0] = new CAArgument(ManifestModule.CorLibTypes.String, new UTF8String(signaturePubKey.ToString()));
            ca.ConstructorArguments[1] = new CAArgument(ManifestModule.CorLibTypes.String, new UTF8String(counterSig));
            CustomAttributes.Add(ca);
        }