Exciter

生命不息、折腾不止

0%

Android安全指北

1 代码

1.1 异常捕获
1.1.1 【必须】ClassCastException异常捕获

通过Intent的getSerializableExtra()方法获取传递过来的数据,必须用try catch处理ClassCastException,避免类型转换出现的异常,如下所示,上个页面传递了一个String,当前页面接收后转换为DataBean,则会出现崩溃,需要try catch处理:

1
Intent intent=new Intent(this,DemoActivity.class);intent.putExtra("data","abc");startActivity(intent);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class DemoActivity extends AppCompatActivity {    

@Override   
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); 
setContentView(R.layout.activity_demo);
try {           
Intent intent = getIntent();           
DataBean dataBean = (DataBean) intent.getSerializableExtra("data");       
} catch (ClassCastException e) {           
e.printStackTrace();       
}   
}
}
1.1.2 【必须】NullPointerException异常捕获

通过Intent的getAction()方法获取数据时,必须判空或者try catch处理,避免空指针异常造成的崩溃:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class DemoActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_demo);
Intent intent = getIntent();
try {
if (intent.getAction().startsWith("hello")) {

}
} catch (NullPointerException e) {
e.printStackTrace();
}
}
}
1.2 信息泄漏
1.2.1 【必须】禁止在release版本下输出log
1
2
3
4
5
6
7
8
9
10
11
public class LogUtils {

private static String TAG = "tag";
private static final boolean ENABLE_LOG = BuildConfig.DEBUG;

public static void d(String msg) {
if (ENABLE_LOG) {
Log.d(TAG, msg);
}
}
}
1.3 WebView安全
1.3.1 【必须】addJavascriptInterface()调用

对于设置 minsdk <= 18 的应用,禁止调用addJavaScriptInterface方法。

1
2
3
4
5
6
7
8
9
10
11
12
13
public class DemoActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_demo);

WebView webView=new WebView(this);
if (Build.VERSION.SDK_INT>Build.VERSION_CODES.JELLY_BEAN_MR2){
webView.addJavascriptInterface(null,"");
}
}
}
1.3.2 【建议】setJavaScriptEnabled()调用

如非必要,setJavaScriptEnabled应设为false。

1
2
3
4
5
6
7
8
9
10
11
12
public class DemoActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_demo);

WebView webView = new WebView(this);
WebSettings settings = webView.getSettings();
settings.setJavaScriptEnabled(false);
}
}
1.3.3 【建议】setAllowFileAccess()调用

如非必要,建议禁止使用File域协议,以避免过滤不当导致敏感信息泄露。

1
2
3
4
5
6
7
8
9
10
11
12
public class DemoActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_demo);

WebView webView = new WebView(this);
WebSettings settings = webView.getSettings();
settings.setAllowFileAccess(false);
}
}