Finalizer攻擊:
網上不少相關資料,但是看懂不代表你真正知道了。看懂再寫出來或者說出來,纔是自己的!所以還是寫寫。
在構造函數中拋出異常,目的是創建對象失敗時當對象拋出異常後,對象會被垃圾清理器回收。而當垃圾清理器準備釋放對象的內存時,它首先調用finalize方法,然後再回收內存。Finalizer攻擊就是重載finalize方法,在這個方法內保存這個對象。這個對象是部分初始化對象,它應該被清除,但是沒有,導致它已經初始化的信息泄漏,並且獲取對象後可以調用其方法,如果對象包含一些操作敏感信息的方法,就會被不法分子利用。I.攻擊示例
易受Finalizer攻擊的代碼示例
class Vulnerable{
String password;
Vulnerable(String password){
if(!checkVerification(password)){
throw new IllegalArgumentException("Fail to verification");
}
this.password = password;
}
private static boolean checkVerification(String password){
return password.equals("34567");
}
}
攻擊代碼
public class Attack extends Vulnerable{
public static Attack instance;
Attack(String password){
super(password);
}
public void finalize(){
instance = this;
}
public static void main(String[] args){
try{
new Attack("23");
}catch(Exception e){
System.out.println(e);
}
System.gc();
System.runFinalization();
if(instance != null){
System.out.println("instance is created!");
}
}
}
II.防範方法
Java SE6以後,如果構造函數在創建java.lang.Object對象前拋出異常,它的finalize方法不會被執行。 所以我們就可以在創建java.lang.Object方法之前拋出異常。Java在調用構造函數創建對象時,除了加載類,執行靜態初始化外,就優先處理構造函數的參數,然後調用隱式或者顯式的this或者super。防範的方法是:一個構造函數調用帶參數的私構造函數;這個參數就是一個函數返回的執行值,而這個函數就執行相應的檢查並且不符合預期情況時拋出異常,這個時候對象的父類java.lang.Object還沒有被創建,finalize方法不會被執行。
防範Finalizer攻擊的代碼
class Invulnerable{
String password;
Invulnerable(String password){
this(checkVerification(password));
this.password = password;
}
private Invulnerable(boolean checkresult){}
private static boolean checkVerification(String password){
boolean result = password.equals("34567");
if(!result){
throw new IllegalArgumentException("Fail to verification");
}
return result;
}
}
攻擊代碼
public class InvalidAttack extends Invulnerable{
public static InvalidAttack instance;
InvalidAttack(String password){
super(password);
}
public void finalize(){
instance = this;
}
public static void main(String[] args){
try{
new InvalidAttack("23");
}catch(Exception e){
System.out.println(e);
}
System.gc();
System.runFinalization();
if(instance != null){
System.out.println("instance is created!");
}
}
}