我们知道使用字符串拼接来形成 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#中)?一种方法是验证输入的转义字符。还有其他方法吗?