c#安全-nativeAOT

文章目录

    • 前记
    • AOT测试
    • 反序列化
    • Emit

前记

JIT\AOT

JIT编译器(Just-in-Time Complier),AOT编译器(Ahead-of-Time Complier)。

在这里插入图片描述

AOT测试

首先编译一段普通代码

using System;
using System.Runtime.InteropServices;
namespace coleak
{class winfun{[DllImport("User32.dll")]public static extern int MessageBox(IntPtr h, string m, string c, uint type);[DllImport("kernel32.dll", EntryPoint = "Beep")]public static extern bool mymethod(uint frequency, uint duration);}class Program{static void Main(string[] args){winfun winfun = new winfun();winfun.MessageBox((IntPtr)0, "yueyy", "coleak",(uint) 0);Random random = new Random();for (int i = 0; i < 10000; i++){winfun.mymethod((uint)random.Next(10000), 100);}Console.ReadLine();}}
}

和csc直接编译相比,AOT发布确实可以防止dnspy出源码,但不能解决反汇编,该加壳还是得加壳

优点

不依赖.net框架环境也可以运行
不会被直接反编译而导致代码泄露

缺点

不能Assembly.Load进行动态加载
不支持32位程序

示例如下

using System;
using System.Reflection;
namespace LoadExe
{class Program{static void Main(string[] args)
{string base64string = @"";byte[] Buffer = Convert.FromBase64String(base64string);Assembly assembly = Assembly.Load(Buffer);Type type = assembly.GetType("DemoExe.Test");MethodInfo method = type.GetMethod("TestMethod");Object obj = assembly.CreateInstance(method.Name);method.Invoke(obj, null);
}}
}
Unhandled Exception: System.PlatformNotSupportedException: Operation is not supported on this platform.at Internal.Reflection.Execution.AssemblyBinderImplementation.Bind(ReadOnlySpan`1, ReadOnlySpan`1, AssemblyBindResult&, Exception&) + 0x39at System.Reflection.Runtime.Assemblies.RuntimeAssemblyInfo.GetRuntimeAssemblyFromByteArray(ReadOnlySpan`1, ReadOnlySpan`1) + 0x58at System.Reflection.Assembly.Load(Byte[], Byte[]) + 0xbeat LoadExe.Program.Main(String[] args) + 0x25at nativeAOT!<BaseAddress>+0x114a40

但是部分反射api仍然有效

using System;
using System.Reflection;
namespace LoadExe
{class Program{public static void Main(){Console.Write("Name of type: ");string typeName = "LoadExe.Program";string methodName = "SayHello";Type.GetType(typeName).GetMethod(methodName).Invoke(null, null);Console.ReadKey();}public static void SayHello(){Console.WriteLine("Hello!");}}
}

具体规则如下

1.APIs that don’t work and will not work

  • APIs that require dynamic code generation: Reflection.Emit, Assembly.Load and friends
  • Obvious program introspection APIs: APIs on Type and Assembly not mentioned above, MethodBase, MethodInfo, ConstructorInfo, FieldInfo, PropertyInfo, EventInfo. These APIs will throw at runtime.
  • APIs building on top of reflection APIs. Too many to enumerate.

2.Reflection-free mode supports a limited set of reflection APIs that keep their expected semantics.

  • typeof(SomeType) will return a System.Type that can be compared with results of other typeof expressions or results of Object.GetType() calls. The patterns commonly used in perf optimizations of generic code (e.g. typeof(T) == typeof(byte)) will work fine, and so will obj.GetType() == typeof(SomeType).
  • Following APIs on System.Type work: TypeHandle, UnderlyingSystemType, BaseType, IsByRefLike, IsValueType, GetTypeCode, GetHashCode, GetElementType, GetInterfaces, HasElementType, IsArray, IsByRef, IsPointer, IsPrimitive, IsAssignableFrom, IsAssignableTo, IsInstanceOfType.
  • Activator.CreateInstance() will work. The compiler statically analyzes and expands this to efficient code at compile time. No reflection is involved at runtime.
  • Assembly.GetExecutingAssembly() will return a System.Reflection.Assembly that can be compared with other runtime Assembly instances. This is mostly to make it possible to use the NativeLibrary.SetDllImportResolver API.

反序列化

JSON格式

using System;
using System.Runtime.Serialization.Json;//添加的引用
namespace ConsoleApp1
{public class Book{public int ID { get; set; }public string Name { get; set; }public float Price { get; set; }}public class Program{static void Main(string[] args){//序列化jsonBook book = new Book() { ID = 101, Name = "C#程序设计", Price = 79.5f };DataContractJsonSerializer formatter = new DataContractJsonSerializer(typeof(Book));using (MemoryStream stream = new MemoryStream()){formatter.WriteObject(stream, book);string result = System.Text.Encoding.UTF8.GetString(stream.ToArray());Console.WriteLine(result);}Console.WriteLine();//反序列化jsonstring oriStr = "{\"ID\":102,\"Name\":\"C# wpf程序设计\",\"Price\":100}";DataContractJsonSerializer formatter1 = new DataContractJsonSerializer(typeof(Book));using (MemoryStream stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(oriStr))){Book outBook = formatter1.ReadObject(stream) as Book;Console.WriteLine(outBook.ID);Console.WriteLine(outBook.Name);Console.WriteLine(outBook.Price);}Console.ReadLine();}}
}

Emit

using System;
using System.Reflection;
using System.Reflection.Emit;
using System.Text;namespace ConsoleApp1
{class Program{static void Main(string[] args){CreateAssembly();Console.ReadKey();}public static void CreateAssembly(){StringBuilder asmFileNameBldr = new StringBuilder();//定义一个程序集的名称var asmName = new AssemblyName("MyAssembly");//首先就需要定义一个程序集AssemblyBuilder defAssembly = AssemblyBuilder.DefineDynamicAssembly(asmName, AssemblyBuilderAccess.RunAndCollect);//定义一个构建类DefineDynamicModuleModuleBuilder defModuleBuilder = defAssembly.DefineDynamicModule("MyModule");//定义一个类TypeBuilder typeBuilder = defModuleBuilder.DefineType("MyModule.MyClass", TypeAttributes.Public);//定义一个方法var defMethodBuilder = typeBuilder.DefineMethod("MyMethod",MethodAttributes.Public,null,//返回类型null//参数类型);Console.WriteLine($"程序集信息:{typeBuilder.Assembly.FullName}");Console.WriteLine($"命名空间:{typeBuilder.Namespace} , 类型:{typeBuilder.Name}");//获取IL生成器var il = defMethodBuilder.GetILGenerator();//定义一个字符串il.Emit(OpCodes.Ldstr, "coleak");//调用一个函数il.Emit(OpCodes.Call, typeof(Console).GetMethod("WriteLine", new Type[] { typeof(string) }));//返回到方法开始(返回)il.Emit(OpCodes.Ret);//创建类型Type dynamicType = typeBuilder.CreateType();object ass = Activator.CreateInstance(dynamicType);dynamicType.GetMethod("MyMethod").Invoke(ass, null);}}
}

.NET Framework 中,有 RunAndSave 、Save 等枚举,可用于保存构建的程序集,但是在 .NET Core 中,是没有这些枚举的,也就是说,Emit 构建的程序集只能在内存中,是无法保存成 .dll 文件的

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/676359.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

全栈光量子计算系统公司ORCA宣布收购GXC的集成光子学部门

内容来源&#xff1a;量子前哨&#xff08;ID&#xff1a;Qforepost&#xff09; 编辑丨慕一 编译/排版丨沛贤 深度好文&#xff1a;1000字丨8分钟阅读 2024年1月30日&#xff0c;全栈光量子计算系统公司ORCA Computing宣布收购总部位于奥斯汀的GXC集成光子学部门。该部门主…

阿里云服务器租用价格表_2024一年_1个月_1小时收费价格表

2024年阿里云服务器租用价格表更新&#xff0c;云服务器ECS经济型e实例2核2G、3M固定带宽99元一年、ECS u1实例2核4G、5M固定带宽、80G ESSD Entry盘优惠价格199元一年&#xff0c;轻量应用服务器2核2G3M带宽轻量服务器一年61元、2核4G4M带宽轻量服务器一年165元12个月、2核4G服…

Flink on k8s之historyServer

1.Flink HistoryServer用途 HistoryServer可以在Flink 作业终止运行&#xff08;Flink集群关闭&#xff09;之后&#xff0c;还可以查询已完成作业的统计信息。此外&#xff0c;它对外提供了 REST API&#xff0c;它接受 HTTP 请求并使用 JSON 数据进行响应。Flink 任务停止后&…

探索设计模式的魅力:代理模式揭秘-软件世界的“幕后黑手”

设计模式专栏&#xff1a;http://t.csdnimg.cn/U54zu 目录 引言 一、魔法世界 1.1 定义与核心思想 1.2 静态代理 1.3 动态代理 1.4 虚拟代理 1.5 代理模式结构图 1.6 实例展示如何工作&#xff08;场景案例&#xff09; 不使用模式实现 有何问题 使用模式重构示例 二、…

SECS/GEM300需要实现哪些内容

GEM300实现设备全自动化&#xff0c;也是金南瓜已经全面支持功能&#xff0c;作为国内首家和最好的300mm标准软件。 GEM300包含E4、E5、E30、E37、E39、E40、E84、E87、E90、E94、E116等 CJob全称Conrtol Job 1. 控制设备作业的控制 2. 包括队列、开始、暂停、继续、完成等等…

STL之stack+queue的使用及其实现

STL之stackqueue的使用及其实现 1. stack&#xff0c;queue的介绍与使用1.1stack的介绍1.2stack的使用1.3queue的介绍1.4queue的使用 2.stack&#xff0c;queue的模拟实现2.1stack的模拟是实现2.2queue的模拟实现 3.总结 所属专栏&#xff1a;C“嘎嘎" 系统学习❤️ &…

SPSS基础操作:对数据按照样本观测值进行排序

在整理数据资料或者查看分析结果时&#xff0c;我们通常希望样本观测值能够按照某一变量的大小进行升序或者降序排列&#xff0c;比如我们想按照学生的学习成绩进行排序&#xff0c;按照销售额的大小对各个便利店进行排序等。以本章附带的数据4为例&#xff0c;如果要按照y4体重…

Linux探秘之旅:透彻理解路径、命令与系统概念

目录 如何远程连接 远程登录简明指南 linux区别 1.严格区分大小写 2.linux的命令返回结果判断 3.如何查看网络信息 4.关于后缀名&#xff08;Linux不关心文件后缀&#xff09; 4.1 需要记忆的后缀 5.echo命令 6.linux一切皆文件 6.1比如磁盘的文件 6.2可执行文件 …

SpringBoot配置文总结

官网配置手册 官网&#xff1a;https://spring.io/ 选择SpringBoot 选择LEARN 选择 Application Properties 配置MySQL数据库连接 针对Maven而言&#xff0c;会搜索出两个MySQL的连接驱动。 com.mysql mysql-connector-j 比较新&#xff0c;是在mysql mysql-connect…

【微机原理与单片机接口技术】MCS-51单片机的引脚功能介绍

前言 MCS-51是指由美国Intel公司生产的一系列单片机的总称。MCS-51系列单片机型号有很多&#xff0c;按功能分位基本型和增强型两大类&#xff0c;分别称为8051系列单片机和8052系列单片机&#xff0c;两者以芯片型号中的末位数字区分&#xff0c;1为基本型&#xff0c;2为增强…

springboot167基于springboot的医院后台管理系统的设计与实现

简介 【毕设源码推荐 javaweb 项目】基于springbootvue 的 适用于计算机类毕业设计&#xff0c;课程设计参考与学习用途。仅供学习参考&#xff0c; 不得用于商业或者非法用途&#xff0c;否则&#xff0c;一切后果请用户自负。 看运行截图看 第五章 第四章 获取资料方式 **项…

Sklearn、TensorFlow 与 Keras 机器学习实用指南第三版(七)

原文&#xff1a;Hands-On Machine Learning with Scikit-Learn, Keras, and TensorFlow 译者&#xff1a;飞龙 协议&#xff1a;CC BY-NC-SA 4.0 第十六章&#xff1a;使用 RNN 和注意力进行自然语言处理 当艾伦图灵在 1950 年想象他著名的Turing 测试时&#xff0c;他提出了…

linux(redhat)重置root密码

首先将root密码改成几乎不可能记住的密码 [rootexample ~]# echo fheowafuflaeijifehowf|passwd --stdin root Changing password for user root. passwd: all authentication tokens updated successfully.重启系统&#xff0c;进入救援模式 出现此页面&#xff0c;按e键 lin…

剑指offer——二维数组中的查找(杨氏矩阵)

目录 1. 题目描述2. 常见错误思路3. 分析3.1 特例分析3.2 规律总结 4. 完整代码 1. 题目描述 在一个二维数组中&#xff0c;每一行都按照从左到右递增的顺序排序&#xff0c;每一列都按照从上到下递增的顺序排序。请完成一个函数&#xff0c;输入这样的一个二维数组和一个整数&…

【精选】java初识多态 多态调用成员的特点

&#x1f36c; 博主介绍&#x1f468;‍&#x1f393; 博主介绍&#xff1a;大家好&#xff0c;我是 hacker-routing &#xff0c;很高兴认识大家~ ✨主攻领域&#xff1a;【渗透领域】【应急响应】 【python】 【VulnHub靶场复现】【面试分析】 &#x1f389;点赞➕评论➕收藏…

DBdoctor恭祝大家龙行龘龘,前程朤朤

值此新年之际&#xff0c;DBdoctor恭祝大家龙行龘龘&#xff0c;前程朤朤。尤其是当前还跟我一样奋斗在护航春节一线的战友们&#xff0c;祝愿大家2024年系统又快又稳。 今年是DBdoctor护航春晚的第三年&#xff0c;聚好看作为海信旗下的互联网科技公司&#xff0c;服务着海信…

MySQL-索引(INDEX)

文章目录 1. 索引概述及优劣势2. 索引结构和不同引擎对索引的支持情况2.1 Btree2.2 Hash索引 3. 索引分类4. 索引语法5. 索引在什么情况下会失效&#xff1f;5.1 最左前缀法则5.2 范围查询5.3 索引列运算5.4 头部模糊查询5.5 OR连接条件5.6 字符串不加引号5.7 数据分布影响 6. …

eosio.token 智能合约介绍

一、目的 eosio.token系统合约定义了允许用户为基于EOSIO的区块链创建、发行和管理代币的结构和操作&#xff0c;它演示了一种实现允许创建和管理代币的智能合约的方法。本文详细介绍了eosio.token系统合约并在本地测试链上实际发行了代币进行演示&#xff0c;适用于EOS智能合…

移动最小二乘法

移动最小二乘法&#xff08;Moving Least Square&#xff0c;MLS&#xff09;主要应用于曲线与曲面拟合&#xff0c;该方法基于紧支撑加权函数&#xff08;即函数值只在有限大小的封闭域中定义大于零&#xff0c;而在域外则定义为零&#xff09;和多项式基函数&#xff0c;通过…

【新书推荐】7.2节 寄存器寻址方式和直接寻址方式

本节内容&#xff1a;寄存器寻址方式的操作数在CPU内部的寄存器中&#xff0c;指令中指定寄存器号。 ■寄存器寻址方式&#xff1a;16位的寄存器操作数可以是AX、BX、CX、DX、SI、DI、SP、BP共计8个16位通用寄存器&#xff1b;8位寄存器操作数可以是AH、AL、BH、BL、CH、CL、D…