加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 如何安全地解析字符串?

发布时间:2020-12-15 05:07:12 所属栏目:Java 来源:网络整理
导读:我们知道使用字符串连接来形成SQL查询会使程序容易受到SQL注入攻击.我通常使用我正在使用的任何数据库软件的API提供的参数功能来解决这个问题. 但我没有听说这是常规系统编程中的一个问题.将以下代码视为允许用户仅写入其私有目录中的文件的程序的一部分. Sc
我们知道使用字符串连接来形成SQL查询会使程序容易受到SQL注入攻击.我通常使用我正在使用的任何数据库软件的API提供的参数功能来解决这个问题.

但我没有听说这是常规系统编程中的一个问题.将以下代码视为允许用户仅写入其私有目录中的文件的程序的一部分.

Scanner scanner = new Scanner(System.in);
String directoryName = "Bob";
String filePath = null;
String text = "some text";

System.out.print("Enter a file to write to: ");
filePath = scanner.nextLine();

// Write to the file in Bob's personal directory for this program (i.e. Bob/textfile.txt)
FileOutputStream file = new FileOutputStream(directoryName + "/" + filePath);
file.write(text.getBytes());

倒数第二行是漏洞吗?如果是这样,如何使程序更安全(特别是在Java,C和C#中)?一种方法是验证转义字符的输入.还要别的吗?

解决方法

这里最简单的解决方案是使用可接受字符的白名单.修改原始代码(包括Java约定,因为你说你是新的…)

package javawhitelist;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class JavaWhiteListExample {

    public static void main(String[] args) throws IOException {

        Scanner scanner = new Scanner(System.in); 
        String directoryName = "Bob"; 
        String filePath = null; 
        FileWriter stream = null;
        String text = "some text";  
        System.out.print("Enter a file to write to: "); 
        filePath = scanner.nextLine();  
        String WHITELIST = "[^0-9A-Za-z]+";
        Pattern p = Pattern.compile(WHITELIST);
        Matcher m = p.matcher(filePath);

        //You need to do m.find() because m.matches() looks for COMPLETE match
        if(m.find()){ 
            //reject input.
            System.out.println("Invalid input.");
        }else{
            // Write to the file in Bob's home directory (i.e. Bob/textfile.txt) 
            try{
                File toWrite = new File(directoryName + File.separator + filePath);

                if(toWrite.canWrite()){
                    stream = new FileWriter(toWrite);
                    stream.write(text);
                }   
            }catch(FileNotFoundException e){
                e.printStackTrace();
            }catch(IOException e){
                e.printStackTrace();
            }finally{
                if(stream != null){
                    stream.close();
                }
            }

        }
    }
}

任何JVM的默认实现都使用用户的所有访问权限运行.使用File.canWrite()方法将有助于确保用户不会写入他/她无权访问的文件.将使用最安全的解决方案(确切地指定文件的去向)
com.sun.security.auth.module.UnixSystem.getName()
并用它来构建
/家庭/ $USER
目录名称的一部分.有些解决方案可能会告诉您使用
System.getProperty( “的user.home”):
或者其他一些,但那些依赖于容易改变的环境变量.

我试图彻底,我希望这会有所帮助.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读