KLOCWORK WHITE PAPER OCTOBER 2013 Enhancing Mobile Development with Klocwork Checkers for Android Developers in various parts of the Android stack have unique security and error detection needs. The kernel and platform developers that use C and C++ on Linux are focused primarily on performance, stability, and security. Application developers who use Java are more interested in functionality and the user experience. While there are some overlaps in some areas, such as security, the ways in which developers achieve these results are different. Many analysis tools fail to recognize these unique challenges, leaving Android developers code vulnerable to security weaknesses and errors. Klocwork Insight analyzes how the Android code is meant to operate by building a knowledge base of every function call in the platform. This analysis provides an understanding of both the Java and C/C++ code that Android developers require. The analysis is performed on a server or the developer s desktop, and has built-in diagnostics and Android-specific checkers. Android-specific checkers Errors can be tricky to find, which is why Klocwork Insight comes with built-in Java and Androidspecific checkers, including: ANDROID.NPE Null pointer exceptions: These red herring errors are annoying, but have to be fixed or they ll bite your ankles. Fortunately, Klocwork Insight detects them right on your desktop before they infect the build. Here s an example of the more loathsome varieties of NPE trying to load a bitmap: public Bitmap loadbitmap(byte [] data) { Bitmap bmp = BitmapFactory.decodeByteArray(data, 0, data.length); // Align bitmap to 4 pixel boundary final Bitmap resized = Bitmap.createScaledBitmap(bmp, (bmp.getwidth() % 4) * 4, bmp.getheight(), true); return resized; When Klocwork Insight sees code like this, it will highlight the offending line inside your IDE, whether you are using Eclipse or IntelliJ IDEA.
As you no doubt are aware, the pointer from an SDK function isn t guaranteed to be valid. Most developers hate adding defensive checks, but it beats getting a call from the CTO on a Saturday afternoon because your app is crashing. To fix this sample, simply test for null as shown below: public Bitmap loadbitmap(byte [] data) { Bitmap bmp = BitmapFactory.decodeByteArray(data, 0, data.length); if (bmp == null) return null; // Align bitmap to 4 pixel boundary final Bitmap resized = Bitmap.createScaledBitmap(bmp, (bmp.getwidth() % 4) * 4, bmp.getheight(), true); return resized; ANDROID.RLK.SQLCON Resource Allocation: This is one of those snake in the grass errors that surprise many of us. The SQLite commands in the Android SDK return a live connection that continues to live after the variable that contains it goes out of scope. Multiple iterations through the same code will result in slow performance as more memory is devoted to storing idle connections. Here s an example: protected void onresume(bundle bundle) { super.onresume(); final SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase( students.db, null, null); db.execsql( Robert ); DROP TABLE Students;-- ); Enhancing Mobile Development with Klocwork Checkers for Android Klocwork White Paper 2
There are two solutions to this issue. The immediate solution is to close the database connection in the same scope it is opened, as shown below. protected void onresume(bundle bundle) { super.onresume(); final SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase( students.db, null, null); db.execsql( Robert ); DROP TABLE Students;-- ); db.close(); A better practice would be to refactor the database connection to the widest scope that s needed. Opening a database connection has a considerable amount of overhead, so either keep the connection persistent or load the data you need from the database into a local collection and close it. JD.INF.AREC Recursion: Some of the Android lifecycle methods expect you to call their superclass method. If you aren t paying attention, you can create a circular reference to your own code. The compiler is perfectly happy generating code from the following snippet. protected void oncreate(bundle bundle) { oncreate(bundle); Inside the IDE, you ll get a warning that your code has a problem. The solution is to call the superclass version of oncreate() as shown below. protected void oncreate(bundle bundle) { super.oncreate(bundle); ANDROID.UF.* Invalid Resource: Android allows developers to access hardware by instantiating an object that is subclassed from the Android base class. This includes the camera as well as media playback and recording. If the object is released, explicitly or implicitly, the reference to the hardware device is no longer valid. The ANDROID.UF group of checkers detects and reports on these potential errors. Enhancing Mobile Development with Klocwork Checkers for Android Klocwork White Paper 3
public boolean onlongclick(view view) { MediaRecorder mrecorder = new MediaRecorder(); mrecorder.setaudiosource(mediarecorder.audiosource.mic); mrecorder.setoutputformat(mediarecorder.outputformat.three_gpp); mrecorder.setaudioencoder(mediarecorder.audioencoder.amr_nb); final File file = new File( test.raw ); if (file.exists()) else mrecorder.setoutputfile(file.getpath()); mrecorder.start(); return true; While the pointer (mrecorder) isn t null, the object it refers to is no longer valid. The developer needs to spend some time refactoring the code for a better flow, but the most immediate solution to this problem is to exit the function when the pointer is released. By the way, there is also an ANDROID.NPE error in that sample. Can you spot it? Here is a solution to the issues reported: public boolean onlongclick(view view) { MediaRecorder mrecorder = new MediaRecorder(); if (mrecorder == null) return false; mrecorder.setaudiosource(mediarecorder.audiosource.mic); mrecorder.setoutputformat(mediarecorder.outputformat.three_gpp); mrecorder.setaudioencoder(mediarecorder.audioencoder.amr_nb); final File file = new File( test.raw ); if (file.exists()) { return false; mrecorder.setoutputfile(file.getpath()); mrecorder.start(); return true; Klocwork s commitment to Android Over half of all smartphones sold today use Android, and it s a popular choice for embedded systems. The Android-specific checkers above demonstrate Klocwork s commitment to Android developers, and you can expect more from us in the months to come. Other Resources Learn more about Klocwork solutions for Android application and device development. Visit the Klocwork Developer Network to see a list of checkers for Android and examples that show you the best way to remedy security vulnerabilities, even if you ve never heard of them before. See how easily you can write secure, reliable Android code by signing up for a free trial of Klocwork Insight. Enhancing Mobile Development with Klocwork Checkers for Android Klocwork White Paper 4
Klocwork: Empowering developers at their desktop Unlike other source code analysis tools, Insight works in the developer s IDE of choice, identifying security weaknesses and errors so they can be fixed before being committed to the build. We don t make you wait until after a build is run to show you potential security vulnerabilities or reliability issues, we show you On-the-Fly as you are typing. You take corrective action immediately, and submit more secure, reliable code into the build process. Using information from the integration project Insight works behind the scenes collecting all the information needed to analyze your code within the context of the entire build taxonomies, security, coding standards, etc. You review the results, fixing errors and setting others to be fixed later or to be ignored, and adding comments to explain your changes. The result is secure code, fewer errors, and faster project completion. About Klocwork In the world of AppSec, developers and the firms that employ them demand tools that provide a competitive edge. Klocwork meets these demands with compelling desktop tools that enable developers to produce secure, reliable software more easily and quickly. Klocwork s unique SCA tool provides accurate, reliable analysis as developers write their code, identifying potential security vulnerabilities and reliability issues before they are submitted to the software build. Additional desktop tools simplify code review, refactoring and architectural analysis. More than 1,100 customers, including the biggest brands in the automotive, consumer electronics, gaming, medical technologies, military and aerospace, mobile device and telecom sectors rely on these tools everyday to make their software more secure and reliable. Creating applications they are proud of. Find out more at www.klocwork.com. IN THE UNITED STATES: 15 New England Executive Park Burlington, MA 01803 IN CANADA: 30 Edgewater Street, Suite 114 Ottawa, ON K2L 1V8 t: 1.866.556.2967 f: 613.836.9088 WWW.KLOCWORK.COM Klocwork Inc. All rights reserved.