绕过C#的类型保护,并在String中存储一个整数 [英] Bypassing C#'s type safeguards and storing an Integer in a String

查看:241
本文介绍了绕过C#的类型保护,并在String中存储一个整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

查看以下代码:

static void Main(string[] args)
{
    string s = null;
    string[] myArray = new string[1];

    { } // do something evil here

    if (s.GetType() == typeof(int))
    {
        Console.WriteLine("This should not happen!"); 
    }
    Console.ReadLine();
}

有没有办法获得这不应该发生写?有人会假设不是。但是,可以使用调试器:将断点放入行 {} //执行某些恶意在这里并在立即窗口中执行以下命令,然后继续:

Is there any way to get This should not happen to write? One would assume not. However, it can be done with the debugger: Put a breakpoint into the line { } // do something evil here and execute the following commands in the Immediate Window before continuing:

((object[])myArray)[0] = 99;
s = myArray[0];

执行继续,不应该发生打印。用Visual Studio 2008测试;这是一个截图:

Execution continues and This should not happen will be printed. Tested with Visual Studio 2008; here is a screenshot:

这种欺骗只能在调试器中使用,还是有一些方法在代码中执行这样一个不安全的作业?

Is this kind of trickery only possible with the debugger or is there some way to do such an "unsafe assignment" in code?

(显然,我只想出科学的好奇心。这个问题和相关评论让我问这个问题。 )

(Obviously, I ask only out of scientific curiosity. This question and the related comments made me ask this question.)

推荐答案

一种技术是使用 LayoutKind.Explicit 来实现联合这可以用来重新解释将任意对象转换为字符串。第一个框是一个int,然后将它分配给该联合的对象字段,然后读出字符串字段。

One technique is using LayoutKind.Explicit to implement a union which can be used to reinterpret cast an arbitrary object to string. First box an int, then assign it to the object field of the union and then read out the string field.

[StructLayout(LayoutKind.Explicit)]
public struct Evil
{
    [FieldOffset(0)]
    public string s;

    [FieldOffset(0)]
    public object o;
}

string ReinterpretCastToString(object o)
{
    Evil evil=new Evil();
    evil.o=o;
    return evil.s;
}

void Main()
{
    string s = ReinterpretCastToString(1);

    if (s.GetType() == typeof(int))
    {
        Console.WriteLine("This should not happen!"); 
    }
}

这很可能是未定义的行为,可能会停止工作任何时候。显然你不应该在一个真实的程序中使用这个。

This is most likely undefined behavior that may stop working at any time. Obviously you shouldn't use this in a real program.

这篇关于绕过C#的类型保护,并在String中存储一个整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆