现在的位置: 首页 > 综合 > 正文

C中位比特操作

2013年08月15日 ⁄ 综合 ⁄ 共 2029字 ⁄ 字号 评论关闭

晚上睡不着,看到这么一个网页http://www.securityfocus.com/archive/1/526439/30/0/threaded

The vulnerability is caused by a int overflow error within the Nginx
ngx_http_close_connection function when r->count is less then 0 or more then 255, which could be exploited
by remote attackers to compromise a vulnerable system via malicious http requests.

大致意思是nginx可能会由于位比特溢出造成exploit。

于是试了一下位比特累加操作。代码如下:

#include <stdio.h>

struct bit{
        unsigned f:5;
        unsigned g:29;
};

int main(){
        struct bit a = {0};
        int i = 0;

        __asm("nop");
        __asm("nop");
        __asm("nop");
        __asm("nop");
        for(i = 0; i < 127; i++){
                __asm("nop");
                __asm("nop");
                __asm("nop");
                __asm("nop");
                __asm("nop");
                a.f++;
                __asm("nop");
                __asm("nop");
                __asm("nop");
                __asm("nop");
                __asm("nop");
        }
        printf("a.f = %d\n", a.f);
        printf("a.g = %d\n", a.g);
        return 0;
}

===================================================================================

root@bogon /tmp # ./a.out
a.f = 31
a.g = 0

可以看出没有溢出情况出现。

===================================================================================

看看汇编代码:

for循环的处理代码如下:

MOVZ Instruction:To convert an unsigned integer to a wider unsigned integer

movzbl指令负责拷贝一个字节,并用0填充其目的操作数中的其余各位,这种扩展方式叫“零扩展”。

0x080483ce <main+42>:   movl   $0x0,-0x8(%ebp)
0x080483d5 <main+49>:   jmp    0x8048403 <main+95>
0x080483d7 <main+51>:   nop
0x080483d8 <main+52>:   nop
0x080483d9 <main+53>:   nop
0x080483da <main+54>:   nop
0x080483db <main+55>:   nop
0x080483dc <main+56>:   movzbl -0x10(%ebp),%eax
0x080483e0 <main+60>:   and    $0x1f,%eax
0x080483e3 <main+63>:   add    $0x1,%eax
0x080483e6 <main+66>:   and    $0x1f,%eax
0x080483e9 <main+69>:   mov    %eax,%edx
0x080483eb <main+71>:   and    $0x1f,%edx
0x080483ee <main+74>:   movzbl -0x10(%ebp),%eax
0x080483f2 <main+78>:   and    $0xffffffe0,%eax
0x080483f5 <main+81>:   or     %edx,%eax
0x080483f7 <main+83>:   mov    %al,-0x10(%ebp)
0x080483fa <main+86>:   nop
0x080483fb <main+87>:   nop
0x080483fc <main+88>:   nop
0x080483fd <main+89>:   nop
0x080483fe <main+90>:   nop
0x080483ff <main+91>:   addl   $0x1,-0x8(%ebp)
0x08048403 <main+95>:   cmpl   $0x7e,-0x8(%ebp)
0x08048407 <main+99>:   jle    0x80483d7 <main+51>

可见有加粗红色部分保证bit操作不会溢出。



抱歉!评论已关闭.