Home > Store

CERT Oracle Secure Coding Standard for Java, The

Register your product to gain access to bonus material or receive a coupon.

CERT Oracle Secure Coding Standard for Java, The

Book

  • Sorry, this book is no longer in print.
Not for Sale

eBook

  • Your Price: $42.39
  • List Price: $52.99
  • Includes EPUB and PDF
  • About eBook Formats
  • This eBook includes the following formats, accessible from your Account page after purchase:

    ePub EPUB The open industry format known for its reflowable content and usability on supported mobile devices.

    Adobe Reader PDF The popular standard, used most often with the free Acrobat® Reader® software.

    This eBook requires no passwords or activation to read. We customize your eBook by discreetly watermarking it with your name, making it uniquely yours.

Description

  • Copyright 2012
  • Dimensions: 7" x 9-1/8"
  • Pages: 744
  • Edition: 1st
  • Book
  • ISBN-10: 0-321-80395-7
  • ISBN-13: 978-0-321-80395-5

“In the Java world, security is not viewed as an add-on a feature. It is a pervasive way of thinking. Those who forget to think in a secure mindset end up in trouble. But just because the facilities are there doesn’t mean that security is assured automatically. A set of standard practices has evolved over the years. The Secure® Coding® Standard for JavaTM is a compendium of these practices. These are not theoretical research papers or product marketing blurbs. This is all serious, mission-critical, battle-tested, enterprise-scale stuff.”

James A. Gosling, Father of the Java Programming Language

An essential element of secure coding in the Java programming language is a well-documented and enforceable coding standard. Coding standards encourage programmers to follow a uniform set of rules determined by the requirements of the project and organization, rather than by the programmer’s familiarity or preference. Once established, these standards can be used as a metric to evaluate source code (using manual or automated processes).

The CERT® Oracle® Secure Coding Standard for JavaTM provides rules designed to eliminate insecure coding practices that can lead to exploitable vulnerabilities. Application of the standard’s guidelines will lead to higher-quality systems–robust systems that are more resistant to attack. Such guidelines are required for the wide range of products coded in Java–for devices such as PCs, game players, mobile phones, home appliances, and automotive electronics.

After a high-level introduction to Java application security, seventeen consistently organized chapters detail specific rules for key areas of Java development. For each area, the authors present noncompliant examples and corresponding compliant solutions, show how to assess risk, and offer references for further information. Each rule is prioritized based on the severity of consequences, likelihood of introducing exploitable vulnerabilities, and cost of remediation.

The standard provides secure coding rules for the Java SE 6 Platform including the Java programming language and libraries, and also addresses new features of the Java SE 7 Platform. It describes language behaviors left to the discretion of JVM and compiler implementers, guides developers in the proper use of Java’s APIs and security architecture, and considers security concerns pertaining to standard extension APIs (from the javax package hierarchy).The standard covers security issues applicable to these libraries: lang, util, Collections, Concurrency Utilities, Logging, Management, Reflection, Regular Expressions, Zip, I/O, JMX, JNI, Math, Serialization, and JAXP.

Sample Content

Online Sample Chapter

The CERT® Oracle® Secure Coding Standard for Java: Input Validation and Data Sanitization (IDS)

Sample Pages

Download the sample pages (includes Chapter 2 and Index)

Table of Contents

Foreword xvii

Preface xix

Acknowledgments xxxi

About the Authors xxxiii

Chapter 1: Introduction 1

Misplaced Trust 2

Injection Attacks 2

Leaking Sensitive Data 4

Leaking Capabilities 6

Denial of Service 7

Serialization 10

Concurrency, Visibility, and Memory 11

Principle of Least Privilege 18

Security Managers 19

Class Loaders 21

Summary 21

Chapter 2: Input Validation and Data Sanitization (IDS) 23

Rules 23

Risk Assessment Summary 24

IDS00-J. Sanitize untrusted data passed across a trust boundary 24

IDS01-J. Normalize strings before validating them 34

IDS02-J. Canonicalize path names before validating them 36

IDS03-J. Do not log unsanitized user input 41

IDS04-J. Limit the size of files passed to ZipInputStream 43

IDS05-J. Use a subset of ASCII for file and path names 46

IDS06-J. Exclude user input from format strings 48

IDS07-J. Do not pass untrusted, unsanitized data to the Runtime.exec() method 50

IDS08-J. Sanitize untrusted data passed to a regex 54

IDS09-J. Do not use locale-dependent methods on locale-dependent data without specifying the appropriate locale 59

IDS10-J. Do not split characters between two data structures 60

IDS11-J. Eliminate noncharacter code points before validation 66

IDS12-J. Perform lossless conversion of String data between differing character encodings 68

IDS13-J. Use compatible encodings on both sides of file or network I/O 71

Chapter 3: Declarations and Initialization (DCL) 75

Rules 75

Risk Assessment Summary 75

DCL00-J. Prevent class initialization cycles 75

DCL01-J. Do not reuse public identifiers from the Java Standard Library 79

DCL02-J. Declare all enhanced for statement loop variables final 81

Chapter 4: Expressions (EXP) 85

Rules 85

Risk Assessment Summary 85

EXP00-J. Do not ignore values returned by methods 86

EXP01-J. Never dereference null pointers 88

EXP02-J. Use the two-argument Arrays.equals() method to compare the contents of arrays 90

EXP03-J. Do not use the equality operators when comparing values of boxed primitives 91

EXP04-J. Ensure that autoboxed values have the intended type 97

EXP05-J. Do not write more than once to the same variable within an expression 100

EXP06-J. Do not use side-effecting expressions in assertions 103

Chapter 5: Numeric Types and Operations (NUM) 105

Rules 105

Risk Assessment Summary 106

NUM00-J. Detect or prevent integer overflow 106

NUM01-J. Do not perform bitwise and arithmetic operations on the same data 114

NUM02-J. Ensure that division and modulo operations do not result in divide-by-zero errors 119

NUM03-J. Use integer types that can fully represent the possible range of unsigned data 121

NUM04-J. Do not use floating-point numbers if precise computation is required 122

NUM05-J. Do not use denormalized numbers 125

NUM06-J. Use the strictfp modifier for floating-point calculation consistency across platforms 128

NUM07-J. Do not attempt comparisons with NaN 132

NUM08-J. Check floating-point inputs for exceptional values 134

NUM09-J. Do not use floating-point variables as loop counters 136

NUM10-J. Do not construct BigDecimal objects from floating-point literals 138

NUM11-J. Do not compare or inspect the string representation of floating-point values 139

NUM12-J. Ensure conversions of numeric types to narrower types do not result in lost or misinterpreted data 141

NUM13-J. Avoid loss of precision when converting primitive integers to floating-point 146

Chapter 6: Object Orientation (OBJ) 151

Rules 151

Risk Assessment Summary 152

OBJ00-J. Limit extensibility of classes and methods with invariants to trusted subclasses only 152

OBJ01-J. Declare data members as private and provide accessible wrapper methods 159

OBJ02-J. Preserve dependencies in subclasses when changing superclasses 162

OBJ03-J. Do not mix generic with nongeneric raw types in new code 169

OBJ04-J. Provide mutable classes with copy functionality to safely allow passing instances to untrusted code 175

OBJ05-J. Defensively copy private mutable class members before returning their references 180

OBJ06-J. Defensively copy mutable inputs and mutable internal components 185

OBJ07-J. Sensitive classes must not let themselves be copied 189

OBJ08-J. Do not expose private members of an outer class from within a nested class 192

OBJ09-J. Compare classes and not class names 194

OBJ10-J. Do not use public static nonfinal variables 197

OBJ11-J. Be wary of letting constructors throw exceptions 199

Chapter 7: Methods (MET) 209

Rules 209

Risk Assessment Summary 210

MET00-J. Validate method arguments 210

MET01-J. Never use assertions to validate method arguments 213

MET02-J. Do not use deprecated or obsolete classes or methods 215

MET03-J. Methods that perform a security check must be declared private or final 217

MET04-J. Do not increase the accessibility of overridden or hidden methods 218

MET05-J. Ensure that constructors do not call overridable methods 220

MET06-J. Do not invoke overridable methods in clone() 223

MET07-J. Never declare a class method that hides a method declared in a superclass or superinterface 226

MET08-J. Ensure objects that are equated are equatable 229

MET09-J. Classes that define an equals() method must also define a hashCode() method 238

MET10-J. Follow the general contract when implementing the compareTo() method 241

MET11-J. Ensure that keys used in comparison operations are immutable 243

MET12-J. Do not use finalizers 248

Chapter 8: Exceptional Behavior (ERR) 255

Rules 255

Risk Assessment Summary 255

ERR00-J. Do not suppress or ignore checked exceptions 256

ERR01-J. Do not allow exceptions to expose sensitive information 263

ERR02-J. Prevent exceptions while logging data 268

ERR03-J. Restore prior object state on method failure 270

ERR04-J. Do not exit abruptly from a finally block 275

ERR05-J. Do not let checked exceptions escape from a finally block 277

ERR06-J. Do not throw undeclared checked exceptions 280

ERR07-J. Do not throw RuntimeException, Exception, or Throwable 285

ERR08-J. Do not catch NullPointerException or any of its ancestors 288

ERR09-J. Do not allow untrusted code to terminate the JVM 296

Chapter 9: Visibility and Atomicity (VNA) 301

Rules 301

Risk Assessment Summary 301

VNA00-J. Ensure visibility when accessing shared primitive variables 302

VNA01-J. Ensure visibility of shared references to immutable objects 306

VNA02-J. Ensure that compound operations on shared variables are atomic 309

VNA03-J. Do not assume that a group of calls to independently atomic methods is atomic 317

VNA04-J. Ensure that calls to chained methods are atomic 323

VNA05-J. Ensure atomicity when reading and writing 64-bit values 328

Chapter 10: Locking (LCK) 331

Rules 331

Risk Assessment Summary 332

LCK00-J. Use private final lock objects to synchronize classes that may interact with untrusted code 332

LCK01-J. Do not synchronize on objects that may be reused 339

LCK02-J. Do not synchronize on the class object returned by getClass() 343

LCK03-J. Do not synchronize on the intrinsic locks of high-level concurrency objects 347

LCK04-J. Do not synchronize on a collection view if the backing collection is accessible 348

LCK05-J. Synchronize access to static fields that can be modified by untrusted code 351

LCK06-J. Do not use an instance lock to protect shared static data 352

LCK07-J. Avoid deadlock by requesting and releasing locks in the same order 355

LCK08-J. Ensure actively held locks are released on exceptional conditions 365

LCK09-J. Do not perform operations that can block while holding a lock 370

LCK10-J. Do not use incorrect forms of the double-checked locking idiom 375

LCK11-J. Avoid client-side locking when using classes that do not commit to their locking strategy 381

Chapter 11: Thread APIs (THI) 387

Rules 387

Risk Assessment Summary 387

THI00-J. Do not invoke Thread.run() 388

THI01-J. Do not invoke ThreadGroup methods 390

THI02-J. Notify all waiting threads rather than a single thread 394

THI03-J. Always invoke wait() and await() methods inside a loop 401

THI04-J. Ensure that threads performing blocking operations can be terminated 404

THI05-J. Do not use Thread.stop() to terminate threads 412

Chapter 12: Thread Pools (TPS) 417

Rules 417

Risk Assessment Summary 417

TPS00-J. Use thread pools to enable graceful degradation of service during traffic bursts 418

TPS01-J. Do not execute interdependent tasks in a bounded thread pool 421

TPS02-J. Ensure that tasks submitted to a thread pool are interruptible 428

TPS03-J. Ensure that tasks executing in a thread pool do not fail silently 431

TPS04-J. Ensure ThreadLocal variables are reinitialized when using thread pools 436

Chapter 13: Thread-Safety Miscellaneous (TSM) 441

Rules 441

Risk Assessment Summary 441

TSM00-J. Do not override thread-safe methods with methods that are not thread-safe 442

TSM01-J. Do not let the this reference escape during object construction 445

TSM02-J. Do not use background threads during class initialization 454

TSM03-J. Do not publish partially initialized objects 459

Chapter 14: Input Output (FIO) 467

Rules 467

Risk Assessment Summary 468

FIO00-J. Do not operate on files in shared directories 468

FIO01-J. Create files with appropriate access permissions 478

FIO02-J. Detect and handle file-related errors 481

FIO03-J. Remove temporary files before termination 483

FIO04-J. Close resources when they are no longer needed 487

FIO05-J. Do not expose buffers created using the wrap() or duplicate() methods to untrusted code 493

FIO06-J. Do not create multiple buffered wrappers on a single InputStream 496

FIO07-J. Do not let external processes block on input and output streams 500

FIO08-J. Use an int to capture the return value of methods that read a character or byte 504

FIO09-J. Do not rely on the write() method to output integers outside the range 0 to 255 507

FIO10-J. Ensure the array is filled when using read() to fill an array 509

FIO11-J. Do not attempt to read raw binary data as character data 511

FIO12-J. Provide methods to read and write little-endian data 513

FIO13-J. Do not log sensitive information outside a trust boundary 516

FIO14-J. Perform proper cleanup at program termination 519

Chapter 15: Serialization (SER) 527

Rules 527

Risk Assessment Summary 528

SER00-J. Maintain serialization compatibility during class evolution 528

SER01-J. Do not deviate from the proper signatures of serialization methods 531

SER02-J. Sign then seal sensitive objects before sending them across a trust boundary 534

SER03-J. Do not serialize unencrypted, sensitive data 541

SER04-J. Do not allow serialization and deserialization to bypass the security manager 546

SER05-J. Do not serialize instances of inner classes 549

SER06-J. Make defensive copies of private mutable components during deserialization 551

SER07-J. Do not use the default serialized form for implementation-defined invariants 553

SER08-J. Minimize privileges before deserializing from a privileged context 558

SER09-J. Do not invoke overridable methods from the readObject() method 562

SER10-J. Avoid memory and resource leaks during serialization 563

SER11-J. Prevent overwriting of externalizable objects 566

Chapter 16: Platform Security (SEC) 569

Rules 569

Risk Assessment Summary 570

SEC00-J. Do not allow privileged blocks to leak sensitive information across a trust boundary 570

SEC01-J. Do not allow tainted variables in privileged blocks 574

SEC02-J. Do not base security checks on untrusted sources 577

SEC03-J. Do not load trusted classes after allowing untrusted code to load arbitrary classes 579

SEC04-J. Protect sensitive operations with security manager checks 582

SEC05-J. Do not use reflection to increase accessibility of classes, methods, or fields 585

SEC06-J. Do not rely on the default automatic signature verification provided by URLClassLoader and java.util.jar 592

SEC07-J. Call the superclass’s getPermissions() method when writing a custom class loader 597

SEC08-J. Define wrappers around native methods 599

Chapter 17: Runtime Environment (ENV) 603

Rules 603

Risk Assessment Summary 603

ENV00-J. Do not sign code that performs only unprivileged operations 604

ENV01-J. Place all security-sensitive code in a single jar and sign and seal it 606

ENV02-J. Do not trust the values of environment variables 610

ENV03-J. Do not grant dangerous combinations of permissions 613

ENV04-J. Do not disable bytecode verification 617

ENV05-J. Do not deploy an application that can be remotely monitored 618

Chapter 18: Miscellaneous (MSC) 625

Rules 625

Risk Assessment Summary 625

MSC00-J. Use SSLSocket rather than Socket for secure data exchange 626

MSC01-J. Do not use an empty infinite loop 630

MSC02-J. Generate strong random numbers 632

MSC03-J. Never hard code sensitive information 635

MSC04-J. Do not leak memory 638

MSC05-J. Do not exhaust heap space 647

MSC06-J. Do not modify the underlying collection when an iteration is in progress 653

MSC07-J. Prevent multiple instantiations of singleton objects 657

Glossary 669

References 677

Index 693

Updates

Submit Errata

More Information

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020