2012-02-27 30 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?