Exemplo n.º 1
0
        public bool IsMatch(MethodDefinition method)
        {
            if (IgnoreSystemMethods && IsSystemMethod(method))
            {
                return(true);
            }
            if (IgnorePInvokeMethods && method.IsPInvokeImpl)
            {
                return(true);
            }
            if (IsExceedMaxInstructionCount(method))
            {
                return(true);
            }

            if (method.ReturnType.FullName == "System.String")
            {
                if (IgnoreMethodsWithoutParam && method.Parameters.Count == 0)
                {
                    return(true);
                }
            }

            string name = method.ToString();

            if (IsMatch(name))
            {
                return(true);
            }
            name = "0x" + TokenUtils.GetFullMetadataTokenString(method.MetadataToken);
            if (IsMatch(name))
            {
                return(true);
            }
            return(false);
        }
Exemplo n.º 2
0
 private string GetTokenString(MetadataToken token)
 {
     return("0x" + TokenUtils.GetFullMetadataTokenString(token));
 }
        private string ReplaceReferencesToken(string file)
        {
            string newFile = Path.ChangeExtension(file, ".Repl.il");

            if (File.Exists(newFile))
            {
                File.Delete(newFile);
            }

            StreamReader sr = null;
            StreamWriter sw = null;

            try
            {
                string oldToken = Options.txtOldTokenText;
                string newToken = Options.txtNewTokenText;

                string oldStr1 = GetAssemblyReferenceString(oldToken);
                string newStr1 = GetAssemblyReferenceString(newToken);

                string oldStr2 = GetCAReferenceString(oldToken);
                string newStr2 = GetCAReferenceString(newToken);

                string newStr3 = GetCAInternalVisibleToReferenceString(Options.ReplKeyFile);
                Regex  rgStr3  = new Regex(@"PublicKey=[0123456789abcdefABCDEF]*");

                string oldBin2 = BytesUtils.BytesToHexString(Encoding.ASCII.GetBytes(oldStr2), true);
                string newBin2 = BytesUtils.BytesToHexString(Encoding.ASCII.GetBytes(newStr2), true);

                string newBin3 = BytesUtils.BytesToHexString(Encoding.ASCII.GetBytes(newStr3), true);
                //PublicKey=50 75 62 6C 69 63 4B 65 79 3D
                Regex rgBin3 = new Regex(@"50 75 62 6C 69 63 4B 65 79 3D [\d\s]+");

                sr = new StreamReader(file);
                sw = new StreamWriter(newFile, false, System.Text.Encoding.Unicode);

                string line;
                while ((line = sr.ReadLine()) != null)
                {
                    if (line.StartsWith(".assembly extern"))
                    {
                        sw.WriteLine(line);
                        while ((line = sr.ReadLine()) != null)
                        {
                            if (line.IndexOf(oldStr1) >= 0)
                            {
                                line = line.Replace(oldStr1, newStr1);
                            }

                            sw.WriteLine(line);

                            if (line == "}")
                            {
                                break;
                            }
                        }
                    }//end of if .assembly extern
                    else if (line.StartsWith("  .custom"))
                    {
                        StringBuilder sb = new StringBuilder();
                        //string lineStart = null;
                        string lineEnd  = null;
                        bool   isBinary = true;

                        while (line != null)
                        {
                            //remove comment
                            int p = line.LastIndexOf(" //");
                            if (p >= 0)
                            {
                                line = line.Substring(0, p);
                            }

                            line = line.Trim();
                            sb.Append(line);
                            sb.Append(" ");

                            if (lineEnd == null)
                            {
                                if (line.IndexOf("= {") >= 0)
                                {
                                    //lineStart = "= {";
                                    lineEnd  = "}";
                                    isBinary = false;
                                }
                                else if (line.IndexOf("= (") >= 0)
                                {
                                    //lineStart = "= (";
                                    lineEnd  = ")";
                                    isBinary = true;
                                }
                            }

                            if (lineEnd != null && line.EndsWith(lineEnd))
                            {
                                break;
                            }

                            line = sr.ReadLine();
                        }

                        line = sb.ToString();

                        if (isBinary)
                        {
                            if (line.IndexOf(oldBin2) > 0)
                            {
                                line = line.Replace(oldBin2, newBin2);
                            }
                            else
                            {
                                Match m = rgBin3.Match(line);
                                if (m.Success)
                                {
                                    string pubKeyString = m.Value.Trim().Substring("50 75 62 6C 69 63 4B 65 79 3D ".Length);
                                    pubKeyString = pubKeyString.Substring(0, pubKeyString.Length - 6); //remove " 00 00"
                                    byte[] pubKey = BytesUtils.HexStringToBytes(Encoding.ASCII.GetString(BytesUtils.HexStringToBytes(pubKeyString)));
                                    string token  = TokenUtils.GetPublicKeyTokenString(TokenUtils.GetPublicKeyToken(pubKey, Mono.Cecil.AssemblyHashAlgorithm.SHA1));
                                    if (token.Equals(oldToken, StringComparison.CurrentCultureIgnoreCase))
                                    {
                                        line = rgBin3.Replace(line, newBin3 + "00 00 ");
                                    }
                                }
                            }
                        }
                        else
                        {
                            if (line.IndexOf(oldStr2) > 0)
                            {
                                line = line.Replace(oldStr2, newStr2);
                            }
                            else
                            {
                                Match m = rgStr3.Match(line);
                                if (m.Success)
                                {
                                    string pubKeyString = m.Value.Substring("PublicKey=".Length);
                                    byte[] pubKey       = BytesUtils.HexStringToBytes(pubKeyString);
                                    string token        = TokenUtils.GetPublicKeyTokenString(TokenUtils.GetPublicKeyToken(pubKey, Mono.Cecil.AssemblyHashAlgorithm.SHA1));
                                    if (token.Equals(oldToken, StringComparison.CurrentCultureIgnoreCase))
                                    {
                                        line = rgStr3.Replace(line, newStr3);
                                    }
                                }
                            }
                        }

                        sw.WriteLine(line);
                    }//end of if .custom
                    else
                    {
                        sw.WriteLine(line);
                    }
                }
            }
            catch
            {
                throw;
            }
            finally
            {
                if (sr != null)
                {
                    sr.Close();
                }
                if (sw != null)
                {
                    sw.Close();
                }
            }
            return(newFile);
        }
Exemplo n.º 4
0
        private void FixAssemblyNameReference(AssemblyDefinition ad, StrongNameKeyPair sn)
        {
            Options.AppendTextInfo(String.Format("Fixing assembly reference: {0}\r\n", ad.Name.FullName));
            foreach (string name in _changedAssemblies.Keys)
            {
                if (name == ad.Name.Name)
                {
                    continue;
                }

                byte[] token  = null;
                byte[] pubKey = null;

                if (sn != null)
                {
                    pubKey = sn.PublicKey;
                    token  = TokenUtils.GetPublicKeyToken(pubKey, AssemblyHashAlgorithm.SHA1);
                }

                FixCustomAttributeReference(ad.CustomAttributes, name, token, pubKey);

                foreach (ModuleDefinition module in ad.Modules)
                {
                    foreach (AssemblyNameReference anr in module.AssemblyReferences)
                    {
                        if (anr.Name == name)
                        {
                            SetAssemblyNamePublicKey(anr, sn);
                            break;
                        }
                    }

                    foreach (TypeDefinition td in module.AllTypes)
                    {
                        FixCustomAttributeReference(td.CustomAttributes, name, token, pubKey);

                        foreach (PropertyDefinition pd in td.Properties)
                        {
                            FixCustomAttributeReference(pd.CustomAttributes, name, token, pubKey);
                        }
                        foreach (MethodDefinition method in td.Methods)
                        {
                            FixCustomAttributeReference(method.CustomAttributes, name, token, pubKey);
                        }
                        foreach (FieldDefinition fd in td.Fields)
                        {
                            FixCustomAttributeReference(fd.CustomAttributes, name, token, pubKey);
                        }
                        foreach (EventDefinition ed in td.Events)
                        {
                            FixCustomAttributeReference(ed.CustomAttributes, name, token, pubKey);
                        }
                    }

                    foreach (Resource r in module.Resources)
                    {
                        if (r is EmbeddedResource)
                        {
                            EmbeddedResource er = (EmbeddedResource)r;
                            FixByteReference(er.GetResourceData(), name, token);
                        }
                        else if (r is AssemblyLinkedResource)
                        {
                            AssemblyLinkedResource alr = (AssemblyLinkedResource)r;
                            if (alr.Assembly.Name == name)
                            {
                                SetAssemblyNamePublicKey(alr.Assembly, sn);
                            }
                        }
                        //else if (r is LinkedResource)
                        //{
                        //    LinkedResource lr = (LinkedResource)r;
                        //}
                    }
                }//end of each module
            }

            Application.DoEvents();
        }
Exemplo n.º 5
0
        private void FixByteReference(byte[] bytes, string adName, byte[] token)
        {
            const int TOKEN_LEN = 16;

            string searchName = String.Format("{0}, Version=", adName);

            byte[] searchBytes = Encoding.UTF8.GetBytes(searchName);

            string searchToken = "PublicKeyToken=";

            byte[] searchTokenBytes = Encoding.UTF8.GetBytes(searchToken);

            string searchNull = "null";

            byte[] searchNullBytes = Encoding.UTF8.GetBytes(searchNull);

            string searchNullLong = "null            ";//16 bytes

            byte[] searchNullLongBytes = Encoding.UTF8.GetBytes(searchNullLong);

            string tokenString = TokenUtils.GetReferenceTokenString(token);

            byte[] tokenStringBytes = Encoding.UTF8.GetBytes(tokenString);

            int index = BytesUtils.ByteSearch(bytes, searchBytes, 0, bytes.Length);

            while (index > 0)
            {
                index = BytesUtils.ByteSearch(bytes, searchTokenBytes, index + searchBytes.Length, bytes.Length - index - searchBytes.Length);
                if (index > 0)
                {
                    index = index + searchTokenBytes.Length;

                    if (token == null)
                    {
                        if (BytesUtils.ByteSearch(bytes, searchNullBytes, index, searchNullBytes.Length) == index)
                        {
                        }
                        else
                        {
                            for (int i = 0; i < searchNullBytes.Length; i++)
                            {
                                bytes[index + i] = searchNullBytes[i];
                            }
                            index += searchNullBytes.Length;
                            for (int i = 0; i < TOKEN_LEN - searchNullBytes.Length; i++)
                            {
                                bytes[index + i] = 0x20;
                            }
                        }
                    }
                    else
                    {
                        if (BytesUtils.ByteSearch(bytes, searchNullBytes, index, searchNullBytes.Length) == index)
                        {
                            if (BytesUtils.ByteSearch(bytes, searchNullLongBytes, index, searchNullLongBytes.Length) == index)
                            {
                                for (int i = 0; i < tokenStringBytes.Length; i++)
                                {
                                    bytes[index + i] = tokenStringBytes[i];
                                }
                            }
                            else
                            {
                                #region complicated, found PublicKeyToken=null and need to extend space to sign, ignore now

                                /*
                                 * //1. extend bytes array
                                 * //2. amend bytes length for custom attribute or resource
                                 * //
                                 * // below is old code for custom attribute only
                                 * {
                                 *  int endIndex = index + 4;
                                 *  int sizeIndex = 2;
                                 *  bool ok = false;
                                 *  if (endIndex - sizeIndex - 1 == (int)bytes[sizeIndex])
                                 *  {
                                 *      ok = true;
                                 *  }
                                 *  else
                                 *  {
                                 *      sizeIndex++;
                                 *      if (endIndex - sizeIndex - 1 == (int)bytes[sizeIndex])
                                 *      {
                                 *          ok = true;
                                 *      }
                                 *  }
                                 *
                                 *  if (ok)//need to extend
                                 *  {
                                 *      byte[] newBytes = new byte[bytes.Length + 12];
                                 *      Array.Copy(bytes, newBytes, index);
                                 *      Array.Copy(tokenStringBytes, newBytes, tokenStringBytes.Length);
                                 *      for (int i = index + 4; i < bytes.Length; i++)
                                 *      {
                                 *          newBytes[i + 12] = bytes[i];
                                 *      }
                                 *      newBytes[sizeIndex] += 12;
                                 *
                                 *      result = newBytes;
                                 *      bytes = newBytes;
                                 *  }
                                 *  else
                                 *  {
                                 *      endIndex = index + 16;
                                 *      sizeIndex = 2;
                                 *      ok = false;
                                 *      if (endIndex - sizeIndex - 1 == (int)bytes[sizeIndex])
                                 *      {
                                 *          ok = true;
                                 *      }
                                 *      else
                                 *      {
                                 *          sizeIndex++;
                                 *          if (endIndex - sizeIndex - 1 == (int)bytes[sizeIndex])
                                 *          {
                                 *              ok = true;
                                 *          }
                                 *      }
                                 *
                                 *      if (ok) //enough room
                                 *      {
                                 *          for (int i = 0; i < tokenStringBytes.Length; i++)
                                 *          {
                                 *              bytes[index + i] = tokenStringBytes[i];
                                 *          }
                                 *      }
                                 *  }
                                 * }
                                 */
                                #endregion complicated, found PublicKeyToken=null and need to extend space to sign
                            }
                        }
                        else
                        {
                            for (int i = 0; i < tokenStringBytes.Length; i++)
                            {
                                bytes[index + i] = tokenStringBytes[i];
                            }
                        }
                    }

                    index = BytesUtils.ByteSearch(bytes, searchBytes, index + searchTokenBytes.Length, bytes.Length - index - searchTokenBytes.Length);
                } //end if searchToken found
            }     //end if searchName found
        }
        private void AddFiles(string path, string match)
        {
            try
            {
                escPressed = false;

                DirectoryInfo di         = new DirectoryInfo(path + Path.DirectorySeparatorChar);
                FileInfo[]    files      = di.GetFiles(match);
                bool          isAssembly = PathUtils.IsAssembly(match);

                foreach (FileInfo file in files)
                {
                    if (escPressed)
                    {
                        break;
                    }
                    if (file.Length == 0)
                    {
                        continue;
                    }

                    SetStatusText(String.Format("Press ESC to cancel: {0}", file.FullName));
                    try
                    {
                        if (isAssembly)
                        {
                            //try
                            //{
                            //    AssemblyName an = AssemblyName.GetAssemblyName(file.FullName);
                            //    DataRow dr = dtFiles.NewRow();
                            //    dr["file_name"] = file.Name;
                            //    dr["assembly_name"] = an.Name;
                            //    dr["version"] = an.Version.ToString();
                            //    dr["public_token"] = TokenUtils.GetPublicKeyTokenString(an);
                            //    dr["processor_architecture"] = an.ProcessorArchitecture == ProcessorArchitecture.None ? String.Empty : an.ProcessorArchitecture.ToString();
                            //    dr["full_name"] = an.FullName;
                            //    dtFiles.Rows.Add(dr);
                            //}
                            //catch (BadImageFormatException)

                            if (PathUtils.IsNetModule(file.FullName))
                            {
                                ModuleDefinition md = ModuleDefinition.ReadModule(file.FullName);
                                DataRow          dr = dtFiles.NewRow();
                                dr["file_name"]              = file.Name;
                                dr["assembly_name"]          = String.Empty;
                                dr["version"]                = String.Empty;
                                dr["public_token"]           = null;
                                dr["target_runtime"]         = md.Runtime.ToString().Replace("Net_", "").Replace("_", ".");
                                dr["processor_architecture"] = GetProcessorArchitecture(md);
                                dr["full_name"]              = md.FullyQualifiedName;
                                dtFiles.Rows.Add(dr);
                            }
                            else
                            {
                                AssemblyDefinition     ad = AssemblyDefinition.ReadAssembly(file.FullName);
                                AssemblyNameDefinition an = ad.Name;
                                DataRow dr = dtFiles.NewRow();
                                dr["file_name"]              = file.Name;
                                dr["assembly_name"]          = an.Name;
                                dr["version"]                = an.Version.ToString();
                                dr["public_token"]           = TokenUtils.GetPublicKeyTokenString(an.PublicKeyToken);
                                dr["target_runtime"]         = ad.MainModule.Runtime.ToString().Replace("Net_", "").Replace("_", ".");
                                dr["processor_architecture"] = GetProcessorArchitecture(ad.MainModule);
                                dr["full_name"]              = an.FullName;
                                dtFiles.Rows.Add(dr);
                            }
                        }
                        else
                        {
                            DataRow dr = dtFiles.NewRow();
                            dr["file_name"] = file.Name;
                            dr["full_name"] = file.FullName;
                            dtFiles.Rows.Add(dr);
                        }
                    }
                    catch
                    {
                        //not .net assembly
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                SetStatusText(null);
            }
        }