2012-02-27 159 views
-1

好吧,我正在對緩衝區溢出進行一些研究。我有一個C程序,容易受到我試圖轉換爲java的變量攻擊的影響。有人認爲他們可以幫助我嗎?到目前爲止,我仍然無法獲得Java代碼進行編譯。JAVA中的緩衝區溢出

C代碼

#include <stdio.h> 
#include <string.h> 

/* 
A routine that checks whether the password is correct or not 
Standard library call "gets()" does not check for buffer overflow 
*/ 
int checkPassword(){ 
    char passwordFlag = 'F'; 
    char inputPwd[10]; 
    memset(inputPwd, 0, 10); 

    gets(inputPwd); 
    if (!strcmp(inputPwd, "goodpass")){ 
     passwordFlag = 'T'; 
    } 
    if (passwordFlag == 'T'){ 
     return 1; 
    } 
    else{ 
     return 0; 
    } 
} 

int main() 
{ 
    printf("Please enter a password\n"); 
    if (checkPassword() == 1) 
    { 
     printf("Successful\n"); 
     return 0; 
    } 
    else{ 
     printf("Access Denied.\n"); 
     return -1; 
    } 
} 

的Java代碼(不是當前編譯)

import java.io.*; 
class Numbers { 
    public static void main(String[] args) { 
      BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 
      System.out.println("Please enter a password"); 
       if (checkPassword() == 1) 
       { 
        System.out.println("Successful"); 
        System.exit(1); //you wouldn't exit here but its not like i'm doing anything important 
       } 
       else{ 
        System.out.println("Access Denied."); 
        System.exit(1); 
       } 


    } 
    public static Integer checkPassword(){ 
       char passwordFlag = 'F'; 
       char inputPwd[10]; 
       memset(inputPwd, 0, 10); 

       gets(inputPwd); 
       if (!strcmp(inputPwd, "goodpass")){ 
        passwordFlag = 'T'; 
       } 
       if (passwordFlag == 'T'){ 
        return 1; 
       } 
       else{ 
        return 0; 
       } 
      } 
} 
+2

在Java中,memset的,獲取並STRCMP是不確定的。 – Alanmars 2012-02-27 03:13:00

+4

關於你的Java代碼有很多很多東西,它們不是Java。 – 2012-02-27 03:14:00

+2

不要只取C庫函數名稱並在Java中使用它們。你需要學習Java方法來完成這些任務。 – Nayuki 2012-02-27 03:20:04

回答

3

那種緩衝區溢出的在Java中不存在。在JVM級別上,會引發IndexOutOfBoundsException。

+0

我知道這應該是輸出'線程中的異常'主要「java.lang.ArrayIndexOutOfBoundsException:10 \t at variable.main(variable_attacke.java:6)''但我只是想達到那個點 – atrueresistance 2012-02-27 03:15:33

+0

在java通用字符串被讀取和處理,繞過了這個問題。你可以從FileInputStream'int ch = in.read()'中的循環中讀取一個字符,並將它放在一個數組中。但是這並不是一種脆弱的感覺,因爲有例外。 – 2012-02-27 03:54:52

2

你的代碼中有幾個問題,我將指出幾個:

char inputPwd[10]; 
memset(inputPwd, 0, 10); 

應該是:

char[] inputPwd = new char[10]; 
// no need to set to 0, since arrays are initialised to zero. 

此外,gets()不存在於Java中,你可能會想:

br.readLine(); 

來代替(你也必須通過你的BufferedReader中的功能,和EIT她的捕獲或拋出它可能產生的異常)。請注意,這讀取整行而不是一個字符串。

不過,我不會擔心轉換它,因爲緩衝區溢出真的不喜歡這個工作,在Java中,請參閱:Does Java have buffer overflows?