C 語言中有趣第指標操作

來源:互聯網
上載者:User

標籤:blog   http   io   資料   ar   art   linux   log   

http://blog.csdn.net/ghevinn/article/details/37651149(反組譯碼題目需要分析)

4、取出記憶體地區的值

在取某記憶體位址開始的一個地區的值的時候,取出的值取決於用來取值的類型,譬如int為4個byte,char為1個byte,程式如:

void main(){
 int a[2] = {261,0};
 int *pi = a;
 char *p = (char*)pi;
 cout << *(int *)p++ << endl;  //取出p地址,轉化為取4個byte,並取出內容,之後p向後移動一位
 cout << *(int *)p << endl;    //取出p地址,轉化為取4個byte,並取出內容
 cout << (int)*p << endl;      //取出1個char類型,並轉換為int型
 cout << (int)*(char *)pi << endl;  //取出pi地址,轉換為char類型,取出內容,並轉換為int型
}
程式輸出:
261
1
1
5

a的儲存地區安排為:byte1=5,byte2=1,byte3~byte8 = 0;
所以*(int *)p++取的為byte1到byte4; 之後的*(int *)p取的是byte2到byte5;
(int)*p取的是byte2;(int)*(char *)pi取的是byte1,之後轉換為int型

 

2.strcpy()函數


問:下面是一個簡單的密碼保護功能,你能在不知道密碼的情況下將其破解嗎?


#include<stdio.h> 
 
int main(int argc, char *argv[]) 

    int flag = 0; 
    char passwd[10]; 
 
    memset(passwd,0,sizeof(passwd)); 
 
    strcpy(passwd, argv[1]); 
 
    if(0 == strcmp("LinuxGeek", passwd)) 
    { 
        flag = 1; 
    } 
 
    if(flag) 
    { 
        printf("\n Password cracked \n"); 
    } 
    else 
    { 
        printf("\n Incorrect passwd \n"); 
 
    } 
    return 0; 

答:破解上述加密的關鍵在於利用攻破strcpy()函數的漏洞。所以使用者在向“passwd”緩衝輸入隨機密碼的時候並沒有提前檢查“passwd”的容量是否足夠。所以,如果使用者輸入一個足夠造成緩衝溢出並且重寫“flag”變數預設值所存在位置的記憶體的長“密碼”,即使這個密碼無法通過驗證,flag驗證位也變成了非零,也就可以獲得被保護的資料了。例如:


$ ./psswd aaaaaaaaaaaaa 
 
Password cracked 
雖然上面的密碼並不正確,但我們仍然可以通過緩衝溢出繞開密碼安全保護。

編譯 gcc file -fno-stack-protector

#include<stdio.h>
int main(int argc, char *argv[])
{
int flag = 0;
char passwd[10];
char input[]={‘a‘,‘a‘,‘a‘,‘a‘,‘a‘,‘a‘,‘a‘,‘a‘,‘a‘,‘a‘,‘\x02‘,‘\x00‘,‘\x00‘,‘\x00‘};
memset(passwd,0,sizeof(passwd));
strcpy(passwd, input);
if(0 == strcmp("LinuxGeek", passwd))
{
flag = 1;
}
if(flag==2)
{
printf("\n Password cracked \n");
}
else
{
printf("%x\n",flag);
printf("\n Incorrect passwd \n");

}
return 0;
}

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.