日期:2014-05-16  浏览次数:20413 次

用FindBugs分析代码漏洞

  hyddd原创,转载请说明!

  FindBugs是一个专门分析JAVA代码问题的静态代码扫描工具,它是由一位马里兰大学的博士写的,官方网站是:http://findbugs.sourceforge.net/index.html,里面有FindBugs工具的下载,并且也包含了那位博士写的关于静态代码分析引擎的一些论文,不过偶还没看。FindBugs可以发现的问题包括:多线程竞争问题,性能问题,安全问题,代码规范......这些下面我都会详细介绍:>,如果想了解更多关于其他语言的静态代码扫描工具信息,可以参考《[hyddd安全性测试笔记2]浅淡静态代码分析工具》。

一.FindBugs的使用

  先说说FindBugs的使用,FindBugs它提供两种工具形式,一种是界面形式的工具,如下图:

  

  另外一种是以Eclipse插件的形式提供的:

  

  个人比较喜欢插件的形式,方便~!

  下面简单介绍FindBugs插件的使用:

  1.右键项目Pop Menu->Find Bugs->Find Bugs,如图:

  

  2.把FindBugs插件的3个功能WorkSpace导出,如图:

  

  (1). Bug Explorer:这里显示的是用FindBugs对这个项目扫描的结果。现在只扫出了一个类型的BUG,同时这个类型的BUG数量为1(见图中括号)。继续打开[DLS]Dead store to local variable,选择其中一项,右键单击,选择Pop Menu中的“Show Bug Details”,我们便会跳转到Bug Details这个WorkSpace。

  

  (2).Bug Details:这里是对BUG问题的描述,包括:Bug类别及程度,Bug的定位,对Bug的解释。

  

  这里这个Bug类别是Dodgy,程度是中等;双击下面会自动定位BUG的位置;最下面是这个BUG的解释,可以根据里面的提示去修改代码:>

  (3).Bug User Annotations:记录一些自己添加的评注。

二.FindBugs的Bug类型及实例代码:

  FindBugs对BUG的解释在官网有详细的说明:http://findbugs.sourceforge.net/bugDescriptions.html#IS2_INCONSISTENT_SYNC。虽然有说明,但说明一般比较简短,而且没有Demo代码,有时候还真没明白它说什么意思:<,所以在这里我打算整理一下之前看过的资料,把问题和解决方案记录下来

Bad practice:

[Hight]

[H B BC] Random object created and used only once

[Medium]

[M B Nm] Method names should start with a lower case letter

[M B Nm] Class names should start with an upper case letter

[M B ODR] Method may fail to close database resource

[M B DE] Method might ignore exception

Correctness:

[Hight]

[H C FS] More arguments are passed that are actually used in the format string

[H C FS] Format string references missing argument

[H C EC] equals() used to compare array and nonarray

[Medium]

[M C RCN] Nullcheck of value previously dereferenced

[M C NP] Method call passes null for unconditionally dereferenced parameter

[M C NP] Possible null pointer dereference

[M B Eq] Class defines compareTo(...) and uses Object.equals()

Experimental:

[Medium]

[M X OBL] Method may fail to clean up stream or resource?

Internationalization:

......

Malicious code vulnerability:

[Medium]

[M V EI2] May expose internal representation by incorporating reference to mutable object

[M V EI] May expose internal representation by returni