JAVA中的缓冲区溢出

时间:2012-02-27 03:07:07

标签: java buffer-overflow

好的,我正在研究缓冲区溢出。我有一个容易受到可变攻击的C程序,我正试图将其转换为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 个答案:

答案 0 :(得分:3)

Java中不存在这种缓冲区溢出。在JVM级别上,将引发IndexOutOfBoundsException。

答案 1 :(得分: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.

此外,Java中不存在gets(),您可能需要:

 br.readLine(); 
而不是(并且您还必须将BufferedReader传递给函数,并捕获或抛出它可能生成的异常)。请注意,这会读取整行,而不仅仅是字符串。

但是,我不担心转换它,因为缓冲区溢出在Java中不能像这样工作,请参阅:Does Java have buffer overflows?