This content was uploaded by our users and we assume good faith they have the permission to share this book. If you own the copyright to this book and it is wrongfully on our website, we offer a simple DMCA procedure to remove your content from our site. Start by pressing the button below!
IBM Press DB2® BOOKS DB2® Universal Database V8 for Linux, UNIX, and Windows Database Administration Certification Guide, Fifth Edition Baklarz and Wong Understanding DB2 9 Security Bond, See, Wong, and Chan Understanding DB2® Chong, Liu, Qi, and Snow High Availability Guide for DB2® Eaton and Cialini DB2® Universal Database V8 Handbook for Windows, UNIX, and Linux Gunning DB2® SQL PL, Second Edition Janmohamed, Liu, Bradstock, Chong, Gao, McArthur, and Yip DB2® for z/OS® Version 8 DBA Certification Guide Lawson DB2® Universal Database V8.1 Certification Exam 700 Study Guide Sanders DB2® Universal Database V8.1 Certification Exams 701 and 706 Study Guide Sanders DB2® Universal Database for OS/390 Sloan and Hernandez The Official Introduction to DB2® for z/OS®, Second Edition Sloan Advanced DBA Certification Guide and Reference for DB2® Universal Database v8 for Linux, UNIX, and Windows Snow and Phan DB2® Express Yip, Cheung, Gartner, Liu, and O’Connell Apache Derby—Off to the Races Zikopoulos, Baklarz, and Scott DB2® Version 8 Zikopoulos, Baklarz, deRoos, and Melnyk
ON DEMAND COMPUTING BOOKS Business Intelligence for the Enterprise Biere On Demand Computing Fellenstein Grid Computing Joseph and Fellenstein Autonomic Computing Murch
RATIONAL® SOFTWARE BOOKS Software Configuration Management Strategies and IBM Rational® ClearCase ®, Second Edition Bellagio and Milligan Implementing IBM® Rational® ClearQuest® Buckley, Pulsipher, and Scott
Project Management with the IBM Rational Unified Process Gibbs IBM Rational ® ClearCase ®, Ant, and CruiseControl Lee Visual Modeling with Rational Software Architect and UML Quatrani and Palistrant
WEBSPHERE® BOOKS IBM ® WebSphere ® Barcia, Hines, Alcott, and Botzum IBM ® WebSphere ® Application Server for Distributed Platforms and z/OS ® Black, Everett, Draeger, Miller, Iyer, McGuinnes, Patel, Herescu, Gissel, Betancourt, Casile, Tang, and Beaubien Enterprise Java™ Programming with IBM ® WebSphere ®, Second Edition Brown, Craig, Hester, Pitt, Stinehour, Weitzel, Amsden, Jakab, and Berg IBM ® WebSphere ® and Lotus Lamb, Laskey, and Indurkhya IBM ® WebSphere ® System Administration Williamson, Chan, Cundiff, Lauzon, and Mitchell Enterprise Messaging Using JMS and IBM ® WebSphere ® Yusuf
MORE BOOKS
FROM
IBM PRESS
Irresistible! Markets, Models, and Meta-Value in Consumer Electronics Bailey and Wenzek Service-Oriented Architecture Compass Bieberstein, Bose, Fiammante, Jones, and Shah Lotus® Notes® Developer’s Toolbox Elliott Developing Quality Technical Information, Second Edition Hargis, Carey, Hernandez, Hughes, Longo, Rouiller, and Wilde Performance Tuning for Linux® Servers Johnson, Huizenga, and Pulavarty RFID Sourcebook Lahiri Building Applications with the Linux Standard Base Linux Standard Base Team An Introduction to IMS™ Meltz, Long, Harrington, Hain, and Nicholls Search Engine Marketing, Inc. Moran and Hunt Can Two Rights Make a Wrong? Insights from IBM’s Tangible Culture Approach Moulton Reger Inescapable Data Stakutis and Webster
Understanding DB2® 9 Security
DB2® Information Management Software
Rebecca Bond Kevin Yeung-Kuen See Carmen Ka Man Wong Yuk-Kuen Henry Chan IBM Press Pearson plc Upper Saddle River, NJ • Boston • Indianapolis • San Francisco New York • Toronto • Montreal • London • Munich • Paris • Madrid Cape Town • Sydney • Tokyo • Singapore • Mexico City ibmpressbooks.com
Library of Congress Cataloging-in-Publication Data
Understanding DB2 9 security : DB2, information management software / Rebecca Bond [et al.]. p. cm. ISBN 0-13-134590-7 (hardback : alk. paper) 1. IBM Database 2. 2. Database security. 3. Database management. I. Bond, Rebecca, 1950QA76.9.D314U64 2006 005.8—dc22 2006027905
All rights reserved. Printed in the United States of America. This publication is protected by copyright, and permission must be obtained from the publisher prior to any prohibited reproduction, storage in a retrieval system, or transmission in any form or by any means, electronic, mechanical, photocopying, recording, or likewise. For information regarding permissions, write to: Pearson Education, Inc. Rights and Contracts Department 75 Arlington Street, Suite 300 Boston, MA 02116 Fax: (617) 848-7047 ISBN 0-13-134590-7 Text printed in the United States on recycled paper at RR Donnelly in Crawfordsville, Indiana. First printing, December 2006
This page intentionally left blank
To my loving and supportive husband of 38 years (the “real” James Bond) who has served as my foundation for so long, I’m surprised his head isn’t engraved “stepping stone; place Rebecca’s foot here.” To Keesa, James, and LaPamela who continue to bring such joy and fulfillment to our lives. You guys rock! To our five grandchildren (Ore, Pure, Porcelain, Witness, River), the next book is for you. Rebecca Bond
Contents Foreward Preface Acknowledgments About the Authors Chapter 1
The Regulatory Environment
5
Chapter
2
DB2 Security–The Starting Point
21
Chapter
3
Understanding Identification and Authentication– The First Line of Defense
41 93
Chapter
4
Securing DB2 on Windows
Chapter
5
Authorization–Authority and Privileges
117
Chapter
6
Label Based Access Control
165
Chapter
7
Encryption (Cryptography) in DB2
237
Chapter
8
Ready, Set, Implement?
255
Chapter
9
Database Auditing and Intrusion Detection
269
Chapter 10
SSH for Data-Partitioning on UNIX Platforms
303
Chapter 11
Database Security—Keeping it Current
309
Chapter 12
Final Thoughts: Security—The Human Factor
319
xi
Contents
Appendix A
Independent Security Packages
327
Appendix B
Kerberos
329
Appendix C
DB2 Audit Scope Record Layouts
337
Appendix D
DB2 Audit—Additional Documentation
349
Appendix E
Security Considerations for DB2
363
Appendix F
Glossary of Authorization ID
375
Appendix G
LBAC-Related SYSCAT views
379
Appendix H
Security Plug-In Return Codes
383
Appendix I
Detailed Implementation for the Case Study in Chapter 3
389
Index
395
xi
Table of Contents
Introduction A Personal Experience Provides Lessons Learned
Chapter 1
The Regulatory Environment
New Regulations, New Responsibilities, New Opportunities Sarbanes-Oxley Section 302 and 404 Responsibilities What Internal Controls? Changing DBA Responsibilities DB2 DBAs and the SOX Mitigation Effort The Participating DBA HIPAA Gramm-Leach-Bliley Federal Information Security Management Act
Chapter 2
DB2 Security—The Starting Point
First Words—What’s the Plan? The DB2 Security Plan Security Plan Meeting Participants Meeting Goals and Desired Outcomes Next Steps DB2 Database Security—Create the Policy Using the Plan to Formulate the Policy Review, Approve, Implement, Maintain General Guidelines—Building the DB2 Database Security Policies Change Control—Things Are Gonna Change Last Words
Chapter 3
Understanding Identification and Authentication— The First Line of Defense
First Words: Why Is Authentication Critical to Database Security? Overview of the Default DB2 Authentication Mechanism Authentication Type What Authentication Type Should I Use? Understanding Authentication—In General SRVCON_AUTH Database Manager Configuration Parameter
1 2
5 5 6 7 7 8 9 13 13 17 18
21 21 22 23 26 34 35 35 35 36 39 40
41 41 42 43 44 44 46
Table of Contents
Authentication Type Negotiation Between the Client and Server Specifying Authentication Type on the DB2 Connect Gateway How to Determine the Authentication Type Used for a Connection Introduction to Security Plug-Ins Why Did DB2 Implement the Security Plug-In Architecture? Type and Categories of Security Plug-Ins IBM-Shipped Default Plug-In Client-Side Auth Plug-Ins on the Database Server Authorization ID Versus User ID Roles of the Different Categories of Security Plug-Ins DB2 Security Plug-In APIs GSS APIs Security Plug-In-Specific Database Manager Configuration Parameters (DBM CFG Parameters) Enabling Security Plug-Ins When Is the Security Plug-In Loaded by DB2? Other Features Available in Customized Security Plug-Ins The Basic Flow of GSS API and DB2 Security Plug-In API Restrictions Imposed on GSS API Plug-Ins by DB2 Kerberos—An IBM-Shipped GSS API-Based Security Plug-In Authorization ID Mapping Consideration Customized Kerberos-Based Security Plug-In IBM-Shipped Kerberos Plug-In (IBMkrb5) More Information about Kerberos The Lightweight Directory Access Protocol (LDAP)—Yet Another IBM-Shipped User ID/Password-Based Security Plug-In IBM-Shipped LDAP Authentication and Group Membership Plug-In Authoring and Implementing Customized Security Plug-Ins Step 1: Include the Security Plug-In Header Files in Your Plug-In Step 2: Write the APIs Constituting Your Plug-In Step 3: Populate the Functions Pointer Structure Before Returning to DB2 Step 4: Compile the Plug-In Source and Create a Shared Library Step 5: Place the Library in the Appropriate Directory Case Study: Using a Customized Security Plug-In to Implement the Ability to Centralize User ID and Password and Group Membership Information in a Database Requirement Proposed Design Detailed Implementation Information Sample Scenarios Scenario 1: Mixed Use of Pre-8.2 and 9 Clients with the GSS API Plug-In Scenario 2: DB2 9 Client Communicating with a Database in a Different Instance with a Different Authentication Setting Scenario 3: Using Kerberos for Authenticating DB2 (Linux/UNIX/Windows) Client in an Environment That Also Has a DB2 for z/OS Client Security Plug-in Deployment Limitations Last Words
First Words Scope of This Chapter First Steps: Build in DB2 Security during Installation Heroes Welcomed Here Documentation Is Necessary Thinking “Security”—Planning the Windows Install Designed Especially for Windows Windows Domain\User Installation User ID DB2_EXTSECURITY The Windows Operating System—The Important Stuff Review Windows Account Policy Settings Lock Down and Protect Windows Accounts Lock Down Unneeded Features for the Windows Registry Windows Active Directory The Local System Account (LSA) Other Considerations Physical Security for Windows Servers Fixpacks, Service Packs, Patches—Use ’em or Lose The Dilemma Last Words
Chapter 5
Authorization—Authority and Privileges
First Words Terminology Object Owner Authorization ID Static SQL Object Best Practices Need-to-Know Least Privilege Separation of Duties Processes to Control and Review Avoid Granting to Groups Due Diligence Documentation Made Easy (or at Least Easier) Using Schemas for Control and Management of Database Objects Avoid Granting to PUBLIC Restricting the PUBLIC from the Start Without the Protection of “Restrictive” Easy Public Revokes Authorities Instance-Level Authority Database-Level Authority How Can Current Authorities Be Determined? Direct Authority Versus Indirect Authority
Privileges SQL Objects and Their Privileges Implicit Granted Authorities and Privileges Authorization Checking for DB2 Commands and Utilities Authorization Checking for SQL Statements Statement Authorization ID Different Authorization Models Available in DB2 Retrieving the Group Membership List for a Given Authorization ID More Ways to Encapsulate When Will Those Grants and Revokes Take Effect? Object Ownership Management SYSIBMADM.OBJECTOWNERS Last Words
Chapter 6
Label Based Access Control
What Is LBAC? A High-Level Overview The LBAC Architecture Security Label Components LBAC Security Policies Security Labels Row Security Labels Column Security Labels User Security Labels Exemptions Protected Table How LBAC Is Enforced Read Access Rules Write Access Rules Array Security Label Component Set Security Label Component Tree Security Label Component Exemptions The Security Plan for Protecting Data Security Plan Meeting Participants Designing the Security Solution Activity Overview for Implementing an LBAC Solution Manipulating Data in Protected Tables Insert Data Records into Protected Tables Retrieve Data Records from a Protected Table Update Data Records in a Protected Table Delete Data Records from a Protected Table Manipulating Data with Security Label with SET Security Label Component Inserting with a Security Label of SET Security Label Component Example Retrieve Data Records Protected by SET Security LabelComponent Elements Updating Data Records Protected by SET Security Label Component Deleting Data Records Protected by SET Security Label Component
Manipulating Data with Security Label with ARRAY Security Label Component Inserting with a Security Label Of ARRAY Component Retrieve Data with a Security Label of ARRAY Security Label Component Update Data with a Security Label Of ARRAY Security Label Component Delete Data with a Security Label of ARRAY Security Label Component Manipulating Data with Security Label with TREE Security Label Component Insert Data with a Security Label Of TREE Security Label Component Scenario Retrieve Data with a Security Label of TREE Security Label Component Update Data with a Security Label of TREE Security Label Component Delete Data with a Security Label of TREE Security Label Component Use Case Scenario Analyzing Data Restrictions Designing the Security Solution Implementing the Security Solution Runtime Usage Managing Security Objects Review the Definition of Security Objects Review Security Labels Review Security Policies Review Security Label Components Dropping Security Labels Dropping Security Policy Dropping Security Label Component Managing User Access to Protected Data Granting Security Labels to Users Granting Exemptions to Users Revoking Security Labels from Users Revoking Exemptions from Users Managing Protected Tables Review List of Protected Tables Altering Table Protection: Adding Column Protection Altering Table Protection: Adding Row Protection Altering Table Protection: Drop Column Protection Altering Table Protection: Alter the Security Policy of a Protected Table Remove Protection from Protected Tables Dropping Protected Tables LBAC Support in Miscellaneous Utilities Views Query Through Views INSERT through Views Materialized Query Table (MQT) Staging Table Typed Table Import Export
Load Copy Table in Control Center Stored Procedure: ADMIN_COPY_SCHEMA Database Backup Alter Table Referential Integrity Constraints Explain db2look Last Words Reference Material
Chapter 7
Encryption (Cryptography) in DB2
First Words The Cryptographic Keys Private Key Cryptography Public Key Cryptography What Type of Encryption Does DB2 Use? Encryption for User IDs and Passwords Passed in the Connect Statement Encryption for Sensitive Data Sent Through the Network Encrypting Sensitive Data Stored on Disk Last Words
Chapter 8
Ready, Set, Implement?
First Words: Just Start…but Where ? Apply Knowledge Reuse An Implementation Beginning Point Keeping It Real—No One Size Fits All Things Not Considered (That Likely Should Have Been) Password Authentication and Maintenance How Sensitive Are You? Implementing Foundational Security Where Design Meets Implementation Watch Out for the Public (What Does the Public Need to Know and When Do They Need to Know It?) Choosing the SHOW SQL option Security Considerations for Upgrades, Migrations, Scalability Security and Database Performance Last Words
Chapter 9
Database Auditing and Intrusion Detection
First Words Crisis Mode Initial Steps to DB2 Database Auditing Corporate Sponsor Discovery For DBAs Only From Analysis to Physical Design db2audit and Intrusion Attempts Before db2audit—Think—Test—Learn
db2audit Facility—What Can It Do? Using db2audit for Multipartition Environments db2audit Facility Safeguards The db2audit Facility Command Syntax Triggers DB2 Recovery Expert for Multiplatform Stored Procedures, UDFs, and Other Programmatic Approaches to Auditing Monitoring, Reporting, and Analyzing Last Words
Chapter 10
SSH for Data-Partitioning on UNIX Platforms
First Words Secure Shell (SSH) for Data-Partitioning Feature on UNIX The Setup Steps Public Key Authentication (per User Account) Host-Based Authentication (per Machine) How to Configure DB2 to Use SSH Last Words
Chapter 11
Database Security—Keeping It Current
First Words Diligence DB2 User Community Resources Security Information on the Web Fixpacks Keeping Current Goes beyond DB2 Mixed Database Environments Vulnerability Assessments Intrusion Detection Prepare for a Breach Preparing for the Future Last Words
Chapter 12
Final Thoughts: Security—The Human Factor
First Words Education and Awareness For Geeks Only For the “Normal” Folks Social Engineering Step on a Crack—Break Security’s Back Publish and/or Perish? Last Words
Appendix A Appendix B
Independent Security Packages Kerberos
Configuring the NAS Kit on UNIX®/Linux® Systems for the IBMKrb5 Plug-In Configuring the Windows® Client and Domain Controller to Enable the Windows Native Kerberos Environment
DB2 Audit Scope Record Layouts DB2 Audit – Additional Documentation
337 349
Security Considerations for DB2
363
Security Considerations (Sourced from Administration Guide: Implementation) Gaining Access to Data Through Indirect Means Default Privileges Granted upon Creating a Database UNIX Platform Security Considerations for Users (Sourced from Administration Guide: Implementation) Windows Platform Security Considerations for Users (Sourced from Administration Guide: Implementation) Security Considerations in an LDAP Environment (Sourced from Administration Guide: Implementation) Security Considerations for Active Directory (Sourced from Administration Guide: Implementation) Security Considerations for Routines (Sourced from SQL Guide) Security Risks Security Considerations for DB2 Administration Server (DAS) on Windows (Sourced from Administration Guide: Implementation) Security Considerations for User Mapping Plug-In for a Federated Environment (Sourced from Websphere Information Integration Documentation)
Appendix F Appendix G Appendix H Appendix I
333 334
363 363 365 367 367 368 368 369 370 372 373
Glossary of Authorization ID LBAC-Related SYSCAT Views
375 379
Security Plug-In Return Codes Detailed Implementation for the Case Study in Chapter 3
Preface Today’s headlines have an unfortunate, recurrent theme…security breaches are becoming common place. Thousands of credit card numbers have been stolen and identity theft is on the rise throughout the world. As a result, legislative bodies are proposing ever more stringent laws and forcing corporations to fund security protections for their citizens’ data. Corporations also recognize that their continued viability depends on ensuring that the customer’s trust is not disrupted by a data breach. Fortunately for all of us, enterprises are becoming increasingly concerned about keeping their (our) data (data that is stored in databases such as DB2) safe. This book is in response to a need for ever-increasing knowledge about database security— knowledge that is not just about “technology” or “management,” but the “whole” of database security.
AUDIENCE Understanding DB2 9 Security is written for DB2 DBAs and their managers. For DBAs, this book provides a wealth of security information specific to both the “new” and the “tried and true” technology delivered in the DB2 9 product. DBAs will appreciate the numerous real-world implementation scenarios and step-by-step examples. Since, in today’s world, database security is not just about the technology, the managerial and “human” aspects of security are covered in their logical progression throughout the chapters. Through the material and examples provided, Understanding DB2 9 Security also provides a strong lesson foundation for students tasked with learning how to securely implement a DB2 database on Linux, Windows, or UNIX platforms. For all readers, the authors encourage you to develop an appreciation for the “whole” of database security.
ORGANIZATION The material in this book is organized in a logical progression from the standpoint of implementing a secure DB2 database environment. It begins by exploring the regulatory environment, continues with the technological and managerial knowledge that is so critical to the success of the effort, transitions to a discussion of post-implementation auditing, and then covers “go forward” considerations. Additional documentation details are provided where appropriate via appendixes.
Preface
xxi
Chapter 1:The Regulatory Environment Before beginning any task, it is wise to know the rules and reasons that drive the results. This Chapter provides an overview of some of the regulatory “drivers” regarding database security.
Chapter 2: DB2 Security—The Starting Point Where do you begin “building security”? Chapter 2 discusses the security “building blocks” that form the foundation for a secure implementation. The processes and team member participation necessary to create security plans and database security policies (essential to creating and maintaining a robust security implementation) are explained in depth.
Chapter 3: Understanding Identification and Authentication— The First Line of Defense Authentication, the process of identifying the user to the database, is a strong security mechanism. This chapter provides a deep dive into the topic.
Chapter 4: Securing DB2 on Windows As compared to their Linux and UNIX counterparts, Windows implementations of DB2 provide unique security opportunities and risks. The extra benefits and extra steps for a secure DB2 Windows environment are covered here.
Chapter 5:Authorization—Authority and Privileges Authorization (authorities and privileges) determine whether a user has the right to access or own a database object. As such it is a strong data protection defense. This complex topic is covered in Chapter 5.
Chapter 6: Label Based Access Control New in DB2 9, Label Based Access Control (LBAC) is an access protection mechanism that provides for a finer granularity of control over data than has been traditionally provided by table privileges. This chapter provides a comprehensive overview of LBAC and includes solid examples showing the robustness of the functionality.
Chapter 7: Encryption (Cryptography) in DB2 Encryption is typically a part of any secure implementation. DB2 9 allows use of encryption for connections, for data “in flight,” and for data on disk. These topics and step-by-step examples are covered in Chapter 7.
xxii
Preface
Chapter 8: Ready, Set, Implement? At what point is it time to begin the implementation? What must be in place before you begin? Find the answers to these questions in Chapter 8.
Chapter 9: Database Auditing and Intrusion Detection Database auditing and intrusion detection are employed for a variety of security reasons. However, setting up for this task involves some serious consideration. Chapter 9 provides both the background discussion and the technical implementation details for auditing and intrusion detection.
Chapter 10: SSH for Data-Partitioning on UNIX Platforms For environments using DB2 9 with the Data Partitioning Feature, security of machine-tomachine communication is necessary. This chapter details the setup and verification steps necessary to ensure that these types of communications don’t become a vulnerability.
Chapter 11: Database Security—Keeping It Current Security is a never-ending process. There is no “finish.” To stay secure, your environment must keep current with the latest patches and fixes. Chapter 11 discusses these and gives details on where to obtain the latest information.
Chapter 12: Final Thoughts: Security—The Human Factor Technology is only one aspect of database security. The human factors (too often overlooked) must be considered. The human aspects of security are covered in Chapter 12.
Acknowledgments Writing a technical work such as this necessitates multiple levels of review by individuals who are typically overtasked and who have little spare time. This book would not exist were it not for the ongoing support of the following individuals who took time from their all too busy schedules to assist us. Their contributions to our research, tireless reviewing of chapters, and overall enthusiasm for the topic were crucial to the effort, and the authors would like to convey their sincere appreciation. Susan Visser Paul Bird Lawrence Wargo Tim Heagarty Bob Harbus Dwaine Snow Walid Rjaibi Michael Snowbell Arnaldo Gouveia Greg Stager Hassan Shazly Herrick Mai Scott Logan
About the Authors Rebecca Bond With a background in finance, healthcare, and government technology consulting, Rebecca developed a passionate interest in data security concepts early in her IT career. Identifying security as an area that was being ignored in favor of more visible priorities on too many technical projects, she began research in 1992 on ways to secure sensitive data. During preparation work on her Master’s Capstone, entitled “Data Security in an HMO,” (a ‘thesis equivalent’ project for her MBA), Rebecca expanded the scope of her interest to include additional aspects of security such as physical security and the role played by human engineering. She began to voraciously read security manuals and analyze prominent (and not so prominent) IT security failings with a focus on how to mitigate those failings. In 1997, Rebecca was tapped as a DB2 UDB DBA on a large state financial project. This was her first introduction to DB2 UDB, and she quickly recognized the power and flexibility of the product. Determined to learn all aspects of the database engine, she began to work toward developing an expert-level competency. At each step of her work toward mastery, she validated her knowledge via the IBM certification process. She currently holds numerous IBM DB2 certifications and has been designated as an IBM DB2 Subject Matter Expert. As an independent DB2 UDB consultant, Rebecca brings a special focus toward security to each project. One of her greatest strengths is designing the database environment with security at the forefront, not as an afterthought. Even when the work day is finished, she continues her research, tenaciously seeking new ways to use the robustness of the DB2 UDB product to provide the highest level of security. During those brief moments when Rebecca’s eyes are not glued to a computer screen, she enjoys spending time gazing at Louisiana’s spectacular sunsets, “working out” on whatever physical fitness machine is part of the latest craze, writing children’s stories, buying shoes, and catching up on “what is really important” via long distance phone calls with her five grandchildren. Rebecca welcomes your correspondence on DB2 security or other topics. Her e-mail address is [email protected].
About the Authors
xxv
Kevin Yeung-Kuen See Kevin Yeung-Kuen See, CISSP, has been a Software Developer at the IBM Toronto Laboratory for the past decade. His experience includes working in the DB2 Security Development team and the DB2 SQL and Catalog Development team. He received a Masters of Mathematics in Computer Science degree (specializing in software engineering) from the University of Waterloo and a Bachelor of Computer Science degree from Acadia University. He is an IBM Certified Solutions Developer for XML and related technologies and an IBM Certified Solutions Expert (DBA for OS390, DBA for Linux/UNIX/Windows, Advanced DBA for Linux/Unix/Windows and DB2 Family Application Development). He is also an ISC2 Certified Information Systems Security Professional. He has written a few IBM developerWorks articles on the topic of DB2 security. In his spare time, he enjoys hiking, learning something new, and trying to figure out the world according to Justin, his toddler son. You can reach him at [email protected].
Carmen Ka Man Wong Carmen Wong is a Staff Software Developer at the IBM Toronto Lab. She recently joined the DB2 Continuing Engineering team, with focus on DB2 Process Model. Prior to that, she worked in the DB2 Administration Tools Development Team for five years. Her experience includes Java GUI development for DB2 Administration Tools, specialized in monitoring tools (Visual Explain and Event Monitor). She was also involved in the LBAC project in the DB2 9 release. Carmen holds a Bachelor of Mathematics in Computer Science degree from the University of Waterloo. She is an IBM Certified Application Developer (DB2 Universal Database V8.1 Family). She has published two LBAC-related tutorials on IBM developerWorks. She can be reached at [email protected].
Yuk-Kuen Henry Chan Henry Chan is an Advisory Software Developer at the IBM Toronto Lab working in the DB2 Continuing Engineering team. Prior to that, he worked on the DB2 Security Development team and the DB2 Relational Database Services team and has been with IBM for ten years. He received a Master of Science degree from the University of Alberta and a Bachelor of Mathematics degree from the University of Waterloo. He is an IBM Certified Solutions Expert (DBA for Linux/Unix/Windows and DB2 Family Application Development).
This page intentionally left blank
Introduction Every DBA needs a super-invisible DBA cape since we always have to be the heroes. —Rebecca Bond
ecurity in any organization often appears to be an insurmountable obstacle. As soon as you get something implemented, it needs to be reviewed and possibly revised; and shirking the responsibility is just not an acceptable option. Just like leaving the door open before a hurricane, it is too late to start to plan a defense after the storm arrives.
S
Costs and time are often cited as insurmountable issues in implementing security. On balance, however, the implementation expense cannot compare to the devastating costs of managing and recovering after a security breach. Today’s high-profile security lapses make headlines and carry the potential to destroy a company and ruin individual careers. Federal, state, and international lawmakers are taking notice of the headlines and their constituents’ complaints. In the United States, Sarbanes-Oxley, HIPAA regulations, and the Gramm-Leach-Bliley Act will soon be joined by other security-based legislative mandates as more and more corporate security breaches are reported. Although it can serve as both a technical and nontechnical reference for database security, this book is not intended to cover every aspect of information security. There is simply too much information to put in one book. Instead, the focus is on one critical piece of the whole: security for your IBM® DB2® 9 Linux®, UNIX®, and Windows® databases. Think of the information stored in those databases as jewels in your corporation’s crown. Its riches hold great potential interest to others. You may have Social Security numbers, names, addresses, and phone numbers stored there. That information is all too tempting for those who want to make an illegal profit or even those who just want to make a public point about security lapses.
1
2
Introduction
When we think about database security, perhaps we mentally imagine someone glaring at a monitor, trying password after password to gain entry to a system or database. If the trend of many high-profile recent database security breaches teaches us anything, however, it is that the threat is both internal and external. We cannot just protect from the “outside,” we have to consider that inappropriate access from the corporation’s employees can do just as much, if not more, damage. The good news is that DB2 9 offers a wealth of ways to control and protect access to your databases. These ever-increasing pressures to protect the database from a variety of threats make it critical to fully understand the numerous security features that DB2 9 provides, what they are, how to implement them, and how you can incorporate them into your overall security policy. In that regard, the focus of the material here is primarily directed toward those individuals holding the responsibilities of DB2 database administrator (DBA) or system administrator (SA). With the DB2 9 release, many new and robust features are introduced to further strengthen DB2 security and facilitate the ability to lock down the database from unintended access. Given these enhanced features, such as Label Based Access Control (LBAC), security options have been richly augmented over previous versions of the product. Whereas security of every database is the goal, the technical aspects of a database security implementation will vary depending on the platform. This book is written from the DB2 9, Linux, UNIX, and Windows perspective. It does not cover DB2 for z/OS® or DB2 for iSeries.
A PERSONAL EXPERIENCE PROVIDES LESSONS LEARNED Security and disaster recovery really hit “home” for one of the authors of this book. Rebecca Bond had been working in New Orleans in the closing days of August 2005. She had returned to her home in Ohio for a weekend trip only to find out when she reached Ohio that Hurricane Katrina had changed course and was directly targeting New Orleans. Not realizing that her return to New Orleans would be delayed for months, she had traveled lightly, bringing only one change of clothes and her USB drive. Still, she knew that the levees were designed to protect the city, so she wasn’t too concerned that the damage would be extensive. When the first levee broke in New Orleans, Rebecca realized that the initial breach was only 50 yards from where she had been living. At first, of course, she was concerned only for her friends and the people who hadn’t made it out of the city. It was much later that she realized that her apartment was probably destroyed along with all its contents. The book she was writing—the book you are reading—was partially completed but had been written (and saved) on computers that were potentially lost during the storm. Starting the task again would have meant months of rewriting chapters and would probably not have been possible because Rebecca was busy dealing with the personal and professional chaos that surrounds any true disaster recovery situation.
Introduction
3
Perhaps by divine intervention, Rebecca had brought her USB drive with her to Ohio. It had served as her backup device throughout the writing process, and she had just saved all the completed chapters the day before leaving New Orleans. Thanks to a backup device that literally is not much bigger than a thumb, this book is a Katrina survivor. Months later, Rebecca was finally able to return to New Orleans. The levee breach, despite being so close to her apartment, had not flooded her street. Her computers were in tact, as well as most of her belongings. Although she feels blessed to have been spared when so many lost so much, she also learned lessons that are appropriate to pass on to the readers of this book. First, disaster comes when you least expect it. Second, you can never have too many backups. Third, don’t count on having access to things that you typically need to do your job. Fourth, overplanning is a thousand times better than no planning. Fifth, there is no such thing as too much redundancy. As you read this book, the authors hope that you can visualize worst-case scenarios and prepare for dealing with a variety of approaches to mitigate any real-life situation you and your corporation are faced with, whether a disaster recovery or a security breach. As hard as it is to think about, it is the very act of preparing for the worst case that provides the greatest assurance of survivability.
This page intentionally left blank
CHAPTER
1
The Regulatory Environment
are providing new career and advancement opportunities for DBAs who underR egulations stand how to enhance security and mitigate risk.
NEW REGULATIONS, NEW RESPONSIBILITIES, NEW OPPORTUNITIES “Fast and loose” was how many were playing the game in the 1990s U.S. corporate environment. Controls and regulations were ignored, financial abuses were covered up, profits appeared to soar (when they were not even maintaining status quo), and on the surface, life in the stock and financial realms appeared to be a never-ending earnings party to which most wanted to be invited. The economy was robust and freewheeling. Many investors, caught up as if the 1880s gold rush had returned, hastily threw down their hard-earned money to get into “the market” before they lost the opportunity to realize the virtually guaranteed “great rewards.” Gains of hundreds of points per day were seen on NASDAQ. Initial public offerings (IPOs) of new companies were sold at several times their estimated market-entry value and were impossible to purchase before the price doubled, tripled, or quadrupled. Wealth appeared to be everywhere. Of course, that’s all history now. The facçade of financial soundness was as true as a fairy tale for some of the largest companies in the U.S. corporate lexicon. By 2002, the U.S. news became rife with tales of corporate corruption, many involving grievous financial irregularities. Evidence showed that some major corporation’s public disclosures to shareholders had not been presenting the true financial status of the company for some time. This was the time of stock price collapses and large corporate bankruptcies. The false wealth had turned to true dismay.
5
6
Chapter 1 • The Regulatory Environment
The American public, seeing their pension funds fall away, their nest egg evaporate, and their stock capital dwindle, had endured enough. Confidence needed to be restored. There was a great outcry from all across the world: “Make them accountable.” So, what does the U.S. Congress do when the citizens demand results? Congress attempted to shove the pendulum toward the opposite side. The regulatory bodies seem determined to make up for lost time. No more would citizens face losing their pension because of financial irregularities. No more would information presented to stockholders be incorrect or misleading. No more would private, personal data be “at risk.” Wait! That wasn’t the problem, was it? Didn’t we just agree that the problem was financial irregularities? How did personal, private data become a regulatory issue? It is interesting that while Congress finally got on board to assuage corporate malfeasance, other corporate controls came to light as being very lax. The poor citizens, having lost all their money in the stock market, were now faced with losing their identity! Unfortunately, with the exception of the HIPPA (Health Insurance Portability and Accountability Act) that dealt solely with health care, Congress hasn’t been able do enough to protect private, personal data, although some new regulations have been put into place. This is evidenced in the virtual daily barrage of headlines citing yet another corporate security breach with thousands of credit card numbers, Social Security numbers, names, and addresses now on the list of stolen articles and presumably in the public domain. Banks, credit agencies, personal registration information for driver’s licenses, car tags … all have suffered unintended leaks. Not yet recovered from the financial missteps, the citizens cried out again. The cry is not yet 100 percent heeded, but in time, it will be. New rules and regulations are rumored to be in consideration. This brings us to today and to the database administrators (DBAs) and system administrators (SAs) who had absolutely nothing to do with any of the wrongdoing. These are the guards of the corporate data; the keepers of the crown jewels. Welcome you heroes who, through documentation, proper procedures, determination, and technology, will turn those regulations into realities and, by your efforts, protect the citizens (and your jobs) from any harm. Bring your Super Invisible DBA cape as we explore the world of regulations … both actual and likely to be proposed … and what they mean to us as we do our jobs.
SARBANES-OXLEY July 30, 2002 was a monumental day for business accountability in the United States. It was on that date that the Sarbanes-Oxley Act of 2002 was signed into U.S. law. With the passage of Sarbanes-Oxley (also known as SOX or SARBOX), strict governmental requirements were put in
New Regulations, New Responsibilities, New Opportunities
7
place. Those included new auditing standards and disclosures, a guarantee of auditor independence, stronger enforcement of corporate responsibility, enhanced conflict of interest provisions, criminal penalties for altering documents or tampering with records, and enhanced financial disclosures. At the present, these requirements are enforced only for large, publicly traded companies; however, many smaller corporations and private companies are following these recommendations because the framework provides for a strong security and accountability matrix, and the regulations are likely to trickle down to them in time anyway. Although several of these new provisions may impact the DBA when setting up a security environment, the ones guaranteed to provide additional work opportunities are sections 302 and 404. These sections refer to corporate responsibility for financial reports and management assessment of internal controls.
Section 302 and 404 Responsibilities Section 302 takes the responsibility for financial data straight to the executive level of the organization. The executive officer of the company has to personally sign and attest that the financial reports are accurate, not misleading, and that they fully disclose financial controls and results of corporation operations. If there are any weaknesses in the design or operation of any control that would result in adversely affecting the recording, processing, aggregation and summarization, or reporting of financial data being suspect in any way, this must be disclosed. Section 404 speaks to management’s assessment of internal controls and is required to be included in the company’s annual report. This section requires the establishment and maintenance of internal control structures and reports the effectiveness of those controls over the course of the previous fiscal year. The firm doing the corporate audit also needs to attest to compliance with Section 404. Making false statements on a Sarbanes-Oxley report is against the law and can lead to hefty fines and/or jail time for the highest corporate officials. It is obvious that the company’s executive officer does not want to sign off on any documentation stating the financial or security soundness of her company without having a reliable way to know that it is safe to do so. To ensure that the information presented in the SOX certifications is “true,” there has been (and will continue to be) a need for a strong foundation of supporting information. To enable this foundation, internal controls will proliferate, and audits will become normal operating procedures.
What Internal Controls? Although there is no true, pure source to refer to for a list of Sarbanes-Oxley controls explaining what they are and how to implement them, your accounting and auditing firms will not be deterred from looking into every nook and cranny of your organization to validate the efficacy of them. That is their job, and they will do it well.
8
Chapter 1 • The Regulatory Environment
Because there is no “one size fits all,” it is best to be prepared with more information than is necessary. This leads us to a discussion of what regulations your CFO is going to be reading before she comes to you to discuss your role. As a part of Sarbanes-Oxley, a nonprofit agency, the Public Company Accounting Oversight Board (PCAOB), was established. The PCAOB may create rules that are then submitted to the U.S. Securities and Exchange Commission (SEC) for approval. The SEC also has rules and regulations that impact internal controls. Throw in the Generally Accepted Accounting Principles (GAAP) that you learned about in your required college business course and any accountancy’s interpretation of those principles, the Committee of Sponsoring Organizations of the Treadway Commission (COSO) a private-sector organization that provides guidance on internal controls, and the Control Objectives for Information and related Technology (COBIT) framework, and you have a general idea of the internal control requirements for Sarbanes-Oxley compliance. How they might impact your Information Technology (IT) department can be further defined based on the company’s business model, the number and types of subsidiaries and remote locations, and various other business model drivers. As you can probably tell from the preceding paragraph, different auditors bring different interpretations on compliance with internal controls. The ones listed in this book are the most frequently cited at this time, but there may be others. It is also probably obvious that the time necessary to implement new internal controls or rework old controls is not trivial. Many larger organizations report exorbitant costs and long lead times associated with SOX implementations. Some of the expenditures are so large that, when publicly announced, the company’s stock price has dropped dramatically because of stockholder’s selling. Sellers cited concerns about the sizable expenses of SOX implementations. The very controls required to prevent the stockholders from “losing their shirts” are, in fact, the ones that are driving the stock prices down (and, therefore, some of the stockholders do, in fact, lose their shirts).
Changing DBA Responsibilities A significant outcome of the SOX regulations to date has been the overtime and additional staffing in IT departments. IT departments are more often working long hours under significant stress to retrofit systems for compliance, and DBAs' efforts are critical to a successful outcome. The world of corporate accountability has changed, and the DBAs must help to rescue their company. DB2 DBAs have now been tasked with new security initiatives. They are required to ensure that only proper, “as-needed” access to the corporate data is granted, that potential misdeeds will be caught at the database layer, and that attempts to change data to hide nefarious deeds will be both unsuccessful and point to a guilty party so that punishment can be meted. Disaster recovery is taken a step further with the requirement to be able to restore to original any data that is changed in a harmful way, whether intentional or unintentional. Of course, the DBA also has to ensure that sensitive data is encrypted. Some DBAs and data analysts may even have to do data quality reviews to show that reports are generated based on factual information.
New Regulations, New Responsibilities, New Opportunities
9
The tasks ahead might begin to feel overwhelming, but fortunately, DB2 DBAs have a wealth of tools to assist in creating these controls and performing these audits. DB2 DBAs are absolutely integral to the success of the company rising to the challenge of SOX compliance. Their role, as a result, has been elevated, and their sphere of influence has increased in most organizations.
DB2 DBAs and the SOX Mitigation Effort Application controls are necessary to confirm the validity of the application transactions. These are the controls designed to prevent fraud, trap or prevent unintentional mistakes, enable tracking of transactions, and ensure completeness of the application’s resulting information. The DBA is likely to be a critical resource in compliance for each of these areas. As the process toward SOX compliance begins, the DBA will likely be asked to participate in preparation of documentation and instantiating additional database implementations to satisfy some of the requirements discovered through the review. During the conversations regarding SOX implementation, the DBA will have a lot to offer in the way of DB2 features that can be deployed to satisfy many of the technical requirements that relate to requiring proof of strength of the company’s internal controls. Some of the most frequently mentioned DB2 features for SOX compliance include auditing, configuration, authorities, privileges, encryption, backups and restores, and transaction replay (roll forward). The DBA’s expertise is also needed for transitioning “user-created mechanisms” that emulate database functionality, especially if they are found lacking in security control mechanisms, such as spreadsheets. A DBA who can write solid SQL is also invaluable to the SOX effort because SQL statements will need to be created for a wide variety of reasons, such as confirming auditing (if the audit data is stored in tables), reviewing privileges granted to users, querying financial information, and verifying that confidential data is secured, just to name a few. Auditing One of the major tools that the DB2 DBA can offer in the arena of internal controls is the ability to audit transactions natively in DB2. Because one goal of SOX is to determine that adequate controls are in place, DB2 auditing is one of the “big guns” that can be positioned to satisfy the requirements to document what applications touched the database, what ID was used to instantiate those transactions, the “context” of the transaction (what SQL was run), and whether the attempt failed or succeeded. As such, DB2 auditing serves multiple purposes for SOX mitigation, including the following: • Provides documentation of transactions applied to the database • Shows any changes in authority including the id used to grant the change • Tracks any changes to the DB2 auditing configuration itself
10
Chapter 1 • The Regulatory Environment
• Can be used as a means to show that all transactions are recorded • Facilitates a first step toward identification of fraudulent database access Chapter 9, “Database Auditing and Intrusion Detection,” covers DB2 auditing more completely. Segregation of Duties Although the DB2 DBA cannot enforce segregation of duties from the corporation level, she certainly can do so from the database and instance level. DB2 offers a wealth of authorities, privileges, labels, and “granted” configurations that can lock down access to the finest grain of detail. For example, there are four different levels of System privileges (SYSADM, SYSCTRL, SYSMAINT, SYSMON) in DB2 that can be assigned to DBAs who need to perform normal day-to-day responsibilities. These can be assigned based on DBA job responsibilities and will be viewed by the auditor as an aid in collusion avoidance. DB2 9 also offers a unique “Security Administrator” authority (SECADM) that can be granted to a user to further define the security granularity. Chapter 5, “Authorization—Authority and Privileges,” provides more information on these topics. With Label Based Access Control (LBAC), new in DB2 9, security labels contained in an object, coupled with the security label granted to the user attempting access, can be used to fine-tune finite security access database controls based on the user’s actual business role. The granularity of access controls in DB2 is robust and will score high marks during the audit. DB2 access control general mechanisms are discussed in detail in Chapters 3, “Understanding Identification and Authentication—The First Line of Defense,” and 4, “Securing DB2 on Windows.” LBAC is discussed in Chapter 6, “Label Based Access Control.” Backups Integral to the SOX guidelines is that data must be recoverable. This is not just a requirement to be able to restore a database, it is also a requirement that data that has been corrupted by any application or user process, whether a normal mistake or as the result of a hack, is restorable to pristine. DB2 has always offered a robust internal utility for database backups. The DB2 BACKUP DATABASE command and associated application program interface (API) is time tested and widely used by DB2 DBAs everywhere. DB2 dropped-table recovery functionality, once enabled, allows a fine level of recovery should a table be accidentally dropped. Other DB2 features and functionality enable you, given the appropriate hardware, to instantiate databases using Flash or split-mirror technology, which can also serve as backup mechanisms. (Split-Mirror technology is exceptionally well covered in the book High Availability Guide for DB2, by Chris Eaton and Enzo Cialini.)
New Regulations, New Responsibilities, New Opportunities
11
As you can see, DB2 recovery options are both plentiful and robust. Some well-known and oftenused examples are as follows: • A restore from a DB2 backup • Restoring a backup image into a different database (redirected restore) • Recovering a dropped table • Restoring a tablespace • Backing up and restoring single or multiple tables using export and import/load functionality • Using the DB2 Recovery Expert to restore a single unit of work With the DB2 restore utility, the database-level restore can be made over the database the backup was taken from, to another database on a different file system (using the redirected option), to a point-in-time (allowing restores to a point prior to the time when some unintended process was run), or the restore can just be to a single affected tablespace. The backup(s) being used for the restore may come from a single backup image or a combination of backup images (from the same database) applied in specific order. The restore may need to be completed with the application of DB2 database transaction logs, or may be completed using only a full backup image, depending on the scenario. The DB2 Recovery Expert is an add-on product requiring a separate license. Given the SOX requirements to be able to recover, if necessary, from virtually any unwanted SQL, the DB2 Recovery Expert provides a virtually infinite level of granularity allowing reversal of unit-ofwork SQL changes to the DB2 database without requiring a database restore operation. The product can read the DB2 transaction logs and can be used to replay transactions in reverse order, backing out the SQL unit of work in question without restricting access to the database for other transactions. As you can tell, the options for recovering a DB2 database are both powerful and flexible. They may be incorporated to play a large role in meeting compliance requirements for disaster recovery and business continuity, too. Encryption Encryption is mentioned by many SOX auditors as necessary for maintaining the confidentiality of data. Although there is no hard-and-fast guideline to determine what is confidential and what is not, it is probably safe to consider personal, identifying information such as Social Security numbers, employee ids, birth dates, and health records to be strong candidates for information requiring encryption.
12
Chapter 1 • The Regulatory Environment
Since Version 6, DB2 has supported password encryption “on the wire” through the use of the SERVER_ENCRYPT database manager configuration parameter. This feature keeps the login password secure and prevents password discovery via sniffing. The DATA_ENCRYPT parameter takes this encryption several steps further by encrypting not only the password, but also SQL, the output of the SQL, and more. DB2 data encryption features are also available for use by application software code via the use of built-in functions such as ENCRYPT, DECRYPT_BIN, DECRYPT_CHAR, and GETHINT. The mechanisms to encrypt/decrypt data rely on a password that can be set interactively or embedded in the application itself, providing additional flexibility. The GETHINT feature is also under code control and can be used to aide the user attempting to remember the password. Given the importance placed on encryption for many current and potential future regulatory requirements, this topic is discussed in detail in Chapter 7, “Encryption (Cryptography) in DB2.” Securing User-Designed Pseudo Databases One of the places security compliance auditors are likely to focus is reviewing the company’s “quasi” database spreadsheets and user-driven database implementations. These are not “true” databases, but they often exist and should be thought of as “pseudo” databases. Many financially oriented employees are comfortable with products such as Excel and tend to try to use them as their “front end” to data in the “real” database. Other users just copy the data from the “real” database into products such as Microsoft Access. Many auditors consider these pseudo databases to be a major risk since this activity typically results in data being manipulated outside the confines of a securely implemented database environment. If the data is manipulated outside of the “real” database and then presented as fact, so the theory goes, the results may not match the reality that would be evident in the “real” database. Because the corporation’s true databases are required to be the gold standard of data, more and more auditors are spending a significant amount of discovery time determining whether these types of pseudo database “pretenders” are being used for data manipulation. When they are discovered, the auditor will spend time determining that they do, in fact, tie to the database. Because the time involved in this type of technical detective work is costly, savvy corporations are beginning to ban pseudo databases and restrict the use of spreadsheet products to presentation of data only. Given the inability to enforce robust access controls surrounding these user-based implementations, the DB2 DBA is likely to be asked to port these pseudo databases into new DB2 instances and true DB2 databases where they can be secured as part of the sanctioned corporate IT realm. Because DB2 supports importing or loading data that has been saved in comma-delimited format (and several other formats), virtually any user-based implementation can be ported with ease to DB2.
HIPPAA
13
The Participating DBA The DB2 DBA will be a major contributor to the success of the SOX audit. The better your knowledge of the functionality of the DB2 product, the better your ability to recommend comprehensive solutions specifically tailored toward SOX fulfillment requirements. Many times, higher levels of management do not understand even the general features of the database products that run in their environments and do not ask the DBA about solutions in a timely manner. This is one time it is best to be proactive. If the DBA can become part of the SOX compliance effort at the initial stages and explain the features of DB2 that can be configured specifically with SOX compliance in mind, the effort will be rewarded with reduced implementation costs and, hopefully, a successful outcome.
HIPAA The Health Insurance Portability and Accountability Act (HIPAA) has been around since 1996. The IT departments for insurance carriers, medical centers, physician offices, pharmacies, and ancillary health providers are all well into compliance efforts. It is likely, however, that there will be increased requirements in the future as the public becomes more aware of their rights under this act and demand ever greater assurance of privacy controls. Other changes may be driven by changes to Medicare and Medicaid provisions or required if the current measures are discovered to be insufficient to ensure patient privacy. HIPAA was the first such act in the United States to impose civil and criminal penalties for improper data disclosure violations, and the penalties can be significant. For example, if identifiable information regarding an individual is disclosed for monetary gain, the offender can be imprisoned for up to 10 years and fined up to $250,000 for each such violation. Also, any person who believes that any health plan provider has not complied with HIPAA provisions may file a complaint, making the attempt to conceal noncompliance fruitless. In other words, HIPAA has the full support of the U.S. justice system, is policed by a combination of both regulatory review and the citizens at large, and requires great diligence to avoid serious consequences. This act has teeth! Goals for HIPAA include ensuring that employers or individuals can renew coverage despite current health conditions, facilitating the ability to switch health-care plans if desired, reducing health-care fraud and abuse, protecting the privacy of individual’s health information, and simplifying administrative tasks. HIPAA regulations deal with data storage in an effort to simplify the sharing of necessary information between insurers and care providers. HIPAA also provides a standardized format for claims submissions meant to ease the flow of information between health-care providers and insurers.
14
Chapter 1 • The Regulatory Environment
With the strong emphasis on security, HIPAA requires health-care organizations to have a verifiable written and implemented security policy and requires completion of risk assessments for compliance. The security policy must be reviewed on a regular basis (usually annually), and the DBA can be expected to be part of that review process (because many of the security controls focus on data protection). Another likely outcome of HIPAA compliance, and new responsibilities for DBAs, is the integration of disparate systems. It is to the health insurer’s benefit to consolidate systems, incorporating a smaller overall number of databases to house as much of the information as possible. This enables the organizational effort toward HIPAA compliance to focus on one infrastructure rather than many. With the requirements for strong authentication of users, auditing of all user access, and the requirement for implementation of appropriate data encryption, having a limited number of database environments may provide significant time and labor savings for the IT staff and a significant cost savings for the corporation. From the DB2 DBA standpoint, perhaps the greatest impact of HIPAA is the prevention of inappropriate viewing or sharing of confidential patient information. After all, who among us wants our employer (or anyone else) to know everything about our health. That doesn’t mean that the health-care organization should not share important health information. In fact, sharing of information is necessary for physicians to keep current on their patient’s care and for insurance companies to pay the bills. If information sharing were to stop, health care in the United States would be seriously compromised. The DB2 DBA dealing with HIPAA compliance will encounter some of the same challenges as the DBA who is dealing with Sarbanes-Oxley compliance. Both require auditing, encryption, and strong authentication. With health care, however, the aspect of “sharing” the data takes the challenge a step or two further. DB2 has many features to aid the DBA in protecting this information. These include auditing, authentication, encryption, and LBAC. Given the criticality of these topics to a successful HIPAA implementation, each of these items is covered later in this book and in much greater detail than provided in the brief overview that follows. Auditing Just as in the Sarbanes-Oxley regulations, auditing is a strong requirement for HIPAA. The information contained in health records can be very personal in nature. Beyond the civil and criminal penalties, the inappropriate disclosure of sensitive health-care information can effectively wreck lives. If the breach is subsequently publicly disclosed, an additional consequence is the likely demise of the health-care concern that failed to protect the data DB2 auditing, therefore, becomes an integral technological control mechanism, because it can be used to determine potentially inappropriate access and also serve as a deterrent if users are aware that their activity is being audited.
HIPPAA
15
The following shows a theoretical example of DB2 auditing at work in a health-care setting.
DB2 Auditing Theoretical Example James is a senior DB2 DBA for a Fortune 500 health insurance organization. While performing his daily review of the DB2 audit logs, he notices a significant increase in the number of attempts to access a program used to retrieve sensitive data.This activity is suspicious, and he begins further investigation. Using the audited event record, James identifies a user ID and application responsible for the increase in the number of program executions.With this information in hand, he reports the suspicious activity to management. Management determines that the ID belongs to a claims processor who would only seldom need access to such sensitive information. Based on the information James provides from the DB2 audit facility, management finds that the claims processor is potentially accessing information on many more individuals than he should to complete his tasks.While management investigates, James is asked to revoke all privileges on the database for the user ID in question, which he does to protect the data from any further access. During the investigation, it is discovered that the claims processor had stored his user ID and password on a sticky note and had “hidden” it underneath his keyboard. An intern who was assisting the claims processor in his work had found the sticky note and, out of curiosity, had logged on to the secure application with the claims processor’s ID. The intern was not aware of the nature of the data he was viewing until he was called in to be dismissed. The claims processor, whose casual approach to securing his user ID was revealed, received a written warning and one year of probation, but was able to keep his job. Yes, this was a completely theoretical scenario, but certainly a plausible one. It shows that the use of the DB2 audit facility can serve as a strong foundation for HIPAA compliance. Authentication Authentication can best be summed up as making sure that you are who you say you are. There are not many situations in which database authentication can be safely ignored, and health care is certainly not one of them. If any data is ever “interesting” to prying eyes, health care would likely top the list for those individuals without scruples. DB2 database authentication is multifaceted and configurable, and the DBA should take as much time as necessary to “get it right,” especially because “getting it right” is a requirement for HIPAA compliance. Encryption HIPAA requires encryption of sensitive data such as Social Security numbers, names, and birth dates. Many organizations are taking this to the next logical step and encrypting diagnosis and
16
Chapter 1 • The Regulatory Environment
medication information for individual records. DB2 supports data encryption and decryption natively through built-in functions. Because the encryption algorithm used by DB2 (RC2 with keys derived from an MD5 hash of the user-supplied passphrase) is designed for efficiency as well as security, this allows for faster retrieval time while still meeting the goal of protecting the data. Label-Based Access Controls New in DB2 9, LBAC enables DBAs to control access using a security label “tied” to a database object coupled with the security label granted to the user who is attempting object access. This new mechanism allows taking security to the “row” and “column” levels and can prevent or allow access to that particular row or column based on the user’s access privileges. This feature provides the DBA with strengthened mechanisms to meet HIPAA requirements. DB2 Anonymous Resolution Sharing of information in health-care settings is a necessity, but security is also a necessity. The DB2 Anonymous Resolution is an add-on product that allows health-care concerns to meet the HIPAA requirements for security while also ensuring that information is appropriately shared. An instance of one use of DB2 Anonymous Resolution in a health-care setting is discussed in the following example.
DB2 Anonymous Resolution in a Theoretical Health-Care Setting Insurance company A needs to determine whether any of its members have additional coverage through its rival, company B. Neither company wants to reveal any additional information to their rival, but they both want to know whether they share any members. If they do share any common members, they might be overpaying for claims, or paying for claims that aren’t their legal responsibility. Using DB2 Anonymous Resolution, each company’s membership roll is funneled through a cleanup process to handle any data format issues.The uniquely identifying data is then hashed using a one-way hashing algorithm.The hashed value is meaningless to anyone viewing it, so the information is protected from discovery. Both insurers agree to have the matching process completed at site A because there is no real data passed in the process and, therefore, no risk in doing so.When a match is found, DB2 Anonymous Resolution issues an alert. This means that each insurance carrier holds a policy on the same insured. At that point, the two insurance carriers can begin the process of correcting the double coverage.
Gramm-Leach-Bliley
17
Through its use of hashing, DB2 Anonymous Resolution does not pass the actual data, but instead anonymously allows a determination that there is a data match. This “match before release” helps eliminate inappropriate sharing of data of information without revealing any actual data during the process. It works even with data that is not in the exact format on both systems.
GRAMM-LEACH-BLILEY If you are a U.S. citizen/resident who was born before 1970, you probably remember the days when banks were banks, insurance companies were only in the business of writing insurance policies, and your definition of a financial institution probably involved a checking account that was held in the bank down the street. With the Gramm-Leach-Bliley Act (GLBA) of 1999, those demarcation lines have become very fuzzy. Insurance companies are now selling financial products, stockbrokers now sell IRAs, and the small bank on the corner was acquired by a national corporation a few years ago. The GLBA was the conduit to these changes. The GLBA brings tough protections for the nonpublic personal information (NPPI) held by financial institutions. Parts of this act also apply to third-party vendors and service providers that maintain or process customer data. The GLBA requires annual notification to customers regarding potential disclosure of identifying information and provisions for customers to avoid such disclosure. Examples of NPPI include customer’s names, Social Security numbers, credit histories, bank account numbers, and any other identifying financial information. Penalties for noncompliance of the GLBA can be severe; and in situations where there is a serious breach of security, the company’s board of directors can be held personally liable for civil and criminal penalties. Noncompliance can also lead to potentially serious, and certainly embarrassing, civil charges against the company president, as was the case for one large U.S. mortgage lender in 2004. Like HIPAA, the GLBA requires a strong overall, written, tested, and auditable security program with appropriate risk assessments. Also like HIPAA, strong access controls, authentication, auditing, encryption, and anonymous sharing of information will all be factors in the financial company’s GLBA solution. The GLBA also features an “opt-out” provision that is unique among the other regulatory initiatives discussed here. Financial institutions often enter into marketing agreements with other financial institutions, sharing information about customers for purposes of gaining additional business. That is one of the reasons you might receive numerous pieces of mail offering financial services through various organizations shortly after you begin a new relationship with a financial institution. Within certain guidelines, this sharing is still permitted under the GLBA, but customers now have the option to opt out of the process. This adds a layer of complexity to the business desire to share information.
18
Chapter 1 • The Regulatory Environment
Just as with the HIPAA regulations, DB2 features such as DB2 audit, encryption, authentication, LBAC, and DB2Anonymous Resolution can all play a role in the GLBA-compliance architecture.
FEDERAL INFORMATION SECURITY MANAGEMENT ACT In 2002, in response to increased terrorist threats, the U.S. Congress enacted the E-Government Act. Title III of the act, named the Federal Information Security Management Act (FISMA), requires U.S. federal agencies, contractors, or any other agencies that support the operations or assets of the federal agency to provide appropriate security for those operations/assets. A key element of FISMA is that these agencies conduct their day-to-day operations employing a security approach that is commensurate with the potential risk. To that end, standards for development and testing have been developed by the National Institutes of Standards and Technology Computer Security Division (NIST). The act mandates reporting by agency heads to the White House, Congress, and the General Accounting Office of the United States, confirming that security policies implemented are adequate and effective. In addition, officials are “graded” on the potential effect a serious security breach would have on the operation. From the DB2 standpoint, the DBA should be prepared to apply whatever security is necessary. Because every federal agency will have potentially different needs, the DBA should be aware of the variety and depth of DB2 security measures, including those discussed for Sarbanes-Oxley, HIPAA, and Gramm-Leach-Bliley: • Authentication • Privileges and authorities • Encryption • LBAC • Auditing • DB2 Recovery Expert and DB2 recovery functionality • DB2 Anonymous Resolution It is important to stress that the security team should make the effort to understand the needs of the particular federal agency before making recommendations or beginning to work on a solution. Each federal agency will have different drivers and different risks. There should be enough time in the project plan to perform risk assessments and gap analysis. After that work has been accomplished, the DBA is in a better position to determine how DB2 should be positioned.
Federal Information Security Management Act
19
As you consider your options for a secure implementation, remember, too, that DB2 offers a rich complement of application tools that you can use to enhance your security arsenal. Triggers, stored procedures, and user-defined functions, for example, often are coded to be used for security purposes. Update triggers, for example, can be coded to insert the “old” value of the row being updated into a separate table. With the old data safely stored, the DBA has both the before and after picture of the data row should there be any question regarding the update operation. Other DB2 mechanisms, such as replication, might prove useful, too. While reading tomorrow’s newspaper today is still not possible, one prediction is virtually certain: There will be more regulations, and the technology of information security will continue to evolve even as security breaches continue. Today, it is difficult to go too many mornings without a newspaper headline screaming about yet another security breach with thousands of pieces of identifying information delivered to the hands of hackers and thieves. If online commerce is to grow, if information technology can ever be trusted by the public, if our IT infrastructures are ever to mature, security has to be a top priority. At this time, the regulations to protect and secure data are new, and, in many cases, standards and requirements are still being formulated even though the “act” has been published and compliance is required. As DBAs, we know the drill. At some point, changes will be mandated, and what is done today to protect the data will need to be enhanced or redesigned in the future. Security will never be a stake in the ground, and the effort of establishing and maintaining a secure environment will always need to be prodded forward. Being reactive is risky. Being proactive is the only safe course.
This page intentionally left blank
CHAPTER
2
DB2 Security— The Starting Point
FIRST WORDS—WHAT’S THE PLAN? When thinking about organizational information security, your mind might jump to the technical details such as firewalls, access control lists, certificates, auditing, encryption, and all those wellknown electronic trappings that present a mental vision of a secure architecture. In fact, if you review the security implementations for most organizations, you will indeed see all those things. Did you ever wonder how those physical and logical layers of security ever started out? I did, and what I found out may surprise you. Despite all the electronic gadgetry, despite the fact that these environments were created by information technologists, despite this being the electronic age, despite the “paperless” society, the best security implementations … the ones that still stand up to the test of time … began as a written security plan on good, old-fashioned paper! If you’re seeking to emulate what other companies have shown to be successful, first you need to have a plan, and then you need to stick to it. That does not mean that you should create the security plan and never modify it, but it does mean that this plan should be solid enough to guide formulation of your organization’s day-to-day database security policies. In today’s lightning-speed development and production environments, slowing down long enough to actually create a plan may appear to be an unaffordable luxury. Consider, however, that this plan does not need to be an impediment to progress, but rather an empowering document, facilitating the time and commitment of resources that must be dedicated to the security initiative. If you happen to be a DBA, that written database security plan can be a lifesaver, both on initial database setup and as an ongoing reminder of the symbiotic relationship between the database and the security of the organization’s information assets. It should give you guidance both before
21
22
Chapter 2
DB2 Security—The Starting Point
and after a database has been launched. It will be an important guide as you formulate your DB2 database policies. It must be an active document, referred to for guidance on a regular basis and updated as change arises. For the corporation’s sake, the database security plan should not suffer the fate of so many others and become yet another a dusty binder stored on the top of someone’s filing cabinet. Perhaps, one of the most important benefits to be gained from creating a database security plan is that the very act of committing the plan to writing will assist in identifying potential security risks that might not be uncovered in a benign way otherwise. If security is not on the corporate conscious, the true threat is masked by all the tasks and energies required just to keep day-to-day operations or development going. Working on any security plan funnels the combined thoughts of the organization into one readable whole and presents in a clearer fashion the ways to address and mitigate those threats.
THE DB2 SECURITY PLAN Because you’re reading this book, it’s obvious that you have an interest in protecting the data assets held by your organization; but unless you have a very small organization with a single very small database, you need a plan and a leader. Formalization of that plan will provide great assistance toward the goal of database security, and during the formulation of that plan, a leader (corporate sponsor) should emerge. Many organizations already have some type of security plan in place that may or may not include specifics on database protection. If your organization has an enterprise-level security plan, the DB2 database security plan should be a significant and highly visible part of that document. If you do not have an enterprise level security plan in place, the DB2 database security plan should still be created, even if it must be undertaken as a standalone document. Given the criticality of protecting the data stored in those DB2 databases, ignoring the security responsibilities may mean unacceptable organizational risk. The DB2 security plan document is a road map that will provide the foundation for the enforcement of the operational DB2 database security policies that will be implemented. It should provide a meeting of the minds with regard to the security of the organization databases and how DB2 should be used to fulfill those needs. If you are a DB2 database administrator, you have a vested interest in getting a DB2 security plan in writing. This plan, once written and approved by management, can be your guideline for setting up your database security policies. It can be referred to when questions arise, such as access levels, provided to auditors to facilitate their reviews, and should be reviewed or revised when new applications are installed. A major bonus for you is that when finalized, it will keep you from having to answer the same questions about security over and over again, saving you time and allowing preservation of your sanity.
The DB2 Security Plan
23
So, if necessary, take the lead on getting a committee involved in formalizing a written DB2 security plan. You may get resistance, but remember that the database you are trying to protect is potentially one of the greatest assets held in trust by your organization (and the people it serves), and, therefore, it should be treated and protected just as any other valuable corporate asset would.
Security Plan Meeting Participants The first step toward achieving your database security plan is to identify the team members who should be involved in the creation and review of the document. In a typical organization, the positions listed in Table 2.1 might be considered key to this task. Table 2.1
Database Security Plan Team Members
All Appropriate Members of Management CIO CTO Vice presidents Division managers Technical team leads Application subject matter experts (SMEs) Network administrators Systems administrators Database administrators (DBAs) Corporate security officers
One important factor in determining who to include is the realization that the matters discussed in these meetings could be used by internal or external sources in inappropriate ways. Because the focus of the meetings is to discuss and mitigate current and future threats, the core meeting group should consist of individuals who are trusted by the organization to maintain the confidentiality of issues discussed. To succeed, the database security plan needs a corporate sponsor. This should be someone within the organization who has the appropriate level of interest, authority, and responsibility to approve, communicate, and enforce the resultant plan. If your corporation has a security officer, especially if the position that person holds has sufficient status within the organization, the security officer may be able to fulfill the sponsor role.
24
Chapter 2
DB2 Security—The Starting Point
Obviously in large organizations, division personnel should be involved in the process. It is important to get their unique perspective on database security because they may face challenges that are not easily identified. Depending on your organizational structure, division technical personnel should be invited to the meeting if they have discrete environments or can provide technical expertise relevant to database or application security. Communication and information from application SMEs will likely be necessary to determine the granularity of database security needed. These are the individuals who can indicate which data needs the most protection, which users should have access and the level of that access, and how to determine whether a breach has occurred. These individuals may be technical leads, application programmers, or just those who know the application well because of their role. For example, an accountant might be the individual who knows the most about the general ledger applications. The remaining participants should be the hands-on technical individuals who typically have the roles of network administrator, system administrator, and DBA. Participation of individuals who fulfill these roles is absolutely critical to successfully designing a plan because each will bring a unique focus to the process. Gather Information Before any meetings are scheduled, there should be some gathering and summarization of information if it is not already readily available to the team. A minimum starting list of items includes the following: • Current security documents • Standards (formal or informal) Any written security guidelines Any informal security policies that have been enforced in the past • Hardware in use or proposed for DB2 databases Machine specifics Physical location • Connectivity mechanisms in use • Current authentication methods • Operating system information OS type OS level • Maintenance procedures, such as patch management, currently in place • Licensing agreements
The DB2 Security Plan
• User and group information • List of DB2 instances by hardware The type of instance Development Test Production • The database manager configuration parameters in use per instance (DBM configuration) • The product and level of the DB2 code base installed (DB2LEVEL command output) • List of DB2 databases by instance • Database configuration(s) (DB configuration) • Backup procedures including types, frequency, and storage location • Applications currently being run (as observed or proposed) • Typical number of users • Access control measures in place Authorities Privileges • List of applications Type Web-based Third-party Batch • Application “owners” • Prior risk assessments • Information on known data classification • Special security considerations Federated Information Integrator High Availability Cluster Multi-Procesing (HACMP™) • Results and recommendations of any security audits that have been performed
25
26
Chapter 2
DB2 Security—The Starting Point
Meeting Goals and Desired Outcomes After you get the appropriate parties and the initial information together, meeting goals should be established. It is difficult to create a database security plan in only one meeting unless your organization is very small, so it might be best to create overall goals and then plan enough meetings to allow time for discussion. Segment the discussion with the idea that internal and external security may pose different threats and, therefore, require a different set of goals. Uniformity of standards can simplify security policies and should be considered to the extent that they can be implemented across the organization without incurring increased risk. The result of these meetings should include a comprehensive, written policy addressing the components of the database security plan, including at a minimum, the following: A. Appropriate analysis of internal and external database security risks and the current approach toward their mitigation B. External security authorization mechanism 1. Group and user naming standards 2. Password standards and change guidelines C. Operating system standards (for DB2 files, file systems, logical volumes) D. A workable blueprint for setting up the DB2 database security policies What security standards should be set for all databases? 1. A List of access control levels by database a. Who needs access and at what level? b. Granularity of access control needed c. What security access is needed by the following? 1. Application 2. Group 3. User 4. Database E. Who will be responsible for internal user and/or group account setup? 1. How will user accounts be tracked? 2. How will terminations and revocations be handled? 3. How will necessary access changes be conveyed?
The DB2 Security Plan
27
F. What approvals are needed? 1. What forms are required? 2. What sign-offs must be in place? G. Identification and classification of extremely sensitive information 1. By database 2. By application 3. By table 4. By column 5. By row H. Identification of overall DB2 security management responsibility 1. Who is the owner? 2. Who can delegate? 3. Who is the custodian? I. Uniformity of database policies and any acceptable deviations J. Auditing requirements K. Incident handling procedures L. The review cycle for the formulated database security plan 1. Are there regulatory requirements for the review cycle? 2. Should the entire plan be reviewed at once? 3. Will there be a review after hardware changes? 4. Will there be a review after software changes? Meeting Facilitation Tools When considering an analysis of internal and external database security risks, you can use a grid approach. Table 2.2 shows a basic example. Table 2.2
Database Security Risk Grid Example
Internal
Threat
Plan
Shared passwords
High
New password policy.
Disgruntled employees
Medium
Review access levels before personnel actions are undertaken. (continues)
28
Table 2.2
Chapter 2
DB2 Security—The Starting Point
Database Security Risk Grid Example (Continued)
Internal
Threat
Plan
Users granted inappropriate access to data
Medium
Check and review current database grants; create an access control policy.
External
Threat
Plan
Introduction of vulnerabilities due to lack of maintenance
High
Schedule maintenance window for patches.
Hacker attack
High
Keep current with patches; encrypt sensitive data; change passwords on a regular basis; enforce password standards; undertake vulnerability assessment.
Web users with incorrect access
High
Check and review current database grants; create an access control policy.
It is likely that this grid (or any other facilitation mechanism used to capture this detail) can grow quite large. It should be viewed as a brainstorming tool to assist in determining the scope of risk. As in the example, it is likely that the items under the Plan column may contain duplications that might occur when one risk can be mitigated by the same action as another risk. An example of this is a risk of external resources and internal resources holding inappropriate access to data. Whereas each presents a different threat to the database and potentially a different level of risk, one action that should be included in the plan for proposed mitigation of both is to review current database access levels and create an enforceable access control policy. The formation of this grid may assist in identifying the highest-priority items that should be addressed first (even before the plan is completed) and might lead to discovery of threats not currently on the corporate radar. As a first step before tackling the robust work of actually formulating the part of the plan that will serve as a blueprint for the DB2 database security policy, the grid will facilitate an assessment of where the corporation stands now with regard to database security and potentially assist in identification of any serious lapses. After the assessment of internal and external threats has been completed, the results should be summarized and organized to be used as input for the next steps. Determining the Authentication Method and User/Password Security Authentication for DB2 databases is handled by a security facility outside of DB2, such as the operating system, Kerberos, or other plug-in. Although it is not necessary at this point in the process to be specific as to the parameter settings (authentication is discussed in detail in Chapter 5, “Authorization—Authority and Privileges”), the overall authentication requirements should be documented. The discussion should include a determination as to where the authentication
The DB2 Security Plan
29
should take place (that is, client, server, DB2 connect server, host) and whether encryption (Chapter 7, “Encryption [Cryptography] in DB2”) is required. Standards should be developed for naming conventions for groups and users. Part of this strategy should be that known default or easily identifiable group names and usernames are not allowed. Some that are commonly used in many DB2 shops (and should therefore be avoided) include the following • db2admin • db2as • db2inst1 • db2fenc1 Another important discussion regarding groups revolves around the DB2 group known as PUBLIC. DB2 comes with this group by default. This group can (and should) be locked down unless there is some documented reason for this group to maintain certain low-level privileges. Prior to DB2 9, this group always received a number of privileges from the moment the database was created. With DB2 9, an alternative for dealing with the PUBLIC group privileges is made available. When creating a new database, adding the keyword RESTRICTIVE changes the default behavior, and no privileges are automatically granted to the PUBLIC group. If this keyword is not used, the following permissions are available to the PUBLIC group after the database has been created: • CREATETAB • BINDADD • CONNECT • IMPLSCHEMA • EXECUTE with GRANT on all procedures in schema SQLJ • EXECUTE with GRANT on all functions and procedures in schema SYSPROC • BIND on all packages created in the NULLID schema • EXECUTE on all packages created in the NULLID schema • CREATEIN on schema SQLJ • CREATEIN on schema NULLID • USE on table space USERSPACE1 • SELECT access to the SYSIBM catalog tables • SELECT access to the SYSCAT catalog views • SELECT access to the SYSSTAT catalog views • UPDATE access to the SYSSTAT catalog views
30
Chapter 2
DB2 Security—The Starting Point
As you can see, the privileges for the PUBLIC group on a newly created database are significant. If discussions yield no valid reason for PUBLIC privileges, the RESTRICTIVE clause should be used for newly created databases. Excellent password security is one of the elements of a strong security plan. In addition to identifying the responsibility for password security enforcement and the mechanisms for change, the following topics should be considered: • Changes Will users change their own passwords? If not, how will they be notified of the changes? • Length of time between required resets/changes If not reset/changed, how long until lockout of the account? How many cycles must be completed before passwords can be reused? • Resets Who will hold responsibility for password resets? Will a secondary authentication be used to allow the user to reset it? Secondary authentication question answered correctly Biometric authentication Electronic device such as a key card • Lockouts How many password attempts before lockout? What forms and approvals are to be in place? Who will have the authority to retrieve a lost password or credential? In considering passwords, a discussion of composition standards for those passwords is necessary. The human factor in password issues is well recognized. If your users are allowed to create their own passwords, without any applicable standards, the strength of those passwords will be suspect. If complex passwords that are not easy to remember are instead assigned to users, in variably they will be written down someplace, and that overrides the strength of the complex password. One approach to this is to create a security password template. This provides the mechanism to ensure that the password meets certain standards, such as three capital letters, two numbers, one symbol, and two lowercase letters. However, this can be problematic. Consider that internal employees will know the template. This information could provide an unintended assist if an internal or former employee wanted to gain access through password hacking.
The DB2 Security Plan
31
It is critical that forbidden passwords include usernames, employee IDs, dictionary words (in any language), and true words with numeric replacements of ones or zeros. All these are easily hacked by a brute-force approach. It’s easy to say that passwords should never be shared, but harder to enforce that standard unless there is some strength behind the security plan, policies, and procedures that can bring consequences to those who violate this essential security foundation. Passwords should also be expired, but this brings up the question “When?” Too-frequent password expiration is problematic because users are tempted to write them down somewhere. A longer time between password changes means a longer exposure period. Changing passwords on a regular interval can be beneficial, but if this actual interval is widely known, this, too, can be a risk. Would you really want a hacker to know that passwords expire on the first Saturday of every other month? Encryption of all passwords is a strong recommendation. DB2 provides easily implemented encryption security features to protect passwords (and more), as discussed in Chapter 7. As with all security features, knowledge of current industry standards and practices regarding password topics will provide the best guidance. As security evolves, so do the attempts to thwart that security, so keeping current through a proactive approach is wise. Discussing the Blueprint Now that you have summarized the results of the internal and external risk assessment for database security and addressed authentication, it is time to begin work on the part of the plan that will eventually be used as a foundation for creating the actual DB2 database security policies. At this point, the team needs to have a good understanding of the internal and external threats that should be addressed to protect the database. During this phase of the meeting process, the team should begin to discuss the security standards for all corporate DB2 databases. Depending on the structure, complexity, and size of the organization, this can be intricate with multiple considerations per division, per database, per machine, and so on. The goal of this part of the plan is to integrate information discovered in previous steps to facilitate creation of the DB2 database security policies. At this phase of the process, the team should begin to discuss a workable set of security standards and how they should be applied. Questions to be answered and topics to be codified in the plan include the following: • The ability to uniformly apply database security standards Are there needs for differing standards based upon …? Divisions OS types and levels File system storage versus raw devices Firewall
32
Chapter 2
DB2 Security—The Starting Point
VPN Federated Replication LDAP Are there special considerations for specific third-party applications? If so, how will these differences be identified and handled? • Access control plan A statement identifying responsibility and ownership Account/group setup Account tracking Terminations Changes Matrixes of access levels needed (see Table 2.3) For authorities For privileges Special Identification of necessary maintenance steps Approvals Forms Sign-offs • Identification of extremely sensitive information for special consideration As mentioned previously, matrixes can aid in identifying access requirements. You can then use these matrixes as input for the DB2 database security policies. The examples in Tables 2.3 and 2.4 consider specific access levels and decode, by group, the level(s) that should be applied. Although the examples represent true discussion points, the values assigned here are for a fictional company, and no special meaning should be ascribed to them. Table 2.3
Database Authorities Matrix
Instance Level
Corporate Tech Arch Group
Corporate DBAs
Division 1 Tech Group
Division 1 DBA Team Lead
Conversion Team
SYSADM
Y
N
N
N
N
SYSCTRL
N
Y
N
Y
N
SYSMAINT
N
Y
Y
Y
N
SYSMON
N
N
N
Y
N
The DB2 Security Plan
33
Database Level
Corporate Tech Arch Group
Corporate DBAs
Division 1 Tech Group
Division 1 DBA Team Lead
Conversion Team
DBADM
N
Y
Y
Y
N
LOAD (with insert privilege)
N
N
N
N
Y
Table 2.4
Database Privileges Matrix Public
All Groups
Software Development
Conversion Group
ETL Group
Connect to database
N
Y
Y
Y
Y
Create new packages
N
N
Y
Y
Y
Create tables
N
N
N
Y
N
Unfenced stored procedures or UDFs
N
N
N
N
Y
Implicitly define schemas
N
N
N
N
N
Connect to database that is in quiesce state
N
N
N
N
Y
Allow user to create a procedure for use by other applications or users
N
N
Y
Y
Y
Definitions and detailed explanations of authorities and privileges are covered in Chapter 5.
You can build similar matrixes to assist in identification of the additional security privileges to be addressed in the DB2 database security policies. These could include the following: • Schema Create objects within the schema Alter objects within the schema Drop objects within the schema • Tablespace Create tables in a specific tablespace • Tables and views Control of a table or view Add columns
34
Chapter 2
DB2 Security—The Starting Point
Add or change comments Add a primary key Add a unique constraint Create or drop a table check constraint Select, insert, update, and/or delete rows Create indexes Export Create and drop foreign keys • Packages Rebind Execute Allow package privileges for others • Drop and control on indexes • Execute routines • Use and alter on sequences • Passthru (in a Federated database environment)
Next Steps Now that the plan has been visualized, it is time to put it to paper. In thinking about what has been covered, it should be obvious that some of the information provided in this living document could be sensitive in nature. It is detailing how your corporation plans to mitigate security risks for the database and, therefore, could provide information to hackers or an internal employee and become an unintended aid for the very risks the plan is meant to address. Think about the “security” of the database security plan document. It should be protected while it is being written. Leaving parts of it lying around while it is being typed is not appropriate. The persons doing the typing should be trusted employees, too. At a minimum, the electronic copies of the plan should be password protected. Because of the sensitivity of the information, it is best to disseminate the plan on an “as needed” basis. One possible scenario is to create a security library with all security documentation provided through a signed checkout process. Other steps such as limiting the use of the document to one room that does not have a copier and stamping each page with a highly specific watermark to verify authenticity could provide some measure of further security.
DB2 Database Security—Create the Policy
35
DB2 DATABASE SECURITY—CREATE THE POLICY DBAs are notoriously overworked. They are an integral part of the day-to-day database management work and serve as the technological wheels of the corporate vehicle. Given their usual desire to stay “hands-on” and the significant tasks that they face, DBAs seldom have the time or inclination for writing documentation. When security is not a priority, database security policies, if they are documented at all, are often vague and will likely suffer from poor implementation. Given the considerable security risks imposed by ad-hoc policies and spotty enforcement, committing the policies to writing and implementing them consistently and successfully is critical. Although a trial-and-error learning approach might work in some database areas, database security is not one of them. It is critical that the DBA who is tasked with creating and implementing the policies understands, and can intelligently implement, all aspects of the DB2 security policies. Auditing is another area that requires a robust comprehension of DB2. For these reasons, the database security policies should not be created or implemented until the DBA has a true comprehension of the available DB2 security options.
Using the Plan to Formulate the Policy If the DB2 database security plan is complete, the creation of the DB2 database security policies will be much easier. Yes, it is true that a database security policy can be put in place even though a database security plan was never created. However, creating only the policy without first laying the foundation of the plan leaves the database policy vulnerable. For example, there might not be a corporate sponsor to favor the necessary work effort, organizational “buy-in” would be missing, and database security efforts would not benefit from the strength of different perspectives. That said, if it just is not possible to get a team together and officially write a database security plan, at least writing the database security policy is the next best choice. Plan or no plan, the DB2 database security policies should be written down, not just implemented.
Review, Approve, Implement, Maintain Before sitting down to translate the information from the plan into workable database security policies, a structure should be in place to determine what reviews, approvals, auditing, and policy maintenance are needed. The goal here is to strengthen the process, not impede it. If the corporation has a technology security officer or group, that group should be part of the review, approval, and maintenance process. If no individual or group holds this authority, the CIO or CTO and/or DB2 team lead should be involved. Rather than have numerous levels of authority
36
Chapter 2
DB2 Security—The Starting Point
involved, the objective is to find the smallest common denominator of personnel with the appropriate level of authority and the ability to do the following: • Review the policies Do they match the objectives of the plan? Are the proposed policies able to be implemented as they are described? Are the appropriate parties tasked with implementing the policies? Are safeguards built in? Is the policy clearly written? Has change management been addressed? • Approve Who has the authority to approve the policies? Are multiple levels of approval desirable? • Implement Identification of personnel to implement Verification of successful implementation Appropriate change management • Audit Validation Quality assurance • Maintain What is the schedule for cyclical review of the policies? Who will maintain the physical security of the policies? Who will be allowed access to the policies? How will be policy itself be distributed and secured? How will changes be managed?
General Guidelines—Building the DB2 Database Security Policies When beginning to create a new DB2 database security policy, a good suggestion is to have a master document that supports all the standards and single or various subdocuments to address the exceptions or differences. This approach may ease regulatory compliance efforts because uniformity across environments will aid auditors as they review for compliance. One direction would be to create a master DB2 database security policy that covers all corporate instances and databases by stating the general, shared policy rules. Then, any exceptions or differences could be detailed separately and incorporated into the policy documents. The master
DB2 Database Security—Create the Policy
37
document might contain items such as the standards and naming conventions for instances and databases or how TCP/IP port numbers for instances are assigned. These are just examples to provide “thought points” for the task of creating the policies. As long as the written policies provide sufficient scope and clarity, the actual form that the final documentation takes is not significant. One major point to consider is how to keep the policies themselves secure. The security plan and policies and their working documents, if made available inappropriately, present a security threat to the organization. If the policies are stored on a network that does not provide sufficient security, for example, they might be compromised and used as a blueprint to devise ways to circumvent all the protections so diligently implemented. Likewise, copies of the security policies or their drafts, left lying on desktops, can be acquired improperly. Keeping the plan and policies secure is just as important as keeping the data itself from falling into the wrong hands. What to Include? The determination of what to include and exclude in the database security policies varies greatly depending on the organizational need. Common to most organizations are items such as naming standards, database-to-storage mappings, application-to-database mappings, and access controls. Beyond those topics, larger organizations typically need to include auditing and encryption, especially if they are under regulatory review. These topics are discussed in general terms here to give some insight on an approach to creating the policies. These topics are indented only to provide a starting point to initiate the process. The successful database security policy at your organization will be unique and a “custom fit” that cannot be easily facilitated by a generic blueprint. Naming Standards The most important considerations for creating naming standards are that 1. They exist. 2. They are not overly complex. 3. They are well documented. 4. They are not so transparent as to aid a hacker. 5. They are enforceable and enforced. Organizations without naming standards cause undue stress for DBAs whether in relation to security or not. It is so much easier, for example, to troubleshoot any security issues with stored procedures if the DBA knows that all stored procedures begin with the prefix SX_ and that they all are stored on a specific file system. If objects suddenly appear to be stored procedures, but do not begin with SX_ and are not on the appropriate file system, the irregularity is more easily discovered if standards are in place and if enforcement has been strict.
38
Chapter 2
DB2 Security—The Starting Point
Mappings While database, application, and storage mappings exist in most organizations as an aid to administration, the implicit security benefit is not always realized. Mappings can prove invaluable to facilitate identification of irregularities (whether accidental or intentional). If a recovery is required for any reason, you can use mappings to confirm that the environment is restored to the original configuration. Mappings for applications, databases, and storage should be included in the database security policies. Access Controls DB2 offers a rich complement of features that can provide a high level of granularity for enabling access controls. Because a thorough understanding of DB2 access control mechanisms is critical to a secure implementation, these topics are covered in depth in Chapter 5, and Chapter 6, “Label Based Access Control.” Once determined, access control mechanisms should be thoroughly documented in the database security policies. The goal should be a standardization of implementation that can be followed by anyone tasked with the work. The policy should spell out not only the initial implementation, but how to handle subsequent implementations. Auditing Another item for inclusion in the database security policies is auditing. (See Chapter 9, “Database Auditing and Intrusion Detection,” for a detailed discussion.) As you read in Chapter 1, “The Regulatory Environment,” auditing is a requirement for compliance mentioned by HIPAA, Sarbanes-Oxley, and Gramm-Leach-Bliley Acts. Many governmental agencies require an almost 100 percent auditing implementation. If auditing is required, whether natively in DB2 or by some other mechanism, this, too, should be detailed by the database security policies. The broad topics regarding auditing that the policy should (at a minimum) include are as follows: • What is audited? • How often will audit records be reviewed? • What personnel will be tasked with audit review? How will they be vetted or authorized? What technical skills will they need for the tasks? Who will they report to? • What storage media will be used and how will it be secured? • How long do audit records need to be kept? • What is the issue discovery reporting process?
Change Control—Things Are Gonna Change
39
Auditing might not be required for every database environment in the enterprise, but to the extent that it is, it should be well documented in the database security policies. Encryption If your organization is planning to use encryption, the database security policies should address how to determine which data is to be encrypted. It is more important to set standards for encryption rather than just list specifically what is initially encrypted. If the policy states, for example, that Table A, Column B must be encrypted, that provides instruction only for one situation. The policy should go further, setting standards that apply across all data, such as the following: • All names • All Social Security numbers • All dates of birth • All personnel actions • User IDs and passwords • Credit card numbers • Etc. Spelling out this information in the policies is necessary because few applications stay static. As new code is introduced and new database objects are created, the database policies can aid in providing a consistency point for encryption. If the requirement is that all SSNs be encrypted, for example, and the policy only states, “Encrypt all Social Security numbers in the Employee table,” what happens when another table is added that also holds Social Security numbers? With standards such as “All SSNs are encrypted,” there is more assurance that the policy will be effective.
CHANGE CONTROL—THINGS ARE GONNA CHANGE Throughout this chapter, we have been dealing with the “present” as if the “future” were never going to impact the process. Now it is time to realize that the future is not going to be ignored forever. It is highly likely that after the plan has been completed (or maybe before), after the policies have been “inked,” and after that secure database is in place, there will be changes. With any security implementation, there are always ways to improve, which translates into “change.” Then, there are the business changes that occur as a matter of routine for most enterprises. They also spell “change.” We cannot forget, too, that technology will advance, hackers will hack, businesses will acquire businesses, best practices will evolve, and employees will move on. To manage the change that is virtually guaranteed in any thriving enterprise, change control is essential. This is not just change control for the database (although that is essential), but also change control for the security architecture and its relevant documentation. At each step along the way, consider how change is going to be managed.
40
Chapter 2
DB2 Security—The Starting Point
LAST WORDS STOP
If you do not have executive sponsorship for your secure implementation, stop here and get it now. Without executive sponsorship, the odds of success are slim.
Security plans and database security policies are essential to creating and maintaining a robust security implementation. They must be effectively written, shared with appropriate personnel, updated when appropriate, and protected just as if they were classified data. They serve as documentation for auditors, management, and appropriate staff and will provide foundational guidance for DBAs and IT departments. Of course, every organization is different, and the security plan and database security policy must be tailored for the specific organizational need instead of striving to meet some arbitrary set of requirements. That is why the involvement of the appropriate personnel at the start of the creation process is crucial. These stakeholders should play an active role in the formulation of the plan, and from the plan, it should be easier for the DBAs to formulate the DB2 database security policies. Taking shortcuts by eliminating documentation introduces significant risk. Even if database security is effectively implemented, when documentation is bypassed, it is increasingly likely that normal changes, which inevitably take place as the application changes, will cause security items to be overlooked. With a security plan and DB2 database security policies, this unintentional oversight is less likely.
CHAPTER
3
Understanding Identification and Authentication—The First Line of Defense A n imaginary conversation between the DB2 database and the user ID: DB2:
“Who are you?”
User ID:
“Why, I am me, of course.”
DB2:
“But who can vouch for you?”
User ID:
“Just ask the DBA in the Super-Invisible Cape.”
FIRST WORDS:WHY IS AUTHENTICATION CRITICAL TO DATABASE SECURITY? When a user claims a specific identity, such as entering a user ID, this process is called identification. Authentication is the process by which the claimed user identity is validated. Authentication is the first line of defense for the DB2 database system; it serves as preventive control to stop any unwanted access to the database. The role authentication plays for DB2 is much like that of the firewall for the corporate network. It is there to protect and defend from unjustified access. You can think of authentication as the master lock for a house where business-critical data resides. (Think of the house as the database.) To access the data, one must have a key (authentication information) to unlock the door and gain entry. This assurance that the seeker of the data has the right key for this particular lock helps prevent unwanted access to the data. Imagine instead
41
42
Chapter 3 • Understanding Identification and Authentication—The First Line of Defense
that the door lock is broken or unintentionally left unlocked; then everyone, including the thieves (hacker or business spy), can go in. When the thieves are inside, the risk of a security exposure accelerates dramatically.
OVERVIEW OF THE DEFAULT DB2 AUTHENTICATION MECHANISM Prior to the release of DB2 8.2, authentication was the role of the operating system (or possibly Kerberos on Windows). DB2 assumed that the operating system of the platform it was running on was the definitive location for authentication. The general approach (which may still be used if desired) was to pass the user ID and password to the underlying operating system on the database server for validation depending on settings chosen for the Database Manager Configuration (DBM CFG) parameter. As of DB2 8.2, DB2 has implemented the security plug-in infrastructure whereby authentication is performed by security plug-in libraries that are dynamically loaded by DB2. For those who prefer the status quo, the existing operating system authentication mechanism is still made available via an IBM®-shipped security plug-in. In addition, the Kerberos authentication method (now a plug-in) was made more robust and provides additional platform support, including AIX®, Sun®, and Linux®. Providing even more ability to custom design security, there is the option to design, code, and implement a customized security plug-in to incorporate any authentication method or business logic. This has opened the door for third-party development of security plugins and enabled a virtually unlimited approach to customization of authentication control designs. Figure 3.1 illustrates how the operating system-based security plug-in verifies the user ID and password when the authentication type has been set to SERVER. (This is the default, out-of-thebox setting.) 1. When a user enters the user ID and password on the connect statement, the user ID and password flow to the database server. 2. The database server passes the user ID and password to the security plug-in. The security plug-in calls the operating system application programming interface (API) to validate the user ID and password. 3. The operating system validates the user ID and password and returns the results via the return code of the operating system API. The security plug-in translates the operating system API return code into one of the published security plug-in return codes. The security plug-in return code is returned back to the database server. 4. The database server will deny the user access to the database if the security plug-in return code indicates that the operating system failed to validate the user ID and
Authentication Type
43
password. Otherwise, the group membership plug-in will be loaded to acquire group membership for the user. The database server will then perform connection authorization checking by consulting the system catalog table SYSCAT.DBAUTH to verify whether the user or one of the groups (including the special group PUBLIC) that the user belongs to has the CONNECT privilege to the database. The user will be granted the access to the database if the sufficient CONNECT privilege is present in the system catalog table.
1 Server Side Security Plug-In 4
Database
User
3
2
Operating System
Figure 3.1
Authentication using operating system-based security plug-in
AUTHENTICATION TYPE The Database Manager Configuration parameter AUTHENTICATION is used to control where authentication takes place and what kind of authentication information (whether a user ID and password pair or a credential such as Kerberos ticket) will be used in the authentication process. Because this is an instance-level parameter, the specified authentication type applies to every database defined in the instance. Any connection to one of these databases will attempt to use this authentication type. However, DB2 does provide an option to override the authentication method at the client. The client can specify an optional authentication clause when cataloguing a database
44
Chapter 3 • Understanding Identification and Authentication—The First Line of Defense
to indicate an authentication type that differs from that of the server. After a negotiation process between the client and server, the final “agreed-upon” authentication type will surface or the connection will be refused if the types are not compatible. This negotiation process is discussed in more detail in a later section of this chapter.
What Authentication Type Should I Use? Authentication type selection is one of the key decisions that should be made according to the corporate security policy. Although authentication mechanisms are reconfigurable at any time (via DB2 configuration updates), the best approach is to do the research up front, know the specific options and combination of options available, and understand the technical ramifications and how they relate to specific business needs before starting any work to establish the database and application environments. Applications being deployed should also be understood before choosing an authentication mechanism, because there is no “one size fits all” when it comes to authentication. Does the data flow need to be encrypted? Is the database being accessed remotely, locally, via the Web? Will there be additional authentication beyond that offered by the database? These are all questions that, when answered, aid in establishing the “right” authentication method from the start.
Understanding Authentication—In General Currently, DB2 supports the following types of authentication methods: SERVER; CLIENT; SERVER_ENCRYPT; DATA_ENCRYPT; DATA_ENCRYPT_CMP; KERBEROS; KRB_SERVER_ ENCRYPT; GSSPLUGIN; GSS_SERVER_ENCRYPT. Table 3.1 summarizes the different types of authentication methods supported by DB2. Table 3.1
Authentication Methods Supported by DB2
Authentication Type
Location Where Authentication Occurs
SERVER
Database server.
ID and password are sent in plain text to the database server, where authentication takes place.
CLIENT
Client.
User ID and password are authenticated at the client. Note that this setting is discouraged unless a strong trust between the client and server can be established. This is explained in depth later in this section.
SERVER_ENCRYPT
Database server.
Encrypted user ID and encrypted password are sent to the database server, where authentication takes place.
Description
Authentication Type
45
Authentication Type
Location Where Authentication Occurs
DATA_ENCRYPT
Database server.
Same as SERVER_ENCRYPT, but certain sensitive data flowing between the client and server in the session is encrypted. This is explained in more detail in Chapter 7, “Encryption (Cryptography) in DB2.”
DATA_ENCRYPT_CMP
Database server.
Same as DATA_ENCRYPT with the exception that this authentication type allows compatibility with down-level products not supporting the DATA_ENCRYPT authentication type. These products are permitted to connect with the SERVER_ENCRYPT authentication type and without encrypting user data.
KERBEROS
KDC. (See the “Kerberos —An IBM-Shipped GSS API-Based Security Plug-In” section later in this chapter for more explanation of KDC.)
Using Kerberos authentication type where authentication takes place on a third-party server—KDC.
KRB_SERVER_ENCRYPT
KDC or database server depending on the result of the negotiation between the client and server. (See the section “Authentication Type Negotiation Between the Client and Server.”)
This authentication type supports both KERBEROS and SERVER_ENCRYPT.
GSSPLUGIN
Depends on the implementation of the GSS API-based security plug-in.
Uses GSS API-based security plugin as authentication method.
GSS_SERVER_ENCRYPT
Database server if SERVER_ ENCRYPT authentication type is chosen. Depends on the implementation of the GSS API-based security plug-in if GSSPLUGIN authentication type is chosen.
This authentication type supports both GSSPLUGIN and SERVER_ENCRYPT.
Description
46
Chapter 3 • Understanding Identification and Authentication—The First Line of Defense
If you have two different types of clients, one type supporting Kerberos or GSS API-based authentication mechanisms while the other type does not, the best course of action is to choose either KRB_SERVER_ENCRYPT or GSS_SERVER_ENCRYPT for authentication on the database server. This equips the database server to support two types of authentication mechanisms simultaneously. When one of the two values is specified on the request by the client connection attempt, the database server can actually authenticate the client using either the Kerberos/GSS API-based authentication mechanism or by using an encrypted user ID and password that is authenticated at the server. In general, client authentication is discouraged given this concern: How secure can a client be? Client authentication defeats the goal of centralized security management. If credential management is handled on the client side, a strong trust between client and server must exist. Consider an environment in which lots of laptops can plug into the company network any time. With client authentication, if the internal intruder manages to discover a user ID for one of the DB2 system administrators, all it takes to become a DB2 system administrator is to create a user ID of the same name locally on the laptop and then connect to the database. Because the user ID and password are authenticated on the client, the password does not even need to be the real password used by the administrator. Should I specify an authentication type on the CATALOG DATABASE command? When a database is cataloged on the client, the user is given an option to specify a preferred authentication type for the client to use. It is strongly suggested that the authentication type be set to the same value as the authentication type specified in the Database Manager Configuration on the database server. If the value is not known, the authentication type should not be specified on the CATALOG DATABASE command. A mismatch between the authentication type specified on the CATALOG DATABASE command on the client and the Database Manager Configuration parameter value on the server can prevent the DB2 client from successfully connecting to the database server and cause a failure with the following message: SQL30082N Attempt to establish connection failed with security reason "17" ("UNSUPPORTED FUNCTION"). SQLSTATE=08001
SRVCON_AUTH Database Manager Configuration Parameter If you have worked with the DB2 product for several releases, you might remember that formerly the instance (Database Manager Configuration) parameter AUTHENTICATION determined client and instance-level operation authorization. The term instance-level operation refers to the tasks required to maintain a database instance such as start database manager (db2start) or get Database Manager Configuration (GET DBM CFG). DB2 8.2 addressed the ability to segregate authentication via a new Database Manager Configuration parameter, SRVCON_AUTH. Previously, the parameter AUTHENTICATION had to perform two roles. On one hand, it indicated what authentication type to use to authenticate the client. On
Authentication Type
47
the other hand, it indicated what authentication method to use for instance-level operation authorization. The SRVCON_AUTH Database Manager Configuration parameter enables the administrator to separate these two tasks using different authentication methods. When specified, the SRVCON_AUTH value is used to dictate what authentication type will be used to authenticate the client, whereas the AUTHENTICATION value indicates what authentication method to use for instance-level operations. Why would you want to specify a value in SRVCON_AUTH? One reason becomes obvious if you are using Kerberos. If there is a requirement to authenticate all connections using Kerberos but the user ID and group information for the user performing any instance-level operations is defined locally to the database server, it might be a good idea to set SRVCON_AUTH to Kerberos and AUTHENTICATION to SERVER or SERVER_ENCRYPT. In this way, for any instance-level operation, additional traffic from the database server to the Kerberos Distribution Center (KDC) will be avoided. (Kerberos is explained in a later section in this chapter.) The default value for SRVCON_AUTH is NOT_SPECIFIED, which means that the Database Manager Configuration AUTHENTICATION value will be used. Changing the value for the SRVCON_AUTH parameter is accomplished by updating the Database Manager Configuration for this parameter. Remember to restart the database instance (db2stop and then db2start) for the new value(s) to take effect. In Figure 3.2, the SRVCON_AUTH parameter is shown being set to use the DATA_ENCRYPT authentication method. (see2@jimmy) /home/see2 $ db2 update dbm cfg using srvcon_auth data_encrypt DB20000I The UPDATE DATABASE MANAGER CONFIGURATION command completed successfully.
Figure 3.2
Setting the SRVCON_AUTH DBM parameter
Authentication Type Negotiation Between the Client and Server There must be some protocol to allow the client and the server to negotiate an authentication type. DB2 uses an open standard architecture called Distributed Relational Database Architecture (DRDA®). DRDA is a set of protocols to enable users to access distributed data, regardless of where it physically resides in an open and robust heterogeneous distributed database environment. The role DRDA plays for DB2 is much like that of the TCP/IP protocol for the network. If you want to gain in-depth knowledge about this topic, you can find the DRDA specifications in open group websites (www.opengroup.org/publications/catalog/c812.htm, www.opengroup. org/publications/catalog/c813.htm, www.opengroup.org/publications/catalog/c814.htm). You can find a simple tutorial at www.dbazine.com/db2/db2-mfarticles/mullins-drda. The DRDA protocol requires that a client must specify an authentication type when initiating a communication session with the server. Thus, DB2 extracts the authentication type from the database catalog AUTHENTICATION value that was specified when the catalog database command was issued.
48
Chapter 3 • Understanding Identification and Authentication—The First Line of Defense
Before reviewing the negotiation steps, consider the idea of a hybrid (either/or) authentication type. KRB_SERVER_ENCRYPT and GSS_SERVER_ENCRYPT are both supported hybrid authentication types. The KRB_SERVER_ENCRYPT authentication type provides the mechanism to allow the server to authenticate the client with either Kerberos security or the encrypted user ID/encrypted password combination. With the GSS_SERVER_ENCRYPT authentication type, the server can authenticate a client with either the GSS API-based security mechanism or an encrypted user ID/encrypted password combination. To avoid complication during the negotiation process, the client should specify an authentication type during database cataloguing if possible. The actual negotiation flow between the client and the database server is performed by DB2 internally, with errors returned whenever the negotiation fails. In the case where the authentication type is not specified when the database is cataloged on the client, DB2 chooses SERVER_ENCRYPT or CLIENT authentication as the initial “trial” authentication type depending on whether the user ID and password are specified. If the user ID and password are specified on the connect statement, DB2 initially picks the SERVER_ENCRYPT authentication type; otherwise, it picks the CLIENT authentication type. The authentication type is sent as part of the first DRDA flow to the database server. The database server looks at its Database Manager Configuration parameter AUTHENTICATION or SRVCON_AUTH to decide whether the authentication type proposed by the DB2 client is acceptable. If it is acceptable, the database server accepts the proposed authentication type and continues the authentication protocol steps; otherwise, the database server rejects the proposed authentication type and sends a list of server-supported authentication types it can accept back to the client. When the client receives the list of server-supported authentication types, it will first check whether the original authentication type was not specified. If not, meaning the CATALOG DATABASE command has specified an authentication type, the client terminates the attempt and returns the following message to the user: SQL30082N Attempt to establish connection failed with security reason "17" ("UNSUPPORTED FUNCTION"). SQLSTATE=08001
If the authentication type was not specified, the client checks the list of server-supported authentication types to see whether one of the types can be used by the client. An example of this is when the authentication type specified at the server is KRB_SERVER_ENCRYPT while the client has not specified any authentication type initially. Table 3.2 shows the information exchange between the client and server.
Authentication Type
49
Table 3.2 Authentication Type Negotiation Scenario 1
Steps
DB2 Client
1
Catalog the database without authentication type.
2
A connect statement is issued without user ID and password specified.
3
Picked CLIENT authentication as initial value.
4
Communication Flow Direction
➔ Client authentication
Server receives the request to use CLIENT authentication and checks the DBM CFG to see whether it is valid.
➔ List of server supported values: Kerberos authentication
Database server decides that
SERVER_ENCRYPT
authentication
4
Client acknowledges that the server has rejected its proposed authentication type and looks for the list of server supported values.
5a
Client determines it can handle Kerberos.
DB2 Database Server
➔ Kerberos authentication
KRB_SERVER_ENCRYPT and CLIENT authentication
are incompatible. Database server will reject the proposed authentication type and send a list of server supported authentication types (for example, Kerberos, server_encrypt) it can accept back to the client.
Server receives the request to use Kerberos authentication and checks the DBM CFG to see that it is okay to use. The authentication for this connection is based on the Kerberos mechanism. (continues)
50
Chapter 3 • Understanding Identification and Authentication—The First Line of Defense
Table 3.2 Authentication Type Negotiation Scenario 1 (Continued)
Steps
DB2 Client
5b
Client determines it cannot handle Kerberos. Client then proceeds to see whether it can use SERVER_ENCRYPT. Unfortunately, the user ID and password are not available, and therefore the client will terminate the attempt and return an error,
Communication Flow Direction
DB2 Database Server
SQLCODE -30082 reason code 17.
If the preceding scenario were modified slightly (with the user specifying the user ID and password on the CONNECT statement), the steps would change as follows. In this scenario, the authentication type specified on the database server is KRB_SERVER_ENCRYPT (that is, Kerberos SERVER_ENCRYPT). A remote client cataloged a database without specifying that the authentication was Kerberos. When a user attempts to connect to the database from the remote client specifying a user ID and password (user ID and password for the KDC) intending to use Kerberos authentication, the connection attempt might fail with this: SQL30082N Attempt to establish connection failed with security reason "24" ("USERNAME AND/OR PASSWORD INVALID"). SQLSTATE=08001
What happened? When a remote client attempts to connect with a user ID and password combination to a database that was not cataloged with a specific authentication type, the DB2 client sends out a request to the server to use the default authentication method, SERVER_ENCRYPT. Because the server actually accepts the SERVER_ENCRYPT authentication type, the server assumes that the client has submitted a user ID and password to be validated by the operating system on the database server. As expected, this causes an error if the user ID and password are not actually defined on the underlying operating system of the database server. To avoid this situation, the authentication type must be specified during the CATALOG DATABASE command on the client. Alternatively, if the user ID/password combination does match with the values on the database server, the connection will succeed. Table 3.3 shows details on the information exchange between the client and server:
Authentication Type
Table 3.3
51
Authentication Type Negotiation Scenario 2
Steps
DB2 Client
1
Catalog the database without specifying any authentication type.
2
A CONNECT statement is issued with user ID and password specified.
3
Picked SERVER_ENCRYPT authentication as initial value.
Communication Flow Direction
➔ SERVER_ENCRYPT
authentication
4
DB2 Database Server
Server receives the request to use client authentication and checks the DBM CFG to see whether it is valid. The database server proceeds. It assumes that the client’s intent was to use the server’s operating system to perform authentication.
➔
5a
SERVER_ENCRYPT
authentication accepted and proceed with the connection
➔ Invalid user ID and/or password
5b
6a
The client is authenticated with SERVER_ENCRYPT.
6b
The client will terminate the connection attempt and return SQLCODE -30082 reason code 17.
If the user ID and password are the same for both the a Kerberos KDC and database server’s operating system, the underlying operating system will successfully validate the user ID and password. The connection will succeed. (See Step 6a.) If the user ID and password are different between the Kerberos KDC and the database server’s operating system, the validation will not succeed, and an error will be returned. (See Step 6b.)
52
Chapter 3 • Understanding Identification and Authentication—The First Line of Defense
Specifying Authentication Type on the DB2 Connect Gateway You might optionally specify an authentication type when issuing the CATALOG DATABASE command on the DB2 connect gateway so that it will apply for all connections passed through the gateway. Changing the authentication type on a limited number of gateways may be substantially less work than changing it for all clients, especially in a large enterprise. If the authentication type cataloged at the gateway is not specified (NOTSPEC), DB2 defaults to SERVER authentication as the outbound authentication type from the gateway. However, if the server rejects SERVER authentication (for example, consider a DB2 server that is using SERVER_ENCRYPT), DB2 will attempt to match the server rejection with what the client sent. If the authentication type cataloged at the gateway is a value other than NOTSPEC, the outbound authentication type from the gateway will be whatever is specified on the gateway. In effect, the authentication type cataloged at the gateway acts as a filter that limits the authentication types allowed through. If the value specified on the gateway does not match with the server, the database server will reject the proposed authentication type and send back a list of “server-supported” authentication types. The DB2 connect gateway will terminate the connection when the server rejects the gateway proposed authentication type and will return the following error to the DB2 client: SQL30082N Attempt to establish connection failed with security reason "17" (“UNSUPPORTED FUNCTION"). SQLSTATE=08001
To avoid connection errors, it is strongly suggested that the gateway authentication type match the authentication type on the server unless it is NOTSPEC. There is one exception to this discussion. In the case of a multiple-partitioned database (DPF) where the client has set the DB2NODE registry variable to specify a specific connection partition (known as the Coordinator NODE) for connection attempts, the client will connect to the cataloged node but hop from there to the indicated node. In this scenario, DB2 will not use the authentication type cataloged at the gateway; the negotiation will be purely between the client and the server.
How to Determine the Authentication Type Used for a Connection At statement completion time for all SQL statements, a SQL Communications Area (SQLCA) data structure is returned to the application. If you dump out the SQLCA for the CONNECT statement (if you are using the DB2 command-line processor, you can issue your CONNECT statement with the -a option. See the example in Figure 3.3), the SQLERRD (5) field of the SQLCA returns the authentication type of the connection. The value is one of the following: 0
Authenticated on the server
1
Authenticated on the client
2
Authenticated using DB2 Connect
3
Authenticated using Distributed Computing Environment security services
4
Authenticated on the server with encryption
5
Authenticated using DB2 Connect with encryption
Introduction to Security Plug-Ins
53
6
Authenticated using Distributed Computing Environment security services or on the server with encryption
7
Authenticated using external Kerberos security mechanism
8
Authenticated using external Kerberos security mechanism or on the server with encryption
9
Authenticated using external GSS API plug-in security mechanism Authenticated using external GSS API plug-in security mechanism or on the server with encryption
10
Authentication not specified
255
In Figure 3.3, notice the SQLCA information. The SQLCA indicates a successful authentication to a database called kevins by a user newton using SERVER authentication. (That is, the SQLERRD fifth field is 0.) (see@jimmy) /home/see2 $ db2 –a connect to kevins user newton using R Database Connection Information Database server SQL authorization ID Local database alias
= DB2/6000 8.2.5 = NEWTON = KEVINS
SQLCA Information sqlcaid : sqlerrmc: sqlerrp : sqlerrd :
Finding authentication type information in the SQLCA
INTRODUCTION TO SECURITY PLUG-INS In response to the increased need for state-of-the-art, up-to-the-moment flexible authentication architectures, DB2 security plug-ins were introduced. Security plug-ins are dynamic loadable libraries that DB2 invokes when performing authentication or group membership lookup. Security plug-ins are implemented at the instance level, and, therefore, a database within the instance will use the same set of security plug-ins.
54
Chapter 3 • Understanding Identification and Authentication—The First Line of Defense
Why Did DB2 Implement the Security Plug-In Architecture? By implementing the authentication and group membership lookup as a loadable security plug-in architecture, DB2 acquires a major flexibility and extensibility gain. It allows DB2 to deliver any new security authentication method quickly and make it release independent. For example, should DB2 decide to deliver a new security plug-in in release x+2, in general, the security plug-in can be copied to a DB2 client and server that are running on an earlier release (release x) that already supports the security plug-in architecture if the required Database Manager Configuration parameter is updated. The down-level DB2 client and DB2 server can also take advantage of the new security plug-in. By making APIs for security plug-in public, you have the flexibility of implementing your own security mechanisms and implementing your unique business logic requirement into the security plug-in. You can choose to build the security plug-in in-house or look to vendors or consultants to help implement your customized security plug-ins. Three factors of information can be used for authentication: • Factor 1 is something you know, such as a password or a PIN. • Factor 2 is something you have, such as an ATM card or a smart card. • Factor 3 is something you are, such as a fingerprint or retina scan. Authentication using only one factor of information is weak in protection. You may now implement a two-factor authentication by writing a customized security plug-in that communicates with smart card servers to authenticate a user entering a password displayed by the smart card (something that user has) after the user enters the PIN to the smart card (something that user knows). Because the smart card password is valid only for a short time, a replay attack should not be possible. An example of a smart card is the RSA® Smart Card 5200.
Type and Categories of Security Plug-Ins There are two categories of security plug-ins: authentication plug-ins (referred to here as an auth plug-ins) and group membership lookup plug-ins (referred to here as group plug-ins). They serve the purpose of authentication and group membership lookup for DB2. There are two types of auth plug-ins: • Client-side or server-side user ID/password-based auth plug-in • Client-side or server-side GSS API-based auth plug-in User ID/password-based auth plug-in implies that a user and password are used for authentication checking. This is easier to implement but is less flexible because only user IDs and passwords are used for authentication purposes, and there can only be one user ID/password-based auth plug-in on the client or the server. You can have more than one user ID/password-based auth
Introduction to Security Plug-Ins
55
plug-in available in the directory, but the Database Manager Configuration parameters to enable it will accept only one name. The related Database Manager Configuration parameters are explained later in this chapter. It is not necessary to have both the client-side and the server-side customized auth plug-ins implemented. For example, if you use only SERVER or SERVER_ ENCRYPT authentication and do not require the Remap User ID feature on the client-side auth plug-in, you do not need a client-side customized auth plug-in on the DB2 client because all the authentication-related operations will be done on the database server. In this case, a server-side customized auth plug-in will suffice. GSS API-based auth plug-ins require a reasonable knowledge of the Generic Security Service application programming interface (GSS API) standard Version 2. This standard is documented in RFC 2743 (www.ietf.org/rfc/rfc2743.txt) and RFC 2744 (www.ietf.org/rfc/rfc2744.txt). GSS API is a generic API used to perform client/server authentication with credentials such as Kerberos tickets or Public Key Infrastructure (PKI) certificates. Its purpose is to address the issue of the similar, but incompatible, security services in use. When you implement the authentication mechanism using GSS API, the implementation should, in theory, be interoperable with various other security mechanisms. DB2 has implemented its Kerberos support by rewriting it as a GSS API-based auth plug-in. SPKM (Simple Public Key Mechanism) and LIPKEY (a Low Infrastructure Public Key mechanism using SPKM) that uses PKI are other examples of security mechanisms that you could implement using a GSS API-based auth plug-in. One advantage of the GSS API-based auth plug-in is that any authentication information, including binary information, can be transmitted between the client and server multiple times to complete the authentication process. GSS API-based auth plug-ins normally require authentication-related work to be done on both sides, and, therefore, a comparable version of the GSS API auth plug-in should be available at both the DB2 client and database server. Unlike user ID/password-based auth plugins, there can be more than one GSS API-based plug-in on either the DB2 client or the DB2 server. On the DB2 server, it is possible to specify a list of GSS API-based plug-ins in a preferred order. This list is sent to the client, and the client goes through the preferred order to find the first one that is available to the client on the list. Figure 3.4 shows four different DB2 clients that have different sets of GSS API-based plug-ins implemented and copied into the correct location. The DB2 server has a list of server-supported GSS API-based plug-ins specified in the DBM CFG srvcon_gssplugin_list in the preferred order. When client 1 connects to the server, the server returns the ordered list, and then goes through the server’s list of plug-ins in the specified order from left to right until it finds the one that is also found in the client security plug-in directory, and then selects it and communicates with the server to use the selected one. As a result, client 1 will use SPKM, client 2 will use LIPKEY, and client 3 will use SPKM. Client 4 will not be able to find one that matches the list, and, therefore, an error (SQLCODE -30082 reason code 32) is returned because there is no matching GSS API plug-in between this client and the database server.
56
Chapter 3 • Understanding Identification and Authentication—The First Line of Defense
Before writing a GSS API-based auth plug-in, the plug-in writer should have a good understanding of GSS API concepts and the APIs. You can find an overview of the GSSAPI at www.gnu.org/ software/gss/manual/html_node/GSS_002dAPI-Overview.html.
IBM-Shipped Default Plug-In IBM currently ships, by default, a client-side operating system–based auth plug-in (IBMOSauthclient), a server-side operating system–based auth plug-in (IBMOSauthserver), an operating system–based group plug-in (IBMOSgroup), and on the supported platforms, a Kerberos-based auth plug-in (IBMkrb5). Figure 3.5 shows the list of the IBM-shipped security plug-ins on the AIX platform.
Introduction to Security Plug-Ins
$ ls 1s –R1 total 3 drwxr–xr–x 2 see build 201 Jun 27 11:58 drwxr–xr–x 2 see build 145 Jun 27 11:58 drwxr–xr–x 2 see build 201 Jun 27 11:58 ./client: total 2 drwxr–xr–x 1 see build 54 Jun 27 11:58 /../../../../common/lib/RS6000_64L/IBMOSauthclient.a drwxr–xr–x 1 see build 46 Jun 27 11:58 ./../common/lib/RS6000_64L/IBMkrb5.a
57
client group server
IBMOSauthclient.a–>.. IBMkrb5.a–>../../../.
./group: total 1 lrwxr–xr–x 50 Jun 27 11:58 IBMOSgroups.a–>../../ 1 see build ../../../common/lib/RS6000_64L/IBMOSgroups.a ./server: total 2 lrwxr–xr–x 54 Jun 27 11:58 IBMOSauthserver.a–>.. 1 see build /../../../../common/lib/RS6000_64L/IBMOSauthserver.a 1 see build 46 Jun 27 11:58 IBMkrb5.a–>../../../. lrwxr–xr–x ./../common/lib/RS6000_64L/IBMkrb5.a
Figure 3.5
List of IBM-shipped security plug-ins on the AIX platform
In the summer of 2006, IBM delivered a client-side Lightweight Directory Access Protocol (LDAP)-based auth plug-in, a server-side LDAP-based auth plug-in, and an LDAP-based group plug-in via the Web for customer download at www14.software.ibm.com/webapp/iwm/web/ preLogin.do?lang=en_US&source=swg-dm-db2ldap.
Client-Side Auth Plug-Ins on the Database Server The client-side auth plug-in needs to be installed on both the client and the server. The reason is that for local authorization (that is, authorization checking for instance-level operations such as db2start or db2trc), the plug-in that DB2 uses is the client plug-in on the database server. Therefore, you should have a client-side auth plug-in installed on your server that matches the type specified in the Database Manager Configuration parameter AUTHENTICATION. For example, if you have a database server where AUTHENTICATION is specified as Kerberos, you need to ensure the DBM CFG parameter CLNT_KRB_PLUGIN is set to either IBMkrb5 (IBMsupplied Kerberos plug-in) or the name of your customized Kerberos-based plug-in (either thirdparty vendor supplied or in-house built). You must also ensure that the Kerberos plug-in is installed into the client plug-in directory on the database server. Otherwise, instance-level operations such as db2start will fail with either SQLCODE of -1365 or SQLCODE of -1366.
58
Chapter 3 • Understanding Identification and Authentication—The First Line of Defense
Authorization ID Versus User ID Authorization ID is an internal ID representing an individual or group to which authorities and privileges within the database are granted. After a user has been authenticated, DB2 no longer uses the user ID or password for further checking (that is, authorization or privilege checking); instead, DB2 uses the authorization ID (auth ID). If using any IBM-shipped security plug-ins, the auth ID is always the uppercase version of the user ID. For a customized security plug-in, a user can choose to return a different value via the security plug-in API db2secGetAuthIDs. However, DB2 will uppercase the value. For example, if the API decides to return aBc as an auth ID for the user newton, DB2 will uppercase it to ABC. From this point on, the user newton will be known as ABC auth ID to DB2, and any privilege or authority checking will be made against ABC. There is a second type of authorization ID known as group auth ID. Group auth IDs refer to the list of uppercase auth IDs generated from the group membership list of the user. During the processing of the CONNECT statement, the group membership lookup will be performed right after authentication. A list of groups that a user is a member of is returned to DB2 via the group plugin API db2secGetGroupForUser. This list of groups is then uppercased and becomes the user’s group auth IDs. Group auth IDs are used for privilege or authority checking, with some exceptions. The exceptions and more details about different type of authorization IDs are discussed in Chapter 5, “Authorization—Authority and Privilege.”
Roles of the Different Categories of Security Plug-Ins A server-side auth plug-in (GSS API-based or user ID/password-based) performs authentication on the database server for incoming connection requests. It is also used to check whether an authorization ID is known to the plug-in. A client-side auth plug-in (GSS API-based or user ID/password-based) performs authentication on the DB2 client. It is also used to perform instance-level local authorization on the database server when instance-level commands, such as db2start, are executed. A group plug-in performs group membership lookup on both the client and the database server. It is also used to check whether an authorization ID is known to the plug-in.
DB2 Security Plug-In APIs The DB2 security plug-in APIs are fully covered in DB2 documentation, and DBAs, independent vendors, and developers can refer to the documentation when implementing a security plug-in. Figures 3.6, 3.7, and 3.8 outline the purpose of the APIs for the group plug-in, client-side auth plug-in, and server-side auth plug-in.
Introduction to Security Plug-Ins
59
Group Plug-in Generate Group List for AUTHID
GROUP PLUG-IN
Check if group exists for an AUTHID.
Figure 3.6
Group membership lookup plug-in
Client-side Plug-in Identification and Authentication Get user name from default login context.*
Validate Password Userid/Password Only
Mutual Authentication
Remap userid/password CLIENT PLUGIN
Get default credential Handle. *
Generate a service ticket.
Process service principal name. *Implicit authentication or for local authorization
Figure 3.7
Client-side auth plug-in
Generate initial credentials.
GSS-API only
60
Chapter 3 • Understanding Identification and Authentication—The First Line of Defense
Server-side Plug-in Identification and Authentication
Userid/Password Only
Process Connection Details
Validate Password
Authorization ID Mapping
Report service principal name CLIENT PLUG-IN
Obtain Server credential handle.
GSS-API Only
Figure 3.8
Check if user exists for an AUTHID.
Process Service Tickets
.Generate mutual authentication t.oken
Server-side auth plug-in
GSS APIs In addition to the set of required DB2 security plug-in APIs, you also need to implement the following list of GSS APIs to complete a GSS API-based security plug-in. • List of client-side APIs gss_init_sec_context
Initiates a security context with a peer application
• List of server-side APIs gss_accept_sec_context
Accepts a security context initiated by a peer
application • List of common APIs on both the client side and server side gss_delete_sec_context
Deletes an established security context
gss_display_status
Converts a GSS API status code to text
gss_release_buffer
Deletes a buffer
Introduction to Security Plug-Ins
61
Releases local data structures associated with a GSS API
gss_release_cred
credential Deletes internal format name
gss_release_name
• List of required types and structures (All types and structures are defined in the gssapiDB2.h header file in sqllib/include.) Structure to hold arbitrary length data, including character strings
gss_buff_desc gss_buffer_t
Pointer to gss_buffer_desc structure Opaque data type that identifies the credential data structure
gss_cred_id_t gss_ctx_id_t
Opaque data type that identifies one end of the GSS API security
context gss_name_t
Opaque data type that points to the internal representation of a principal
name OM_uint32
32-bit unsigned integer
• List of required definitions (All definitions are defined in the gssapiDB2.h header file in sqllib/include.) Delegation requested
GSS_C_DELEG_FLAG
Signifies that the gss_buffer_desc does not contain any data
GSS_C_EMPTY_BUFFER
Indicates a GSS major status code
GSS_C_GSS_CODE
Indicates that mechanism does not support context expiration
GSS_C_INDEFINITE
Indicates a GSS minor status code
GSS_C_MECH_CODE
Mutual authentication requested
GSS_C_MUTUAL_FLAG
GSS_C_NO_BUFFER Signifies that the gss_buffer_t variable does not point to a valid gss_buffer_desc structure GSS_C_NO_CHANNEL_BINDINGS GSS_C_NO_CONTEXT
No communication channel bindings
Signifies that the gss_ctx_id_t variable does not point to a
valid context GSS_C_NO_CREDENTIAL
Signifies that gss_cred_id_t variable does not point to a
valid credential handle Signifies that the gss_name_t variable does not point to a valid
GSS_C_NO_NAME
internal name GSS_C_NO_OID
Use default authentication mechanism
GSS_C_NULL_OID_SET GSS_S_COMPLETE
Use default mechanism
API completed successfully
GSS_CONTINUE_NEEDED Processing is not complete and the API must be called again with the reply token received from the peer
62
Chapter 3 • Understanding Identification and Authentication—The First Line of Defense
Security Plug-In-Specific Database Manager Configuration Parameters (DBM CFG Parameters) Security plug-in specific Database Manager Configuration parameters include those listed in Table 3.4. Table 3.4
Indicates whether authentication plug-ins run in a separate process. The only value supported currently is the default, UNFENCED.
GROUP_PLUGIN
Name of the group management plug-in library. If blank, the DB2-supplied OS-based group plug-in is used.
CLNT_PW_PLUGIN
Name of the client-side password authentication plug-in. If blank, this defaults to the DB2-supplied OS-based plug-in. Functions in this plug-in will also be used for connection if CLIENT authentication is used for the connection and local instance-level actions if the AUTHENTICATION parameter is set to SERVER, CLIENT, SERVER_ENCRYPT, DATA_ENCRYPT, or DATA_ENCRYPT_CMP.
CLNT_KRB_PLUGIN
Name of the client-side Kerberos plug-in. If blank, it is assumed that no Kerberos support is available. This plug-in will also be used for a connection if Kerberos authentication is used for the connection and local instance-level actions; so if the AUTHENTICATION parameter is set to KERBEROS or KRB_SERVER_ENCRYPT, this must be filled. On Windows platforms, this is filled with IBMkrb5 by default.
LOCAL_GSSPLUGIN
Name of the GSS API plug-in to be used for instance-level identification. Cannot be blank if AUTHENTICATION is set to GSSPLUGIN or GSS_SERVER_ENCRYPT.
SRVCON_PW_PLUGIN
Name of the server-side password authentication module that will be used for database connections and instance attachments. If blank, it defaults to the DB2-supplied OS-based plug-in.
SRVCON_GSSPLUGIN_LIST
Comma-separated list of the names of all GSS API-style plug-ins that the server can support. This list should be ordered by preference, with the most preferred plug-in first. This list will be used when SRVCON_AUTH is set to KERBEROS, KRB_SERVER_ENCRYPT, GSSPLUGIN, or GSS_SERVER_ENCRYPT.
Introduction to Security Plug-Ins
63
The following is the output for the GET DATABASE MANAGER CONFIGURATION command when all parameters are set to their default values (out of the box): Client Userid/password Plugin (CLNT_PW_PLUGIN) = Client Kerberos Plugin (CLNT_KRB_PLUGIN) = Group Plugin (GROUP_PLUGIN) = GSS Plugin for Local Authorization (LOCAL_GSSPLUGIN) = Server Plugin Mode (SRV_PLUGIN_MODE) = UNFENCED Server List of GSS Plugins (SRVCON_GSSPLUGIN_LIST) = Server Userid/password Plugin (SRVCON_PW_PLUGIN) = Server Connection Authentication (SRVCON_AUTH) = NOT_SPECIFIED Database manager authentication (AUTHENTICATION) = SERVER
Enabling Security Plug-Ins If you are using only an operating system for your authentication and group membership lookup, it is not necessary to perform any of the following steps. The default values will handle the backward-compatibility. The only database manager configuration parameters that you might need to modify are SRVCON_AUTH and AUTHENTICATION to allow you to use a different authentication type for connection- versus instance-level authorization. The following four tables show a step-by-step guide to enable different types of security plug-ins on the client or the database server. The Kerberos plug-in can be enabled either as Kerberos authentication type or GSSPLUGIN authentication type. The determining factor is whether your client or server wants to support more than one type of GSS API-based security plug-in (only one of them can be Kerberos); you should use the GSSPLUGIN authentication plug-in enablement method. Table 3.5
1
Enabling User ID/Password Authentication Plug-Ins Steps on the Client
Steps on the Server
Place plug-in library in client plug-in directory. This step is not necessary if you are using the IBM-shipped operating system client-side authentication plug-in.
Place the plug-in in the server plug-in directory. This step is not necessary if you are using the IBM-shipped operating systembased server-side authentication plug-in.
Update CLNT_PW_PLUGIN with the client plug-in name.
Update SRVCON_PW_PLUGIN with the server plug-in name.
If CLNT_PW_PLUGIN is left blank, it will default to the IBM-provided plug-in, IBMOSauthclient. If you do not use CLIENT authentication and do not require the remap user ID feature on the client-side auth plug-in, this step is not necessary, and nothing is required on the client. (continues)
64
Table 3.5
Chapter 3 • Understanding Identification and Authentication—The First Line of Defense
Enabling User ID/Password Authentication Plug-Ins (Continued) Steps on the Client
2
Steps on the Server Set SRVCON_AUTH to a system authentication type (that is, CLIENT, SERVER, SERVER_ENCRYPT, DATA_ENCRYPT, and DATA_ENCRYPT_CMP). or Set SRVCON_AUTH to NOT_SPECIFIED and set authentication to a system authentication type. If SRVCON_PW_PLUGIN is left blank, it defaults to the IBM-provided plug-in, IBMOSauthserver.
Table 3.6
1
Table 3.7
Enabling Group Membership Lookup Plug-Ins Steps on the Client
Steps on the Server
Place plug-in library in client plug-in directory. This step is not necessary if you are using the IBM-shipped operating system group plug-in.
Place the plug-in in the server plug-in directory. This step is not necessary if you are using the IBM-shipped operating systembased group plug-in.
Update GROUP_PLUGIN with the name of the group plug-in.
Update GROUP_PLUGIN with the name of the group plug-in.
If GROUP_PLUGIN is left blank, it defaults to the IBM provided plug-in, IBMOSgroups.
If GROUP_PLUGIN is left blank, it defaults to the IBM-provided plug-in, IBMOSgroups.
Enabling GSS API Authentication Plug-Ins Steps on the Client
Steps on the Server
1
Place the plug-in library in the client plug-in directory.
Place the plug-in in the server plug-in directory.
2
Optional: Catalog a database indicating that the client will use only a GSS API plug-in for authentication (for example,
Update SRVCON_GSSPLUGIN_LIST with an ordered list of supported plug-in names. Then, you should enable the GSSPLUGIN authentication mechanism by either.
db2 catalog db testdb at node testnode authentication gssplugin).
Introduction to Security Plug-Ins
65
Steps on the Client
Steps on the Server
Multiple plug-ins may exist on the client. In this case, the server dictates which one is used.
Setting SRVCON_AUTH to a GSSPLUGIN or Setting SRVCON_AUTH to NOT_SPECIFIED and AUTHENTICATION to GSSPLUGIN To perform local authorization: Place the client plug-in library in the client plug-in directory. Update LOCAL_GSSPLUGIN with the name of this plug-in.
Table 3.8
Enabling Kerberos Plug-Ins Steps on the Client
Steps on the Server
1
Place the plug-in library in the client Place the plug-in in the server plug-in directory. plug-in directory. This step is not necessary This step is not necessary if you are using the if you are using the IBM-shipped Kerberos IBM-shipped Kerberos plug-in. plug-in.
2
Update CLNT_KRB_PLUGIN with the name of the Kerberos plug-in.
Update SRVCON_GSSPLUGIN_LIST with the server Kerberos plug-in name.
If blank, DB2 assumes that the client is incapable of using Kerberos. The default Kerberos plug-in provided by DB2 is named IBMkrb5. For platforms supporting Kerberos, the IBMkrb5 library will already be present
in the client plug-in directory. 3
Optional: Catalog a database indicating that the client will use the Kerberos plug-in for authentication (for example, db2 catalog db testdb at node testnode authentication kerberos target principal service/ host@REALM).
Set SRVCON_AUTH to KERBEROS or KRB_SERVER_ENCRYPT. or Set SRVCON_AUTH to NOT_SPECIFIED and set AUTHENTICATION to KERBEROS or KRB_SERVER_ENCRYPT.
66
Chapter 3 • Understanding Identification and Authentication—The First Line of Defense
When Is the Security Plug-In Loaded by DB2? DB2 will load the client-side authentication security plug-in when a connection is issued on the DB2 client. DB2 preloads all the authentication server-side security plug-ins during the START DATABASE MANAGER operation; this is done to improve the performance of a connection. The group membership lookup is loaded whenever group membership information is required on the DB2 client or on the database server. If you are writing a security plug-in, one important piece of information is the fact the security plug-in on the client (including client-side auth plug-in and client-side group plug-in) is loaded with the privileges of the user ID that issued the connect statement or instance-level operation, and it might not have enough privilege to access information such as the password file. The security plug-in on the database server, including server-side auth plug-in and server-side group plug-in, are loaded with the instance owner privileges. Again, it could only access information that instance owners can access but cannot access information such as the password file that requires root access on UNIX or Administrators access on Windows. Thus, it might be necessary to write a separate program such as a daemon that runs with sufficient privileges and has the security plug-in communicate with the program to perform the required checking.
Other Features Available in Customized Security Plug-Ins A number of the new features listed here can be considered by the DBA when implementing customized security plug-ins: • Perform user ID, password and namespace remapping on the client. This is only applicable to user ID/password-based plug-ins. This feature is particular useful in a three-tier system where the Web server and the DB2 client form the middle tier. • Perform auth ID remapping on the server. This feature allows different user IDs to share the same authorization ID on the database server once authenticated. An example of where this feature could be used is when there are employees in a department who have rotating shifts and perform similar tasks every day requiring the same privileges. So, by using this feature, they can all be authenticated independently and can use the privileges associated with the common auth ID to perform their tasks. To find out which employee performed which task and when, DB2 allows the server-side plug-in to return the real name, which is then audited. For more information, refer to the db2secGetAuthid API. • User namespace is supported on all platforms. Two-part user IDs, such as DOMAIN\ user, on the connect statement are now possible. It can help to implement the separation of duties security principle for access control (as discussed in Chapter 5). • Refuse connections based on communication information. This feature can be used when you want to allow only a few IP addresses to be logged in to the database at a particular time.
Introduction to Security Plug-Ins
67
• A simple early intrusion detection can be implemented using a customized plug-in. For example, code logic can be added to db2secValidatePassword API of a user ID/password-based auth plug-in to keep track of a large volume of incorrect user ID and password authentication requests. When this is found, it can then trigger some action such as sending an e-mail to the system administrator or security administrator. If the GSS API-based auth plug-in is used, this logic can be added to gss_accept_ sec_context API. • Implement client operating system–specific logic. If you want your DB2 Windows client to authenticate against a different KDC than the DB2 UNIX or Linux client, you can obtain the client operating system from the client information structure returned from the client information callback function.
The Basic Flow of GSS API and DB2 Security Plug-In API Table 3.9 provides a simplified illustration of the basic client-server flows involved in the GSS API authentication process used by DB2. Note that the tokens are binary data managed and used by the security mechanism, and only the underlying security mechanism is required to interpret them. Table 3.9
1. The server obtains its principal name and credential handle at plug-in initialization time (db2secServerAuthPluginInit). Note that on the server, plug-ins are loaded and initialized as part of the start database manager operation (db2start).
2. Process server principal name (db2secProcessServerPrincipalName). 3. Obtain credentials to send to server gss_init_sec_context). ➔
4. Verify and accept client credentials (gss_accept_sec_context). Return the mutual authentication token if requested. Note that if there is more information required, step 3 and step 4 can loop multiple times until either client or server has indicated that it will no longer accept more authentication tokens. (continues)
68
Chapter 3 • Understanding Identification and Authentication—The First Line of Defense
Table 3.9
DB2 GSS API Authentication Process (Continued)
Client
Server 5. Obtain the auth IDs for the principal initiating the context (db2GetAuthIDs) and obtain group membership information for the principal by calling group membership plugin (db2secGetGroupsForUser).
6. Perform mutual authentication if required (gss_init_sec_context).
➔
7. Delete context (gss_delete_sec_ context) and clean up by calling gss_ release_buffer, gss_release_ name, and db2secFreeToken. If the user ID and password is explicitly specified, DB2 will also call db2secFreeInitInfo during the cleanup phase.
7. Delete context (gss_delete_sec_ context) and clean up by calling db2secFreeToken. DB2 will also call the group membership plug-in API db2secFreeGroupList to clean up memory allocated during the call to get the group membership.
Figures 3.9 and 3.10 show how the authentication information can flow between the client and server and how either the client or server can stop the loop by returning GSS_S_COMPLETE on the APIs.
Restrictions Imposed on GSS API Plug-Ins by DB2 GSS API is a standard that DB2 supports. However, DB2 imposes restrictions on how the GSS API functions are implemented. Following are some of them: • The default security mechanism is assumed, and, therefore, there is no OID consideration. • The only GSS services requested in gss_init_sec_context () are mutual authentication and delegation. DB2 will request a ticket for delegation but will never use that ticket to generate a new ticket. • Only the default context time is requested. • Context tokens from gss_delete_sec_context () are not sent from the client to the server and vice versa. • Anonymity is not supported. • Channel binding is not supported.
Multiple flows where the server indicated it will no longer accept more authentica-
70
Chapter 3 • Understanding Identification and Authentication—The First Line of Defense
KERBEROS—AN IBM-SHIPPED GSS API-BASED SECURITY PLUG-IN Kerberos is one of the key single sign-on solutions on the market. It is based on an open standard. Kerberos is essentially a secure network authentication protocol that employs a system of shared secret keys and is able to provide robust security against impersonation and reply attacks. With Kerberos, passwords are never flown on the wire, and the server and client may authenticate one another (referred to as mutual authentication). A three-tier system is used in which encrypted tickets (provided by a separate server called the Kerberos Key Distribution Center, or KDC for short) are exchanged between the application server and client rather than text user ID and password pairs. These encrypted service tickets (credentials) are understood only by the client and the server, so there is minimal security risk, even in the event that the ticket is intercepted from the network. A client must perform two steps to communicate with a server. The first step is to acquire a “ticket-granting” ticket. This usually occurs when a user logs in to the system and issues the KINIT command to authenticate to the KDC. The second step is to acquire a “session ticket” that can be used to communicate with the server using the ticket-granting ticket. Figures 3.11 and 3.12 show a basic overview of how Kerberos works. Inside a KDC, there are two services and a KDC database. The database contains an entry called a principal and the associated encryption key for each registered user. The encryption key is derived from the user’s input password when it registers with the KDC. The two services are the authentication service (AS) and ticket-granting service (TGS). The authentication service as named is responsible for authenticating a user before giving the initial credential—the TGT. The TGS is responsible for granting tickets. During Kerberos authentication, the following eight steps are performed (the last two only if mutual authentication is requested): 1. Client requests a TGT by authenticating itself to the Kerberos AS via kinit on UNIX and Linux and by logging in to a domain on Windows. 2. The AS sends back the TGT to the client after the user has authenticated successfully. 3. With TGT, the client requests a service granting ticket (that is, session key) to access a server. 4. TGS generates a session key and then sends the key to the client (encrypted using the client’s private key). In addition, the KDC encrypts the session key, along with some information about the client, in the server’s private key (collectively the ticket) and provides it to the client. 5. The client encrypts an authenticator with the session key and sends that, together with the ticket, to the server. 6. The server decrypts the ticket and extracts the session key.
Requesting session key and connecting to the server using the session key
7. If the server is requested to do so, it uses the session key to decrypt the authenticator, extract the timestamp from within the authenticator, encrypt the timestamp with the session key, and send it to the client. The return of this encrypted token constitutes the initiation of mutual authentication. 8. The client uses the session key to decrypt the token, and if the timestamp matches that from the authenticator, mutual authentication is considered successful. It is important to understand that Kerberos can perform only authentication, whereas the group membership lookup relies on other mechanisms such as the default server-side operating system–based group plug-in or LDAP group plug-in.
72
Chapter 3 • Understanding Identification and Authentication—The First Line of Defense
Authorization ID Mapping Consideration An authorization ID (auth ID) is derived from the first part of the principal name. For example: see/[email protected] will become SEE. So, the first part of the principal acted like a user ID, and, therefore, it must follow the user ID naming convention for DB2: • Character strings that represent names of database manager objects can contain any of the following: a–z, A–Z, 0–9, @, #, and $. • User IDs and groups may also contain any of the following additional characters when supported by the security plug-in: _, !, %, (, ), {, }, -, ., ^. • User IDs and groups containing any of the following characters must be delimited with quotations when entered through the command line processor: !, %, (, ), {, }, -, ., ^. • The first character in the string must be an alphabetic character, @, #, or $; it cannot be a number or the letter sequences SYS, DBM, or IBM. • User IDs cannot exceed 30 characters on Windows 32-bit operating systems and 8 characters on all other operating systems. • Group IDs cannot exceed 30 characters in length. On Windows platforms, the IBM-shipped Kerberos plug-in (IBMkrb5) assumes the @ character to be the domain separator. Therefore, @ cannot be used as part of the username. A principal name is in one of the two formats: name@REALM or name/instance@REALM. Because the first part of the principal name is used for authorization ID-derivation, it is possible that two principal names from the different Kerberos realms can be mapped to the same auth ID. For example: see/[email protected] and see/[email protected] will be mapped to the same auth ID SEE. It is also possible that two principal names from the same name but different instances map to the same auth ID. For example, see/[email protected]. com and see/[email protected] will be mapped to the same auth ID SEE. Therefore, it is recommended that a unique namespace for the name within all the trusted realms is maintained. This means all principals with the same name (first part of the principal name), regardless of the realm or instance, should belong to the same user.
Customized Kerberos-Based Security Plug-In If you have a need to include business logic or want to take advantage of some of the new features available to customized security plug-ins, you might choose to implement a customized version of the Kerberos-based security plug-in developed in-house or through a vendor. The source code of the UNIX/Linux IBM Kerberos auth plug-in is open to the public. It is located in sqllib/samples/security/plugins/IBMkrb5.c.
The Lightweight Directory Access Protocol (LDAP)
73
IBM-Shipped Kerberos Plug-In (IBMkrb5) IBMKrb5 on Windows platforms takes advantage of Windows native Kerberos support, and it
behaves the same way as earlier releases of DB2. IBMKrb5 on UNIX®/Linux® platforms makes use of the NAS® toolkit (IBM® Network Authenti-
cation Services toolkit, which is based on MIT Kerberos). It is supported only on platforms where the NAS toolkit is available. Starting with DB2 8.2, the supported platforms are AIX® 5.2 or later (32 bit or 64 bit), Solaris® 8 or later (32 bit or 64 bit), and Red Hat® Linux Advanced Server® 3 (Intel 32 bit). Starting on DB2 9, the platforms supported include AIX 5.2 (32 bit and 64 bit), AIX 5.3 (32 bit and 64 bit), Solaris 9 (32 bit and 64 bit), Solaris 10 (32 bit and 64 bit), Red Hat Enterprise Linux Advanced Server 4 (Intel 32 bit and 64 bit), and SUSE® Linux SLES® 9 (Intel 32 bit and 64 bit).
More Information about Kerberos Appendix B, “Kerberos,” briefly explains how to configure your system as a Kerberos environment that is ready for DB2. There is also a brief interoperability explanation between different platforms.
THE LIGHTWEIGHT DIRECTORY ACCESS PROTOCOL (LDAP)—YET ANOTHER IBM-SHIPPED USER ID/PASSWORD-BASED SECURITY PLUG-IN The Lightweight Directory Access Protocol, better known as LDAP, is based on the X.500 standard, but is significantly simpler and more readily adapted to meet custom needs. Unlike X.500, LDAP supports TCP/IP, which is necessary for Internet access. The core LDAP specifications are all defined in RFCs. You can find a complete list of LDAP-related RFCs on the LDAPman RFC page (www.ldapman.org/ldap_rfcs.html). An LDAP directory can store a wide range of heterogeneous data in one tree: e-mail address, user management data, and much more. An LDAP directory is much like a hierarchical database. A well-known hierarchical database is IBM IMS. LDAP directories are heavily optimized for read performance, thus making it a good candidate for authentication and group membership lookup purposes. What the LDAP directories look like is up to your organization’s need. The application that uses these directories needs to be written based on the agreed-upon directories’ design. LDAP provides a way to centralize information on a server, thus making it an attractive identity management tool. Figure 3.13 is a sample LDAP directory tree that can be used to represent user and group information for authentication and group membership lookup purposes.
74
dn: 0=ibm.c=us objectclass: top objectclass: organization o: IBM
Chapter 3 • Understanding Identification and Authentication—The First Line of Defense
dn: ou=IT.o=ibm.c=us
The Lightweight Directory Access Protocol (LDAP)
75
The root node is o=ibm, c=us. It means that all the users who belong to the IBM enterprise can be managed in this domain. And ou=IT,o=ibm,c=us is a branch node; it represents a department in IBM and can be used to manage the users in more detail. For example, we can search a user who is in the IT department directly from this branch node, and there is no need to always begin from the root node. Node uid=usr1,ou=IT,o=ibm,c=us is a leaf node that represents a user in DB2; it contains valid information, such as password, for this user. In this tree, there are also two group’s nodes: cn=mgr1,o=ibm,c=us and cn=db2grp,o=ibm,c=us. Both of them can be used in DB2 for authorization. We can assume a manager has a higher authority than a common employee on a salary database. Then, if usr1 and usr2 belong to group mgr1, both of them will have higher access authority on the salary database. On the other hand, cn=mgr1,o=ibm,c=us is a usual group with two members (uid=usr1,ou=IT,o=ibm,c=us and uid=usr2,ou=Sales,o=ibm,c=us), whereas cn=db2grp,o=ibm,c=us is a nested group with a member cn=mgr1,o=ibm,c=us, which is also a group. Using LDAP to perform authentication has a similar flow to that of using the underlying operating system for authentication with the exception that the user information is stored on a third server rather than locally on the database server. Figure 3.14 illustrates the connection flow using LDAP authentication.
1 Server-Side Security Plug-In 4
Database
User
3
2
LDAP Server
Figure 3.14
Authentication using IBM-shipped LDAP-based security plug-in
76
Chapter 3 • Understanding Identification and Authentication—The First Line of Defense
1. When a user enters the user ID and password on the connect statement, the user ID and password are flowed to the database server. 2. The database server passes the user ID and password into the security plug-in. The LDAP auth plug-in uses the supplied user ID and password to perform an LDAP bind against the LDAP server. If the bind succeeds, the user ID and password is validated as being correct. Otherwise, the user ID and password failed the validation. 3. The LDAP auth plug-in validates the user ID and password and returns one of the published security plug-in return codes to the database server. 4. The database server denies the user access to the database if the LDAP auth plug-in return code indicates that it failed to validate the user ID and password. Otherwise, the LDAP group membership plug-in (if group_plugin is set to use the LDAP group plug-in; otherwise, the operating system–based group plug-in will be used) will be loaded to acquire group membership for the user. The database server then checks the system catalog table SYSIBM.SYSDBAUTH to verify whether the user or one of the groups that the user belongs to has CONNECT privilege to the database. The user is granted the access to the database if the sufficient CONNECT privilege is present in the system catalog table. It is best to have Secure Sockets Layer (SSL) for the communication between the DB2 client or DB2 server and the LDAP server because sensitive data, such as user IDs and passwords, is sent over the wire.
IBM-Shipped LDAP Authentication and Group Membership Plug-In Independent of the product release, IBM has delivered a client-side LDAP-based auth plug-in, a server-side LDAP-based auth plug-in, and an LDAP-based group membership lookup plug-in via the Web. To learn how to configure the DB2 client and server and the LDAP server, refer the documentation that is part of the deliverable.
AUTHORING AND IMPLEMENTING CUSTOMIZED SECURITY PLUG-INS There are five steps to create a DB2 security plug-in. The following subsections explain each step in more detail.
Step 1: Include the Security Plug-In Header Files in Your Plug-In db2secPlugin.h and gssapiDB2.h are the two header files needed to implement customized security plug-ins. The gssapiDB2.h header file is needed only if you are building a GSS API plug-in. Figure 3.15 shows the location of the two required header files for implementing security plug-ins on a Windows system.
Authoring and Implementing Customized Security Plug-Ins
Figure 3.15
77
Security plug-in-related header files
Step 2:Write the APIs Constituting Your Plug-In Implement all the required APIs based on the type and categories of the security plug-in. The set of required APIs are well documented in DB2 documentation (and in the header file listed in Step 1). Initialization APIs for each type of plug-in return the set of function pointers for the rest of the implemented APIs. Listing 3.1 shows a sample implementation of db2secServerAuthPluginInit API for a user ID/password-based auth plug-in. Listing 3.1
Chapter 3 • Understanding Identification and Authentication—The First Line of Defense
Security Plug-In Initialization API (Continued)
fns->version = DB2SEC_API_VERSION; fns->plugintype = DB2SEC_PLUGIN_TYPE_USERID_PASSWORD; fns->db2secDoesAuthIDExist = &is_user; fns->db2secFreeErrormsg = &free_error_message; fns->db2secFreeToken = &free_token; fns->db2secGetAuthIDs = &getauthids; fns->db2secServerAuthPluginTerm = &terminate_plugin; fns->db2secValidatePassword = &validatePassword; /* Example on how to use logMessage_fn */ /* Will log the init successful information into db2diag.log at DIAGLEVEL 3 */ (logMessage_Fn)(DB2SEC_LOG_WARNING, "db2secServerAuthPluginInit successful", strlen(“db2secServerAuthPluginInit successful")); return DB2SEC_PLUGIN_OK; }
Step 3: Populate the Functions Pointer Structure Before Returning to DB2 The functions pointer returns pointers to all the APIs required for the particular plug-in library that you have implemented. For example, in the case of group plug-ins, it contains pointers to your implementations of the db2secDoesGroupExist, db2secFreeErrormsg, db2secFreeGroupListMemory, db2secGetGroupsForUser, and db2secPluginTerm APIs. Listing 3.2 shows a snippet of how the functions pointer can be populated for the group plug-in library. Listing 3.2
Step 4: Compile the Plug-In Source and Create a Shared Library After you finish coding your security plug-in, compile it as either a 32-bit or 64-bit loadable object to correspond with your DB2 instance. The library created must have the same name as the
Authoring and Implementing Customized Security Plug-Ins
79
plug-in name. Libraries must be shared libraries with the appropriate platform-specific extension. For example, if the name of your plug-in is myPlugin, the following extensions are required: • myPlugin.dll (Windows) • myPlugin.a (AIX) • myPlugin.so (Linux, AIX, Sun Solaris, HP-UX on IA64) • myPlugin.sl (HP-UX on PA-RISC) Libraries must be threading safe (re-entrant) and C linkage must be used (at least for the initialization functions).
Step 5: Place the Library in the Appropriate Directory Security plug-in libraries must be placed in specific directories: • Windows sqllib\security\plugin\\client sqllib\security\plugin\< instance name >\server sqllib\security\plugin\< instance name >\group
For the IBM-supplied default plug-ins sqllib\security\plugin\IBM\client sqllib\security\plugin\IBM\server sqllib\security\plugin\IBM\group
For the IBM-supplied default plug-ins sqllib/security32/plugin/IBM/client sqllib/security32/plugin/IBM/server sqllib/security32/plugin/IBM/group
In Linux/UNIX, similar directories for 64-bit libraries are used as above, except that the subdirectory name security64 is used rather than security32. On Windows 64-bit instances, both 32-bit and 64-bit plug-ins will be in the same directory, but the 64-bit plug-ins will be added with a
80
Chapter 3 • Understanding Identification and Authentication—The First Line of Defense
64 suffix; Using our previous example, the 32-bit plug-in will be myPlugin.dll while the 64-bit plug-in should be named as myPlugin64.dll.
NOTE Plug-ins located under the IBM subdirectory are reserved for the IBM-shipped default plug-ins. Any other customized plug-in placed in this directory will be lost the next time you apply a new Fixpack or release.
CASE STUDY: USING A CUSTOMIZED SECURITY PLUG-IN TO IMPLEMENT THE ABILITY TO CENTRALIZE USER ID AND PASSWORD AND GROUP MEMBERSHIP INFORMATION IN A DATABASE Identity management is costly and error prone because it is a highly manual process, especially when identity management is not centralized. Kerberos and LDAP are the two commonly used centralized repositories for identity. A third approach is to centralize the identity into a database.
Requirement Assume Company X has three different instances: inst1, inst2, and inst3. The company wants to have all user information—user ID, password, and group membership—for all three instances centralized.
Proposed Design A new instance called inst_auth is created for this matter. In this instance, we will create one database called dbauth that contains all the user information such as user ID, password, and authorization ID and group list in one single table. The password stored in the table is a hashed value of the actual password. MD5 and SHA are the well-known fixed-length one-way hashing functions. HAVAL is a variable-length one-way hashing algorithm. Because sensitive data will flow on the wire, the authentication type chosen for this instance, and therefore database dbauth is DATA_ENCRYPT, to ensure that the data and the authentication flow are all encrypted. Table 3.10 shows a proposed layout.
Case Study: Using a Customized Security Plug-In to Implement the Ability to Centralize User ID and Password and Group Membership Information in a Database.
Data
Data
81
Data
Server security plug-in for inst1
Inst_auth
Data
Data Data
Data
Data
Server security plug-in for inst2
Server security plug-in for inst3
Title An external invoked program (can be running daemon) that takes the information flowed from the server security plug-in and compares with the information fetched from the database in inst_auth
Figure 3.16
Using database to centralize the identity management
An administrative application should be designed and implemented. It is needed to perform continuous maintenance of the user information such as adding users, removing users, changing group information, changing passwords, and changing the authorization ID mapping for a user. A customized server user ID/password-based auth plug-in and a customized group membership lookup plug-in should be implemented and installed on the database server where each instance (inst1, inst2, inst3) resides. Any connection to the database in one of the three data instances will use these customized plug-ins because the Database Manager Configuration parameters work on an instance level.
82
Table 3.10
Table - Auth_Info
Unique Index
Check Constraint Ensuring the Number Cannot Be > 3
Char (1)
Integer
Unique Index
Check Constraint Ensuring the Number >=0
Data type
varchar (256)
varchar (256)
Date
Column name
userid
password
pw_expire_date
account_status number_ auth ID of_failed_ login
numGroup groupinfo
Sample row 1
user1
…
2007-0101
N
0
USER1
3
"\006GROUP1\ 007MYGROUP\ 008MYGROUP3"
Sample row 2
newton
…
2006-12-31 E
1
NEWTON
2
"\006GROUP1\ 008MYGROUP2"
Sample row 3
einstein
…
2007-03-12 L
3
EINSTEIN
0
NULL
varchar (256)
Integer
varchar (32672) nullable
Chapter 3 • Understanding Identification and Authentication—The First Line of Defense
Index or Constraint Requirement for the Individual Column
Check Constraint Ensuring Only N, E, or L Can Be Used for This Column (N = Normal, E = Expired, L = Locked Out)
Case Study: Using a Customized Security Plug-In to Implement the Ability to Centralize User ID and Password and Group Membership Information in a Database.
83
An external program, either invoked by the plug-ins or running as a daemon, communicates with the above plug-ins. The task for this external program is to connect to the database dbauth and retrieve information from the table for a given user ID or auth ID.
Detailed Implementation Information Administrative Application The administrative application can be a GUI-based or a text menu–based application. It establishes a connection to the dbauth database (that resides in inst_auth instance) and uses SQL statements to interact with the table auth_info that resides in the database. The following is a list of tasks required: 1. Given a user ID, unlock the user account: db2 "UPDATE AUTH_INFO SET ACCOUNT_STATUS = 'N' WHERE USERID = "
2. Given a user ID, reset the number of failed login attempts: db2 "UPDATE AUTH_INFO SET NUMBER_OF_FAILED_LOGIN = 0 WHERE USERID = "
3. Given a user ID, reset the password and thus automatically update the password expiration date to 90 days after the reset. (This assumes the corporate policy has set password expiration at 90 days.) First, the new password is hashed by using the chosen hashing algorithm. Then issue this: db2 "UPDATE AUTH_INFO SET PASSWORD = WHERE USERID = "
And then this: db2 "UPDATE AUTH_INFO SET PW_EXPIRE_DATE = (CURRENT DATE + 90 DAYS) WHERE USERID = "
There is an alternative for the second update. An update trigger can be created on the column password that automatically updates the pw_expire_date. The syntax to create this trigger is as follows: db2 "CREATE TRIGGER NEW_EXPIRE AFTER UPDATE ON AUTH_INFO(PASSWORD) FOR EACH ROW MODE DB2SQL UPDATE AUTH_INFO SET PW_EXPIRE_DATE = (CURRENT DATE + 90 DAYS)."
4. Create a new user. A simple insert statement will do as long as all the information is formatted to the table layout. Once again, the password is hashed: db2 "INSERT INTO AUTH_INFO VALUES "
84
Chapter 3 • Understanding Identification and Authentication—The First Line of Defense
5. Delete an existing user: db2 "DELETE FROM AUTH_INFO WHERE USERID = "
6. Update the group information for a user: db2 "UPDATE AUTH_INFO SET NUMGROUPS = "
And: db2 "UPDATE AUTH_INFO SET GROUPINFO = "
7. Update the auth ID for a user. To simplify the work for the group plug-in, the design has placed the work of making the list of groups into the formatted string as required by DB2 (as stated in the db2secGetGroupsForUser API) in this administrative application. The group string is in a format listed on the Table 3.11 (required for the db2secGetGroupsForUser API), where the length is in the first byte followed by the group name and length of the second group followed by the group name and so on: db2 "update auth_info set authid = where userid = "
8. Reactivate an expired account: db2 "UPDATE AUTH_INFO SET ACCOUNT_STATUS = 'N' WHERE USERID = AND ACCOUNT_STATUS = 'E'"
9. Expire an account: db2 "UPDATE AUTH_INFO SET ACCOUNT_STATUS = 'E' WHERE USERID = "
The External Program or the Daemon This auxiliary program establishes a connection to the dbauth database residing in inst_auth instance and retrieves the row from the database based on the input value coming from the security plug-in. So, why doesn’t this design establish the connection within the security plug-in? The main reason is that the security plug-in is running unfenced in the database engine agent address space, which has the DB2 engine library loaded. If the security plug-in was also to perform the connection, the DB2 client library would need to be loaded, too, into the database engine agent address space. This can potentially cause undesired consequences such as corruption of the database engine. Therefore, an external program or daemon approach is strongly encouraged. As mentioned previously, there should be a daemon running on the database server for each instance. An alternative is to have a daemon application running locally on the database server at instance inst_auth and then have the security plug-in communicate with the daemon across the network with an agreed-upon port number. SSL should be considered if using the alternative approach (to protect the information sent across the network).
Case Study: Using a Customized Security Plug-In to Implement the Ability to Centralize User ID and Password and Group Membership Information in a Database.
85
How the communication takes place between the daemon and the security plug-in is determined during implementation. One choice is to use a named pipe. The output from the daemon will include a security plug-in return code as listed in Appendix H, “Security Plug-In Return Codes,” or the Application Development Client Volume “Return codes for security plug-ins” section. Table 3.11 shows the tasks that this daemon must perform. Table 3.11
Tasks Performed by This Daemon
Task Task Number Description D1
User ID and password verification (optionally change password if the new password clause is used in the connect statement)
Input from the Security Plug-In
Output to the Security Plug-In
User ID and password hash value and optionally the hash of the new password
Security plug-in return code. If the return code is DB2SEC_ PLUGIN_OK,
DB2 will also return the group list information for this user.
Algorithm 1. Select the entire row where the user ID matches the input value and the column userid on table auth_info. 2. If no row is found, this user does not exist; return DB2SEC_PLUGIN_BADUSER.
3. Check whether account_ status = 'E' (expired). If so, return DB2SEC_ PLUGIN_UID_EXPIRED. 4. Check whether account_ status = 'L'. If so, return DB2SEC_PLUGIN_USER_ SUSPENDED.
5. Check whether pw_expire_ date <= current date. If so, return DB2SEC_ PLUGIN_PWD_EXPIRED.
6a. If the password does not match, check that the number_of_failed_login
+1 is greater than 3. If so, issue an update: db2 "UPDATE AUTH_INFO SET ACCOUNT_STATUS = 'E' AND NUMBER_OF_ FAILED_LOGIN = NUMBER_ OF_FAILED_LOGIN +1"
(continues)
86
Table 3.11
Chapter 3 • Understanding Identification and Authentication—The First Line of Defense
Tasks Performed by This Daemon (Continued)
Task Task Number Description
Input from the Security Plug-In
Output to the Security Plug-In
Algorithm And return: DB2SEC_PLUGIN_USER_ SUSPENDED
6b. If number_of_failed_ login is less than 3, then issue an update: db2 "UPDATE AUTH_INFO SET NUMBER_OF_FAILED_ LOGIN = NUMBER_OF_ FAILED_LOGIN +1"
And return: DB2SEC_PLUGIN_BADPWD
7. We arrive to this point knowing that the password and other criteria have checked out. The only task left is to update the password hash if a new password’s hash is given by issuing: db2 "UPDATE AUTH_INFO SET PASSWORD = " The return code will be DB2SEC_ PLUGIN_OK and the group list information is returned to the plug-in.
D2
Retrieve the auth ID for an authenticated user
User ID (that is already previously authenticated)
1. Security plug-in return code. 2. Auth ID for the corresponding user.
Issue: db2 "SELECT AUTHID FROM AUTH_INFO WHERE USERID = "
If no row is returned, return DB2SEC_PLUGIN_ UNKNOWNERROR. This should
never happen because the user should have just been authenticated. Otherwise, return DB2SEC_PLUGIN_OK and the retrieved auth ID.
Sample Scenarios
87
Task Task Number Description
Input from the Security Plug-In
Output to the Security Plug-In
D3
Auth ID
Security plug-in return code.
Check whether an auth ID exists
Algorithm Issue: db2 "select count(authid) from auth_info where authid = "
The value returned should be either 0 or 1 because the auth ID column is a unique column. A count of 0 means no such auth ID exists, so return DB2SEC_PLUGIN_INVALIDU SERORGROUP; otherwise, return DB2SEC_PLUGIN_OK.
D4
Get the group list for a given user using the auth ID
Auth ID
1. Security plug-in return code. 2. Group list if found.
Issue: db2 "select groupinfo, numGroups from auth_info where authid = "
If numGroups = 0, return DB2SEC_PLUGIN_BADUSER.
If numGroups > 0, return the group list and DB2SEC_PLUGIN_OK.
You can find detailed implementation information for the group and server plug-in used in this case study in Appendix I, “Detailed Implementation for the Case Study in Chapter 3.”
SAMPLE SCENARIOS Sometimes, DBAs are presented with challenges requiring solutions that are not easily researched. For example, it is not every day that the DBA works on implementing a security plugin, let alone one that presents an especially challenging level of complexity. To facilitate comprehension, the following sample scenarios are played out to provide examples of ways to “cope” with some of the more challenging aspects of the technical DB2 security architecture.
88
Chapter 3 • Understanding Identification and Authentication—The First Line of Defense
Scenario 1: Mixed Use of Pre-8.2 and 9 Clients with the GSS API Plug-In In this scenario, the environment has a lot of DB2 clients. Some clients are plug-in enabled and some are not. The DBA wants to start rolling out the GSS API plug-in on the database server. Prior to using the GSS API plug-in, the clients were using client, server, or SERVER_ENCRYPT authentication. (The down-level client (prior to 8.2) is shown as c1, the DB2 9 client is shown as c2, and the DB2 9 server is shown as s1 to illustrate the scenario.) • Down-level client c1 1. No need to do anything if the database is not cataloged with AUTHENTICATION CLIENT or AUTHENTICATION SERVER. If cataloged with the authentication CLIENT or authentication SERVER, recatalog the database without specifying an authentication clause or use the authentication options SERVER_ENCRYPT. This client uses the SERVER_ENCRYPT authentication type for authentication, and the authentication will occurs using the server-side user ID/password-based auth plug-in. • DB2 9 client c2 1. Install the client-side GSS API plug-in(s) in the client plug-in directory. 2. Catalog the database specifying the authentication options with the authentication type GSSPLUGIN. In this scenario, a hybrid authentication type is used at the database server, so you must catalog the database with the authentication GSSPLUGIN; otherwise, it will default to use SERVER_ENCRYPT on the initial DRDA flow if you specified a user ID and password on the connect statement. See the section “Authentication Type Negotiation between the Client and Server” for more details. • DB2 9 server s2 1. Install the server-side GSS API plug-in(s) in the server plug-in directory. 2. Update DBM CFG parameter SRVCON_GSSPLUGIN_LIST with the ordered list of the supported GSS API plug-in names. Note that the list should be in the order of preference. 3. Update DBM CFG parameter SRVCON_AUTH to GSS_SERVER_ENCRYPT. After you update the SRVCON_AUTH to GSS_SERVER_ENCRYPT, the server handles the new clients using the GSS API plug-in and still uses SERVER_ENCRYPT to deal with other clients (including down-level clients) that do not support GSS API plug-in. 4. Restart the instance database manager by issuing a stop database manager (DB2STOP) and start database manager (DB2START).
Sample Scenarios
89
Scenario 2: DB2 9 Client Communicating with a Database in a Different Instance with a Different Authentication Setting In this scenario, there are three databases (dbase1, dbase2, dbase3) that belong to instances inst1, inst2, inst3, respectively. • For inst1 to use SRVCON_AUTH = SERVER_ENCRYPT 1. Install the server-side user ID/password-based plug-in (for example, server_upw) in the server plug-in directory. 2. Update the Database Manager Configuration parameter SRVCON_PW_PLUGIN with the name of the server-side user ID/password-based plug-in. 3. Update the Database Manager Configuration parameter SRVCON_AUTH to SERVER_ENCRYPT. 4. Restart the instance database manager by issuing a stop database manager (DB2STOP) and start database manager (DB2STOPT). • For inst2 to use SRVCON_AUTH = Kerberos 1. Install the server-side Kerberos based plug-in (for example, krb) in the server plugin directory. 2. Update the Database Manager Configuration parameter SRVCON_GSSPLUGIN_LIST with the name of the server-side Kerberos-based plug-in. 3. Update the Database Manager Configuration parameter SRVCON_AUTH to Kerberos. 4. Restart the instance database manager by issuing a stop database manager (DB2STOP) and start database manager (DB2START). • For inst3 to use SRVCON_AUTH = gssplugin 1. Install the server-side GSS API-based plug-in (for example, krb, gss1, gss2) in the server plug-in directory. 2. Update the Database Manager Configuration parameter SRVCON_GSSPLUGIN_LIST with the name of the server-side GSS API-based plug-ins in the order of preference. For example, assume you prefer gss2 to krb to gss1, and then update the Database Manager Configuration parameter using SRVCON_GSSPLUGIN_LIST 'gss2,krb, gss1'. Note: do not put spaces before or after the comma in the list; otherwise, it will be considered part of the security plug-in name. Notice that the krb can be the same Kerberos-based plug-in from inst2. Because Kerberos is implemented using GSS API infrastructure, it can be used as a GSS API plug-in. Update DBM CFG using SRVCON_GSSPLUGIN_LIST 'GSS2,KRB,GSS1'. 3. Update the Database Manager Configuration parameter SRVCON_AUTH to gssplugin.
90
Chapter 3 • Understanding Identification and Authentication—The First Line of Defense
4. Restart the instance database manager by issuing a stop database manager (DB2STOP) and start database manager (DB2START). • If the client wants to communicate with the databases in all three instances 1. Update the Database Manager Configuration parameter CLNT_PW_PLUGIN with the client-side user ID/password plug-in (for example, clnt_upw). This is an optional step because the authentication is done on the server. If you have implemented remap user ID capability in the client-side user ID/password plug-in, you must perform this step. 2. Update the Database Manager Configuration parameter CLNT_KRB_PLUGIN with the client-side Kerberos plug-in (for example, krb). 3. Install the client-side plug-ins (clnt_upw, krb, and gss2). In this scenario, we intentionally do not install the gss1 GSS API-based plug-in to simulate real-life situation where the server installed the superset of all GSS API-based plug-ins used by any client. 4. Catalog the database dbase1 (without specifying AUTHENTICATION or specify the authentication as SERVER_ENCRYPT). 5. Catalog the database dbase2 (without specifying AUTHENTICATION or specify the authentication as KERBEROS). 6. Catalog the database dbase3 (without specifying AUTHENTICATION or specify authentication as gssplugin). 7. Issue the statement db2 "connect to dbase1 user <userid> using <password>" ===>. This connection uses SERVER_ENCRYPT; while on the client, it uses clnt_upw (from clnt_pw_plugin), and on the server, it uses server_upw (from srvcon_pw_plugin). 8. Issue the statement db2 "CONNECT TO DBASE2 USER USING " ===>. This connection uses Kerberos; while on the client, it will use krb (from clnt_krb_plugin), and on the server, it will use krb (from srvcon_gssplugin_list). 9. Issue the statement db2 "CONNECT TO DBASE3 USER USING " ====>. This connection uses the gssplugin; on the client, it selects gss2 even though both gss2 and krb are listed. This is because the srvcon_gssplugin_list dictates the preference order. The server will then be notified by the client to use gss2. Therefore, both the client and the server will use gss2. Note that unlike the user ID/password plug-in case, the GSS API-based plug-in needs to have the same name on both client and the server.
Sample Scenarios
91
Scenario 3: Using Kerberos for Authenticating DB2 (Linux/UNIX/Windows) Client in an Environment That Also Has a DB2 for z/OS Client DB2 for z/OS can accept only Kerberos when acting as a server and cannot use Kerberos when acting as a client. In this case, there is no choice but to use two types of authentication for these two types of clients. You can accomplish this by using the KRB_SERVER_ENCYRPT authentication type for the z/OS client to enable SERVER_ENCRYPT authentication. The DB2 (Linux/UNIX/Windows) client will use Kerberos for authentication. If you would like to centralize the entire user set connecting from DB2 z/OS clients in a single location, using the LDAP server-side auth plug-in is a viable solution. One issue here is that the RACF ticket (Z/Series authentication credential) sent by DB2 z/OS must be customized to a short string per the DB2 (Linux/UNIX/Windows) password requirements. • DB2 for z/OS client c1 1. Make sure the client is set up to use encrypted user ID and encrypted password for authentication with the server. • DB2 (Linux/UNIX/Windows) client c2 1. Install the client-side Kerberos-based plug-in (for example, krb) in the client plug-in directory. 2. Catalog the database specifying the authentication options with the authentication type Kerberos. In this scenario, a hybrid authentication type is used at the database server, so you must catalog the database with the authentication Kerberos; otherwise, it will default to use SERVER_ENCRYPT on the initial DRDA flow if you specified a user ID and password on the connect statement. See the section “Authentication Type Negotiation Between the Client and Server” for more details. • DB2 (Linux/UNIX/Windows) server 1. Install the server-side Kerberos based plug-in (for example, krb) in the server plugin directory. 2. Install the IBM-shipped or customized server-side LDAP-based plug-in (for example, ldap_server) in the server plug-in directory. 3. Update the Database Manager Configuration parameter SRVCON_GSSPLUGIN_LIST with the name of the server-side Kerberos-based plug-in. 4. Update the Database Manager Configuration parameter SRVCON_PW_PLUGIN with the name of the server-side LDAP-based plug-in. 5. Update the Database Manager Configuration parameter SRVCON_AUTH to KRB_SERVER_ENCRYPT. 6. Restart the instance database manager by issuing a stop database manager (DB2STOP) and start database manager (DB2START).
92
Chapter 3 • Understanding Identification and Authentication—The First Line of Defense
SECURITY PLUG-IN DEPLOYMENT LIMITATIONS Some limitations apply when it comes to plug-ins. Although these change from release to release, the ones that a DBA might encounter in Version 9 are as follows: • The admin server (DAS) is not plug-in enabled. So, any action through the Control Center (or any other DB2 GUI tool) that occurs through the admin server (rather than over a database connection) prompts for a user ID and password that will be validated against the local operating system, /etc/passwd on UNIX). Unfortunately, when the Control Center prompts for a user ID and password, it is not clear whether it will be used for a database connection or to connect to the admin server, and it is often hard to predict which one will be used based on the action performed. • The Java client (JCC) does not support customized user ID/password-based security plug-ins for authentication or customized group lookup security plug-ins. • Other DB2 products such as DB2 on Z/Series®, I/Series®, or VM/VSE® do not support any form of security plug-ins. They also do not support the GSS API plug-in authentication methods except Kerberos. Note that DB2 on Z/Series does not support the Kerberos authentication type as a client. • Q replication does not work with security plug-ins. • If the initial credentials for the GSS API plug-in are expired, DB2 will not automatically renew them. • In a multi-tier situation, a client may connect to a server that, in turn, needs to connect a back-end server. To gain access to the back-end database server, either the client must obtain credentials to access the back-end database server and then pass them on to the intermediate server, or else the intermediate server must obtain the credentials to access the end server itself. Preferably, the credentials should be obtained using the client’s authority. This is known as credential delegation. Currently, DB2 does not support this.
LAST WORDS Think of authentication as the first soldier in the battle of DB2 database defense. Implementing a good authentication mechanism on your database system can prevent any unwanted or unauthorized access on the spot. Users must also play a big role here. No matter what authentication method you use, there is always additional authentication information (such as password) that the user must have. If the user fails to safeguard this authentication information, authentication will fail to fulfill its mission as a preventive control.
CHAPTER
4
Securing DB2 on Windows
it is confession time. How many of you DBAs out there spent hours playing Solitaire O kay, on Windows 3.1?
FIRST WORDS DB2 9 on Windows has come to the forefront as a robust solution for organizations standardizing on the Windows platform. As deployments on Windows platforms continue to increase, DB2 DBAs can expect to be asked to support these environments. If you are a UNIX or Linux DBA, the good news is that the majority of the code base for the DB2 product is primarily the same for Linux, UNIX, and Windows platforms, but there are some significant security differences based on operating systems. In a Windows environment, there may be considerable differences in the division of responsibilities between the DBA and systems administrator as compared to other operating system/DB2 combinations. It is more often the case that the Windows DBA will also be the Windows system administrator, and, therefore, the security burden, instead of being split between two distinct groups responsible for the day-to-day corporate infrastructure tasks, potentially, will be held by one group or even, in very small shops, one individual. This means that the DB2 Windows DBA holds an increasing responsibility for security for both the corporate database and the operating system where it lives. Such a nondivision of labor increases the potential for the subtleties of security to be overlooked. The Windows DB2 DBA should be encouraged to cross-train in administering a Windows operating system whether she will be functioning as a Windows system administrator or not. Windows
93
94
Chapter 4 • Securing DB2 on Windows
operating systems employ unique security features and introduce equally unique issues for the DBA tasked with protecting the DB2 databases. No matter what your platform preference, due diligence in setting up DB2 is required, so the additional training expenses can be cost-effective if the return on the investment is a stronger security implementation.
SCOPE OF THIS CHAPTER Windows installations of DB2 produce a database environment that is tightly entwined with the operating system. Making your Windows environment as secure as possible (hardening the operating system) provides increased security for the DB2 database environment. Conversely, failing to secure your Windows environment may make your DB2 database environment an attractive target. At the time this book was being written, the primary Windows operating system products in use for DB2 installations were Windows XP, Windows 2000, and Windows Server 2003. The comments and recommendations in this chapter refer primarily to DB2 9 installations on those product levels, but many topics will also be useful if the Windows operating system environment is a precursor or a successor to those levels. Much of this chapter deals heavily with the installation and initial setup of DB2 on Windows because the best place to start is at the beginning. If your environment is already instantiated, it is equally important to review the items documented and explained in the “installation” information to determine whether security improvements to your environment can be made post-install. The majority of the security items covered regarding installation can still be implemented even if the product has been installed for some time. Of course, when there is no luxury of performing a “clean” install, due diligence is an absolute requirement. When changing parameters and settings on a live system, the normal testing and quality-assurance steps cannot be avoided, and a lot of time and effort may be invested prior to making any change. Although this might make the task of post-configuring a DB2/Windows environment to incorporate security measures more challenging, it also makes it more important because the longer the exposure, the higher the likelihood of an incident. If your role is that of a DBA, you may or may not have the expertise to harden your Windows operating system environment, but you will be expected to have the DB2 9 product and all databases configured securely. This book can provide you with the DB2 pieces that are important as they relate to the Windows operating system environment, but it is important to understand that the implementation of security should be collaboration between the DBAs who know the database environment and personnel who understand the Windows operating system security measures. If you are “lucky” enough to be “both” of those people, you will need further study beyond the information provided here to hack-proof your operating system.
First Steps: Build in DB2 Security During Installation
95
Finally, although this chapter does deal specifically with topics exclusive to DB2 9 Windows environments, it does not redundantly cover topics already covered elsewhere in this book, so it is recommended that you review the content of the other chapters, too.
FIRST STEPS: BUILD IN DB2 SECURITY DURING INSTALLATION Heroes Welcomed Here If your manager asked you for a cost/benefit analysis on retrofitting DB2 security on Windows after the install versus installing DB2 with security in mind, which option would be most likely to appear cost-effective? Considering the extra work involved to test and certify the changes on a “working” system, if it is possible to build security at the install level, there will be an associated cost savings. Every manager out there likes to hear the term cost savings; so, if you want to be a hero, building security in from the start is the logical choice.
Documentation Is Necessary Prior to beginning the DB2 9 installation process, it is a good idea to document the planned approach. A step-by-step installation document can be used during the install to verify that important security steps were not forgotten in the haste to get the environment up and running. An added benefit from documenting the installation is that the DBA can refer to this document each time a patch or Fixpack is needed, review it in light of any new security recommendations, and use it as a foundation for subsequent DB2 installs. Surprisingly, not every DBA documents the installation process. It is understandable that for technically oriented individuals, writing documentation is not the fun part of the job. Fun or not, when it comes to security, it is wise to be able to answer the “how did you do it?” questions that inevitably arise when there is any indication that something is not working as planned, especially if you are playing the dual role of DBA and Windows administrator. One of the first lessons learned when on the receiving side of a security audit is that documentation from “the beginning of time” (or at least the beginning of the environment) until the moment of the audit is critical. Obviously, the documented installation information must be kept confidential and needs to be protected in the same manner you protect the company’s security policies (see Chapter 2, “DB2 Security—The Starting Point”). For any DB2 installation on a Windows platform, it is a good idea to document (at a minimum) the following: • All changes done to harden the Windows operating system prior to install • Windows operating system (and Service Patch) levels • Date of the installation • Name of the person(s) doing the installation
96
Chapter 4 • Securing DB2 on Windows
• Media used (for example, E.S.E. CD v 9.0 for Windows 32 bit) • Instance name/ID • User IDs/groups for the SYSADM, SYSMAINT, SYSCTRL, and SYSMON groups • ID used to do the install • Fenced ID • DAS (DB2 Administration Server) ID • A copy of the response file, if used • Documentation of all post-install changes to configuration values • Documentation of any post-install permission changes to files, accounts, groups, or DB2 directories
Thinking “Security”—Planning the Windows Install When planning the installation of DB2 on a Windows environment, it is important to consider security before beginning any actual setup work. A new, “clean plate” installation of DB2 provides an opportunity to build in security from the start, while retrofitting security into a Windows environment is an ongoing concern. First, consider the ID that will be used for the installation. The requirements for the installation ID are that the ID is either • An administrator via security access • An administrator ID on the local system • An administrator ID on the domain There are some differences in the way the DB2 install process defines default users and groups depending on whether the install is on Windows (versus UNIX environments). On Windows, the default ID, db2admin, is used for the DAS (DB2 Administration Server), the instance owner and the fenced owner. The db2admin ID is a well-known user ID; so if the defaults were not changed during the installation, this user ID should be changed immediately after the install. Fortunately, using only one shared ID for the instance owner, fenced owner, and DAS is not a requirement. The more robust approach is to use three different user IDs: one for the instance ID, one for the fenced ID, and a third for the DAS ID for the installation. This adds a layer of security depth for these high-level accounts. Although possible, the use of the Windows Control Panel for changing the DAS user ID after the installation is not recommended unless you know and are familiar with the changes necessary to
First Steps: Build in DB2 Security During Installation
97
implement the access rights that will need to be reset after the change. Instead, the recommended approach for changing the user ID/password is to log on to the Windows machine using an account that has local administrator authority. Change the ID and password using the db2admin command syntax as follows: db2admin setid <userid> <password>
The user ID and password must match an existing user account holding local administrator authority; otherwise, an error is returned indicating that SQL4412N The logon user account for the DB2 Administration Server is invalid. A successful change will return SQL4402W The DB2ADMIN command was successful. One additional security consideration with the DAS is that by default it supports “search” (remote discovery) requests from clients. Although this provides an aid for communication setup, it also opens a security concern. A more secure way to enable communication pathways is to use a “cataloging” approach, either by commands or by tools such as the Configuration Assistant. Changing the DAS DISCOVER default of SEARCH to DISABLE after the installation of the product is recommended: db2 update admin cfg using discover disable
Response File A feature that provides an alternative method of installation (via a “response file”) can also provide enhanced security. Although the use of a response file is not exclusive to the Windows platform, in practicality its use is more prevalent on Windows installations. The DB2 response file is an editable text file that “feeds” the parameter values to the product during the installation. The response file requires specific ids for users and groups and does not use the defaults automatically. Editing the response file (or generating one) to supply the most secure options for the parameter values ensures that the DB2 9 installation process begins with a strong security base. If you decide to use response files, you have three options: 1. Use the DB2 Setup Wizard GUI and choose the Custom installation option. When prompted to Select the installation action, click the check box to Save your settings in a response file. You will be prompted to choose a name for the file and provide a path. As part of the installation process, the DB2 Setup Wizard saves the response file based on the parameters chosen during the DB2 setup process. (See Figure 4.1a, 4.1b, and 4.1c.)
98
Figure 4.1a
Figure 4.1b
Chapter 4 • Securing DB2 on Windows
First Steps: Build in DB2 Security During Installation
Figure 4.1c
99
Saving the response file using the Setup Wizard
2. Use the Response File Generator. The Response File Generator utility is available only on Windows platforms. You can invoke it from the command line, and it has both optional and required parameters. Table 4.1 lists the options. db2rspgn –d z:\path -i –noctlsrv -nodlfm
Table 4.1
Flags for the db2rspgn Command
Switch
Required or Option
Definition
-d
Required
Indicates where the response file (and any instances files) will be written.
-i
Optional
This parameter can be used to specify specific instance(s). If not specified, all instances are included.
-noctlsrv
Optional
If specified, the control server instance profile will not be generated.
-nodlfm
Optional
When using data links, this parameter can optionally be set to avoid generating an instance profile for the Data Links File Manager instance.
When generated, you can modify the file as appropriate. At a minimum, you should modify the file indicating acceptance with the license agreement.
100
Chapter 4 • Securing DB2 on Windows
3. Modify the sample response file. The sample response files are text files and can be found on the installation CD in the \db2\windows\samples directory. All DB2 response files end with the .rsp extension, but the naming convention changes depending on the product being installed. Some of the product examples are db2ese.rsp (Enterprise Server Edition), db2wse. rsp (Workgroup Server Edition), db2exp.rsp (Express Edition), and db2pe.rsp (Personal Edition). The response file can be opened and edited using any text editor product such as Notepad. Initially, many of the lines are commented out with an asterisk (*). Editing the file and removing the leading asterisk for a specific line enables that parameter to be read during a response file installation. An Excerpt from a Sample Response File * General Options * ---------------PROD = ENTERPRISE_SERVER_EDITION INSTALL_OPTION = SINGLE_PARTITION LIC_AGREEMENT = DECLINE **You must change this to ACCEPT to indicate your acceptance of the license agreement before continuing. *FILE = C:\Program Files\IBM\SQLLIB *INSTALL_TYPE = TYPICAL, COMPACT, or CUSTOM **Default=TYPICAL . . . . * Select Language *----------------*LANG = DE ** German *LANG = DK ** Danish *LANG = FI ** Finnish *LANG = FR ** French *LANG = EN ** English . . . * Select Features (CUSTOM install option only) *----------------------------------------------*COMP = APPLICATION_DEVELOPMENT_TOOLS *COMP = IBM_JRE *COMP = IBM_JDK *COMP = LDAP_EXPLOITATION *COMP = CLIENT_TOOLS *COMP = DB2_WEB_TOOLS . . . *COMP = TCPIP_DB2_CLIENT_SUPPORT *COMP = TCPIP_DB2_LISTENER_SUPPORT * General information for instance to be created * ----------------------------------------------INSTANCE = DB2 DEFAULT_INSTANCE = DB2 DB2.NAME = DB2
First Steps: Build in DB2 Security During Installation
ESE, WSE, CLIENT, STANDALONE or SATELLITE 60000 4 YES or NO
* Default Instance Logon Settings
* ------------------------------*Enter the user name and password that will be used to administer the DB2 instance. *char(30) represents a word with a maximum of 30 characters. DB2.USERNAME = char(30) [char(20) for Windows NT] *DB2.DOMAIN = char(14) DB2.PASSWORD = char(14) *======================================================================= *The remaining settings in this response file are optional. ...
Response files use an asterisk (*) for comments. Remove the line’s leading asterisk to enable that option for installation.
Although numerous parameters are available for change within the response file, when it comes to security, the philosophy that less is more should be considered for the options actually installed for DB2. For example, do not install more language options than are needed to meet the company’s business need. Likewise, you would not want to switch every DB2 Profile Registry option on just to make sure everything was covered. The response file gives you an opportunity to plan and review each install option to be sure that your installation makes sense from both the application and security standpoints. Each product has its own sample response file, so it is best to match the sample response file to the product base being planned. If you prefer, you can create your own response file by using any text editor. When building the text file from scratch, remember that any items that are necessary for the install, but not included, will be set to defaults. Although sample product response files, on first glance, appear similar, the parameters listed in each are tailored to the product being installed. The examples in this chapter refer to the Enterprise Server Edition, Single Partition installation, and the install is presumed to be on a Windows platform. Security Parameters in the Response File Although not all response file items relate to security, working through a sample response file affords the opportunity to review available options and decide whether they pose a security issue for your environment. Even if you are installing using another method, reviewing the sample response file is an aid to understanding the wealth of configuration options available during a DB2 installation and how DB2 “plays” in your environment.
102
Chapter 4 • Securing DB2 on Windows
One particular advantage to generating the response file using either the Setup Wizard or the Response File Generator is that the resulting file will contain encrypted passwords, as shown in Figure 4.2.
Although there are numerous items in the response file to consider, review the following, in particular, with security in mind. Response File Parameters DBM (Instance)-Level Parameters • DB2.AUTHENTICATION Authentication plays such a critical role in securing your DB2 environment that it is explained in detail in Chapter 5, “Authorization—Authority and Privileges.” It is important to understand the various configuration options for authentication and how to implement them in a manner that is most secure for the specific architecture being deployed. This is not the time to just trust that the default is “good enough.” It is important to delve into this topic until a complete understanding is obtained. • DB2.CATALOG_NOAUTH Consider leaving this parameter disabled by keeping the default value (No). When enabled, this would allow users who do not hold SYSADM, SYSCTRL, or SYSMAINT authority to catalog an instance, database, or an ODBC connection. Although allowing users to catalog connectivity in a development environment may be acceptable, it is risky to do so in a production environment. • DB2.DISCOVER This parameter makes it easier for developers and users to catalog communication to the database. In other words, communication pathways to the database can be determined if this parameter is enabled. To prevent a client from “discovering” the database on local and remote networks, change this parameter from its default of SEARCH to DISABLE. It is best to catalog specific connection information rather than allow clients to use discovery options. For a production environment, you should disable this option.
First Steps: Build in DB2 Security During Installation
103
• DB2.DISCOVER_INST Similar to the previous DISCOVER option, this is an instance discovery option that is set to ENABLE by default. Changing this value to DISABLE will prevent unwanted detection of the instance. In production, you should disable this option. • DB2.TRUST_ALLCLNTS and DB2.TRUST_CLNTAUTH If the DBM AUTHENTICATION parameter is set to CLIENT, TRUST_ALLCLNTS and TRUST_CLNTAUTH are used in combination to determine where user connections are authorized. If the DBM AUTHENTICATION parameter is set to any value other than CLIENT, these two parameters are not used. The distinction is important. If AUTHENTICATION is set to CLIENT, TRUST_CLNTAUTH is set to CLIENT, and TRUST_ALLCLNTS is set to YES, for example, all trusted clients are considered to have been previously authenticated, and no user ID/password is needed and no extra verification is performed. A trusted client is assumed to be coming from an operating system that has the mechanisms in place to validate security credentials. An example of an operating system that is not considered to have this capability is Windows 98. The TRUST_ALLCLNTS parameter is commonly used for DRDA connections from DB2 for z/OS. If you set this parameter to DRDAONLY, all clients that do not connect from one of these DRDA connections are required to supply a user ID/password combination for authentication. Note that neither of these parameters is changeable from the defaults unless AUTHENTICATION has first been set to CLIENT. If you attempt to modify these settings in the response file and have not set AUTHENTICATION to CLIENT, you will receive the following message: SQL5154N The requested combination of configuration values for "authentication" and "trust_clntauth" is not allowed. Reason code = "1".
From a security standpoint, configuring AUTHENTICATION to CLIENT is strongly discouraged because this setting allows connections without requiring a user ID and password. • DB2.SYSADM_GROUP, DB2.SYSCTRL_GROUP, DB2.SYSMAINT_GROUP To provide the finest granularity of access for privileged system accounts, these three groups should be set up independently from each other. In the response file, assign a group name value to each of these groups so that groups for each will be created. After the install, use these groups to add user IDs based on specific, well-defined job roles. Users belonging to these groups hold high-level authorities on the database environment (as discussed in detail in Chapter 5).
104
Chapter 4 • Securing DB2 on Windows
Creating DB2 Privileged Groups Using the Response File DB2.SYSADM_GROUP DB2.SYSCTRL_GROUP DB2.SYSMAINT_GROUP
= IPASAGRP = IPBSCGRP = IPCSMGRP
Instance DB2 Registry Variables • DB2.DB2COMM Possible values for this communications parameter are TCPIP, APPC, NETBIOS, NPIPE, or blank. It is best to enable only those communication protocols that are actually needed by the application to prevent unnecessary exposure. If only TCP/IP is needed, it should be the only protocol enabled. Extended Security Parameters • DB2_EXTSECURITY This DB2 Profile Registry variable is available only for Windows environments. This feature installs by default unless its response file setting is changed to No. When enabled, an additional layer of protection deploys, locking down DB2 system files and preventing unauthorized access to DB2. (See Figure 4-3 for more on this topic.) • DB2_ADMINGROUP_NAME The response file default for this value is DB2ADMNS. This value is changeable. When specifying a name other than the default, if the group name does not exist, the installation creates it. If specifying a group name that already exists, the security policies for that group may be modified to comply with DB2 requirements for the group, thus potentially elevating privileges for users of the existing group. Any user who belongs to this group (and any local administrator account) has full control of the database. User IDs for DBAs and others that need full access should be added to this group after the install. • DB2_USERSGROUP_NAME This value defaults to DB2USERS if not defined. This value can be changed to indicate a different name for the DB2 Users group. Users that are assigned to this group generally have write and execute privileges on the databases. The install does not add users to this group; therefore, they must be added post install and prior to successful database access. Now that your customized response file is generated, consider how you are going to secure it. Just like every piece of information that could aid a hacker, the configured response file must be protected according to the security policy.
Designed Especially for Windows
105
DESIGNED ESPECIALLY FOR WINDOWS DB2 provides specific features to take advantage of the inherent operating system security structures in Windows environments.
Windows Domain\User DB2 supports two-part user IDs for Windows logins for both “connect” (to the database) and “attach” (to the instance) attempts. By the use of domain\user functionality, there is no need for a broadcast to all domain servers to authenticate the user on the Windows system. This provides a security benefit, too, because it adds a layer of complexity to a user login and might aid in preventing denial-of-service attacks.
Installation User ID The user ID chosen to perform the install of DB2 will not have native ability to run any DB2 commands unless the ID is either that of a local administrator or has been added to the DB2USERS or DB2ADMNS groups. The installation process can be used to create the DB2USERS and DB2ADMNS groups, but the installation user ID is denied privileges within the DB2 environment unless the user ID is specifically added to one or both of these groups (or is a local administrator). This “hands-off” approach between the installation user ID and the database environment adds depth to security. Unless there is a strong specific reason to do so, it is better to keep this user ID as an independent “install only” account. After the install, this ID should be moved from the Windows Administrator group to a less-privileged group such as Power Users. DB2_EXTSECURITY
Unless specifically deselected during an installation of DB2 9 on a Windows platform, extra operating system–based security features are enabled that modify the access control lists, Windows registry entries, and some runtime memory settings. These changes add depth to the security of the DB2 installation on Windows and restrict the rights that normal users have when accessing DB2 resources. With this functionality, DB2 builds a Windows registry key, DB2_EXTSECURITY, which sets a flag that determines whether DB2 runtime code security checks should be performed. This functionality applies only to normal users and not DBA or system administrator users. When enabled, the Windows registry variable DB2_EXTSECURITY will be set to Yes. When DB2_EXTSECURITY is enabled, access to DB2 specific Windows Services, DB2’s System Files, DB2 Window’s registry keys, and network shares are tightly controlled on the local Windows machine running DB2. Only users who belong to DB2ADMINS or DB2USERS groups or local administrators have access (see Figure 4.3).
106
Chapter 4 • Securing DB2 on Windows
Figure 4.3
The DB2_EXTSECURITY Windows registry setting
In addition to the option to enable this functionality during an install, the DB2_EXTSECURITY security features can be enabled via execution of the db2extsec.exe command. The executable is shipped with the product and is stored in the $installpath/SQLLIB/bin directory. This command, when run by a user ID with SYSADM authority, provides the same changes that are invoked when using the Setup Wizard in Typical mode and keeping the default for the Enable Operating System Security check box. The command can take three parameters: • /u (usergroup) • /a (admin group) • /r (reverse) db2extsec.exe /u DB2USERS /a DB2ADMNS
If you do enable these features via the db2extsec.exe command and later decide to back out the changes, the options to do so vary depending on whether other changes have been made since the db2extsec.exe command was run. 1. Prior to making any further changes, run the db2extsec.exe command again with the –r (reverse) option: db2extsec.exe -r
2. Alternatively, add the Windows Authenticated Users group to both the DB2ADMNS and DB2USERS group.
THE WINDOWS OPERATING SYSTEM—THE IMPORTANT STUFF You might be asking why this topic is included here. After all, items such as Windows accounts, services settings, and the Windows registry are part of the operating system, not part of DB2. Unfortunately, anyone who is interested in gaining inappropriate access to the databases housed in the Windows environment probably does not share this vision of a demarcation line between the
The Windows Operating System—The Important Stuff
107
two products. DB2 and Windows are separate only until the point DB2 is installed on Windows. Then, the two products develop a dependency on each other, or more specifically, DB2 develops a dependency on Windows to do its part in a fully functional robust security implementation. Going over the entire Windows Security Model would require another book. If you are familiar with this topic at all, you have an advantage over many DBAs. However, you do not have to personally understand every nuance of the Windows Security Model to securely implement DB2. Although it is a good idea to have access to an expert, you do not necessarily have to be one yourself. What you do need is enough information to understand the pieces that interact with DB2 and how they impact security for the database environment. If you want your database to be secure, in addition to all the DB2 security features you need to consider, you need to make sure Windows is hardened to the fullest extent possible. This is where the expertise of a knowledgeable Windows system administrator is invaluable. If you do not have a Windows system administrator, of if you are the Windows system administrator, this section presents a minimal overview of the items you need to check.
Review Windows Account Policy Settings Review the account policy settings for Windows security for appropriateness. You can find these accounts in the Windows Control Panel under Administrative Tools. • Passwords must meet complexity requirements. This setting should be changed from the default to require the use of complex passwords. When set to require complex passwords, all new or changed passwords are required to meet the following standards: Not be or contain the user’s account name Contain a mix of characters from at least three of these groups: Digits (0–9) Lowercase characters (English) Uppercase characters (English) Symbols (such as &, $, #,) Length of at least six characters Because most of today’s password-cracking programs can exhaust a six-characterlength passwords in minutes, often seconds, it is generally encouraged that an eightcharacter minimum should be set. • Enforce password history. To prevent reuse of the same passwords repeatedly, consider changing the default of 1 to a value of up to 24.
108
Chapter 4 • Securing DB2 on Windows
• Minimum password age. Consider setting this value to a minimum of two days. The goal is to prevent a situation where a user simply runs a script to set enough passwords in the history series to reach a point where an old password can be used again quickly. • Maximum password age. To enforce frequent changes of passwords, consider changing the maximum password age to 30 days (see Figure 4.4).
Figure 4.4
Changing the maximum password age
Lock Down and Protect Windows Accounts To protect from unwanted access to the Windows machine, review and mitigate the following items: • Default Administrator Account The Windows “Administrator” account is very well known and should be considered at risk. One way to thwart this vulnerability is to rename the existing Administrator account. To add an extra layer of protection, after renaming the original Administrator account, consider creating a safety net by re-creating the named Administrator account
The Windows Operating System—The Important Stuff
109
with no privileges or rights assigned to the ID. This “decoy” Administrator account can prove useful when auditing for suspicious logins or discovering users attempting to upgrade their privileges. • Account Lockout Duration and Threshold The Account Lockout Duration and the Account Lockout Threshold settings work together to lock an account experiencing a frequent number of incorrect password attempts. For example, setting an Account Lockout Threshold of 3 and an Account Lockout Duration of 30 minutes means that after 3 login attempts using an incorrect password, the account in question will be locked for 30 minutes. A consideration should be made as to whether setting values for these parameters would open the enterprise to a denial-of-service attack because a massive influx of logons with an incorrect password would effectively lock out service for any accounts that were “hit’ for the length of time specified by the Account Lockout Duration. • Guest Accounts It is a good idea to verify that Guest accounts are, in fact, disabled even though that is the default. To be extra cautious, assign a strong password to the default Guest account, too (see Figure 4.5).
Figure 4.5
Verify that the Guest account is disabled
110
Chapter 4 • Securing DB2 on Windows
Lock Down Unneeded Features for the Windows Registry Locking down the Windows registry is typically something that should be attempted only by a knowledgeable Windows system administrator because mistakes can have serious implications to the health and well being of the machine and, therefore, the database. However, to the extent possible, the Windows registry for the machine housing the DB2 database environment should be protected from unwanted access. When thinking about the Windows registry, items that may impact security should be reviewed to see whether hardening their access is possible. Here are some examples of items to check: • Remote registry access. Although this parameter does drive Windows registry behavior, it is actually controlled as a Windows service. The Remote Registry service makes the Windows registry available to other users on the network. Consider stopping and then manually controlling this service via the Windows Control Panel, Administrative Tools, and Services screen. Doing so will prohibit changes to the registry unless the user is logged on to the machine locally. If remote registry access is not needed at all in your environment, consider disabling this service. Note that if this service is disabled, any services that depend on the Remote Registry service will fail to start at next reboot, so caution is advised if making this change (see Figure 4.6).
Figure 4.6
Windows Remote Registry service
The Windows Operating System—The Important Stuff
111
• Review Windows registry keys. Another way to control which users are allowed remote access to the Windows registry is to change the registry itself. Again, caution is encouraged if this is the approach planned. The registry key HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\ SecurePipeServers\winreg can be modified to include only those groups or users who should have this access. Users and groups can also be added to specifically deny access. To access the permissions, find the key in the Windows registry, right-click, and choose Permissions (see Figure 4.7).
Figure 4.7
Changing the Windows registry WINREG permissions
112
Chapter 4 • Securing DB2 on Windows
• Review Windows/DB2 registry keys. Not all users require access to the DB2 Windows registry keys. Review the following keys and consider restricting the keys to Windows Administrators, SYSTEM, and DBA accounts where appropriate. HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\DB2
Windows Active Directory You can think of the Windows Active Directory as a type of logical phone book that stores information about system users. It provides a centralized location for the users and computer settings for the organization and allows Windows administrators to centralize policy implementation across the enterprise. Although not a requirement, DB2 can be used in conjunction with the Windows Active Directory, and the database instances and directories can be incorporated via configuration settings. This means that when you are using Active Directory, cataloging the instances and databases on client machines on the network is not required. Moving databases between servers is also easier to support because only the database directory at the Active Directory machine needs to be changed, and the changes will then be replicated across the other servers in the domain. In large environments, the features provided by Windows Active Directory can provide ease of administration for DB2, which makes its use attractive. When Windows Active Directory is enabled, DB2 objects are registered under the Computer container. To perform the registration, the user ID has to have privileges that can be conferred by membership in any of the Administrators, Domain Administrators, or Enterprise Administrators groups. Once registered, by default these objects are updatable by Administrators and readable by any authenticated user. Allowing any authenticated user to read the object information allows anyone to see information that would provide insight into where the instances and database “live.” To mitigate the security concerns, change the default permissions so that only selected, necessary user groups have permissions to read this information. You can do this by using the Active Directory Management Console (Microsoft Management Console).
The Local System Account (LSA) The LSA provides an “elevated privilege” account that does not need a password. On the surface, this sounds like a benefit because password maintenance is not required. The LSA account holds unlimited access, so there will be no tasks that cannot be accomplished with it. If your perspective is “ease of administration,” the LSA provides that ease. If your perspective is security, the LSA should not be used for DB2.
Other Considerations
113
Although DB2 can take advantage of the ease-of-use features of the Windows LSA for Windows services, or even for the DB2 install itself, obviously there are security concerns. Because the LSA is not required for the install or any DB2 services, instead consider using a domain name/user ID combination created explicitly for this purpose. If installing DB2 on a server that is not a domain controller, you can also use the domain name\user ID for the install or use a local user ID to avoid using the LSA. When creating an install account, verify that the account belongs to the Windows Administrator group and assign a strong password and advanced user rights for the following: • Act as part of the operating system • Debug programs • Log in as a service • Create a token object • Increase quotas • Lock pages in memory • Replace a process level token Because the install ID was created solely for the purpose of installing DB2, when the install is completed, the install ID can be removed from the Administrators group. Consider keeping the ID available for use with further Fixpack installs and move it back into the Administrators group only during those times when it is explicitly needed.
OTHER CONSIDERATIONS Physical Security for Windows Servers This topic is easy to overlook, and although it is not exclusively a concern for only Windows environments, the author’s experience indicates that Windows servers are more frequently left out of physical security planning and implementation. Although it is true that DBAs and system administrators do not often have responsibilities for physical security, they certainly pay the price if physical security leads to a breach. Regardless of who in the organization claims the physical security domain, it is important that someone does. Items to consider include the following: • Server rooms Access controls Console placement and protection Backup power supplies
114
Chapter 4 • Securing DB2 on Windows
Backup communication methods Security lighting with redundancy Guards or guarding mechanisms Alarms for intrusion detection, fire, power loss, and so on Protection against shoulder surfing Video of critical areas • Storage Lockable cabinets Document storage for sensitive written information Accessible by authorized individuals Backups in a central location and secured from being removed without permission
FIXPACKS, SERVICE PACKS, PATCHES—USE ’EM OR LOSE You have finally completed setting up the environment. All the security pieces have been reviewed, and you are satisfied that you have done your best to mitigate any security concerns. What’s next? Security should be thought of as a never-ending skirmish. As soon as you win one, start girding for battle for the next. Your Windows arsenal includes Windows service packs and patches and DB2 Fixpacks. As soon as a vulnerability is discovered, application vendors and hackers start working on it. The application vendors are rushing to mitigate the concern; the hackers are rushing to concern those who mitigate. Who will win? If history is any indicator, the application vendors will beat the hackers. They will release a patch before many (or in most cases, any) breaches occur. Sadly, however (and herein is the real issue), not every company will take advantage of the fix, so the hackers might win some because an available update was not installed, leaving the system to be compromised.
The Dilemma If you have done your homework and kept your documentation current, you have your initial install documents. Having done one install makes it easier to do the next. A DB2 Fixpack is just an install, so why not just go ahead and apply Fixpacks as they become available? Microsoft® also makes it easy to keep current fixes applied. They offer an automatic update service for Windows systems, and these can be silently pushed to the organization’s Windows machines without significant resources.
Last Words
115
So, what’s the dilemma? In an-ongoing concern, “slamming” in changes is usually not encouraged. Testing and a quality-assurance effort are obviously required. That is why being proactive is absolutely critical if you want your organization to continue to maintain its security edge. Building “security in” means nothing if you stop there. All the hard work, all the reviews, all the documentation, all the plans, all the policies go by the wayside if the necessary patches are not applied. For any application that interacts with the Windows operating system, this is especially true. As one of the more heavily used operating system products, it also attracts a lot of interest from the hacker community. Hackers have been at it long enough to feel “at home” on the Windows system. Like dealing with unwelcome guests, it is your goal to make them increasingly uncomfortable until they decide to more on to more-hospitable grounds. To lessen their comfort level, keep current on updates, patches, and Fixpacks.
LAST WORDS Although the information in this chapter relates to implementations of DB2 9 on Window machines, it does not encompass material covered elsewhere in this book, so reading the remaining chapters is encouraged. Security for DB2 9 in any environment should be considered from the moment the project is visualized. Building “security in” from the launch of the project provides a secure foundation, allowing the layering of security depth going forward. When you are following this approach, upfront analysis, planning, and documentation should precede any actual physical setup work. The DB2 response file provides robust information about the specific parameters that you can customize for the DB2 9 install. Regardless of the installation method, reviewing the DB2 response file with a focus on security is recommended. The parameters in this file can spur knowledge transfer, trigger thoughts on a security approach, and can provide a background for detailed discussions about how best to implement or retrofit security. The file can also serve as foundational documentation for the environment because it can include comments. A configured response must be protected in the same manner you would use to protect any security document that could provide a hacker with sensitive information. Given the symbiotic interaction between DB2 9 and the Windows operating system, a Windows system administrator should be consulted early in the analysis phase for insight and recommendations for hardening the Windows environment prior to installing the DB2 product base. If this is not possible and the DBA has to do these tasks, prior training regarding the Windows operating system is highly recommended. During the install, DB2 9/Windows-specific security features—including response files, db2_extsecurity, support for two-part names, and support for Active Directory—should be
116
Chapter 4 • Securing DB2 on Windows
considered. Windows settings and database environment settings should also be reviewed after the install. After the product has been installed, the process of security becomes an ongoing concern between the DBAs and the Windows system administrators. Review, mitigation, and test cycles should be the norm. Fixpacks, patches, and service packs should be tested and applied as soon as possible after their release as a part of a controlled approach to robust security in depth. Physical security should not be overlooked. Because of the decreasing size of hardware, machines housing highly sensitive information are getting smaller and smaller and may no longer qualify for a full “server room” treatment with controlled access. Without strong physical security controls, all the previous work to secure the database is moot because failure to control physical access is equivalent to turning over the keys to the database.
CHAPTER
5
Authorization—Authority and Privileges
I
have the authority, and it would be my privilege, to authorize your entry into the realm of DB2 security.
FIRST WORDS Remember the house in Chapter 3, “Understanding Identification and Authentication—The First Line of Defense”? We talked about the lock on the front door of the house as the first line of defense, just like authentication is the first line of defense for database security. What if each door inside the house had a lock, too? Locking individual rooms can be considered a second line of defense and is fundamental to a “defense-in-depth” security approach. In this analogy, each room’s lock represents an authorization requirement that determines whether an individual has the right to access a database object. Different tenants (users) have different keys (authority or privilege sets) that confer the right to access certain rooms (sets of data and database objects). This chapter discusses the different options and reviews some security best practices that can help in authority/privilege and object ownership management.
TERMINOLOGY Although the definitions of object owner and authorization ID (auth ID) might seem obvious, in fact, they are a little complicated. As you read through the remaining material in this chapter, you might want to refer to the following definitions to help clarify these terms.
117
118
Chapter 5 • Authorization—Authority and Privileges
Object Owner As you might expect, from a DB2 perspective, the object owner is the authorization ID identified to the system as owning the object. In other words, when any object is created, DB2 must assign an authorization ID as the owner of the newly created object. As such, that authorization ID is required by DB2 to maintain any required privileges for the specific object (if any) and, depending on the type of object, DB2 also provides certain implicit privileges on that object. Although the initial owner of an object is assigned by DB2 based on the authorization ID of the statement that created that object, you can change object ownership at any time by using the TRANSFER OWNERSHIP SQL statement. The consequences of an object owner losing privileges vary depending on the type of SQL object in question. With the exception of routines, if the object owner were to lose privileges required for accessing the underlying object, the SQL object would be dropped or would become inoperative. If the object is a routine, the REVOKE itself would fail with a SQLCODE of -478. To illustrate, authorization ID NEWTON has been granted SELECT privilege on table BOSS.T1. NEWTON then creates a view, NEWTON.V1, which selects from the table BOSS.T1. If the SELECT privilege on the table BOSS.T1 is revoked from NEWTON, the view NEWTON.V1 becomes inoperable (provided the PUBLIC group does not hold the required privilege). If the object is a routine (function, stored procedure, or method), the REVOKE SQL statement fails with SQLCODE of -478. For example, authorization ID NEWTON has been granted EXECUTE privilege on function BOSS.F1, and NEWTON creates a new function, NEWTON.F2, which is sourced from BOSS.F1. If PUBLIC does not hold the EXECUTE privilege on the function BOSS.F1, any attempt to revoke the EXECUTE privilege on function BOSS.F1 from NEWTON is restricted. SQLCODE of -478 will be received, and the REVOKE SQL statement will fail.
Authorization ID In Chapter 3, the difference between user ID and authorization ID (auth ID) was discussed. It is the authorization ID (and not the user ID) that is used for DB2 authorization purposes. The initial authorization ID for a connection is acquired as part of the authentication process and is typically the uppercase version of the user ID (unless customized logic within a customized authentication security plug-in is used). This type of authorization ID is referred to as a user authorization ID and represents a unique individual within DB2. There are also group authorization IDs, which represent a collection of individuals. The actual membership of each group is defined and controlled outside of the database. A list of relevant group auth IDs for any given user auth ID is gathered as part of the authentication process and is typically (unless a customized group plug-in is in use) the uppercase version of each group name associated with the external user ID.
Best Practices
119
The principles of primary authorization ID, secondary authorization ID, system authorization ID, session authorization ID, routine invoker authorization ID, routine definer authorization ID, package authorization ID, and statement ID are detailed in Appendix F, “Glossary for Authorization ID.”
Static SQL Object A static object is a SQL object that was created by an authorized user (initial owner of the object) using data definition language (DDL) or a static SQL statement. These objects are considered static because the required privileges of the object owner are checked on the underlying object only at the time of creation. After that, the object is considered valid as long as the object owner holds the privileges on the underlying object (that is, the privileges are not revoked using a REVOKE statement), and no additional checking is done on the subsequent use of the object.
BEST PRACTICES As with any technology project, someone has undoubtedly “been there, done that.” From a security standpoint, it is a good idea to seek out and emulate these best practices to avoid the pitfalls that others have already discovered. Let’s begin our research into best practices by reviewing some well-known principles of security and discovering how they apply to DB2. Authorization is the main security mechanism within the DB2 database to help you protect your data. When considering database authorization, it is important that you follow the three foundational principles of good security control: • Need to know • Least privilege • Separation of duties Equally important is having clearly defined processes for controlling and reviewing all privileges and authorities. This implies that you will have a thorough set of policies and procedures, as discussed in Chapter 2, “DB2 Security—The Starting Point.”
Need-to-Know One of the first security principles introduced in any security-based curriculum is “need to know.” Just as the name implies, this principle states that an individual should have access only to the data necessary to complete the tasks that fulfill his or her specific job roles within an organization. No extraneous information beyond that absolutely required should be provided. Need-toknow applies a standard of minimal information and, implicitly, minimal risk.
120
Chapter 5 • Authorization—Authority and Privileges
An example of applying the need-to-know principle is accomplished by creating a view to implement read access control for both the rows and columns on the underlying table. The view is created as a need-to-know enforcement, enabling the user to access only the required data rows or data columns. The users do not need to know what the CEO earns, so they will not be able to see that information when they retrieve rows from the view. Creating this type of view is actually quite simple. Using the HR.SALARY_TABLE as an example, you can create a view such as db2 "CREATE VIEW MY_SALARY AS (SELECT SALARY FROM HR.SALARY_TABLE WHERE EMP_NAME = SESSION_USER)"
And grant each employee SELECT privilege on the view: db2 "GRANT SELECT ON HR.MY_SALARY TO KEESA"
As a result, each employee can only retrieve the rows from the view that show his or her own salary information. The user keesa (with a user auth ID KEESA) can see her salary, but cannot see any other employee’s salary.
Least Privilege The security concept of “least privilege” requires that each individual is given (granted) only the most restrictive set of privileges needed for the performance of authorized tasks. This principle complements the need-to-know security privilege and is designed to further reduce risk. Least privilege enforces minimal rights as a “risk-limiting” approach. An example of applying least privilege is granting UPDATE privilege at the individual column level instead of granting the UPDATE privilege on the entire table. To illustrate, consider the JTB.HOURS table. The supervisor is tasked with updating the allowable sick leave time for each employee. To calculate the allowable sick leave, the supervisor needs to be able to read all rows and columns in the JTB.HOURS table but only needs to update one of them. Recognizing the concept of least privilege, the DBA applies restrictive rights, as follows: db2 "GRANT SELECT ON TABLE JTB.HOURS TO KEESA" db2 "GRANT UPDATE(SICK_LEAVE) ON TABLE JTB.HOURS TO KEESA"
Now, the user keesa (with a user auth ID KEESA) can read all the data in the table but can only update the SICK_LEAVE column. Another possible application of least privilege might involve using an alternative dynamic SQL authorization model such as DYNAMICRULES(BIND). In this scenario, only one authorization ID has the privileges required (the package owner). All others can gain privileges only when dynamic SQL is issued from within that particular package. (Of course, they must have EXECUTE privileges on that package.) In other words, if a package is bound with DYNAMICRULES(BIND), any user who has access to the package and runs it “inherits” the privileges associated with the authorization ID that bound the package. The inherited privilege is effective only within the scope of executing the package.
Best Practices
121
Separation of Duties The methodology of “separation of duties” applies a checks-and-balances approach to a secure implementation. The mechanisms of this security principle require that critical tasks be divided among two or more individuals to ensure that one person cannot independently complete tasks that would impose a security risk. Separation of duties among individuals decreases the likelihood of fraud (collusion excepted, of course). There are two types of separation of duties: static and dynamic. Static separation of duties imposes the restriction that one individual cannot have two conflicting job roles. Dynamic separation of duties imposes the restriction (at privilege execution time) by enforcing a policy that one individual cannot perform two conflicting job roles at the same time. You can use customized DB2 security plug-ins to implement dynamic separation of duties by separating each duty into different namespaces. (See Chapter 3 for information on security plugins.) For example, if Joe is a financial statement auditor but can also act as an accountant for a company, we can implement the two namespaces—auditor and accountant—and have the customized security plug-in use two different auth IDs depending on which namespace Joe is connected to. If Joe functions as an accountant for certain tasks, he connects using the Joe\accountant login. For this work, the auth ID JOE_ACCT allows him to act as an accountant, and he should not be able to access auditor-specific information. When Joe needs to perform his duty as an auditor, he connects as Joe\auditor. The auth ID JOE_AUDITOR is now in use, and Joe should be able to access only auditing information granted to the auth ID JOE_AUDITOR.
Processes to Control and Review Periodic review of privileges and object ownership, removal of unnecessary privileges, and appropriate approval for the addition of privileges are vital process flows to ensure that the basic security tenants of need-to-know, least privilege, and separation of duties are enforced and maintained. These principles are foundational for any secure implementation and should follow the written security policies and guidelines of the corporation. One extremely important role is that held by the DBA, who performs the task of allowing database and object access. This process of “granting” access is kin to opening the door to the database guests. As such, it is a key function for process control and review. Limiting the ability to apply database GRANTS to only those “security-knowledgeable” and responsible individuals is important to minimize risk. Obviously, these individuals must be required to follow the security policies and procedures to ensure that appropriate approval has been obtained before they begin the process of granting privileges. Using db2audit (discussed in Chapter 9, “Database Auditing and Intrusion Detection”) to capture SECMAINT events will provide an audit trail that can be reviewed to determine the grantor of any undesired privilege. Using this information (extracted from the db2audit logs) is highly recommended for auditing this type of critical security task because it will provide a layer of accountability and add depth to
122
Chapter 5 • Authorization—Authority and Privileges
your security implementation. The audit trail information can also be invaluable for process review and refinement because it can be used to raise questions such as “Why did our DBA have to GRANT READ on the SYSIBM tables to 30 new users?”
Avoid Granting to Groups For busy DBAs, it is tempting to grant authority and privilege to a group of users via the group authorization ID. This makes authority and privilege management much simpler but may violate the security principles of least privilege and need to know. Because group membership is assigned outside the database (see Chapter 3), assigning privileges and authorities to groups might mean that the DBA who grants to groups has to trust that those groups are properly maintained so that users inherit only the specific authorities they need and nothing more. Without adequate communication and controls, it is possible that a user may be assigned inappropriate or excessive group membership designations and, therefore, excessive privileges.
Due Diligence Authority or privilege should be granted based only on legitimate need-to-know reasons. The minimum required (least) authority or privilege should be granted. Thus, it is important for the DBAs to keep their knowledge current and understand all the available authorities and privileges available in DB2 before beginning the process of granting access. Consider, too, that application developers have conflicting priorities and do not always have security in mind during development. They might use a higher level of authority than required to make the testing and development effort smoother. Thus, it is important for the DBA to review any authority or privileges granted as part of the application installation or configuration to ensure it adheres to the least-privilege principle.
Documentation Made Easy (or at Least Easier) As mentioned in Chapter 2, policies must be put in place to document access controls. As part of this effort, READ and WRITE access for each table should be clearly defined. One method that is easy to implement and useful to facilitate the documentation effort is the COMMENT feature (an SQL construct). When creating comments, remember that the comment that is set will be stored in the DB2 system catalog tables and can be retrieved via appropriate DB2 SYSCAT views. For example, table comments are stored in SYSCAT.TABLES, index comments are stored in SYSCAT.INDEXES, and so on. Subsequent SQL statements can be used to retrieve this information by inspecting the
Best Practices
123
REMARKS column from the associated SYSCAT view. For example, to set a comment for the HR.SALARY_TABLE, issue this command: COMMENT ON HR.SALARY_TABLE IS 'ACCESS POLICY = ACC-1002; last reviewed 09/2006'
Once set, any user who has been granted SELECT on SYSCAT.TABLES can retrieve the comment by issuing this SQL statement: SELECT REMARKS FROM SYSCAT.TABLES WHERE TABSCHEMA = 'HR' AND TABNAME = 'SALARY_TABLE'
Using Schemas for Control and Management of Database Objects When managing a database that is shared by many functional areas/users within the company, it is important to be able to identify “who owns what.” One simple solution is to define a “wall” and develop a set of rules to ensure that whereas each functional area has access to their own objects, they are prevented from getting to objects on the other side of the wall. The DB2 schema can act as this wall. Schemas are database objects that provide the ability to group database objects together while still logically separating them within the same DB2 database. Schemas provide the ability to separately “name qualified” objects within the same database. To reduce the user’s access to only those database objects necessary for performance of their particular job functions, logically grouping the database objects into schemas facilitates the granting of appropriate access. The goal is to build a barrier for each functional area, allowing them to create, drop, and alter SQL objects of their own while logically remaining separate from other users’ objects. The need-to-know principle is observed because users only “know” about their own objects and only have access to their own objects within the schema. Of course, one way to provide this level of separation is to have a database for each user/project, but that would cause a management nightmare. The better alternative is to separate the database objects using different schemas. For example, if a database is used for code management (version control) purposes and there is more than one project occurring simultaneously, using separate schemas can avoid interference. Perhaps, both projects need a table with exactly the same name. It might not make sense from a versioning standpoint to share the table between the two projects. With two separate schemas, however, the two tables can be built, each with the same name, but stored in separate schemas. When appropriate access permissions are granted, each project uses its own independent version of the table. By default, the database-level authority IMPLICIT_SCHEMA is granted to PUBLIC unless the database is created using the RESTRICTIVE option (discussed later in this chapter). As a general rule, IMPLICIT_SCHEMA should be revoked from the PUBLIC group for several reasons because it provides the ability for any user to create a new schema whether the user realizes he or she has
124
Chapter 5 • Authorization—Authority and Privileges
done so. Many DBAs revoke this authority as a matter of course because it makes the task of schema management easier. IMPLICIT_SCHEMA authority can be revoked using the DB2 Control Center or by connecting to the database (to revoke IMPLICIT_SCHEMA, the user must hold DBADM or SYSADM authority) using the command line: db2 "REVOKE IMPLICIT_SCHEMA ON DATABASE FROM PUBLIC"
Obviously, those users who hold DBADM or SYSADM still have the ability to create any schema name that does not yet exist as deemed necessary. Regular users (unless they have been given additional authorities), however, can now create only a schema explicitly or implicitly that matches the authorization ID of the connection session (session authorization ID). For example, user boss (with user auth ID BOSS) cannot successfully issue the command CREATE SCHEMA ZURBIE despite the fact that the schema ZURBIE does not exist. Revoking IMPLICIT_SCHEMA from PUBLIC is a good practice in most database environments. If a schema name other than the one that matches the SESSION auth ID is needed (perhaps the schema name WEBSPHERE is needed, for example), the best approach is to contact the database administrator (DBADM) and security administrator (SECADM) to perform the following steps: 1. The DBADM user issues this: db2 "CREATE SCHEMA WEBSPHERE";
2. The schema WEBSPHERE is created and owned by the DBADM. 3. The SECADM user issues this: db2 "TRANSFER OWNERSHIP PRESERVE PRIVILEGE"
OF
SCHEMA
WEBSPHERE
TO
USER
BOSS
The schema is now owned by the authorization ID BOSS. The new owner, BOSS, can then revoke all the privileges that the DBADM has on the schema WEBSPHERE. (Note that DBADM is a super-privileged user in the database, so this will not stop any DBADM attempts to access any object in the transferred schema. However, this step helps reduce the unnecessary privilege, which is a step closer to the principle of least privilege.) If an identical set of objects is required by more than one user (as in the version control scenario discussed previously), DB2 provides the built-in function SYSPROC.ADMIN_COPY_SCHEMA to facilitate this task. This built-in function provides the ability to copy an arbitrary source schema (which may be different from the current schema) to an arbitrary target schema. This task may be accomplished with or without data and provides the option to transfer ownership of all new objects as part of the task. If the transfer ownership option is not specified, the owner of the target objects is the connected user. If a new owner is specified, however, ownership of the new objects is transferred to the new owner without additional effort.
Best Practices
125
Avoid Granting to PUBLIC Granting any authority or privilege to the special DB2 group PUBLIC implicitly provides any user with that same granted authority or privilege. In fact, the CONNECT privilege itself can be granted to PUBLIC, which would mean that any successfully authenticated user will have the ability to log on to the database. Although allowing the PUBLIC group to hold privileges and authorities might ease the DBA administrative burden, the security risk for any production (and most other) databases is typically far too great to tip the balance in favor of letting PUBLIC retain any authority. Obviously, the foundational least-privilege and need-to-know security principles are violated when the PUBLIC group holds authority or privilege. To avoid “overgranting” and assuming unnecessary risk, database privileges and authorities should be given only to a specific target, whether a single user or a group. The safest route, therefore, is to avoid granting any authority or privilege to PUBLIC and to revoke any privileges and authorities currently held by this group.
Restricting the PUBLIC from the Start With DB2 9, the DBA’s burden of revoking all PUBLIC grants has been taken into account. DBAs now have the option of creating any new databases using a new keyword option RESTRICTIVE. The use of this keyword during the CREATE DATABASE command means that the new database will be created without the normally granted PUBLIC privileges. In other words, the implicit grants to PUBLIC are omitted during the creation of the database. You can specify the keyword RESTRICTIVE on the CREATE DATABASE command or specify SQL_DB_RESTRICT_ACCESS_YES for the restrictive field in the SQLEDBOPTIONS data structure parameters embedded within the SQLEDBDESCEXT structure when using CREATE DATABASE API (that is, SQLECREA). You can find out whether the database is created with the restrictive set by querying the database configuration parameter RESTRICT ACCESS. Figure 5.1 shows an example of a database being created without restrictive option. This is verified by obtaining the value of the “Restrict access” database configuration parameter. C:\>db2 create db JRJTKB DB20000I The CREATE DATABASE command completed successfully. C:\>db2 get db cfg for JRJTKB : Restrict access
Figure 5.1
grep –i restrict = No
Determining whether the database was created via the “restrictive” clause
126
Chapter 5 • Authorization—Authority and Privileges
Without the Protection of “Restrictive” If the database were created without using the RESTRICTIVE option, or if it were migrated from a previous release, the RESTRICTIVE option is not available, and the PUBLIC group is likely to hold privileges that should make most DBAs nervous. Fortunately, you can revoke these. Before any REVOKE statements are performed to remove privileges from the PUBLIC group, the DBA might want to discover what rights this group actually has. This is a good practice because after privileges have been removed, they might need to be regranted to users or groups who had previously not specifically needed them because they could use the “inherited” privileges. One way to determine the privileges currently held by the PUBLIC group is to run the following SQL query. db2 "SELECT OBJECTSCHEMA, OBJECTNAME, OBJECTTYPE, PRIVILEGE FROM SYSIBMADM.PRIVILEGES WHERE AUTHID = 'PUBLIC'"
During a default database-creation operation, DB2 implicitly grants the following set of privileges to PUBLIC. (Some of the privileges exist only if the database was migrated from a previous version.) • CREATETAB privilege • BINDADD privilege • CONNECT privilege • IMPLSCHEMA privilege • EXECUTE with GRANT on all procedures in schema SQLJ • EXECUTE with GRANT on all functions and procedures in schema SYSPROC • EXCEUTE and BIND on all packages created in the NULLID schema • CREATEIN on schema SQLJ • CREATEIN on schema NULLID • USE on tablespace USERSPACE1 • SELECT access to the SYSIBM catalog tables • SELECT access to the SYSCAT catalog views • SELECT access to the SYSCATV82 catalog views • SELECT access to the SYSSTAT catalog views • UPDATE access to the SYSSTAT catalog views
Best Practices
127
Easy Public Revokes You can revoke PUBLIC privileges via REVOKE SQL statements or via the Control Center. If using the Control Center, the DBA can use the Show SQL option to view the SQL before it is applied. Because it is likely that these privileges will need to be regranted to specific users or groups, saving the SQL to a file is highly recommended. The file can serve as a foundation for regranting least privilege to specific users and groups. The Control Center example in Figure 5.2a, 5.2b, and 5.2c steps through the process of using the Control Center to save the SQL statements. In this example, only the CONNECT privilege REVOKE statement is shown because it was the only option selected to be revoked. However, there is no restriction on choosing multiple items to revoke simultaneously. In other words, the DBA can select as many (or as few) options as desired, and the SQL for all the options to be revoked will display when the Show SQL button is selected.
Figure 5.2a
128
Chapter 5 • Authorization—Authority and Privileges
Figure 5.2b
Figure 5.2c
Using the Control Center to save the SQL for PUBLIC revokes
Authorities
129
AUTHORITIES The complementary terms authority and privilege refer to mechanisms used to give an authorization ID the ability to perform an operation or access data. Let’s begin with clarifying these two terms. Authority is a predefined role or entity with certain privileges at the instance or database level. There are two types of authorities: instance-level authority and database-level authority. Privilege is held at the individual SQL object level inside the database. Figure 5.3 shows the hierarchy of authorities at the instance and database levels. Note in the diagram that the authority on the parent node encompasses the authority of the child node. SYSADM is the root authority of all authority and privileges except SECADM.
Instance-Level Authority There are four instance-level authorities: system administration authority (SYSADM), system control authority (SYSCTRL), system maintenance authority (SYSMAINT), and system monitor authority (SYSMON).
130
SYSADM
SYSCTRL DBADM
SYSMAINT
LOAD
CONNECT
BINDADD
CREATETAB
SECADM
CREATE_NOT_ FENCED_ROUTINE
SYSMON
Figure 5.3
Hierarchy of authorities
QUIESCE_ CONNECT
Chapter 5 • Authorization—Authority and Privileges
CREATE_EXTER NAL_ROUTINE
IMPLICITSHEMA
Authorities
131
Table 5.1 provides a brief summary and comparison of each instance authority level. Table 5.1
Instance-Level Authorities
Authority
Description
SYSADM
Highest level of administrative authority for DB2 Has control over all the resources created and maintained by the Database Manager for the instance Has implicit DBADM authority within any database under the instance Grants and revokes SECADM authority within any database under the instance Designed for DB2 administrators who need to have full access to utilities and data
SYSCTRL
Highest level of system control authority for DB2 Performs all operations affecting system resources for the instance Does not allow access to any data inside the database unless the user or group has been explicitly granted the privilege to access the data and the privilege to connect to the database Designed for users administrating instances that have sensitive data in one or more databases within the instance
SYSMAINT
Second highest level of system control authority for DB2 Performs maintenance operations on all the databases for the instance Does not allow access to any data inside the database unless the user or group has been explicitly granted the privilege to access the data and the privilege to connect to the database Designed for users maintaining databases in an instance where one or more databases contains sensitive data
SYSMON
Lowest level of system control authority for DB2 Takes database system monitor snapshots of the instance and any database inside the instance Cannot alter system resource usage Does not allow access to any data inside the database unless the user or group has been explicitly granted the privilege to access the data and the privilege to connect to the database Designed for users monitoring databases in an instance
Acquiring and Revoking Instance-Level Authority As in previous versions of DB2, instance-level authority is acquired via group membership. The groups themselves are typically set up and managed by the Linux, UNIX, or Windows system
132
Chapter 5 • Authorization—Authority and Privileges
administrators. The DBA’s role is to make sure that the appropriate group names for each of these highly privileged roles are then identified to DB2. Once the system authority groups are created, they are provided to DB2 via updates to the corresponding Database Manager Configuration (DBM) parameters: SYSADM_GROUP, SYSCTRL_ GROUP, SYSMAINT_GROUP, and SYSMON_GROUP. For example, if user "newton" (user auth ID “NEWTON”) belongs to the group build (group auth ID “BUILD”), and this group is designed as the system administrator group for a DB2 instance, the DBM would be updated with this information via the command: db2 "UPDATE DBM CFG USING SYSADM_GROUP BUILD"
After the UPDATE DBM CFG command completes successfully, any member of the group BUILD will be a SYSADM for the instance. Note that you must stop (db2stop) and restart (db2start) the instance after issuing the UPDATE DBM CFG command for the new parameter to take effect. Removing SYSADM authority for a particular user requires that user’s ID be removed from the SYSADM group. For example, when newton’s ID is removed from the build group by the AIX admin, newton’s days as a SYSADM are over. Things change. Fortunately, changing the SYSADM group to a completely different group can be accomplished at any time by issuing another update DBM CFG parameter command to set the value for the new group. If a new group, JTB_GRP, has been created by the AIX system administrator, for example, and should now replace the former group as the SYSADM group for the instance, the commands to accomplish this would be as follows: db2 "UPDATE DBM CFG USING SYSADM_GROUP JTB_GRP"; db2stop; db2start;
Now, the users who belong to the AIX group JTB_GRP hold SYSADM authority, and the users who belong to the previous group do not (unless their IDs have been moved into the new group). SYSADM (and DBADM)—Things to Avoid
As you can imagine, SYSADM and DBADM authorities deserve a lot of consideration given their high level of privilege. Individuals who hold these designations should also be individuals who are well versed in security as it applies to day-to-day database operations. In some special situations, performance of their daily tasks can introduce risk unless these individuals take care to avoid implicitly passing on elevated privileges. For example, a privileged user who holds SYSADM or DBADM authority is often tasked with performing operations such as precompiling or binding a package or creating a static SQL object. It
Authorities
133
is important to be aware that elevated privileges can be inadvertently passed to the end user during these types of operations. If a user holding DBADM were to issue the command db2 "BIND PACKAGE jtb.bnd"
the OWNER authorization ID for the bound package would be that of the user holding the DBADM authority. If you consider the risk of these types of “inherited” ownership operations, it becomes obvious that users holding DBADM should avoid being the owners of the package or the static SQL object to avoid passing on indirect inheritance of elevated privileges to the end user. Users holding DBADM can avoid this risk by specifying an appropriate value for the OWNER clause when precompiling or binding a package. To bind the package specifying an owner, the DBADM could call the BIND command as follows: db2 "BIND PACKAGE jtb.bnd OWNER KEESA"
Now, the owner of the package is the user keesa (with user auth ID "KEESA"), not the DBADM. In the case of object creation, the DBADM can use the SET SESSION_USER statement to create the object on behalf of the actual designated owner. As an example, to set this value before creating any new objects for the user auth ID "KEESA", the DBADM issues this command: db2 "SET SESSION_USER = KEESA"
All objects created in this SQL session will now be owned by user auth ID "KEESA". By not using SYSADM or DBADM as object owners, the principle of least privilege is enforced, and no additional authority or privileges are given to the end user indirectly. Note, too, that if a user holding SYSADM performs operations such as bind or precompile, DB2 will implicitly grant DBADM authority to the SYSADM. In most environments, these “super-privileged” authorities should be kept separate. Allowing the SYSADM to also hold DBADM would violate the principle of least privilege and would compromise inherent separation of duties. For this reason, allowing those users with SYSADM to “inherit” DBADM authority in this manner is strongly discouraged. Default Versus Security—Let Security Win This One All four database manager configuration parameters—SYSADM_GROUP, SYSCTRL_GROUP, SYSMAINT_GROUP, and SYSMON_GROUP—default to NULL for a new installation. Also, if the Database Manager Configuration is reset (db2 "reset dbm cfg") these values return to NULL. Think back to your first programming class. What does NULL mean exactly…the absence of something? Don’t let it mean the absence of security for your DB2 instance. On UNIX and Linux installations, a NULL value for the SYSADM_GROUP forces DB2 to allow SYSADM authority for any user who belongs to the primary group of the instance owner. If the primary group of the instance owner contains more than one user, any other users who also belong to that same primary instance owner group can act as SYSADM for this instance. To illustrate, if the IDs kbond and jbond are both part of the instance owner group instgrp, and the value for the
134
Chapter 5 • Authorization—Authority and Privileges
DBM parameter SYSADM_GROUP is left as the installation default (NULL), either jbond or kbond can act as SYSADM for this instance. Obviously, this may or may not be the desired result; but
either way, it is not a sound practice. On Windows installations, a NULL value for the SYSADM_GROUP means DB2 allows SYSADM operations by any user in the local administrators group on the local system. Again, the default might not provide a solid approach to securing DB2 instances. Although the instance will function even if the System groups are set to NULL, leaving these parameters at their defaults defies best security practices and is strongly discouraged. When things are “working,” it might be tempting to continue the status quo; so it is important to set these values right after any new instance is created. That way, when the environment is ready, the DBA does not have to make a maintenance window to assign the appropriate groups for the DBM.
Database-Level Authority Ten database-level authorities can be granted or revoked: • DBADM (database administrator) • SECADM (security administrator) • CONNECT • BINDADD • CREATETAB • CREATE_EXTERNAL_ROUTINES • CREATE_NOT_FENCED_ROUTINE • IMPLICIT_SCHEMA • LOAD • QUIESCE_CONNECT Table 5.2 provides a brief summary and comparison of each database authority level. Table 5.2
Database-Level Authorities
Authority
Description
DBADM
The second highest level of administrative privilege next to SYSADM. Privileges are restricted to an individual database within an instance. Designed for administrators who require full access to data and objects inside the database but do not require the maintenance capability that SYSCTRL or SYSMAINT possesses. (continues)
Authorities
Table 5.2
135
Database-Level Authorities (Continued)
Authority
Description It includes all the database-level authorities except SECADM and implicitly has all privileges within the database except those reserved for SECADM. When DBADM authority is granted to an auth ID, all other database level authorities except SECADM will also be implicitly granted to the same auth ID. After revoking the DBADM from an auth ID, the other implicitly granted database-level authorities remain, and they must be explicitly revoked from the auth ID as deemed necessary.
SECADM
A companion authority to DBADM. Provided to handle security matters inside the database such as transferring ownership of an object and creating, dropping, altering, granting, and revoking of objects that are part of LBAC. Does not allow access to any data unless explicitly granted. This authority possesses power that SYSADM or DBADM authority does not. Primarily used for security purposes.
CONNECT
Allows the user to connect to the database after successful authentication.
BINDADD
Allows the user to create new packages in the database.
CREATETAB
Allows the user to create a new table in the database.
CREATE_EXTERNAL_ROUTINE
Allows the user to create an external routine in the database. Note: CREATE_EXTERNAL_ROUTINE authority will be implicitly (automatically) granted to the same auth ID when the auth ID is granted the CREATE_NOT_FENCED_ROUTINE authority. CREATE_EXTERNAL_ROUTINE authority cannot be revoked from the auth ID if the auth ID still possesses the CREATE_ NOT_FENCED_ROUTINE authority.
CREATE_NOT_FENCED_ROUTINE
Allows the user to create a routine that is not fenced, meaning it is running inside the address space of an agent. Also referred to as a “trusted” routine.
IMPLICIT_SCHEMA
Allows the user to implicitly create schemas that do not already exist.
LOAD
Allows the user to invoke the load utility. Additional privileges on the target table may be required depending on the option specified.
QUIESCE_CONNECT
Allows the user to connect to the database while it is in a quiesced state.
136
Chapter 5 • Authorization—Authority and Privileges
Maintain Separation To ensure critical separation of security duties, a database administrator (DBADM) should not also hold security administrator authority (SECADM) or vice versa. If it is necessary to have a single user perform both these high-level security functions, other appropriate monitoring processes (including appropriate DB2 auditing of SECMAINT events) should be in place to provide accountability. Granting and Revoking Database-Level Authorities The SQL statement GRANT (database authorities) is used to grant database authority to a user auth ID (that is, USER clause), group auth ID (that is, GROUP clause), or PUBLIC. The SQL statement REVOKE (database authorities) is used to revoke a database authority from a user auth ID (that is, USER clause), group auth ID (that is, GROUP clause), or PUBLIC. Optionally, you can use the Control Center to grant and revoke database-level authorities. Some exceptions apply. For security reasons, DBADM authority cannot be granted to PUBLIC. SECADM authority, which should be conferred only to the most trusted individuals, can only be granted to a user auth ID and not to a group. Similar to instance-level authorities, only grant the minimum required (least) privilege necessary. For example, users should not be granted DBADM just because they need to load data into a table. In this case, users should be granted only the combination of LOAD authority and any required SELECT, INSERT, UPDATE, or DELETE privileges on the table. BY ALL Revocation Approach
When revoking an authority or a privilege, it is important to understand the BY ALL approach used by DB2. This means that the privilege(s) are revoked from the specified list of user or group auth IDs or PUBLIC regardless of who granted it. For example, the user auth ID SEE has been granted CREATETAB authority by database administrator 1. A System Administrator has subsequently granted user auth ID SEE DBADM authority (which automatically granted all other database-level authorities, including CREATETAB authority). After a privilege/authority review, user auth ID SEE has been found to have excess authority and privilege. All database authorities are revoked from authID SEE by the System Administrator who issues the following REVOKE SQL statement: db2 "REVOKE CONNECT, BINDADD, CREATETAB, CREATE_EXTERNAL_ROUTINE, CREATE_NOT_FENCED_ROUTINE, IMPLICIT_SCHEMA, LOAD, QUIESCE_CONNECT, DBADM ON DATABASE FROM USER SEE [BY ALL]"
BY ALL is the default regardless of whether you specify it. After the completion of the REVOKE statement, the CREATETAB authority granted by database administrator 1 is also implicitly revoked because of the BY ALL logic.
Authorities
137
How Can Current Authorities Be Determined? The GET AUTHORIZATIONS CLP command is an effective way to find out what authorities one currently holds. The DB2 API sqluadau also provides similar functionality, and it can be embedded in a program. Both the GET AUTHORIZATIONS command and the sqluadau API output exclude providing information for the SECADM authority. SECADM authority can be determined by reviewing the catalog view SYSCAT.DBAUTH. Listing 5.1 shows the output of the GET AUTHORIZATIONS command for the instance owner SEE who has just created a database. Listing 5.1
Get Authorizations Output
db2 => GET AUTHORIZATIONS Administrative Authorizations for Current User Direct SYSADM authority = NO Direct SYSCTRL authority = NO Direct Direct Direct Direct Direct
Direct CREATE_NOT_FENC authority Direct IMPLICIT_SCHEMA authority Direct LOAD authority Direct QUIESCE_CONNECT authority Direct CREATE_EXTERNAL_ROUTINE authority Direct SYSMON authority Indirect SYSADM authority Indirect SYSCTRL authority
Chapter 5 • Authorization—Authority and Privileges
To find out whether the auth ID SEE has SECADM, connect to the database and issue the following SQL statement (assuming you have SELECT access privileges to the SYSCAT.DBAUTH view): db2 "SELECT SECURITYADMAUTH FROM SYSCAT.DBAUTH WHERE GRANTEE = 'SEE'"
Alternatively, you can discover all the database-level authorities granted to a particular auth ID by issuing the following SQL statement: db2 "SELECT GRANTOR, DBADMAUTH, SECURITYADMAUTH, CONNECTAUTH, BINDADDAUTH, CREATETABAUTH, EXTERNALROUTINEAUTH, NOFENCEAUTH, IMPLSCHEMAAUTH, LOADAUTH, QUIESCECONNECTAUTH FROM SYSCAT.DBAUTH WHERE GRANTEE = ''"
Direct Authority Versus Indirect Authority As you can see in the output from the GET AUTHORIZATIONS command in the preceding section, a user can obtain an authority by having it directly granted to their authorization ID. What may not be as obvious is that the authority can also be given indirectly if it is granted to a group authorization ID to which the user belongs or if the authority has been granted to PUBLIC. A user can have an authority from both direct and indirect sources. For example, by default, the database creator (the user that issues the CREATE DATABASE command) has both direct CREATETAB and indirect CREATETAB (via PUBLIC) authorities. Note that if the database is created with the RESTRICTIVE option, the database creator will not have CREATETAB via PUBLIC (indirect) authorities. Note that no one will have direct SYSADM, SYSCTRL, SYSMAINT, or SYSMON. This is because these authorities are acquired via group membership, which is external to DB2. Recall from Chapter 3 that group membership can be defined on the operating system if the default operating system–based group plug-in is used, via LDAP if the IBM-shipped LDAP-based group plug-in is used, or any other external mechanism as defined by a customized group plug-in.
PRIVILEGES SQL Objects and Their Privileges In Figure 5.4, privileges are organized into a hierarchy with the arrow pointing to the parent privilege on the left. For example, control privilege on a table includes all the other table-level privileges. On the right side of the graphic, the oval circle indicates which catalog view can be examined to determine the privileges that have been granted.
Privileges that are associated with a SQL object Privileges that are not associated with a SQL object Exemption (on one or all access rule for a specified LBAC security policy)
setsessionuser
Figure 5.4
DB2 privileges
Exemption
Setsessionuser
SYSCAT. SECURITYPOLICYEXEMPTIONS
SYSCAT. SURROGATEAUTHIDS
140
Chapter 5 • Authorization—Authority and Privileges
You can also obtain the privilege information using the PRIVILEGES administrative view. For example, to obtain the privilege granted for any procedure for all authorization IDs, you can issue the following: db2 "SELECT AUTHID, PRIVILEGE, OBJECTNAME, OBJECTSCHEMA FROM SYSIBMADM.PRIVILEGES WHERE OBJECTTYPE = 'PROCEDURE'"
Table 5.3 provides a brief summary and comparison of each privilege. Table 5.3
DB2 Privileges Summary
Object
Privilege
Description
Index
CONTROL
Allows the user to have control on the index. This privilege is used on drop index only.
Package
CONTROL
Allows the user to rebind, drop, and execute the package and grant package privileges to others.
BIND
Allows the user to bind or rebind the package or create a new version of the package.
EXECUTE
Allows the user to execute the package.
Routine (function, procedure and method)
EXECUTE
Allows the user to execute the routine.
Schema
ALTERIN
Allows the user to alter objects defined in that schema.
CREATEIN
Allows the user to create objects defined in that schema.
DROPIN
Allows the user to drop objects defined in that schema.
ALL ACCESS
Allows the user read and write access with the security label.
READ ACCESS
Allows the user read access with the security label.
WRITE ACCESS
Allows the user write access with the security label.
USAGE
Allows the user to use NEXTVAL and PREVVAL expressions for the sequence.
ALTER
Allows the user to alter sequence properties using ALTER SEQUENCE statement.
Server
PASSTHRU
Allows the user to access and use a specified data source in a pass-through mode in a federated environment.
Tablespace
USE
Allows the user to create tables in a specified tablespace.
This keyword allows every available privilege, including CONTROL, to be granted to the user. The user has all rights to the object. Gives the user all privileges on the table, view, MQT, staging table, or nickname, and the ability to grant those privileges to others (except CONTROL). Allows the user to alter the definition of the table or the nickname.
CONTROL
ALTER
(table and nickname) DELETE
Allows the user to delete rows in the table, MQT, staging table, or updatable view. To delete a row from a nickname, the delete privilege on the nickname is required in addition to the required privilege at the data source for the delete operation.
INDEX (table
and nickname) INSERT
REFERENCES
(table) SELECT
UPDATE
XSR object
USAGE
Allows the user to create an index on a table or an index specification on a nickname. Allows the user to insert data into a table, an updatable view, an MQT, and a staging table and run the import utility against a table, an updatable view, an MQT, and a staging table. To insert or import into a nickname, the insert privilege on the nickname is required in addition to the required privilege at the data source for the delete operation. Allows the user to create or drop a foreign key referencing the table as parent. Allows the user to retrieve data, create encapsulated objects such as a view referencing the table, and run the export utility against the object. Allows the user to issue an update statement on the object. Allows the user to use the XML schema (XSR object). Currently, usage privilege on XSR objects can be granted only to PUBLIC.
Exemption on one or all access rules for a specified LBAC security policy
EXEMPTION
Allows the user to access a protected table without the exempted rule being enforced.
Setsessionuser
SETSESSIONUSER
Allows the user to use the SET SESSION AUTHORIZATION statement to set the session authorization ID to a specified authorization ID.
142
Chapter 5 • Authorization—Authority and Privileges
A security label access or exemption rule can be granted only to user auth IDs (USER). It cannot be granted to a group auth ID (GROUP) or PUBLIC. The setsessionuser privilege cannot be granted to PUBLIC. GRANTED WITH and CONTROL—More Than You Bargained For?
As mentioned previously, privileges can be granted or revoked using the Control Center or via SQL statements. Although DB2 makes granting easy, it is up to the DBA to truly understand both the explicit and implicit operations performed during this process to avoid granting more than intended. Specifying the WITH GRANT OPTION on the GRANT SQL statement allows the target authorization ID (that is, grantee) to, in turn, GRANT the received privileges to other user auth IDs or group auth IDs. The WITH GRANT OPTION can be specified on the GRANT SQL statement when granting privileges associated with packages, routines, schemas, sequences, tablespaces, tables, views, MQTs, staging tables, and nicknames. Note that using the WITH GRANT OPTION is a risky approach to take because the grants can cascade from one user to another. This is likely to violate the enterprise’s security policies and is not a good practice even in development environments. Using this option introduces some significant risk into the database environment. Tables, indexes, views, MQTs, staging tables, nicknames, and packages can be granted to users or groups with CONTROL privilege. CONTROL privilege provides the recipient with elevated privileges, including the ability to DROP the object in question or GRANT privileges to others. Given the breadth of the risk, allowing CONTROL privileges to be granted on objects in the database is not a sound security practice. Any attempt to grant the CONTROL privilege along with the WITH GRANT OPTION will result in a warning, and the WITH GRANT OPTION will not be applied for the CONTROL privilege. For packages, tables, views, MQTs, staging tables, and nicknames, granting CONTROL to an auth ID will cause all other object-level privileges to be granted to the auth ID, too. You cannot revoke individual privileges without first revoking the CONTROL privilege from the auth ID. To illustrate some of the pitfalls, consider the following scenario.
• User auth ID JBOND is successfully granted privileges as follows: SQL 1
db2 "GRANT SELECT, CONTROL ON TABLE DB2ASAM.EMPHIST_AUDIT TO USER JBOND"
Privileges
143
• The DBA runs the following SQL to determine the privileges held by JBOND: SQL 2 db2 "SELECT CHAR(TABSCHEMA,7) AS SCHEMA, CHAR(TABNAME,14) AS TABNAME, CHAR(CONTROLAUTH,1) AS C, CHAR(ALTERAUTH,1) AS A, CHAR(DELETEAUTH,1) AS D, CHAR(INDEXAUTH,1) AS X, CHAR(INSERTAUTH,1) AS I, CHAR(REFAUTH,1) AS R, CHAR(SELECTAUTH,1) AS S, CHAR(UPDATEAUTH,1) AS U FROM SYSCAT.TABAUTH WHERE GRANTEE = 'JBOND'"
• The DBA is confused to discover that JBOND has more privileges than expected: SCHEMA TABNAME C A D X I R S U ------- -------------- - - - - - - - DB2ASAM EMPHIST_AUDIT Y G G G G G G G
By granting CONTROL ON TABLE DB2ASAM.EMPHIST_AUDIT, the DBA also implicitly granted all these other privileges to JBOND and also gave JBOND the ability to grant those privileges to others. At this point, the DBA discovers that a mistake was made and that the user who should get CONTROL ON TABLE DB2ASAM.EMPHIST_AUDIT is actually KBOND. User JBOND should have only SELECT privilege on the table. • The DBA attempts to remove DELETE, INSERT, UPDATE, and REFERENCES privileges for user JBOND, but receives an error: SQL 3 db2 "REVOKE DELETE, INSERT, UPDATE, REFERENCES ON TABLE DB2ASAM.EMPHIST_AUDIT FROM USER JBOND" DB21034E The command was processed as a SQL statement because it was not a valid Command Line Processor command. During SQL processing it returned: SQL0558N An attempt to revoke a privilege from "JBOND" was denied because "JBOND" would still hold "CONTROL" authority. SQLSTATE=42504
• To REVOKE the extra privileges from JBOND, the DBA must first revoke CONTROL on the table: SQL 4 db2 "REVOKE CONTROL ON TABLE DB2ASAM.EMPHIST_AUDIT FROM USER JBOND" DB20000I The SQL command completed successfully.
• Now the DBA again runs SQL 3 to revoke DELETE, INSERT, UPDATE, and REFERENCES on the table from JBOND. This time, the command completes successfully. However, there is still a problem. When the DBA again runs SQL 2 to
144
Chapter 5 • Authorization—Authority and Privileges
recheck the privileges held by JBOND on the DB2ASAM.EMPHIST_AUDIT table, the user still has more privileges than desired: SCHEMA TABNAME C A D X I R S U ------- -------------- - - - - - - - DB2ASAM EMPHIST_AUDIT N G N G N N Y N
• The DBA realizes that the ALTER and INDEX privileges were also implicitly granted with the CONTROL privilege and now must be revoked: SQL 5 db2 "REVOKE ALTER,INDEX ON TABLE DB2ASAM.EMPHIST_AUDIT FROM USER JBOND"
• Rerunning SQL 2 to check again, the DBA determines that the inappropriate grants to user JBOND are now reversed and that SELECT is the only remaining privilege held by JBOND on the EMPHIST_AUDIT table: SCHEMA TABNAME C A D X I R S U ------- -------------- - - - - - - - DB2ASAM EMPHIST_AUDIT N N N N N N Y N
When it comes to granting privileges, less is definitely more. You should grant only the minimum required (least) privilege to the need-to-know user or group of users. For example, if the user needs to INSERT and UPDATE some rows in a table, you should grant only those two privileges to the user. Never grant more than required.
IMPLICIT GRANTED AUTHORITIES AND PRIVILEGES As briefly discussed in the preceding sections, implicitly granted authorities or privileges are automatically granted by DB2 when certain database operations are performed. Because these are granted outside the normal database policies and procedures, these implicit authorities or privileges should be well understood by the DBA and SECADM. These implicit privileges should be revoked if deemed necessary. All implicitly granted authorities or privileges will have SYSIBM (that is, DB2 system) as the grantor listed on the corresponding system catalog table. You can find out how many rows of these authorities or privileges existed in the database by invoking the following SQL statement: SELECT 'DATABASE' AS TYPE, COUNT(*) AS COUNT FROM SYSCAT.DBAUTH WHERE GRANTOR = 'SYSIBM' UNION SELECT 'TABLESPACE' AS TYPE, COUNT(*) AS COUNT FROM SYSCAT.TBSPACEAUTH WHERE GRANTOR = 'SYSIBM' UNION SELECT 'TABLE' AS TYPE, COUNT(*) AS COUNT FROM SYSCAT.TABAUTH WHERE GRANTOR = 'SYSIBM' UNION
Implicit Granted Authorities and Privileges
145
SELECT 'PACKAGE' AS TYPE, COUNT(*) AS COUNT FROM SYSCAT.PACKAGEAUTH WHERE GRANTOR = 'SYSIBM' UNION SELECT 'ROUTINE' AS TYPE, COUNT(*) AS COUNT FROM SYSCAT.ROUTINEAUTH WHERE GRANTOR = 'SYSIBM' UNION SELECT 'INDEX' AS TYPE, COUNT(*) AS COUNT FROM SYSCAT.INDEXAUTH WHERE GRANTOR = 'SYSIBM' UNION SELECT 'COLUMN' AS TYPE, COUNT(*) AS COUNT FROM SYSCAT.COLAUTH WHERE GRANTOR = 'SYSIBM' UNION SELECT 'SCHEMA' AS TYPE, COUNT(*) AS COUNT FROM SYSCAT.SCHEMAAUTH WHERE GRANTOR = 'SYSIBM' UNION SELECT 'PASSTHRU' AS TYPE, COUNT(*) AS COUNT FROM SYSCAT.PASSTHRUAUTH WHERE GRANTOR='SYSIBM' UNION SELECT 'SECURITY LABEL ACCESS' AS TYPE, COUNT(*) AS COUNT FROM SYSCAT.SECURITYLABELACCESS WHERE GRANTOR='SYSIBM' UNION SELECT 'SECURITY POLICY EXEMPTIONS' AS TYPE, COUNT(*) AS COUNT FROM SYSCAT.SECURITYPOLICYEXEMPTIONS WHERE GRANTOR='SYSIBM' UNION SELECT 'SEQUENCE' AS TYPE, COUNT(*) AS COUNT FROM SYSCAT.SEQUENCEAUTH WHERE GRANTOR='SYSIBM' UNION SELECT 'XSROBJECT' AS TYPE, COUNT(*) AS COUNT FROM SYSCAT.XSROBJECTAUTH WHERE GRANTOR='SYSIBM' ORDER BY 1, 2;
Table 5.4 summarizes the cases where implicit privileges are granted. Table 5.4
Implicit Privileges Summary Recipient of the Privileges/Authorities
Operation
Implicit Privileges/Authorities
Create a new database
DBADM and all database level authorities The creator of the database. except SECADM • CREATETAB authority PUBLIC unless the • BINDADD authority restrictive option is speci• CONNECT authority fied on CREATE • IMPLSCHEMA authority DATABASE. • EXECUTE with GRANT privilege on all procedures in schema SQLJ • EXECUTE with GRANT privilege on all functions and procedures in schema SYSPROC • BIND privilege on all packages created in the NULLID schema
(continues)
146
Table 5.4
Chapter 5 • Authorization—Authority and Privileges
Implicit Privileges Summary (Continued)
Operation
Implicit Privileges/Authorities
Create a new database.
• EXECUTE privilege on all packages created in the NULLID schema • CREATEIN privilege on schema SQLJ • CREATEIN privilege on schema
Recipient of the Privileges/Authorities
NULLID
• USE privilege on tablespace USERSPACE1
• SELECT privilege to access the SYSIBM catalog tables • SELECT privilege to access the SYSCAT catalog views • SELECT privilege to access the SYSCATV82 catalog views • SELECT privilege to access the catalog views • UPDATE privilege to update the SYSSTAT catalog views Grant DBADM to an auth ID.
All other database level authorities except The auth ID of the recipient of DBADM.
SECADM
Execute create schema statement.
CREATEIN, ALTERIN, DROPIN schema
Execute a create statement without qualifying the object name with the schema and the schema does not exist yet (that is, schema is implicitly created by DB2).
CREATEIN, ALTERIN, DROPIN schema
CREATEIN schema privilege
PUBLIC
Creating a table, creating an index, or binding a new package.
CONTROL privilege on the table or index
Initial owner of the object.
Create a view.
CONTROL privilege on the view if the user has CONTROL privilege for all the
privilege on newly created schema
privilege
The initial owner of the schema. If the authorization clause is specified, the initial owner is the specified authorization ID; otherwise, it is the session authorization ID. The initial owner of the object that causes the schema to be implicitly created.
or package. Initial owner of the view.
tables, views, and nicknames referenced in the view definition (continues)
Authorization Checking for SQL Statements
Table 5.4
147
Implicit Privileges Summary (Continued)
Operation
Implicit Privileges/Authorities
Create SQL stored procedure (packaged procedure).
CONTROL privilege on the hidden
internally generated package*
The first time SYSADM creates Assumes the SYSADM does not already a view, trigger, routine or binds have the required privilege or DBADM a new package. explicitly to perform the create or bind, and so DB2 implicitly grants DBADM
Recipient of the Privileges/Authorities Initial owner of the routine. SYSADM
*To find the hidden internally generated packages, execute the following query:
SELECT DEP.BNAME, DEP.BSCHEMA FROM SYSIBM.SYSDEPENDENCIES DEP, SYSCAT.PROCEDURES PROC WHERE PROC.PROCNAME = '' AND PROC.PROCSCHEMA = '' AND DEP.DTYPE = 'L' AND DEP.DNAME = PROC.SPECIFICNAME AND DEP.DSCHEMA = ''
AUTHORIZATION CHECKING FOR DB2 COMMANDS AND UTILITIES When invoking DB2 commands (such as an update on a Database Manager Configuration parameter) or utilities (such as LOAD) via the CLP or API interfaces, authorization checking is done at the time of execution of the command. The authorization ID used for checking is the system authorization ID. If a connection to a database or an attachment to the instance is required for the command or utilities, DB2 uses the authorization ID associated with the user ID that is used for the authentication (that is, the system authorization ID) regardless of whether a SET SESSION_USER SQL statement has been issued. If no connection or attachment is required, DB2 uses the authorization ID associated with the user ID that is currently logged on. Group privileges are also considered.
AUTHORIZATION CHECKING FOR SQL STATEMENTS To understand how authorization checking is done for SQL statements, you need to understand the statement authorization ID concept and the different authorization models available in DB2.
Statement Authorization ID This authorization ID is used for authorization checking for a SQL statement. The statement authorization ID is also the owner of the object when a DDL (data definition language) statement is issued to create a SQL object (such as CREATE VIEW). Packages, too, are owned by the statement authorization ID that performs the precompile or bind operation unless the OWNER option is specified as part of the precompile or bind command.
148
Chapter 5 • Authorization—Authority and Privileges
Different Authorization Models Available in DB2 Just as there are two different types of SQL (static and dynamic), there are two key SQL authorization models used in DB2. A static authorization model is used for authorization checking during the creation of static SQL objects. Static SQL object operations include operations such as CREATE VIEW and precompiling or binding (that is, bind time) for a package that contains static SQL statements. With a static SQL statement, the syntax is fully known at compile time. This differs from a dynamic SQL statement, where the exact SQL syntax is not known until the actual runtime execution. In the static authorization model, the user auth ID of the initial owner of the SQL object, which is the statement authorization ID, is used for authorization checking. Group privileges associated with the object’s initial owner are not considered. (The only exception is if the PUBLIC group holds the privilege.) The actual privilege checking is done during the SQL object creation, such as during the precompile or bind time, for a static SQL package. At runtime, the end user requires only access to the static object and does not need to hold any privileges on the underlying object. For example, if a package inserts a row into a table when called, the user needs EXECUTE privilege on the package and does not need to hold INSERT privilege on the underlying table. A dynamic authorization model is used for authorization checking during the execution or runtime of a package that contains dynamic SQL statements or any DDL statements that are not used to create static SQL objects. (See the “Group Privilege Restriction” section for the list of DDL statements used to create static SQL objects). The dynamic SQL authorization model depends on the package in which that dynamic SQL is executed and the value of the DYNAMICRULES option (dynamic SQL rules) specified when the package was precompiled or bound. If the dynamic SQL rule is not specified during the PRECOMPILE or BIND of a package that contains dynamic SQL statements, the dynamic authorization model will, by default, use the session authorization ID of the connected user as the statement authorization ID for authorization checking. Similarly, the user session auth ID will be used for authorization checking for DDL statement issued in the package. Group privileges are considered during authorization checking under this model. For more information on how the DYNAMICRULES option affects the authorization checking, refer to the “Dynamic SQL Rules” section. What about the SQL statement entered through the DB2 Command Line Processor (CLP), Call Level Interface (CLI), Java Database Connectivity (JDBC), or Control Center? Although they have packages associated with them, the SQL is entered at runtime. For this reason, these SQL statements are actually dynamic SQL statements because the syntax is not known until the user enters the statement. As a result, any SQL statement (submitted via CLP or Control Center or CLI or JDBC) will use the dynamic authorization model.
Authorization Checking for SQL Statements
149
Retrieving the Group Membership List for a Given Authorization ID You can retrieve this list of groups of which a given authorization ID is a member by using the SYSPROC.AUTH_LIST_GROUPS_FOR_AUTHID table function. For example, if you want to retrieve the list of groups for auth ID NEWTON, issue the following query: db2 "SELECT * FROM TABLE (SYSPROC. AUTH_LIST_GROUPS_FOR_AUTHID ('NEWTON')) AS T"
Note that this function works only if you are using the operating system–based group membership lookup (such as the IBM-shipped group membership lookup plug-in). If you use another mechanism, such as the LDAP group membership lookup plug-in, the list of groups might not correspond to the list of groups obtained by DB2 during authentication. Group Privilege Restriction Sometimes, the privileges granted to a group are not checked. Privileges granted to a group auth ID are not considered for SQL objects (such as tables) referenced in the CREATE TABLE/ALTER TABLE ADD CHECK CONSTRAINT, CREATE FUNCTION, CREATE INDEX EXTENSION, CREATE METHOD, CREATE PROCEDURE, CREATE SCHEMA, CREATE TABLE, CREATE TRANSFORM, CREATE TRIGGER, CREATE VIEW, and DECLARE GLOBAL TEMPORARY TABLE statements or during the binding of a package that contains static SQL statements. When thinking about why group privileges are not always checked for certain static SQL, remember that group membership is managed outside of DB2. When a user’s membership in a group is altered, therefore, this information is not dynamically communicated to DB2. Instead, DB2 obtains updated group membership information for a user only when the user re-establishes a connection to the database (and after the group membership has changed). Static SQL statements inside an embedded program and static SQL objects require continued existence of privileges for their survival. This inability to be informed of changes in privileges resulting from changes in group membership would prevent DB2 from maintaining the security integrity of the database. As a protection, the required privileges of the initial OWNER are checked on the underlying object only at the time of creation and do not include the privileges the OWNER holds as a member of a group. After that, the object is considered valid as long as the initial OWNER holds the privileges (that is, the privileges are not revoked using a REVOKE statement) and no additional checking is done on the subsequent use of the object. The following static SQL objects are affected by this restriction: CHECK CONSTRAINTS FUNCTIONS INDEX EXTENSIONS MATERIALIZED QUERY TABLES
150
Chapter 5 • Authorization—Authority and Privileges
METHODS PROCEDURES SCHEMAS STAGING TABLES TRANSFORM GROUPS TRIGGERS VIEWS DECLARED GLOBAL TEMPORARY TABLES STATIC SQL IN A PACKAGE
When creating any of these listed static SQL objects, the initial OWNER might need one or more of the following privileges where group privileges are not considered: ALL ACCESS (or READ or WRITE ACCESS) on security label USAGE on the underlying XSR EXECUTE on the underlying function EXECUTE on the underlying procedure EXECUTE on the underlying method USAGE on the underlying sequence CONTROL on the underlying table or the underlying view or the underlying nickname SELECT, INSERT, UPDATE, or DELETE on the underlying table or the underlying view
The following four examples are common situations encountered by DB2 DBAs in the performance of their daily responsibilities. For simplicity, assume that user auth ID USER2 belongs to only one group dbuser (group auth ID DBUSER).
Example 1 The DBA needs to create an SQC embedded program. Inside the source file is the following static SQL statement: EXEC SQL INSERT INTO USER1.T1 VALUES (:hostvar1)
When user USER2 attempts to PRECOMPILE the PACKAGE, DB2 will only check to determine whether the INSERT privilege on USER1.T1 has been granted to USER2 or PUBLIC. Even though the INSERT privilege on USER1.T1 might have been granted to group DBUSER, DB2 will not take this privilege into account.
Authorization Checking for SQL Statements
151
Example 2: View CREATE VIEW USER2.V1 AS SELECT * FROM USER1.T2
When user USER2 attempts to create the above view, DB2 will check only whether the SELECT privilege on USER1.T2 is granted to USER2 or PUBLIC. Even though the SELECT privilege on USER1.T2 might have been granted to the group DBUSER, DB2 will not take this privilege into account.
Example 3: SQL procedure CREATE PROCEDURE USER2.PROC1 (I INTEGER) LANGUAGE SQL SPECIFIC AX BEGIN INSERT INTO USER1.T1 VALUES (I + 1000); END%
When user USER2 attempts to create the above SQL procedure, DB2 will check only whether the INSERT privilege on USER1.T1 has been granted to USER2 or PUBLIC. Even though the INSERT privilege on USER1.T1 might already be granted to group DBUSER, DB2 will not take this privilege into account.
Example 4: Sourced function CREATE FUNCTION USER2.SOURCED1 (PARM1 SHORT) RETURNS SHORT SPECIFIC SOURCED1 SOURCE USER1.F1 (SHORT);
When user USER2 attempts to create the above function, DB2 will check only whether the EXECUTE privilege on USER1.F1 is granted to USER2 or PUBLIC. Even though the EXECUTE privilege on USER1.F1 might already be granted to group DBUSER, DB2 will not take this privilege into account.
In each of these examples, the group privileges will not be considered. Because groups are managed outside of the database, DB2 would not know whether the user had been removed from the group. Dynamic SQL Rules As mentioned earlier, dynamic SQL statements by default use the SESSION authorization ID of the connected user for any authorization checking (RUN behavior). Authorization checking
152
Chapter 5 • Authorization—Authority and Privileges
behavior can be altered if the DYNAMICRULES option is specified when a package is created. Six values can be specified for this option: BIND RUN DEFINEBIND DEFINERUN INVOKEBIND INVOKERUN
The last four values are dual values that behave differently in a standalone program versus inside a routine environment. As a result, the six DYNAMICRULES values are mapped to four different types of behaviors—RUN, BIND, DEFINE, and INVOKE—which affect the selection of the authorization ID used for checking privileges on the underlying objects and the default qualifier used for unqualified objects. The following table shows how the six different DYNAMICRULES values behave in two environments: inside a standalone program and inside a routine. Table 5.5
Dynamic SQL Rules Standalone Program Environment
Dynamicrules Value
Behavior of Dynamic SQL Statements
BIND
BIND behavior
RUN
DEFINEBIND
DEFINERUN
RUN behavior
BIND behavior
RUN behavior
Authorization ID Used for Checking Privileges on Underlying Objects
Routine Environment
Behavior of Dynamic SQL Statements
The implicit or explicit value of the OWNER BIND option
BIND behavior
ID of User Executing Package
RUN
The implicit or explicit value of the OWNER BIND option
DEFINE
ID of User Executing Package
DEFINE
behavior
behavior behavior
behavior
Authorization ID Used for Checking Privileges on Underlying Objects The implicit or explicit value of the OWNER BIND option ID of User Executing Package Routine definer (not the routine’s package owner) Routine definer (not the routine’s package owner)
(continues)
Authorization Checking for SQL Statements
Table 5.5
153
Dynamic SQL Rules (Continued) Standalone Program Environment
Dynamicrules Value INVOKEBIND
Behavior of Dynamic SQL Statements BIND
behavior
INVOKERUN
RUN behavior
Authorization ID Used for Checking Privileges on Underlying Objects The implicit or explicit value of the OWNER BIND option ID of User Executing Package
Routine Environment
Behavior of Dynamic SQL Statements INVOKE
behavior
INVOKE
behavior
Authorization ID Used for Checking Privileges on Underlying Objects Current statement authorization ID when routine is invoked Current statement authorization ID when routine is invoked
Note that the following SQL statements are disallowed unless you are running in a RUN behavior: GRANT, REVOKE, ALTER, CREATE, DROP, COMMENT ON, RENAME, SET INTEGRITY, and SET EVENT MONITOR STATE. The DEFINEBIND, DEFINERUN, INVOKEBIND, and INVOKERUN DYNAMICRULES options behave differently if the package is run in the standalone environment versus being run inside a routine environment. The term routine environment implies that the package is associated with an external routine (external scalar function, external table function, external method, and external stored procedure) or a SQL procedure. Authorization checking is different between the four dynamic SQL statement behaviors. The INVOKE behavior (the routine environment) and the RUN behavior (the standalone environment) requires the SESSION authorization ID who executes/invokes the routine or the package to hold all the necessary privileges for the underlying objects via either the user authorization ID, group privileges, or PUBLIC. The DEFINE behavior (the routine environment) and the BIND behavior (the standalone environment) provide a level of authority or privilege encapsulation by checking the privileges of the underlying objects against the binder authorization ID of a package or the definer authorization ID of a routine. Group privileges are not considered in this authorization checking of the underlying objects. Of course, privilege granted to PUBLIC is considered as usual. The SESSION authorization ID executing/invoking the routine or the package is required only to have the EXECUTE privilege on the package or the routine via any of the following: user privileges, group privileges, or PUBLIC.
154
Chapter 5 • Authorization—Authority and Privileges
Using the DEFINE behavior and the BIND behavior allows a dynamic SQL statement to use the static authorization model. When using the DB2 Stored Procedure Builder or when using the command line to create SQL stored procedures, users might not be aware that the SQL procedures they create have actually been designed as package procedures. This means that DB2 will internally generate an SQC program and precompile, bind, and then link the package with the SQL procedure, all transparent to the user. Most stored procedures are created using static SQL in the procedure body. The following CREATE PROCEDURE statement is an example. CREATE PROCEDURE USER2.SP1 (I INTEGER) LANGUAGE SQL SPECIFIC AX BEGIN CALL USER1.SP2 (I); END%
Here is the CREATE PROCEDURE USER2.SP1 written using a dynamic SQL-based procedure body: CREATE PROCEDURE USER2.SP1 (I INTEGER) LANGUAGE SQL SPECIFIC AX BEGIN DECLARE STMT VARCHAR(300); DECLARE V1 INTEGER; SET STMT = 'CALL USER1.SP2 (I)'; PREPARE ST FROM STMT; EXECUTE ST INTO V1; END%
After being converted to a dynamic SQL-based procedure body, the internal procedure package that is created and associated with the SQL procedure can also make use of the DYNAMICRULES functionality if the registry variable DB2_SQLROUTINE_PREPOPTS is set to one of the six values: BIND, RUN, DEFINEBIND, DEFINERUN, INVOKEBIND, INVOKERUN. To set this registry variable, you can use the following syntax: db2set DB2_SQLROUTINE_PREPOPTS=""
For example, if you want to use the BIND behavior for your dynamic SQL in the stored procedure body, you need to set the registry variable using the following command: db2set DB2_SQLROUTINE_PREPOPTS="DYNAMICRULES BIND"
Because setting the registry variable requires a restart of the Database Manager and because it is applied to all databases in the database instance, DB2 provides an alternative to only set this option for the scope of a connection session. By using the built-in procedure SYSPROC.SET_ ROUTINE_OPTS, you can set the DYNAMICRULES option for only the current connection session. Execute the following CALL SQL statement to enforce the BIND behavior for your dynamic SQL in the stored procedure body (for any SQL procedure created in this session): CALL SYSPROC.SET_ROUTINE_OPTS('DYNAMICRULES BIND');
Authorization Checking for SQL Statements
155
More Ways to Encapsulate In addition to using packages and routines as encapsulating objects, views and triggers can also eliminate the need to grant authorizations to underlying objects. Let’s revisit the view MY_SALARY as an example of a way to encapsulate privileges within a view object: CREATE VIEW MY_SALARY AS (SELECT SALARY FROM HR.SALARY_TABLE WHERE EMP_NAME = SESSION_USER)
Now that the MY_SALARY view limits the employee’s ability to see information beyond his or her need to know, grant each employee SELECT on the view. This eliminates the need to give the employee access to the underlying HR.SALARY_TABLE table. (Only the VIEW DEFINER needs access to the underlying table.) If it becomes necessary to remove access to salary information for a specific user, revoking the user’s SELECT privilege on the MY_SALARY view can be accomplished without affecting any other users. Similarly, triggers can function as encapsulating objects. In Listing 5.2, a trigger is designed to function as an auditor for the insertion activity. Listing 5.2
Example on how to use “Instead of ” Triggers for Auditing Purpose
-- A simple employee table CREATE TABLE EMPLOYEE (NAME VARCHAR (1024), EMPLNUM INTEGER, DEPTNUM INTEGER) -- The exception table to store bad record that is entered CREATE TABLE BADRECORD (NAME VARCHAR (1024), EMPLNUM INTEGER, DEPTNUM INTEGER, REQUESTORID VARCHAR (1024), DATEREQUEST TIMESTAMP, REJECTREASON VARCHAR(30)) -- The transaction_record table CREATE TABLE TRANSACTION_RECORD (EMPLNUM INTEGER, REQUESTORID VARCHAR (1024), DATEREQUEST TIMESTAMP) -- User only interface with this view CREATE VIEW EMPLOYEE_VIEW AS SELECT * FROM EMPLOYEE -- Instead of trigger on the view to function as encapsulating object and auditor CREATE TRIGGER INSERT_EMPLOYEE_V INSTEAD OF INSERT ON EMPLOYEE_VIEW REFERENCING NEW AS NEW_ROW FOR EACH ROW MODE DB2SQL BEGIN ATOMIC DECLARE INVALIDREASON VARCHAR(30); SET INVALIDREASON = CASE WHEN NEW_ROW.EMPLNUM IS NULL OR NEW_ROW.EMPLNUM <= 0 THEN 'EMPLNUM' WHEN NEW_ROW.DEPTNUM IS NULL OR NEW_ROW.DEPTNUM <= 0 THEN 'DEPTNUM' WHEN NEW_ROW.NAME IS NULL THEN 'NAME' ELSE NULL END; IF INVALIDREASON IS NOT NULL THEN INSERT INTO BADRECORD VALUES (NEW_ROW.NAME, NEW_ROW.EMPLNUM, NEW_ROW.DEPTNUM, CURRENT_USER, CURRENT_TIMESTAMP, INVALIDREASON); ELSE
(Continues)
156
Listing 5.2
Chapter 5 • Authorization—Authority and Privileges
Example on how to use “Instead of ” Triggers for Auditing Purpose (Continued)
INSERT INTO EMPLOYEE (NEW_ROW.NAME, NEW_ROW.EMPLNUM, NEW_ROW.DEPTNUM); END IF; INSERT INTO TRANSACTION_RECORD (new_row.emplnum, CURRENT_USER, CURRENT_TIMESTAMP); END%
An end user such as a manager will need to have only INSERT privilege on the view EMPLOYEE_VIEW to add the new employee to the underlying table, EMPLOYEE. Simple error conditions are checked within the trigger, and every insertion will be audited into the TRANSACTION_RECORD table for future reference. The end user does not require access to any of these underlying tables because the trigger initial OWNER authorization ID will be used for authorization checking. In this example, the trigger and the view provide encapsulation of privilege and shield from the user from discovering the underlying business logic activity such as auditing.
WHEN WILL THOSE GRANTS AND REVOKES TAKE EFFECT? You’re granting. You’re revoking. You’re a very busy DBA. Suddenly, it occurs to you that it would be nice to know when these operations are going to take effect. You have come to the right place for that information. The short answer is that GRANTS and REVOKES of authorities or privileges take effect the next time these authorities or privileges are checked against the user. To help understand this process, let’s work through an example. Assume the INSERT access to the underlying table NEWTON.T1 is granted to authorization ID BOSS and user auth ID BOSS’s group auth IDs (or PUBLIC) does not have access to NEWTON.T1. The objective is to use three packages to INSERT two rows to table NEWTON.T1 with the values being supplied (input) from the command line during package execution. Table 5.6 outlines the statement units for each package. If a user holding SYSADM issues db2 "REVOKE INSERT ON TABLE NEWTON.T1 FROM USER BOSS"
between the execution of unit 1 and unit 2, there will be different outcomes for packages BOSS.STATICPKG, BOSS.DYNPKG1, and BOSS.DYNPKG2. The static INSERT SQL statement in BOSS.STATICPKG will succeed, whereas the dynamic REVOKE operation will be in a wait state (waiting on a package lock) until the unit of work has committed (that is, a COMMIT SQL statement is issued) for the package BOSS.STATICPKG. The dynamic INSERT SQL statement in BOSS.DYNPKG2 will fail with insufficient privilege (sqlcode -551), but the dynamic INSERT SQL statement in BOSS.DYNPKG1 will succeed because its privilege was checked during the PREPARE.
Package boss.dynpkg1 (Dynamic SQL) Using DYNAMICRULES BIND— The Dynamic SQL Statement Prepared Once at the Beginning
Package boss.dynpkg2 (Dynamic SQL) using DYNAMICRULES BIND—The Dynamic SQL Statement Prepared at Each Operating Unit
strcpy (hostVarStmt, "INSERT INTO NEWTON.T1 VALUES (?)");
strcpy (hostVarStmt, "INSERT INTO NEWTON.T1 VALUES (?)");
EXEC SQL PREPARE Stmt1 from hostVarStmt;
EXEC SQL PREPARE Stmt1 from hostVarStmt;
EXEC SQL EXECUTE Stmt1 using :hostvar1;
EXEC SQL EXECUTE Stmt1 using :hostvar1;
SYSADM issues a "REVOKE INSERT on table NEWTON.T1 from USER BOSS" here.
—
—
—
2
EXEC SQL INSERT INTO NEWTON.T1 VALUES (:hostvar2);
EXEC SQL EXECUTE Stmt1 using :hostvar2;
strcpy (hostVarStmt, "INSERT INTO NEWTON.T1 VALUES (?)");
EXEC SQL COMMIT;
EXEC SQL COMMIT;
EXEC SQL PREPARE Stmt1 from hostVarStmt;
When Will Those Grants and Revokes Take Effect?
Table 5.6
EXEC SQL EXECUTE Stmt1 using :hostvar2; EXEC SQL COMMIT;
157
158
Chapter 5 • Authorization—Authority and Privileges
The reason the static INSERT SQL statement in BOSS.STATICPKG succeeds is because static SQL uses the static authorization model. (The underlying privileges/authorities are checked at compile time.) At the revocation of privileges or authorities (REVOKE SQL statement), DB2 internally checks that the DEFINER or BINDER of the static SQL object has the required privileges/authorities (via the PUBLIC group) to maintain the existence of the object; otherwise, the object becomes invalidated or inoperable. In this example, the package will be invalidated, and the status field in the system catalog table will be updated. However, because the package is already loaded from the catalog and executing, it will continue to execute until a commit occurs. If the package is accessed again after the commit, an implicit rebind of the package will occur, which will perform the privilege check of the package owner. In the case where the underlying privileges include the EXECUTE privilege on a routine, the revocation will fail if it causes other static SQL objects to become invalidated or inoperable.
OBJECT OWNERSHIP MANAGEMENT In addition to managing the privileges and authorities, the DBA may also be tasked with management of the ownership of SQL objects. This can be a challenging task (even more so when employees or end users move around a lot) and can create a nightmare of authority and privilege management. Consider the case where an end user is an owner for a particular SQL object. Revoking privilege or authority from this user might cause SQL objects to be invalidated or dropped which might not be a desirable behavior. The Orphan Authorization ID Approach The orphan authorization ID approach is one way to handle the object ownership issue before the object is even created. This approach involves the following steps: 1. Designate a DB2 authorization ID that cannot be used for a connection to the database. In other words, it does not have access to the CONNECT privilege directly or indirectly (for example, PUBLIC) or is blocked by the authentication mechanism (for example, invalid or undefined user ID). 2. Grant the required privileges directly to this authorization ID so that it can create and own SQL objects. 3. Grant the SETSESSIONUSER privilege to the user who will be issuing the BIND command or CREATE statements. (Note that only SECADM can grant this privilege; DBADM cannot grant this privilege.) 4. Have the user invoke the SET SESSION AUTHORIZATION (SETSESSIONUSER) statement to switch to the orphaned authorization ID. As this ID, the user can issue the required
Object Ownership Management
159
statements to create the objects desired (or bind the package) followed by appropriate grants. 5. Revoke the SETSESSIONUSER privilege from the user. Example The DBADM needs to implement a procedure that returns the salary of the person whose name is provided in the input parameter. Because SALARY is a sensitive table, the user might not be able to get access to it directly. The DBADM does not want to own this procedure. A workaround involves using the orphan ID SAL_OWNER. The DBADM first grants the SELECT privilege to a new user with the authorization ID SAL_OWNER. The SECADM then grants SETSESSIONUSER ON USER SAL_OWNER to the DBADM. The DBADM sets SETSESSIONUSER as SAL_OWNER and executes the CREATE PROCEDURE statement. The procedure is now defined and owned by SAL_OWNER. Then, the SECADM revokes SETSESSIONUSER on USER SAL_OWNER from the DBADM. For this particular example, you could also make use of LBAC to set up an access policy for each row. Read Chapter 6, “Label Based Access Control,” for more details on the security features that LBAC provides. SYSIBMADM.OBJECTOWNERS
You can retrieve object ownership information from the OBJECTOWNERS administrative view. This view returns all object ownership for every authorization ID of type USER that owns an object and that is defined in the system catalogs. If you want to retrieve the owner of the view NEWTON.EMPLOYEE_VIEW, you can issue the following: db2 "SELECT OWNER FROM SYSIBMADM.OBJECTOWNERS WHERE OBJECTSCHEMA='NEWTON' AND OBJECTNAME = 'EMPLOYEE_VIEW' AND OBJECTTYPE = 'VIEW'"
If you need to find out everything owned by your ID, you could issue the following: db2 "SELECT OBJECTSCHEMA, OBJECTNAME, OBJECTTYPE FROM SYSIBMADM.OBJECTOWNERS WHERE OWNER = SESSION_USER"
Transferring Ownership As this topic implies, ownership of a database object can be transferred to other user authorization IDs. Security administrators (SECADM) or the original definer/owner of the object can perform a transfer of ownership of a given object. However, the security administrator cannot transfer the ownership of an object to himself/herself; otherwise, SQLCODE of -20379 will be returned.
160
Chapter 5 • Authorization—Authority and Privileges
To transfer the ownership of an object to a new owner, the new owner must possess sufficient privileges on the underlying object. That being said, certain SQL objects, such as ALIAS CONSTRAINTS (including primary key, foreign key, and check) DATABASE PARTITION GROUP EVENT MONITOR FUNCTION MAPPING NICKNAME SCHEMA (implicit and explicit created) TABLESPACE DATA TYPE (structured type and distinct type) TYPE MAPPING
do not reference other SQL objects, and thus there is no underlying object; as a result, the new owner does not require any privileges to accept ownership of these objects. Table 5.7 Lists the SYSCAT views that hold information on the database objects and dependencies. Table 5.7
Dependency Catalog Views
Database Objects
Catalog Views
CONSTRAINT
SYSCAT.CONSTDEP
FUNCTION
SYSCAT.ROUTINEDEP SYSCAT.ROUTINES (For a sourced function)
INDEX
SYSCAT.INDEXDEP
INDEX EXTENSION
SYSCAT.INDEXEXTENSIONDEP
METHOD
SYSCAT.ROUTINEDEP
PACKAGE
SYSCAT.PACKAGEDEP
PROCEDURE
SYSCAT.ROUTINEDEP
TABLE
SYSCAT.TABDEP
TRIGGER
SYSCAT.TRIGDEP
VIEW
SYSCAT.VIEWDEP
XSROBJECT
SYSCAT.XSROBJECTDEP
Table 5.8 shows an example of transferring ownership of a SQL object.
Transfer Ownership Example
Description USER2 is the original owner of the source function sourced1.
User auth ID Issuing the SQL Statement USER2
SQL Statement
Output
CREATE FUNCTION SOURCED1 (X INTEGER) All SQL statements return sqlcode SPECIFIC SOURCED1 RETURNS INTEGER of 0 indicating successful operation. SOURCE SYSFUN.ABS (INTEGER)
USER2 granted the execute privilege on his sourced function with the “with grant option” to user zurbie.
GRANT EXECUTE ON SPECIFIC FUNCTION USER2.SOURCED1 TO USER ZURBIE WITH GRANT OPTION
USER2 also granted only execute privilege on his sourced function to user boss.
GRANT EXECUTE ON SPECIFIC FUNCTION USER2.SOURCED1 TO USER BOSS
ZURBIE using the execute privilege with grant option to create a table with check constraint that reference User2’s sourced function.
Description Security administrator performs the transfer ownership of the check constraint from ZURBIE to BOSS.
User auth ID Issuing the SQL Statement SECADM
Output
TRANSFER OWNERSHIP OF CONSTRAINT ZURBIE.MYTABLE.CHECK1 TO USER BOSS
The TRANSFER OWNERSHIP statement returns sqlcode of 0 indicating successful operation.
SELECT TABSCHEMA, TABNAME, CONSTNAME, OWNER FROM SYSCAT.CHECKS WHERE CONSTNAME = "CHECK1" AND TABSCHEMA = "ZURBIE" AND TABNAME = "MYTABLE"
Owner has changed to BOSS.
Chapter 5 • Authorization—Authority and Privileges
Note that despite the fact Database that BOSS does not have the administrator (DBADM) “with grant option” on the or any authorized sourced function, the owneruser who can access ship of the check constraint is the catalog view successfully transferred to BOSS because execute privilege is the minimum required privilege to maintain the existence of the static SQL object—check constraint.
SQL Statement
Last Words
163
LAST WORDS A current understanding of best practices, authorizations, and privileges is critical to the success of a secure DB2 implementation. The importance of a “depth of product knowledge” cannot be overstressed. DB2 knowledge (or lack thereof) will be a prime indicator of the strength of the applied database security. Therefore, a strong DB2 education should precede any implementation. If you are the DBA or SECADM, encourage your management to invest in appropriate training to allow you to polish your DB2 security skills. After reading the descriptions of static versus dynamic authorization models, you might be wondering which authorization model is best? There is no definite rule or answer to this question. It is based on the company security policy and how you want to manage the authorities and privileges. However, in general, the static authorization model allows you to grant to the least privilege to the fewest people. Before you leave this chapter, consider auditing for your authorization process. DB2 provides an instance-level audit facility to record all instance- and database-level activities so that unanticipated access to data can be detected. To learn more about this topic, review Chapter 9.
This page intentionally left blank
CHAPTER
6
Label Based Access Control
unite! One of the best ways to keep out the bad guys is to take control…Label Based D BAs Access Control, that is.
WHAT IS LBAC? A HIGH-LEVEL OVERVIEW Label Based Access Control (LBAC) is an access control mechanism that provides a finer granularity of control over data than has been traditionally provided by table privileges. LBAC restricts access to objects based on the sensitivity (as represented by a security label) of the information contained in the objects and the formal authorization (that is, clearance) of subjects to access information of such sensitivity. By default, a user cannot access data protected by LBAC unless a valid security label is granted. LBAC in DB2 9 is implemented using a security policy formally defined and assigned to a table by the database security administrator. Each security policy describes the format and contents of a security label within that policy and the set of access rules used to determine whether read or write access is to be allowed. Individual security labels are assigned to columns and data rows and to users. When a user attempts to access the protected data, the access rules within the security policy are used to determine whether the access is to be allowed based on the security labels assigned to the user and data involved in the attempted access. Prior to the introduction of LBAC, administrators wanting to have access control for data at the column or row level either had to enforce such logic in their applications or use a combination of views and triggers to ensure that only appropriate data was accessed by each person. In both cases, the enforcement of the access control rules was not pervasive or transparent to the
165
166
Chapter 6 • Label Based Access Control
application layer. With the introduction of LBAC, the access control mechanism is defined directly on the table containing the data so that all data access is controlled and there are no changes required to the application layer to use the LBAC approach to data access control. An additional advantage of LBAC over other approaches it that unlike the others, users with DBADM authority cannot access any data without a formally assigned access label. The LBAC approach emphasizes data security above all other considerations and requires that there exists a formal separation of responsibilities between the general database administration authorities and those individuals specifically responsible for security administration of LBAC. For this reason, LBAC requires the administrator to hold the security administration (SECADM) authority to define and administer security policies over protected data; this is a distinct and separate database authority than the database administrator (DBADM) authority. Unlike a DBADM, security administrators do not have implicit privileges over tables and other database objects and can only perform the specific tasks enabled for them to do in DB2. Neither the SECADM nor DBADM authority can access LBAC-protected data without being assigned a specific access label by a second party. This chapter introduces you to the basic concepts of LBAC, including how the different pieces work together, with a step-by-step guide user-case scenario to demonstrate how to develop an LBAC solution in a production environment. The chapter also covers some tasks that security administrators might come across when they manage the secured tables. The DBA should be aware, however, that LBAC is not a standalone function. After protection is applied to tables, other utilities that interact with the protected tables could be impacted. It is essential for security administrators to understand the possible side effects to other operations after LBAC is applied.
THE LBAC ARCHITECTURE LBAC introduces three new database objects: • Security label component • Security policy • Security labels The LBAC objects can be created and maintained only by a security administrator. One must have SECADM authority to execute the CREATE or DROP statements for the LBAC objects. For details about SECADM authority, see Chapter 5, “Authorization—Authority and Privileges.”
The LBAC Architecture
167
Element
{ { Security Label Components
Figure 6.1
Security Labels
Security Labels
Security Policy A
Security Policy B
The relationship between various LBAC objects
Security Label Components A security label component is the basic building block for security labels. It can be used to model the security structure of the data to be protected. Security labels that will be attached to protected data and granted to users will be created based on the elements of the security label component. A security label component is a database object that can be created and dropped. However, after the security label component has been created, the definition cannot be altered. There are three types of security label components: ARRAY, SET, and TREE. An ARRAY is an ordered set of elements. The first element in the list has the highest rank, and the last element has the lowest rank. For instance, if we need to tag data with three levels of confidentiality: ‘Highly Sensitive,’ ‘Sensitive,’ and ‘Public,’ you could create a security label component as follows: CREATE SECURITY LABEL COMPONENT LEVEL ARRAY ['Highly sensitive', 'Sensitive', 'Public']
A SET is an unordered set of elements: CREATE SECURITY LABEL COMPONENT COMPARTMENTS SET {'Collection', 'Research', 'Analysis'}
168
Chapter 6 • Label Based Access Control
TREE elements are arranged in a tree structure. Each element in the three structures has a parent, except the first element, which must be specified as the root of the tree. For instance, to model the organization hierarchy, the ‘Corporate’ is at the top level of the hierarchy. The branches at various regions are ‘Asia,’ ‘North America,’ and ‘Europe.’ Then, the ‘North America’ market is further categorized into ‘US’ and ‘Canada.’ The security label component can be created as a tree structure as follows: CREATE SECURITY LABEL COMPONENT REGIONS TREE ( 'Corporate' ROOT, 'Asia' UNDER 'Corporate', 'North_America' UNDER 'Corporate', 'Europe' UNDER 'Corporate', 'US' UNDER 'North_America', 'Canada' UNDER 'North_America' )
Note that the maximum number of elements allowed for a security label component is 64.
LBAC Security Policies The LBAC security policy defines the following: • The set of security label components to be used for creating security labels • The access rules used to determine whether a user with security label_X can access the data protected with label_Y CREATE SECURITY POLICY DATA_ACCESS COMPONENTS LEVEL, COMPARTMENTS, REGIONS WITH DB2LBACRULES RESTRICT NOT AUTHORIZED WRITE SECURITY LABEL
The DB2 system provides a set of rules, DB2LBACRULES, for comparing the values of security label components. The set of rules defines how the read-and-write access is enforced. In DB2 9, the DB2 system does not support customized LBAC rules. Security administrators can use the predefined set of rules provided by the DB2 system. More detail about the access rules and how LBAC is enforced is covered in the “How LBAC Is Enforced” section later in this chapter. When you are creating a protected table, the table can be attached only to one security policy. You can use a security policy to protect multiple tables. The security administrator can also define multiple security policies in a database to protect different tables.
Security Labels Security labels are applied to table data for restricting access. They are granted to database users for accessing protected data. Each security label is associated with a security policy and is constructed using the elements of the security label components defined for such security policy.
The LBAC Architecture
169
The security labels can be configured to represent the criteria of who can access what data. For instance, if the DBA needs to restrict access to most users but also needs to allow the executives to access highly sensitive data, a security label to provide this functionality can be written as follows: CREATE SECURITY LABEL DATA_ACCESS.SL_EXECUTIVESECLABEL COMPONENT LEVEL 'Highly sensitive', COMPONENT COMPARTMENTS 'Collection', 'Research', 'Analysis', COMPONENT REGIONS 'Corporate'
Row Security Labels A row security label is stored in a column of type SYSPROC.DB2SECURITYLABEL within each data row. The column stores the name of the security label. When a row is inserted into the protected table, the user can specify the security label to be inserted. The security label must belong to the security policy that is protecting the table. If no security label is provided in the INSERT statement, the security label granted to the user for write access is used.
Column Security Labels A security label for column protection is attached to the column. A protected table may contain several protected columns each attached to a security label, which associates with the security policy attached to the table. The security label information is stored in the SYSCAT.COLUMNS catalog table.
User Security Labels To access protected data, a user needs to be granted security labels. A security label can be granted to a user for reading, and another one for writing, but limited to a maximum of one security label per access type per security policy. When a user tries to access protected data, the user’s security label is compared to the security label protecting the data. A user can see only data that is allowed by the associated access rules.
Exemptions An exemption provides a way to bypass certain access rules in a particular security policy. For instance, an executive is allowed to read data of any COMPARTMENTS. Therefore, instead of creating a security label with all COMPARTMENTS elements, an exemption can be granted as follows on the DB2LBACREADSET rule: GRANT EXEMPTION ON RULE DB2LBACREADSET FOR DATA_ACCESS TO USER EXECUTIVE
170
Chapter 6 • Label Based Access Control
A user can be granted multiple exemptions. If a user is granted with an exemption to every rule used by a security policy, the user can access all the protected data of the table. The security administrator must take extra precaution in granting exemptions to users because when an exemption is granted to a user, you lose control over the actions that a user can take on the protected data.
Protected Table A table can be protected with row protection or column protection or both. A table becomes a protected table when it is attached to a security policy. Tables can be protected with row level granularity. The table is attached to a security policy, and one of the columns is of type DB2SECURITYLABEL to hold the security label that protects the row data. A table can be marked protected during creation time in the CREATE TABLE statement, or protection can be added to an existing table using the ALTER TABLE statement. If you want to create a protected table ProtTable with SECCOL as the column to store the security label, use CREATE TABLE PROTTABLE (C1 char(10), C2 int, SECCOL DB2SECURITYLABEL ) SECURITY POLICY DATA_ACCESS
Existing tables can be altered to be row-level protected by attaching a security policy to the table and adding a DB2SECURITYLABEL column to store the security label in the records: ALTER TABLE PROTTABLE ADD COLUMN SELCOL DB2SECURITYLABEL ADD SECURITY POLICY DATA_ACCESS
A table protected with column-level granularity is attached to a security policy. One or more columns are associated with the security label defined on such security policy. A table can be marked as protected during creation time in the CREATE TABLE statement, or protection can be added to an existing column using the ALTER TABLE statement. If you want to create a protected table ProtTable and protect pCol with the security label DATA_ACCESS.SL_HIGH_SENSITIVE, use CREATE TABLE PROTTABLE3 (C1 char(10), C2 int, pCol int SECURED WITH SL_HIGH_SENSITIVE ) SECURITY POLICY DATA_ACCESS
How LBAC Is Enforced
171
You can alter existing tables to be column-level protected by attaching a security policy to the table and securing an existing column with a security label: ALTER pCol SECURED WITH SL_HIGH_SENSITIVE ADD SECURITY POLICY DATA_ACCESS
HOW LBAC IS ENFORCED When a user attempts to access protected data, the LBAC rules enforce access restriction. For each read-or-write operation on the protected table, the security label granted to the user is compared with the security label used to protect the table data. A user can be granted a read security label and a write security label for each security policy. The read security label is used when a user attempts read access against a protected table. Read access occurs in a number of explicit and implicit ways: A SELECT statement on a protected table is an explicit attempt while less obvious attempts occur within a subselect clause of an UPDATE or DELETE statement. The write security label is applied when a user attempts to modify protected data such as through an INSERT, UPDATE, or DELETE statement on a protected table. Each security label component type has a rule for read access and a rule for write access. Access is not allowed when the user security label cannot meet the condition of the access rule. One aspect of LBAC that is important to keep in mind is that for all access to a protected table, it is always the access labels granted to the session authorization ID that are used to determine the user’s ability to succeed in the attempted access. Unlike the authorization ID used for privilege checking, access labels cannot be inherited from other authorization IDs through mechanisms such as views, the DYNAMICRULES bind option, or static SQL statements. In all cases, it is the session authorization ID that is used by LBAC and not the authorization of the statement or database object such as a view or trigger. In other words, whereas the SQL statement authorization ID is the one used by DB2 9 for authorization checking, it is the session authorization ID (that will actually receive the data) that is analyzed by LBAC for eligibility. When you create a security policy, you must specify the LBAC rule set that will be used with that policy to control access. Security labels that belong to the security policy are compared using the LBAC rule set. In DB2 9, a predefined set of rules, DB2LBACRULES, is provided to be used to enforce LBAC.
Read Access Rules The read security label is used when a user attempts to read against a protected table. The read access rules occur explicitly when a SELECT statement is executed and implicitly during UPDATE and DELETE operations.
172
Chapter 6 • Label Based Access Control
The security label may be made up of elements from the security label component of type ARRAY, SET, or TREE. Each component type has a read access rule: • DB2LBACREADARRAY governs the read access to the ARRAY component. The elements in the user’s security label must not be lower than the elements in the data row’s security label. Otherwise, access is not allowed. • DB2LBACREADSET governs the read access to the SET component. The SET component in the user’s security label must include each element of the SET component in the data row’s security label. • DB2LBACREADTREE governs the read access to the TREE component. The user’s security label must include at least one of the elements in the TREE component that is equal to or ancestor of the data row’s security label. For row access, the DB2 system obtains the security label granted to the user, and for each row the user tries to access, the read access rules of the security policy associated to the protected table takes effect. If the read access rule does not permit the user access, the row is discarded, and no error is returned. For column access, if the user cannot access the column, an error is returned.
Write Access Rules The write security label is used when a user attempts to write against a protected table during INSERT, UPDATE, or DELETE operation. Each component type ARRAY, SET, and TREE has a write access rule: • DB2LBACWRITEARRAY governs the write access to the ARRAY component. The user’s security label must be equal to the ARRAY component of the data row’s security label. If the user needs to write a value which is higher or lower than the values of their write security label, an exemption on the DB2LBACWRITE ARRAY can be granted to the user with WRITE-UP or WRITE-DOWN option. WRITE-UP allows the session authorization ID to write with a security label that has higher value that the write security label of the user. WRITE-DOWN allows the session authorization ID to write with a security label that has lower value than the write security label of the user. By default, the user can write only with the same value of the write security label that the user holds. • DB2LBACWRITESET governs the write access to the set component. The user’s security label must include each set component of the data row’s security label. • DB2LBACWRITETREE governs the write access to the tree component. The user’s security label must include at least one of the elements in the TREE component that is equal to or ancestor of the data row’s security label.
How LBAC Is Enforced
173
For row access, data that can be written must be a subset of the data that can be read. (That is, the write rules explicitly reinforce the read rules.) If the security policy associated with the protected table does not permit the access, the row cannot be inserted, updated, or deleted. A security violation is returned. The same behavior applies to column access. Table 6.1
Summary of the DB2LBACRULES
Type of Component
Rule Name
Type of Access
Access Is Allowed in the Following Conditions
DB2LBACREADARRAY
Read
The user’s value is higher or equal than the protecting value.
DB2LBACWRITEARRAY
Write
The user’s value is equal to the protecting value.
DB2LBACREADSET
Read
The user value contains all the protecting values.
DB2LBACWRITESET
Write
DB2LBACREADTREE
Read
DB2LBACWRITETREE
Write
ARRAY
SET
TREE The user’s value is equal to or an ancestor of one of the protecting values.
Let’s see some examples on how the rules are applied in comparing the elements of a security label.
Array Security Label Component Suppose we have an ARRAY security label component [‘Sensitive’, ‘General’, ‘Unclassified’], where ‘Sensitive’ ranks the highest, and ‘Unclassified’ ranks the lowest.
174
Chapter 6 • Label Based Access Control
Table 6.2 Compare the User Security Label and the Data Security Label Based According to the Read-and-Write Access Rules for Array Security Label Component User Security Label
Data Security Label
Read Access Allowed by DB2LBACREADARRAY?
Write Access Allowed by DB2LBACWRITEARRAY?
‘(Sensitive)’
‘(Sensitive)’
Allowed: Same value.
‘(Sensitive)’
‘(General)’
Allowed: ‘Sensitive’ is higher than ‘General’.
Not allowed by default. Allowed if exemption is granted on write-down access.
‘(General)’
‘(Sensitive)’
Not allowed: ‘General’ is lower than ‘Sensitive’.
Not allowed by default. Allowed if exemption is granted on write-up access.
‘(General)’
‘()’
Allowed: Protecting value is empty.
Not allowed since empty is lower than ‘General’. Allowed if exemption is granted on write-down access.
‘()’
‘(General)’
Not allowed: Empty value is blocked by nonempty protecting value.
‘()’
‘()’
Allowed: Protecting value is empty.
Set Security Label Component Suppose we have a SET security label component {‘sales’, ‘hr’, ‘r&d’}. Table 6.3 Compare the User Security Label and the Data Security Label Based According to the Read-and-Write Access Rules for Set Security Label Component User Security Label
Data Security Label
Access Allowed by B2LBACREADSET/DB2LBACWRITESET?
‘(sales, r&d)’
‘(sales, r&d)’
Allowed: Same value.
‘(sales, r&d)’
‘(sales)’
Allowed: User value contains all the elements of the protected value.
‘(sales)’
‘(sales, r&d)’
Not allowed: User value does not have ‘r&d’.
‘(sales)’
‘()’
Allowed: Protecting value is empty.
‘()’
‘(sales)’
Not allowed: Empty value is blocked by nonempty protecting value.
‘()’
‘()’
Allowed: Protecting value is empty.
How LBAC Is Enforced
175
Tree Security Label Component Suppose we have a TREE security label component as follows. HEAD_QUARTER
WEST
CENTRAL
CENTRAL_SOUTH
Figure 6.2
EAST
CENTRAL_NORTH
The security label component has a TREE structure
Table 6.4 Compare the User Security Label and the Data Security Label Based According to the Read-and-Write Access Rules for Tree Security Label Component User Security Label
Data Security Label
Access Allowed by DB2LBACREADTREE/ DB2LBACWRITETREE?
‘(HEAD_QUARTER)’
‘(CENTRAL)’
Allowed: ‘HEAD_QUARTER’ is the ancestor of ‘CENTRAL’.
Allowed: User value contains all of the elements of the protected value.
‘(CENTRAL)’
‘(CENTRAL, EAST, WEST)’
Allowed: User value contains at least one element of the protected value.
‘(WEST)’
‘(EAST)’
Not allowed: ‘WEST’ does not contain ‘EAST’ nor is an ancestor of ‘EAST’.
‘(WEST)’
‘()’
Allowed: Protecting value is empty.
‘()’
‘(WEST)’
Not allowed: Empty value is blocked by nonempty protecting value.
‘()’
‘()’
Allowed: Protecting value is empty.
Exemptions Exemptions for one or more access rules could be granted to a user so that these specific access rules will not be applied when a protected table is accessed by the user to whom the exemption is granted.
176
Chapter 6 • Label Based Access Control
Exemptions can be granted to any of the read-and-write access rules. For the predefined DB2LBACRULES, there are six access rules: DB2LBACREADSET DB2LBACREADARRAY DB2LBACREADTREE DB2LBACWRITESET DB2LBACWRITEARRAY DB2LBACWRITETREE Syntax: >>-GRANT EXEMPTION ON RULE--+-access-rule-+--FOR--policy-name---> '-ALL---------' >--TO USER--authorization-name---------------------------------><
Only a security administrator (that is, a user holding SECADM) has the authority to grant and revoke exemptions from users. When granting an exemption on the DB2LBACWRITEARRAY rule, there are two options: WRITEUP and WRITEDOWN. Writeup exemption is granted to allow the user to write with a security label that has elements higher than the elements in the user security label. Writedown exemption is granted to allow the user to write a security label that contains elements lower than the elements in the user security label. The options are for ARRAY security label component type only. There is not writeup or writedown for TREE and SET security label component. By default, neither writeup nor writedown is allowed. The user can only write data that is protected by the same security label value that the user is granted. Exemption can also be granted on all the access rules by issuing this statement: GRANT EXEMPTION ON RULE ALL FOR <security policy> TO USER <session authorization id>
This implies that one can have complete access to all protected data of such a policy. Exemption on all the write rules would be useful if a user needs to load data into a protected table. This exemption should be granted with extra precaution because granting exemption on all rules implies the user has full write access to the protected table. It is a best practice to revoke the exemption when the access is not needed.
The Security Plan for Protecting Data
177
THE SECURITY PLAN FOR PROTECTING DATA Security Plan Meeting Participants When designing an LBAC solution, the security administrator has to work with the database administrator to create a plan; decide what data is sensitive and needs to be protected, and how the data can be protected using the LBAC objects; and to determine who owns the table data and who officially requires access to the protected data. It is the job of the security administrator to create and maintain the LBAC objects. The security administrator also has the authority to grant security labels and exemptions to users, and revoke them if access is no longer needed. After the LBAC objects are created and granted to users, users can apply the security policy to protect tables with sensitive data. As discussed in Chapter 2, “DB2 Security—The Starting Point,” a security plan should be reviewed regularly to ensure sensitive data is protected and user access to protected data is properly granted.
Designing the Security Solution Designing an LBAC solution to protect table data involves several steps. First, you need to analyze and identify the security requirements: • Which table contains sensitive data • What data is sensitive and needs to be protected • The level of data restrictions required Then, you need to determine who is allowed to access the protected data and the level of access. After the security requirements have been established, the next step is to design the security solution with the LBAC objects. When designing the security solution, you need to consider the following: • The row and column security labels that need to protect the columns and rows • The user security labels that grant users the appropriate access • The security label components that create the security labels • Any exemptions required to bypass certain access restrictions
178
Chapter 6 • Label Based Access Control
Activity Overview for Implementing an LBAC Solution Implementing an LBAC solution requires the following steps: 1. Create the security label components, which are essential elements for creating the security policy in the next step. 2. After the security label components are created, define the LBAC security policies by specifying what security label components are to be used. 3. Then, create the security labels for the security policy using the elements of the security label components associated with the security policy. 4. With the security policy and security labels ready, the security administrator can grant security labels to users to create protected tables. 5. The SECADM then needs to grant the security labels to users for accessing the protected table. Currently, LBAC does not offer an approach to alter the security label format, base security policy attributes, or elements in a security label component. Therefore, the design phase for an LBAC solution is a crucial step to be sure security objects are created that meet the security needs. See Figure 6.3 for a graphical overview of the necessary steps to enable an LBAC solution.
Manipulating Data in Protected Tables
Authid with CREATE table privilege
179
SECADM
User
Create Security Label Component
Create Security Policy
Create Security Label
Grant security label to authid(U) to create protected tables
Create protected table
Grant security label to authid(U) to create protected tables
Grant Exemption on access rule to authid(U) if needed
Operate on Protected Table
Figure 6.3 The activity diagram demonstrates the workflow used to apply LBAC to enable access controls on database tables
MANIPULATING DATA IN PROTECTED TABLES Data manipulation includes read, write, and delete records. Actions are done by SELECT, INSERT, UPDATE, and DELETE SQL statements. When data is manipulated in protected tables, the user security label is compared with the security label protecting the row or column according to the access rules defined by the security policy.
180
Chapter 6 • Label Based Access Control
Insert Data Records into Protected Tables To populate a protected table with data, you can use the INSERT statement to write one record at a time. Similar to inserting data to a regular table, the authorization ID of the statement must have INSERT privilege on the table. The authorization ID of the session needs the following to insert a record into a row protected table successfully: • Hold a security label with write access that belongs to the security policy which protects the table • May need to hold an exemption on one or more write access rules of the security policy that protects the table When inserting a record into a row protected table, you are not required to explicitly specify the security label for the DB2SECURITYLABEL column in the INSERT statement. By default, the security label granted to the user for write access is used. Users can also INSERT with any value that the LBAC write access rules allow them to. The DB2 system compares the user’s security label and the security label used for insertion based on the access rules used by the security policy. Depending on how the security policy is created, there are two possible outcomes if the write access rule is violated: • If the security policy is created with the option RESTRICT NOT AUTHORIZED WRITE SECURITY LABEL, the INSERT operation fails and an error is returned. • If the OVERRIDE NOT AUTHORIZED WRITE SECURITY LABEL option is specified in the CREATE SECURITY POLICY statement, or no option is specified, the INSERT operation is successful. However, the default write security label is used rather than the security label specified by the user. No error is returned. When inserting a record into a column-protected table, one or more columns is attached to a security label. The user’s security label will be compared with the security label that protects the column. If the comparison fails, the record is not inserted into the table. A user can hold only one security label for read access and one security label for write access. Those security labels could be the same or different. If the user does not have a read security label but has a write security label, the user could still INSERT a record using the VALUES clause because such an INSERT requires only write access. However, the user cannot read the record after INSERT.
Retrieve Data Records from a Protected Table Data records are retrieved from a protected table in a number of ways, such as with SELECT statements. The authorization ID of the statement is required to have SELECT privilege on the table, and the session authorization ID needs to be granted with a security label with read access or exemption on read access rule in some cases.
Manipulating Data in Protected Tables
181
For tables with protected rows, each record (row) contains a security label. When a user issues a SELECT query on the protected table, the security label granted to the user for read access is compared with the security label in the record. The read access rule determines whether the record is returned in the result set. No error is returned if the user is not allowed to read a record. For tables with column protection, each protected column is attached to a security label. The security label is stored in the system catalog table SYSCAT.COLUMNS. When a user issues a SELECT query on a column-protected table, the security label granted to the user for read access will be compared with the security labels that are attached to the columns. The read access rule determines whether the user is allowed to read the column. If read access is not allowed, an error is returned and no rows will be returned.
Update Data Records in a Protected Table To update a table, the authorization ID of the statement is required to have UPDATE privilege on the table. Similar to inserting data records into a protected table, to successfully update records into a protected table, the session authorization ID must have been granted with a valid security label or exemption to read and write the record. Updating a row involves reading a row and writing new values to the row. Therefore, the user must hold a security label allows them to read the protected row, and a security label with write access or exemption to write new values to the protected field. If the user is updating unprotected fields, no security label with write access is required. When you are updating a table with a protected column, the access restrictions apply only when updating the protected column. If a table contains some protected columns, but no protected rows, users are not required to hold a security label with write access if they want to update unprotected columns. If executing an UPDATE statement does not update a record due to an LBAC restriction, the user may or may not see an error message. The behavior can be summarized as follows. Table 6.5
Result of UPDATE Operation Based on Read-and-Write Security Labels Granted
Has READ Access?
Has WRITE Access?
Result of UPDATE
Yes
Yes.
Successful
Yes
No, but has write security-label granted. Security policy is created with RESTRICT NOT AUTHORIZED WRITE SECURITY LABEL option.
Fail with error SQL20402N. The authorization ID does not have the LBAC credentials to perform the UPDATE operation on the table. continues
182
Chapter 6 • Label Based Access Control
Table 6.5 Result of UPDATE Operation Based on Read-and-Write Security Labels Granted (Continued) Has READ Access?
Has WRITE Access?
Yes
No, but has write security label granted. Security policy is created with OVERRIDE NOT AUTHORIZED WRITE SECURITY LABEL option.
Result of UPDATE Successful, but the write security label of the session authorization ID will be used in the UPDATE operation.
Yes
No write security label is granted.
Fail with error SQL20402N.
No
—
Failed because no row is fetched. SQL0100W returned.
Delete Data Records from a Protected Table To delete records from a table, the authorization ID of the statement is required to have DELETE privilege on the table, and the session authorization ID needs to be granted with a security label with read-and-write access, or exemption on the access rules in some cases. When a user attempts to delete some protected rows from a table, only the set of rows that the user is allowed to read and write can be removed from the table. If a user cannot read a row, the row appears to be invisible to the user and cannot be deleted. No error is returned. If a user can read the row, then, when trying to delete the row, the user’s write security label is compared to the security label that is protecting the row. If the user does not have write access to the row, the DELETE statement fails. Error SQL20264N is returned. When deleting rows in a table with protected columns, the user must have write access to all the protected columns in the table. Otherwise, SQL20264 is returned.
MANIPULATING DATA WITH SECURITY LABEL WITH SET SECURITY LABEL COMPONENT Inserting with a Security Label of SET Security Label Component An INSERT operation needs to satisfy the DB2LBACWRITESET access rule when a table is protected with security labels of the SET security label component. The DB2LBACWRITESET requires that the elements in the security label protecting the row/ column need to be a subset of the elements in the write security label of the session authorization ID to insert a record successfully.
Manipulating Data with Security Label with SET Security Label Component
183
Scenario The EMPLOYEE table contains sensitive data. Employees can view records of others in the same department. The SALARY column has restrictive access and can only be viewed by managers. Managers cannot write to the SALARY column. Note that for the sake of simplifying the example, all references to prerequisite privileges have been removed but the reader is reminded that table privileges are still required for any access to a protected table prior to LBAC enforcement. A security label component is created for protecting the EMPLOYEE table. • SLC_DEPT of SET component type is created with elements {‘D001’, ‘D002’, ‘D003’, ‘MGMT’} based on the departments in the company. A security policy EMPLOYEE_POLICY is created with SLC_ DEPT security label components, with the RESTRICT NOT AUTHORIZED WRITE SECURITY LABEL option. The following security labels are created: Security Label Row security labels: EMPLOYEE _POLICY.SL_D001 EMPLOYEE _POLICY.SL_D002 EMPLOYEE _POLICY.SL_D003
Security label component elements D001 D002 D003
Column security labels: EMPLOYEE_POLICY.SL_MGMT
MGMT
User security labels: EMPLOYEE _POLICY.SL_D001_M EMPLOYEE _POLICY.SL_D002_M EMPLOYEE _POLICY.SL_D003_M
D001, MGMT D002, MGMT D003, MGMT
The EMPLOYEE table is protected by the EMPLOYEE_POLICY. The SEC_LABEL column stores the security label which identifies the department that an employee belongs to. The record for a manager would tag with the ‘MGMT’ element. The Salary column is protected by the SL_MGMT security label. The EMPLOYEE table contains the following records. Table 6.6
EMPLOYEE Table
EMPNO
FIRSTNME
LASTNAME
PHONE
SEC_LABEL
SALARY (Attached to SL_MGMT)
121
Joe
Cool
905-384-2642
SL_D001
65000
211
Ray
Summer
905-979-2321
SL_D002
60000
321
Jane
Lu
416-343-3432
SL_D003
70000 continues
184
Table 6.6
Chapter 6 • Label Based Access Control
EMPLOYEE Table (Continued)
EMPNO
FIRSTNME
LASTNAME
PHONE
SEC_LABEL
SALARY (Attached to SL_MGMT)
111
Mike
Smith
416-343-3566
SL_D001_M
80000
212
Carol
Mo
647-804-2232
SL_D002_M
85000
311
Peter
San
416-784-3343
SL_D003_M
90000
Users of the EMPLOYEE table are granted with security labels. Table 6.7
Security Labels Granted to Session Authorization ID
Session authorization ID
Read security label
Write security label
JOEC
SL_D001
None
RAYS
SL_D002
None
JANEL
SL_D003
None
MIKES
SL_D001_M
SL_D001
CAROLM
SL_D002_M
SL_D002
PETERS
SL_D003_M
SL_D003
Example Mike tries to insert a record into the EMPLOYEE table by executing the following statement: INSERT INTO EMPLOYEE (EMPNO, FIRSTNME, LASTNAME, PHONE, SEC_LABEL) VALUES ('122', 'Katy', 'Sun', '905-212-5533', SECLABEL_BY_NAME('EMPLOYEE_POLICY', 'SL_D001'))
The INSERT operation is successful because the row security label contains only the element ‘D001’, which is the subset of his write security label {‘D001’}. Mike does not have the authority to write to the SALARY column because his write security label contains the ‘D001’ element only, but the SALARY column is protected by a security label with element ‘MGMT’. The INSERT would fail if the SALARY column is not nullable and does not have a default value.
Manipulating Data with Security Label with SET Security Label Component
185
The EMPLOYEE table now becomes this. Table 6.8
EMPLOYEE Table
EMPNO
FIRSTNME
LASTNAME
PHONE
SEC_LABEL
SALARY
121
Joe
Cool
905-384-2642
SL_D001
65000
122
Katy
Sun
905-212-5533
SL_D001
211
Ray
Summer
905-979-2321
SL_D002
60000
321
Jane
Lu
416-343-3432
SL_D003
70000
111
Mike
Smith
416-343-3566
SL_D001_M
80000
212
Carol
Mo
647-804-2232
SL_D002_M
85000
311
Peter
San
416-784-3343
SL_D003_M
90000
Example Mike is assisting Carol. He tries to insert a record for her department by issuing this: INSERT INTO EMPLOYEE (EMPNO, FIRSTNME, LASTNAME, PHONE, SEC_LABEL) VALUES ('216', 'Alex', 'Wood', '905-434-7454', SECLABEL_BY_NAME('EMPLOYEE_POLICY', 'SL_D002'))
Mike is holding a write security label with elements {‘D001’}. However, he is using a security label with security label component elements {‘D002’}. Because ‘D002’ is not in the subset of the user security label {‘D001’}, the DB2LBACWRITESET rule is violated. Because the EMPLOYEE_POLICY is created with the RESTRICT NOT AUTHORIZED WRITE SECURITY LABEL option, the statement would fail during execution. SQL20402N is returned. The authorization ID does not have the LBAC credentials to perform the INSERT operation on table. No record is inserted. If EMPLOYEE_POLICY is created with the OVERRIDE NOT AUTHORIZED WRITE SECURITY LABEL option, the INSERT operation will succeed, but the SECL_LABEL column will be inserted with SL_D001 because it is the write security label granted to Mike.
Retrieve Data Records Protected by SET Security Label Component Elements When a table is protected with security labels of the SET security label component, a SELECT operation needs to satisfy the DB2LBACREADSET access rule.
186
Chapter 6 • Label Based Access Control
The DB2LBACREADSET requires that the elements in the security label protecting the row/column need to be a subset of the elements in the read security label of the session authorization ID to insert a record successfully. When data is retrieved from a protected table, the read security label of the session authorization ID will be compared with the security label in the DB2SECURITYLABEL column and any security label attached to a protected column if a protected column is accessed. Example Joe is granted with the read security label SL_D001 when he issues the query SELECT * from EMPLOYEE
Access is denied because Joe does not have authority to read the SALARY column. SQL20264N is returned because the authorization ID does not have READ access to the SALARY column. Example Joe then queries the EMPLOYEE table by specifying the unprotected columns explicitly: SELECT EMPNO, FIRSTNME, LASTNAME, PHONE from EMPLOYEE
The SL_D001 is compared with the labels stored in the SEC_LABEL column. Table 6.9 the Rows
Joe’s Read Security Label Is Compared to Data Security Label for Read Access of
EMPNO
SEC_LABEL
Security Label Comparison
121
SL_D001
Allowed
122
SL_D001
Allowed
211
SL_D002
Not allowed: because SL_D001 does not contain element D002
321
SL_D003
Not allowed: because SL_D001 does not contain element D003
111
SL_D001_M
Not allowed: because SL_D001 does not contain element MGMT
212
SL_D002_M
Not allowed: because SL_D001 does not contain element D002 and MGMT
311
SL_D003_M
Not allowed: because SL_D001 does not contain element D003 and MGMT
Therefore, two records are returned.
Manipulating Data with Security Label with SET Security Label Component
Table 6.10
187
Joe Can See the Two Rows in the EMPLOYEE Table
EMPNO
FIRSTNME
LASTNAME
PHONE
121
Joe
Cool
905-384-2642
122
Katy
Sun
905-212-5533
Joe cannot see other records because the row security labels used to protect other rows contain elements that Joe’s read security label does not have. Example Carol is granted with the SL_D002_M for read access. The security label contains the elements D002 and MGMT, which allow her to read rows protected by a security label that matches or is a subset of the two elements when she issues this query SELECT EMPNO, FIRSTNME, LASTNAME, PHONE, VARCHAR(SECLABEL_TO_CHAR('EMPLOYEE_POLICY', SEC_LABEL )), SALARY FROM CKMWONG.EMPLOYEE;
The SL_D002_M is compared with the security labels attached to protected column, SALARY, and the security label stored in the SEC_LABEL column. Table 6.11 Carol’s Read Security Label Is Compared to Data Security Label for Read Access of the Rows EMPNO
SEC_LABEL
Security Label Comparison
121
SL_D001
Not allowed: because SL_D002 does not contain element D001
122
SL_D001
Not allowed: because SL_D002 does not contain element D001
211
SL_D002
Allowed
321
SL_D003
Not allowed: because SL_D002 does not contain element D003
111
SL_D001_M
Not allowed: because SL_D002 does not contain element D001
212
SL_D002_M
Allowed
311
SL_D003_M
Not allowed: because SL_D002 does not contain element D003
188
Chapter 6 • Label Based Access Control
The two records protected with security labels that contain any of the elements {‘D002’, ‘MGMT’} are returned. Table 6.12 Carol’s Read Security Label Is Compared to Data Security Label for Read Access of the Rows EMPNO
FIRSTNME
LASTNAME
PHONE
SEC_LABEL
SALARY
211
Ray
Summer
905-979-2321
SL_D002
60000
212
Carol
Mo
647-804-2232
SL_D002_M
85000
Example HR staff member, Nancy, is allowed to read all the records in the EMPLOYEE table. There are two ways to accomplish it: 1. Create a security label that contains all the elements. 2. Grant Nancy the DB2LBACREADSET exemption. Granting exemption is not recommended because the user can bypass the read access rules for SET security label components. You will lose control over the action of the user both for existing security labels and any security labels created in the future that is associated with the security policy.
Updating Data Records Protected by SET Security Label Component Updating protected records requires that the user has read and write access on the record. This implies that both DB2LBACREADSET and DB2LBACWRITESET access rules have to be satisfied. Example Peter holds the security label SL_D003_M for read access and SL_D003 for write access. When Peter issues the following UPDATE statement UPDATE EMPLOYEE SET LASTNAME = 'WHITE' WHERE EMPNO='321'
the row is protected by the security label SL_D003, which matches the user read security label. Because Peter is updating a nonprotected column, write security label is not required. The statement executed successfully.
Manipulating Data with Security Label with SET Security Label Component
189
Example Peter issues the following UPDATE statement: UPDATE EMPLOYEE SET LASTNAME = 'WHITE' WHERE EMPNO='211'
The row is protected by the security label SL_D002. The read security label that Peter holds does not contain the elements in SL_D002. Read access is violated. Message SQL0100W is returned. No row was found for SELECT, UPDATE, or DELETE; or the result of a query is an empty table. The table is not updated because Peter cannot read the row in the first place. Example Peter issues the following UPDATE statement: UPDATE EMPLOYEE SET SECLABEL = SECLABEL_BY_NAME('EMPLOYEE', 'SL_D001') WHERE EMPNO='321'
The statement fails. Peter holds the read security label SL_D003_M and thus is allowed to read the record. However, the DB2LBACWRITESET rule is violated because Peter holds the SL_D003 security label, which does not contain the element ‘D001’. Because the EMPLOYEE_POLICY is created with the RESTRICT NOT AUTHORIZED WRITE SECURITY LABEL option, the statement would fail to execute. SQL20402N is returned because authorization ID does not have the LBAC credentials to perform the UPDATE operation on table. Example The current EMPLOYEE table contains the following Table 6.13
EMPLOYEE Table
EMPNO
FIRSTNME
LASTNAME
PHONE
SEC_LABEL
SALARY
121
Joe
Cool
905-384-2642
SL_D001
65000
122
Katy
Sun
905-212-5533
SL_D001
211
Ray
Summer
905-979-2321
SL_D002
60000
321
Jane
WHITE
416-343-3432
SL_D003
70000
111
Mike
Smith
416-343-3566
SL_D001_M
80000
212
Carol
Mo
647-804-2232
SL_D002_M
85000
311
Peter
San
416-784-3343
SL_D003_M
90000
190
Chapter 6 • Label Based Access Control
Peter issues the following UPDATE statement: UPDATE EMPLOYEE SET PHONE ='905-423-8302' WHERE SECLABEL = SECLABEL_BY_NAME('EMPLOYEE', 'SL_D003')
Because Peter holds the SL_003_M security label for read access, the where clause in the UPDATE statement filters the result set to return one record. Table 6.14
Peter San Is Able to Read One Row
EMPNO
FIRSTNME
LASTNAME
PHONE
SEC_LABEL
SALARY
321
Jane
WHITE
416-343-3432
SL_D003
70000
Because Peter holds the SL_D003 security label for write access, the UPDATE is successful. Table 6.15
Peter San Is Able To Write to One Row
EMPNO
FIRSTNME
LASTNAME
PHONE
SEC_LABEL
SALARY
321
Jane
WHITE
905-423-8302
SL_D003
70000
Deleting Data Records Protected by SET Security Label Component Deleting a protected record requires the user to have read-and-write access to the record, which implies that both DB2LBACREADSET and DB2LBACWRITESET access rules have to be satisfied. Example Jane holds the security label SL_D003 for read access. When Jane issues the following DELETE statement DELETE FROM EMPLOYEE WHERE EMPNO = 321;
the statement fails to execute because Jane does not have write access on the SALARY protected column. SQL20264N is returned. The authorization ID does not have WRITE access to the SALARY column. Example Peter holds the security label sl_D003_M for read-and-write access. When Peter issues the following DELETE statement DELETE FROM EMPLOYEE WHERE EMPNO = 321;
Manipulating Data with Security Label with ARRAY Security Label Component
191
the row is protected by SL_D003, and the SALARY column is protected by SL_MGMT. Peter has READ access to the record where EMPNO equals ‘321’. However, Peter does not have WRITE access on the SALARY column because the WRITE security label SL_D003 does not contain the element ‘MGMT’. The statement failed with sqlcode SQL20264N. The authorization ID does not have WRITE access to the column SALARY column.
MANIPULATING DATA WITH SECURITY LABEL WITH ARRAY SECURITY LABEL COMPONENT Inserting with a Security Label Of ARRAY Component An INSERT operation needs to satisfy the DB2LBACWRITEARRAY access rule when a table is protected with security labels of the ARRAY security label component. The DB2LBACWRITEARRAY requires that the elements in the security label protecting the row/column cannot be higher than or lower than the elements in the write security label of the session authorization ID to insert a record successfully. INSERT is not allowed if the user’s security label value is higher or lower than the security label to be inserted.
Scenario A security label component SLC_SECLEVEL of ARRAY component type is created with elements [‘Sensitive’, ‘Confidential’, ‘Unclassified’]. A security policy ITEM_PRICING_POLICY is created with SLC_SECLEVEL security label component. One security label is created for each security level with names: SL_SENSITIVE, SL_CONFIDENTIAL, and SL_UNCLASSIFIED, for the security policy ITEM_PRICING_POLICY: Security Label: ITEM_PRICING_POLICY.SL_SENSITIVE ITEM_PRICING_POLICY.SL_CONFIDENTIAL ITEM_PRICING_POLICY.SL_UNCLASSIFIED
The PRODUCT table is protected by the ITEM_PRICING_POLICY. Items that are going to be on special order for promotion are marked as SENSITIVE. Items that are new for the next season will be marked as CONFIDENTIAL. Items that are currently available are marked as UNCLASSIFIED.
192
Chapter 6 • Label Based Access Control
General staff can query to see what products are available. Department managers are allowed to check any new items coming for the next season to plan ahead for space allocation. Store managers can see what items are on special order for promotion. The PRODUCT table also contains the clearance price, which is also marked as sensitive, and only store managers can access it. Department managers can change the price of products that are available on the shelf. The PRODUCT table contains the following records. Table 6.16
PRODUCT Table
ID
ITEM_NAME
PRICE
SEC_LABEL
Clearance (Protected by SL_SENSITIVE)
001
Jeans
25
SL_UNCLASSIFIED
8
002
Tees
15
SL_UNCLASSIFIED
4
003
Shoes
60
SL_CONFIDENTIAL
20
004
Plant
5
SL_CONFIDENTIAL
3
005
Carpet
100
SL_SENSITIVE
50
006
TV
300
SL_SENSITIVE
250
Users of the PRODUCT table are granted with the security labels as follows. Table 6.17
Security Labels Granted to Session Authorization ID
Session Authorization ID
Read Security Label
Harry
SL_SENSITIVE
Write Security Label SL_ SENSITIVE + Exemption on ARRAY WRITEDOWN
Randy
SL_SENSITIVE
SL_SENSITIVE
Ron
SL_CONFIDENTIAL
SL_CONFIDENTIAL
Jason
SL_UNCLASSIFIED
None
Manipulating Data with Security Label with ARRAY Security Label Component
193
Example Harry tries to insert a record into the PRODUCT table by executing the following statement: INSERT INTO PRODUCT values (007, 'Lamp', 50, SECLABEL_BY_NAME('ITEM_PRICING_POLICY', 'SL_UNCLASSIFIED'), 30 )
The INSERT statement executes successfully because Harry holds the SL_SENSITIVE WRITE security label and is granted with ARRAY WRITEDOWN exemption. He can write to the SEC_LABEL column with the SL_UNCLASSIFIED security label and can insert a value into the Clearance column which is protected by SL_CONFIDENTIAL. The PRODUCT table now becomes as shown in Table 6.18. Table 6.18 PRODUCT Table ID
ITEM_NAME
PRICE
SEC_LABEL
Clearance (Nullable, Protected by SL_SENSITIVE)
001
Jeans
25
SL_UNCLASSIFIED
8
002
Tees
15
SL_UNCLASSIFIED
4
003
Shoes
60
SL_CONFIDENTIAL
20
004
Plant
5
SL_CONFIDENTIAL
3
005
Carpet
100
SL_SENSITIVE
50
006
TV
300
SL_SENSITIVE
250
007
Lamp
50
SL_UNCLASSIFIED
30
Example A customer returned some items that are no longer tracked in the PRODUCT table. Ron executed the following statement to add the item back to the table for tracking purpose: INSERT INTO PRODUCT (ID, ITEM_NAME, PRICE, SEC_LABEL) values (099, 'Sandal', 15, SECLABEL_BY_NAME('ITEM_PRICING_POLICY', 'SL_UNCLASSIFIED') )
Ron holds the write security label SL_CONFIDENTIAL. However, the DB2LBACWRITEARRAY WRITE access rule blocks him from writing with the security label SL_UNCLASSIFIED
194
Chapter 6 • Label Based Access Control
because the element ‘Unclassified’ is lower than ‘Confidential’. The DB2LBACWRITEARRAY is violated if the row security label is higher or lower than the user security label. Besides, Ron’s WRITE security label blocks him from writing to the Clearance column which is protected by SL_SENSITIVE. The column security label has the element ‘Sensitive’ that ranks higher than ‘Confidential’. SQL20402N is returned. The authorization ID does not have the LBAC credentials to perform the INSERT operation on the table.
To allow Ron to write using SL_UNCLASSIFIED, you need to grant him with the DB2LBACWRITEARRAY WRITEDOWN exemption with the following statement: GRANT EXEMPTION ON RULE DB2LBACWRITEARRAY WRITEDOWN FOR ITEM_PRICING_POLICY TO USER RON
The PRODUCT table now becomes as shown in Table 6.19. Table 6.19
PRODUCT Table
ID
ITEM_NAME
PRICE
SEC_LABEL
Clearance (Nullable, Protected by SL_SENSITIVE)
001
Jeans
25
SL_UNCLASSIFIED
8
002
Tees
15
SL_UNCLASSIFIED
4
003
Shoes
60
SL_CONFIDENTIAL
20
004
Plant
5
SL_CONFIDENTIAL
3
005
Carpet
100
SL_SENSITIVE
50
006
TV
300
SL_SENSITIVE
250
007
Lamp
50
SL_UNCLASSIFIED
30
099
Sandal
15
SL_UNCLASSIFIED
Retrieve Data with a Security Label of ARRAY Security Label Component When a table is protected with security label of ARRAY security label component, a SELECT operation needs to satisfy the DB2LBACREADARRAY access rule. The DB2LBACREADARRAY rule requires the elements in the security label protecting the data to have equal or lower value than the elements in the read security label of the session authorization ID.
Manipulating Data with Security Label with ARRAY Security Label Component
195
Example Harry is a store manager, and is granted with the SL_SENSITIVE security label. When Harry issues the query SELECT id, item_name, price, varchar(seclabel_to_char('ITEM_PRICING_POLICY', sec_label)), Clearance FROM PRODUCT
all records are returned. The SL_SENSITIVE security label contains the ‘Sensitive’ element from the SLC_SECLEVEL, which has the highest rank in the array. Therefore, Harry’s security label has the highest value and can read rows that are protected by security labels with a lower value. Example Ron is the department manager, and granted with the SL_CONFIDENTIAL security label. Ron issued the following query to retrieve the list of products: SELECT ID, ITEM_NAME, PRICE, SEC_LABEL from PRODUCT;
Table 6.20 Row
Compare Ron’s Read Security Label with the Product Security Label for Each
ID
SEC_LABEL
Security Label Comparison for Read Access
001
SL_UNCLASSIFIED
Allowed: ‘CONFIDENTIAL’ is higher than ‘UNCLASSIFIED’.
002
SL_UNCLASSIFIED
Allowed: ‘CONFIDENTIAL’ is higher than ‘UNCLASSIFIED’.
003
SL_CONFIDENTIAL
Allowed: Element values are equal.
004
SL_CONFIDENTIAL
Allowed: Element values are equal.
005
SL_SENSITIVE
Not allowed: ‘CONFIDENTIAL’ is lower than ‘SENSITIVE’.
006
SL_SENSITIVE
Not allowed: ‘CONFIDENTIAL’ is lower than ‘SENSITIVE’.
007
SL_UNCLASSIFIED
Allowed: ‘CONFIDENTIAL’ is higher than ‘UNCLASSIFIED’.
099
SL_UNCLASSIFIED
Allowed: ‘CONFIDENTIAL’ is higher than ‘UNCLASSIFIED’.
Six records are returned in the result set.
196
Table 6.21
Chapter 6 • Label Based Access Control
Six Records Are Returned to Ron
ID
ITEM_NAME
PRICE
SEC_LABEL
001
Jeans
25
SL_UNCLASSIFIED
002
Tees
15
SL_UNCLASSIFIED
003
Shoes
60
SL_CONFIDENTIAL
004
Plant
5
SL_CONFIDENTIAL
007
Lamp
50
SL_UNCLASSIFIED
099
Sandal
15
SL_UNCLASSIFIED
Ron’s read security label contains the ‘Confidential’ element. The DB2LBACREADARRAY rule allows him to see rows protected by SL_CONFIDENTIAL and SL_UNCLASSIFIED, but he cannot access the rows protected with SL_SENSITIVE because ‘Confidential’ has a lower value than ‘Sensitive’. If Ron includes the Clearance column in the query, error SQL20264N will be returned because Ron does not have read access on the Clearance column protected by SL_SENSITIVE.
Update Data with a Security Label Of ARRAY Security Label Component Updating protected records requires the user to have read-and-write access on the record. This implies that both DB2LBACREADARRAY and DB2LBACWRITEARRAY access rules have to be satisfied. Example Ron has SL_CONFIDENTIAL for all access. Ron is granted with exemptions to WRITEDOWN. If Ron issues the following UPDATE statement: UPDATE PRODUCT SET CLEARANCE=5 WHERE ID='099'
the statement fails with SQL20264. Ron is not allowed to read the Clearance column because the ‘Confidential’ element has a lower value than the element ‘Sensitive’. Therefore, the UPDATE fails. Example If Ron tries to update the price of the ‘Sandal’ by issuing the following statement: UPDATE PRODUCT SET PRICE=10 WHERE ID='099'
Manipulating Data with Security Label with ARRAY Security Label Component
197
Because Ron has read and write access to the PRICE column, the statement executes successfully. The record becomes as shown in Table 6.22. Table 6.22
One Record Is Returned to Ron
ID
ITEM_NAME PRICE SEC_LABEL
099
Sandal
10
Clearance (Protected by SL_SENSITIVE)
SL_CONFIDENTIAL
Note that the SEC_LABEL column is updated implicitly to SL_CONFIDENTIAL, the WRITE security label granted to Ron.
Delete Data with a Security Label of ARRAY Security Label Component Deleting a protected record requires the user to have read-and-write access to the record, which implies that both the DB2LBACREADARRAY and DB2LBACWRITEARRAY access rules have to be satisfied. Because the PRODUCT table contains a protected column, the session authorization ID who executes the DELETE statement is required to have write access to the protected column for the deletion to be successful. Example Ron tried to delete the product ‘Sandal’ by issuing this: DELETE FROM PRODUCT WHERE ID='099'
Ron cannot write to the protected column, Clearance. SQL20264 is returned. Ron does not have WRITE access to the CLEARANCE column. Example Randy holds the SL_SENSITIVE label for all access. If Randy executes the statement DELETE FROM PRODUCT
The records are checked as shown in Table 6.23.
198
Chapter 6 • Label Based Access Control
Table 6.23 Randy’s Security Label Is Compared for Read-and-Write Access on the PRODUCT Table ID
SEC_LABEL
Security Label Comparison for Read Access
Security Label Comparison for Write Access
001
SL_UNCLASSIFIED
Yes: ‘SENSITIVE’ is higher
002
SL_UNCLASSIFIED
than ‘UNCLASSIFIED’.
No, write security label ‘SENSITIVE’ cannot write a row security label ‘UNCLASSIFIED’ unless WRITE-DOWN exemption is granted.
003
SL_CONFIDENTIAL Yes: ‘SENSITIVE’ is higher than ‘CONFIDENTIAL’.
004
SL_CONFIDENTIAL Yes: ‘SENSITIVE’ is higher than ‘CONFIDENTIAL’.
005
SL_SENSITIVE
006
SL_SENSITIVE
007
SL_UNCLASSIFIED
099
SL_UNCLASSIFIED
No, write security label ‘SENSITIVE’ cannot write a row security label ‘CONFIDENTIAL’ unless WRITE-DOWN exemption is granted.
Yes.
Yes.
Yes: ‘SENSITIVE’ is higher than ‘UNCLASSIFIED’.
No, write security label ‘SENSITIVE’ cannot write a row security label ‘UNCLASSIFIED’ unless WRITE-DOWN exemption is granted.
Therefore, Randy can read eight records but can only write two. Without LBAC ARRAY controls, Randy’s SQL statement would delete all the rows in the table. With LBAC controls, the SQL statement cannot be successful because the SQL operation cannot delete just the two rows that Randy has “write security” for and leave behind the remainder. The statement fails with SQL20402N. Randy does not have the LBAC credentials to perform the DELETE operation on the PRODUCT table. If Randy has WRITEDOWN exemption granted, the statement will succeed.
Manipulating Data with Security Label with TREE Security Label Component
199
Example Harry holds the SL_SENSITIVE security label for read and write, and has been granted with the ARRAY WRITEDOWN exemption. The security labels allow him to read and write all the rows in the PRODUCT table. If Harry executed the same DELETE statement, all the records in the table will be deleted.
MANIPULATING DATA WITH SECURITY LABEL WITH TREE SECURITY LABEL COMPONENT Insert Data with a Security Label Of TREE Security Label Component An INSERT operation needs to satisfy the DB2LBACWRITETREE access rule when a table is protected with security labels of the TREE security label component. The DB2LBACWRITETREE requires the user to have at least one element in the user security label that matches with the elements in the row security label used for the INSERT operation. INSERT is not allowed if none of the user’s security label values is equal to or an ancestor of one of the security labels to be inserted.
Scenario The SALES table contains records about sales from different regions. To restrict staff from accessing sales data of other regions, the SALES table needs to be protected. The security label component SLC_REGION is created to represent the different sales region, and will be used to protect the SALES table. The SLC_REGION contains HEAD_QUARTER as the root of the tree, followed by ‘EAST’, ‘WEST’, ‘CENTRAL’, as the child nodes, and the ‘CENTRAL’ region is divided into ‘CENTRAL_NORTH’ and ‘CENTRAL_SOUTH’. A security policy, REGION_POLICY is defined with the SLC_REGION security label component. Security labels are created for each of the elements in the SLC_REGION.
200
Chapter 6 • Label Based Access Control
HEAD_QUARTER
WEST
CENTRAL
CENTRAL_SOUTH
EAST
CENTRAL_NORTH
Figure 6.4 The SALES regions of the organization is represent as a TREE security label component
The following security labels are created: Security Label: REGION_POLICY.SL_HQ REGION_POLICY.SL_EAST REGION_POLICY.SL_WEST REGION_POLICY.SL_CENTRAL REGION_POLICY.SL_CENTRAL_N REGION_POLICY.SL_CENTRAL_S REGION_POLICY.SL_REGIONS
Security Label Component: HEAD_QUARTER EAST WEST CENTRAL CENTRAL_NORTH CENTRAL_SOUTH EAST, WEST, CENTRAL
The SALES table has the following records. Table 6.24
SALES Table
ID
SALES_DATE
SALES_PERSON
SALES
REGION
SEC_LABEL
1
01/04/2006
LEE
2000
EAST
SL_EAST
2
11/04/2006
GOUNOT
3300
WEST
SL_WEST
3
30/04/2006
LUCCI
2320
CENTRAL_N
SL_CENTRAL_N
4
02/05/2006
SAI
1100
CENTRAL_S
SL_CENTRAL_S
5
20/05/2006
BROWN
2020
WEST
SL_WEST
Users of the SALES table are granted with the following security labels.
Manipulating Data with Security Label with TREE Security Label Component
Table 6.25
201
Users’ Session Authorization IDs and the Security Labels Granted to Them
Responsibility
Session Authorization ID Read Security Label
Write Security Label
CEO
FRED
SL_HQ
None
Sales manager for East region
EASON
SL_EAST
SL_EAST
Sales manager for West region
WILLIAM
SL_WEST
SL_WEST
Sales manager for NANCY Central north region
SL_CENTRAL_N
SL_CENTRAL_N
Sales manager for Central region
CARL
SL_CENTRAL
SL_CENTRAL
General Manager for Sales
SEAN
SL_REGIONS
SL_REGIONS
Example EASON holds the SL_EAST for write access. He tries to insert a record into the SALES table as follows: INSERT INTO SALES (SALES_DATE, SALES_PERSON, SALES, REGION) values ('2006-05-24', 'Smith', 3200, 'EAST')
The INSERT statement executed successfully. The SEC_LABEL column is populated with the WRITE security label granted to EASON. The table becomes as shown in Table 6.26. Table 6.26
SALES Table
ID
SALES_DATE
SALES_PERSON
SALES
REGION
SEC_LABEL
1
01/04/2006
LEE
2000
EAST
SL_EAST
2
11/04/2006
GOUNOT
3300
WEST
SL_WEST
3
30/04/2006
LUCCI
2320
CENTRAL_N
SL_CENTRAL_N
4
02/05/2006
SAI
1100
CENTRAL_S
SL_CENTRAL_S
5
20/05/2006
BROWN
2020
WEST
SL_WEST
6
24/05/2006
SMITH
3200
EAST
SL_EAST
202
Chapter 6 • Label Based Access Control
Example Carl, tries to update the SALES table on Nancy’s behalf for a sales record in CENTRALNORTH. Carl holds the SL_CENTRAL security label with contains the element ‘CENTRAL’. INSERT INTO SALES (SALES_DATE, SALES_PERSON, SALES, REGION, SEC_LABEL) values ('2006-05-24', 'Needs', 1200, 'CENTRAL_NORTH', SECLABEL_BY_NAME('REGION_POLICY', 'SL_CENTRAL_N') )
The statement executed successfully because the element ‘CENTRAL’ is the ancestor of ‘CENTRAL_NORTH’. Therefore, the DB2LBACWRITETREE access rule is satisfied. A new record is added to the SALES table. Table 6.27
SALES Table after Inserting a New Record
ID
SALES_DATE SALES_PERSON SALES
REGION
SEC_LABEL
1
01/04/2006
LEE
2000
EAST
SL_EAST
2
11/04/2006
GOUNOT
3300
WEST
SL_WEST
3
30/04/2006
LUCCI
2320
CENTRAL_NORTH
SL_CENTRAL_N
4
02/05/2006
SAI
1100
CENTRAL_SOUTH
SL_CENTRAL_S
5
20/05/2006
BROWN
2020
WEST
SL_WEST
6
24/05/2006
SMITH
3200
EAST
SL_EAST
7
24/05/2006
NEEDS
1200
CENTRAL_NORTH
SL_CENTRAL_N
Example Carl, is covering for William while William is on vacation. Carl tries to update the SALES table to add a sales record in the West region. Carl holds the SL_CENTRAL security label which contains the element ‘CENTRAL’. INSERT INTO SALES (SALES_DATE, SALES_PERSON, SALES, REGION, SEC_LABEL) values ('2006-05-25', 'GOUNOT', 2320, 'WEST', SECLABEL_BY_NAME('REGION_POLICY', 'SL_WEST') )
However, the SL_CENTRAL security label does not contain the element ‘WEST’ or its ancestor. Therefore, the statement failed with SQL20402N. Carl does not have the LBAC credentials to perform the INSERT operation on the SALES table.
Manipulating Data with Security Label with TREE Security Label Component
203
If the REGION_POLICY is not created with the RESTRICT NOT AUTHORIZED WRITE SECURITY LABEL option, however, a record will be inserted with the SEC_LABEL column containing the write security label of Carl; that is, SL_CENTRAL. In that case, no error message is returned. Example Nancy holds the SL_CENTRAL_N security label for all access. A sales order applies to the CENTRAL wide region. She tries to insert a record as follows: INSERT INTO SALES (SALES_DATE, SALES_PERSON, SALES, REGION, SEC_LABEL) values ('2006-05-25', 'White', 2000, 'CENTRAL', SECLABEL('REGION_POLICY', '(CENTRAL_NORTH, CENTRAL_SOUTH)') )
The INSERT statement is successful even though the security label that Nancy holds only contains the element ‘WEST’. The DB2LBACWRITETREE requires the user to have at least one element in the user security label that matches with the elements in the row security label used for the INSERT operation. Because the ‘WEST’ element matches, the record is inserted without error. The SALES table becomes as shown in Table 6.28. Table 6.28
SALES Table after Inserting a New Row
ID
SALES_DATE
SALES_PERSON SALES REGION
SEC_LABEL
1
01/04/2006
LEE
2000
EAST
SL_EAST
2
11/04/2006
GOUNOT
3300
WEST
SL_WEST
3
30/04/2006
LUCCI
2320
CENTRAL_NORTH
SL_CENTRAL_N
4
02/05/2006
SAI
1100
CENTRAL_SOUTH
SL_CENTRAL_S
5
20/05/2006
BROWN
2020
WEST
SL_WEST
6
24/05/2006
SMITH
3200
EAST
SL_EAST
7
24/05/2006
NEEDS
1200
CENTRAL_NORTH
SL_CENTRAL_N
8
24/05/2006
WHITE
2000
CENTRAL
SLC_REGION: (CENTRAL_ NORTH, CENTRAL_ SOUTH)
204
Chapter 6 • Label Based Access Control
Retrieve Data with a Security Label of TREE Security Label Component When a table is protected with security label of TREE security label component, a SELECT operation needs to satisfy the DB2LBACREADTREE access rule. As with the DB2LBACWRITETREE rule, the DB2LBACREADTREE requires the user to have at least one element in the user security label that matches with the elements in the security label used to protect the data. SELECT is not allowed if none of the user’s security label values is equal to or an ancestor of the security label protecting the data.
Example The executive, Fred, is granted with security label REGION_POLICY.SL_HQ for read access. When Fred executes the query SELECT ID, SALES_DATE, SALES_PERSON, SALES, REGION, VARCHAR(SECLABEL_TO_CHAR('REGION_POLICY',SEC_LABEL)) FROM SALES
the query returns all the records in the SALES table because the HQ element is the root of the TREE, which is the ancestor of all elements. Example Nancy holds the SL_CENTRAL_N security label and issues the same query to retrieve the sales records. Table 6.29
Nancy’s Security Label Is Compared for Read Access on the SALES Table
ID
SEC_LABEL
Security Label Comparison
1
SL_EAST
Not allowed: SL_CENTRAL_N does not contain element ‘EAST’.
2
SL_WEST
Not allowed: SL_CENTRAL_N does not contain element ‘WEST’.
3
SL_CENTRAL_N
Allowed.
4
SL_CENTRAL_S
Not allowed: SL_CENTRAL_N does not contain element ‘CENTRAL_SOUTH’.
5
SL_WEST
Not allowed: SL_CENTRAL_N does not contain element ‘WEST’.
6
SL_EAST
Not allowed: SL_CENTRAL_N does not contain element ‘EAST’. (continues)
Manipulating Data with Security Label with TREE Security Label Component
205
Table 6.29 Nancy’s Security Label Is Compared for Read Access on the SALES Table (Continued) ID
SEC_LABEL
Security Label Comparison
7
SL_CENTRAL_N
Allowed
8
SLC_REGION:(CENTRAL_NORTH, CENTRAL_SOUTH)
Allowed: SL_CENTRAL_N contains element ‘CENTRAL_NORTH’.
Therefore, three records are retrieved. Table 6.30
Records Returned to Nancy from the Query
ID
SALES_DATE
SALES_PERSON SALES REGION
SEC_LABEL
3
30/04/2006
LUCCI
2320
CENTRAL_NORTH CENTRAL_NORTH
7
24/05/2006
NEEDS
1200
CENTRAL_NORTH CENTRAL_NORTH
8
24/05/2006
WHITE
2000
CENTRAL
CENTRAL_NORTH
Update Data with a Security Label of TREE Security Label Component Updating a protected record requires the session authorization ID to have read-and-write access on the record. This implies both DB2LBACREADTREE and DB2LBACWRITETREE access rules have to be satisfied. Example Carl holds the SL_CENTRAL security label for all access. He tries to fix the sales data of the record with ID ‘7’ by issuing this: UPDATE SALES SET SALES=2200, SEC_LABEL= SECLABEL('REGION_POLICY', SECLABEL_TO_CHAR('REGION_POLICY',SEC_LABEL)) WHERE ID='7'
The record is protected by SL_CENTRAL_N. SL_CENTRAL contains the element ‘CENTRAL’, which is the ancestor of CENTRAL_NORTH. Therefore, the statement executes successfully. Table 6.31
Record Is Updated in the SALES Column
ID
SALES_DATE
SALES_PERSON SALES REGION
SEC_LABEL
7
24/05/2006
NEEDS
CENTRAL_NORTH
2200
CENTRAL_NORTH
206
Chapter 6 • Label Based Access Control
Example Nancy holds the SL_CENTRAL_N security label for all access. She tries to update the sales record with ID ‘8’ by issuing this: UPDATE SALES SET SALES=2500 WHERE ID='8'
The record is protected by a security label with elements {‘CENTRAL_NORTH’, ‘CENTRAL_SOUTH’}. SL_CENTRAL_N contains the element ‘CENTRAL_NORTH’, which is one of the elements in the row security label. This satisfies the DB2LBACREADTREE access rule. Nancy tries to update an unprotected column. The write security label is updated in the SEC_LABEL column. The statement executes successfully.
Delete Data with a Security Label of TREE Security Label Component Deleting a protected record requires the session authorization ID to have read and write access on the record. This implies both DB2LBACREADTREE and DB2LBACWRITETREE access rules have to be satisfied. Example Eason issues a DELETE statement to remove the sales record protected by the ‘EAST’ security component element: DELETE FROM SALES
Only records that Eason has read-and-write credential access for will be deleted. If Eason has read access on some of the rows but does not have write access on those same rows, the DELETE operation fails. Table 6.32
Eason’s Security Label is compared for DELETE operation on the SALES table
ID
SEC_LABEL
Security Label Comparison
1
SL_EAST
Allowed.
2
SL_WEST
Not allowed to read: SL_EAST does not contain element ‘WEST’.
3
SL_CENTRAL_N
Not allowed to read: SL_EAST does not contain element ‘CENTRAL_NORTH’.
4
SL_CENTRAL_S
Not allowed to read: SL_ EAST does not contain element ‘CENTRAL_SOUTH’.
5
SL_WEST
Not allowed to read: SL_ EAST does not contain element ‘WEST’.
6
SL_EAST
Allowed. (continues)
Use Case Scenario
207
Table 6.32 Eason’s Security Label is compared for DELETE operation on the SALES table (Continued) ID
SEC_LABEL
Security Label Comparison
7
SL_CENTRAL_N
Not allowed to read: SL_EAST does not contain element ‘CENTRAL_NORTH’.
8
SLC_REGION: Not allowed: SL_EAST does not contain element (CENTRAL_NORTH, ‘CENTRAL_NORTH’ or ‘CENTRAL_SOUTH’. CENTRAL_SOUTH)
As a result, the records with ID 1 and 6 are deleted, because Eason only has read-and-write access on those two records. Example Sean issued the same DELETE statement. Sean holds the SL_REGIONS for read-and-write access. Therefore, he is allowed to read and write all records in the table. By issuing the DELETE FROM SALES
statement, all records will be deleted.
USE CASE SCENARIO Let’s walk through a scenario showing how LBAC can be used to impose access restrictions to table data. The Life Health Care Center is reviewing the HIPAA regulations dealing with the client visit record data storage that can be shared with health plan providers. For every client visit, a record is created in the database with information about the visit, diagnostic result, service provided, cost of the service, client’s health insurance provider, and so on. Information about the service provided and the cost is shared with the client’s health insurance provider for claim processing. Health insurance providers are allowed to read records of their clients but not others. The diagnostic results are highly confidential and should be handled only by the Health Care Center staff. Client visit records are to be stored in the VISIT_RECORD table, which is shown in Figure 6.5.
208
Chapter 6 • Label Based Access Control
Confidential R&W
Health Insurance Company A Claims Processor Health Care Provider Staff
R
R&W
Health Insurance Company B Claims Processor
Figure 6.5 The VISIT_RECORD table. The confidential columns can be accessed by staff in the Life Health Care Center only. Health Insurance providers are restricted to read only the records of their clients.
Column name ---------------RECORDID CLIENTNO DATE *DIAGONSTIC SERVICE_DESC AMOUNT INSURER_ID CLAIMED
Type schema --------SYSIBM SYSIBM SYSIBM SYSIBM SYSIBM SYSTEM SYSIBM SYSIBM
Type name Length Scale Nulls ------------------ -------- ----- ---CHARACTER 6 0 No CHARACTER 6 0 No DATE 4 0 No CLOB 1048576 0 No VARCHAR 255 0 No DECIMAL 6 2 No CHARACTER 6 0 No DATE 4 0 No
Columns with an asterisk (*) contain confidential information. Table 6.33
Some of the Staff Who Can Access the VISIT_RECORD Table
Staff
Position
Henry
Life Health Care Center staff
Anson
Claims processor of health insurance company A (IC011)
Anna
Claims processor of health insurance company B (IC012)
Use Case Scenario
209
Based on this scenario, summarize your security requirements as follows in Table 6.34. Table 6.34
Security Requirements of Users with Various Responsibilities READ Access
WRITE Access
Life Health Care Center staff
Full access
Full access
Claims processor of insurance company
Only columns and their client records that are not confidential
No access
Analyzing Data Restrictions You need to determine how to restrict access to columns that are confidential, and restrict records to be read by a certain groups of people. You need to enforce the following restrictions: • Columns—Confidential columns can be read and written by Health Care Center staff only. Insurance company claims processors have no access to the confidential column. • Rows—Health Care Center staff can read and update all the records. Insurance company claims processors can read but cannot update client records of their insurance company. To restrict access to the column that is confidential, the column can be protected with a security label. To allow claims processors to access the records of their clients only, each row would be tagged with a security label that indicates the insurance company. The write restriction can be implemented by not granting write access security labels to the managers. On the table level, write restriction can also be implemented by revoking the write privileges to the table from the claims processors.
210
Chapter 6 • Label Based Access Control
Table 6.35 Tag the Columns That Are Confidential with a Security Label to Make It Protected, and Tag Each Row with a Security Label to Apply Access Control Based on the Insurance Company
RECORDID CLIENTNO DATE
Row SERVICE Sec DIAGNOSTIC _DESC AMOUNT INSURER_ID CLAIMED Label
000010
C00101
2006/03/04 …
…
200
IC011
000011
A00721
2006/03/05 …
…
325
IC012
000012
L05031
2006/03/05 …
…
128
IC011
2006/03/04
Designing the Security Solution After determining the security requirements, design the security labels that will control access to the data in the VISIT_RECORD table. In designing a security solution, you need to consider the following: • Row and column security labels required for protecting the columns and rows • User security labels to grant the users the appropriate access • Security label components for creating the security labels Column Security Label For column protection, one column security label is required to tag the confidential column. The security label could simply be made up of a security label component with an element called ‘CONFIDENTIAL’. A SET type component can be used in this case. Row Security Labels For row protection, a security label is required to tag the rows based on the insurance company. Thus, one security label is required for each insurance company. The Life Health Care Center currently deals with five insurance companies. Given that there are five insurance companies, five security labels will be created to identify them. Health Care Center staffs are allowed to access all the rows. Thus, the security label component for creating these security labels could be structured as a TREE, with the Health Care Center as the root, and the insurance companies that deal with the Health Care Center as the child. User Security Label for the Health Care Center Staff The security label granted to the medical record analysts should allow them to read and write all records, including the confidential columns. Thus, the security label should include the elements from the column security label and the row security label that can access all rows.
Use Case Scenario
211
User Security Label for the Claims Processor of Health Insurance Providers The security label granted to the claims processor should allow them to read the records of their clients only. The security label should include the element of the insurance company ID. Security label Components A SET type security label component is required for the column security label, with one element ‘CONFIDENTIAL’. A TREE type security label component is required for the row security label, with ‘IC_ROOT’ as the root, and the insurance companies IDs ‘IC011’, ‘IC012’, ‘IC013’, ‘IC014’, and ‘IC015’ as the child elements.
Implementing the Security Solution Steps Overview 1. Define the security policies and labels. a. Define the security label components. b. Define the LBAC security policy. c. Define the security labels. 2. Create the VISIT_RECORD table by adding a security label column for the row level protection, mark the confidential columns as protected, and attach the security policy to the table. 3. Grant the appropriate security labels to the staff.
Step 1: Privilege and Authority Requirements Requires SECADM authority to create security objects. Step 1.1: Defining the Security Label Components From the analysis, two security label components are required. The security label components can be created using the following statement: CREATE SECURITY LABEL COMPONENT SLC_LEVEL SET {'CONFIDENTIAL'}
212
Chapter 6 • Label Based Access Control
CREATE SECURITY LABEL COMPONENT SLC_INSURANCE TREE ('IC_ROOT' ROOT, 'IC011' UNDER 'IC_ROOT', 'IC012' UNDER 'IC_ROOT', 'IC013' UNDER 'IC_ROOT', 'IC014' UNDER 'IC_ROOT', 'IC015' UNDER 'IC_ROOT' )
Step 1.2: Defining the Security Policy After the security label component is created, the next step is to create the security policy. A security policy with a name VISIT_RECORD_POLICY that uses the SLC_LEVEL and SLC_INSURANCE security label components can be created using the following statement: CREATE SECURITY POLICY VISIT_RECORD_POLICY COMPONENTS SLC_LEVEL, SLC_INSURANCE WITH DB2LBACRULES RESTRICT NOT AUTHORIZED WRITE SECURITY LABEL
Step 1.3: Defining the Security Label From the analysis, the following security labels are needed: • One column security label • Five security labels for row protection and for the insurance company claims processor • One user security label for Health Care Center staff The security labels can be created using the following statements: For column protection: CREATE SECURITY LABEL VISIT_RECORD_POLICY.SL_VISIT_RECORD COMPONENT SLC_LEVEL 'CONFIDENTIAL'
For Health Care Center staff: CREATE SECURITY LABEL VISIT_RECORD_POLICY.SL_HC_STAFF COMPONENT SLC_LEVEL 'CONFIDENTIAL', COMPONENT SLC_INSURANCE 'IC_ROOT'
Step 2: Creating the Protected VISIT_RECORD Table Privilege and Authority Requirements for the Creator of the Table: • CREATETAB authority. • Creator of the table should be granted with a security label that is associated with the VISIT_RECORD_POLICY. The security label will be used as the default value for the ROW_SEC_LABEL column. For example, assume the administrator holds the VISIT_RECORD_POLICY.SL_HC_STAFF security label. GRANT SECURITY LABEL VISIT_RECORD_POLICY.SL_HC_STAFF TO USER FOR ALL ACCESS
To secure the VISIT_RECORD table, all confidential columns need to be secured with the VISIT_RECORD_POLICY.SL_VISIT_RECORD security label. To secure the rows, a new column will be added to hold the security label for tagging the departments. The table can be protected by executing the following statement: CREATE TABLE VISIT_RECORD ( RECORDID CHARACTER (6), CLIENTNO CHARACTER(6), DATE DATE, DIAGONSTIC CLOB(1M) SECURED WITH SL_VISIT_RECORD, SERVICE_DESC VARCHAR(255), AMOUNT DECIMAL (6), INSURER_ID CHARACTER (6), CLAIMED DATE, ROW_SEC_LABEL DB2SECURITYLABEL) SECURITY POLICY VISIT_RECORD_POLICY
Upon successful execution of the statement, the VISIT_RECORD table is protected.
214
Column name ———————— RECORDID CLIENTNO DATE *DIAGONSTIC SERVICE_DESC AMOUNT INSURER_ID CLAIMED ROW_SEC_LABEL
Chapter 6 • Label Based Access Control
Type schema ————SYSIBM SYSIBM SYSIBM SYSIBM SYSIBM SYSTEM SYSIBM SYSIBM SYSIBM
Type name ————————— CHARACTER CHARACTER DATE CLOB VARCHAR DECIMAL CHARACTER DATE DB2SECURITYLABEL
Length Scale Nulls ———— ——- ——6 0 No 6 0 No 4 0 No 1048576 0 No 255 0 No 6 2 No 6 0 No 4 0 No 4 0 No
where (*) are protected columns.
Step 3: Granting the Security Labels to the Staff Privilege and authority requirements: SECADM authority is required.
After the VISIT_RECORD table has been protected, no user can access the table until security labels are granted to them. Assume Henry, Anson, and Anna have read privilege on the table. To allow them to access the table, grant the SECURITY labels to the users with the following statements: GRANT SECURITY LABEL VISIT_RECORD_POLICY.SL_HC_STAFF TO USER HENRY FOR ALL ACCESS GRANT SECURITY LABEL VISIT_RECORD_POLICY.SL_INSURANCE_IC011 TO USER ANSON FOR READ ACCESS GRANT SECURITY LABEL VISIT_RECORD_POLICY.SL_INSURANCE_IC012 TO USER ANNA FOR READ ACCESS
Runtime Usage This section explains some of the runtime scenarios after the VISIT_RECORD table is protected. Example 1 Assume the VISIT_RECORD has the following records.
Use Case Scenario
Table 6.36
215
The VISIT_RECORD Table
RECORDID CLIENTNO DATE
SERVICE INSURER Row Sec DIAGNOSTIC _DESC AMOUNT _ID CLAIMED Label
000010
C00101
2006/03/04
…
…
200
IC011
2006/03/04 SL_ INSURANCE_ IC011
000011
A00721
2006/03/05
…
…
325
IC012
2006/03/05 SL_ INSURANCE_ IC012
000012
L05031
2006/03/05
…
…
128
IC011
2006/03/05 SL_ INSURANCE_ IC011
* DIAGNOSTIC column is protected by SL_VISIT_RECORD.
Henry holds the SL_HC_STAFF security label for all access. The SL_HC_STAFF security label contains the SLC_LEVEL:(‘CONFIDENTIAL’), and SLC_INSURANCE:(‘IC_ROOT’). He tries to read the VISIT_RECORD table by issuing this: SELECT * from VISIT_RECORD;
Henry has read access to the protected column because his read security label contains ‘CONFIDENTIAL’. For row access, because ‘IC_ROOT’ is the ancestor element of ‘IC011’ and ‘IC012’, Henry can read all the rows in the table. The statement executed successfully. All records of the VISIT_RECORD table are returned. Example 2 Henry tries to insert a record into the VISIT_RECORD table by issuing the following: INSERT INTO VISIT_RECORD (RECORDID, CLIENTNO, DATE, DIAGONSTIC, AMOUNT, INSURER_ID, ROW_SEC_LABEL) VALUES ('000329', 'C00902', '2006-04-25', 'Require blood test', 233, 'IC012', SECLABEL_BY_NAME('VISIT_RECORD_POLICY', 'SL_IC012'))
To insert the record, two write access controls are in effect. • Write to protected column ‘DIAGNOSTIC’ • Write the row security label: IC012 Henry has write access to the protected column because his write security label contains ‘CONFIDENTIAL’. For row access, because ‘IC_ROOT’ is the ancestor element of ‘IC011’ and ‘IC012’, Henry can insert the record into the table. The statement executed successfully.
216
Chapter 6 • Label Based Access Control
Example 3 Anson holds the security label SL_INSURANCE_IC011 for read access. Anson tries to read the VISIT_RECORD table by issuing this: SELECT * from VISIT_RECORD;
To successfully read the records, Anson needs read access on the protected column and read access on the rows. The read security label that Anson holds does not contain the ‘CONFIDENTIAL’ element. This violates the DB2LBACREADSET access rule on the protected column. Query execution failed with SQL20264N. ANSON does not have READ access to the column “DIAGONSTIC” of the VISIT_RECORD table.
Anson tries to read the unprotected columns in the VISIT_RECORD table by issuing the following: SELECT RECORDID, CLIENTNO, DATE, SERVICE_DESC, AMOUNT, INSURER_ID, CLAIMED FROM VISIT_RECORD;
Because Anson is not accessing the protected column, only the row security labels will be checked. Table 6.37
Anson’s Security Label Is Compared for Read Access on the VISIT_RECORD Table
RECORDID Row Sec Label
Access Allowed?
000010
SL_INSURANCE_IC011
Allowed. Equal value.
000011
SL_INSURANCE_IC012
Not allowed. Violates the DB2LBACREADTREE rule. SL_INSURANCE_IC011 does not contain ‘IC012’, nor is an ancestor of ‘IC012’.
000012
SL_INSURANCE_IC011
Allowed. Equal value.
000329
SL_INSURANCE_IC012
Not allowed. SL_INSURANCE_IC011 does not contain ‘IC012’.
The statement executed successfully. Two records with RECORDID ‘000010’ and ‘000012’ are returned.
Managing Security Objects
217
Example 4 Anna holds the SL_INSURANCE_IC012 security label for read access. Anna tries to manipulate record in the VISIT_RECORD table. First she queries for the record: SELECT INSURER_ID from VISIT_RECORD WHERE CLIENTNO='A00721';
Anna is accessing the unprotected column, so only the row access control will be checked. The record with CLIENTNO ‘A00721’ is protected by SLC_INSURANCE_IC012. The user security label matches the value. The statement executed successfully. The value of INSURER_ID is returned. Anna then tries to update the value of the INSURER_ID. UPDATE VISIT_RECORD SET AMOUNT = 400 WHERE CLIENTNO='A00721'
Anna does not have WRITE security label. Therefore, she does not have authority to write to the VISIT_RECORD table. Access violation error SQL20402N is returned. Anna does not have the LBAC credentials to perform the UPDATE operation on the table VISIT_RECORD. The same statement executed by Henry will be successful because Henry has read-and-write access to the record.
MANAGING SECURITY OBJECTS After a security solution is designed and implemented, the setup has to be maintained and reviewed. The following are some general tasks that a security administrator would perform: • Review the definitions of the security objects created • Review the security objects that are no longer in use and remove them
Review the Definition of Security Objects Review Security Labels Security label objects information can be accessed from the SECURITYLABELS catalog view. The definition of a security label can be retrieved using the following statement: SELECT SECLABELID, SECLABEL_TO_CHAR('<policy-name>',seclabel) FROM SYSCAT.SECURITYLABELS WHERE SECLABELNAME=''
218
Chapter 6 • Label Based Access Control
Review Security Policies Security policy information can be accessed from the SECURITYPOLICIES catalog view. To retrieve the list of security label components used by a security policy, use the following statement: SELECT COMPNAME FROM SYSCAT.SECURITYPOLICIES P, SYSCAT.SECURITYLABELCOMPONENTS C, SYSCAT.SECURITYPOLICYCOMPONENTRULES R WHERE P.SECPOLICYID = R.SECPOLICYID and R.COMPID=C.COMPID and P.SECPOLICYNAME='<policy-name>'
Review Security Label Components Security label component information can be accessed from the SECURITYLABELCOMPONENTS catalog view. To retrieve the list of component elements of a security label component, use the following statement: SELECT ELEMENTVALUE, PARENTELEMENTVALUE FROM SYSCAT.SECURITYLABELCOMPONENTELEMENTS E, SYSCAT.SECURITYLABELCOMPONENTS C WHERE E.COMPID=C.COMPID and C.COMPNAME='' ORDER BY PARENTELEMENTVALUE
If security objects are no longer in use, the objects can be dropped.
Dropping Security Labels To drop a security label, it must no longer be in use. A security label is not in use if • The security label is not granted to any user. • The security label is not being used in a protected table. To check whether a security label is granted to any user, run the following query: SELECT GRANTEE FROM SYSCAT.SECURITYLABELACCESS WHERE SECLABELID = (SELECT SECLABELID FROM SYSCAT.SECURITYLABELS WHERE SECLABELNAME = '' AND SECPOLICYID = (SELECT SECPOLICYID FROM SYSCAT.SECURITYPOLICIES WHERE SECPOLICYNAME = '<policy-name>'))
Managing Security Objects
219
To check whether a security label is used in a protected table, run this query: SELECT TABNAME, COLNAME FROM SYSCAT.COLUMNS WHERE SECLABELNAME = (SELECT SECLABELNAME FROM SYSCAT.SECURITYLABELS WHERE SECLABELNAME ='' AND SECPOLICYID = (SELECT SECPOLICYID FROM SYSCAT.SECURITYPOLICIES WHERE SECPOLICYNAME = '<policy-name'>))
If both queries return empty result sets, the security label can be dropped using the drop statement: DROP SECURITY LABEL <security-label-name>
Otherwise, the statement will return the following: SQL20404N The security label object “<security label>” cannot be dropped because it is currently in use. Reason code “1.”
Dropping Security Policy An LBAC security policy is not in use if • It is not used in any of the protected tables. • There are no security labels associated with the security policy. • There is no exemption granted on any of the access rules. To check whether a security policy is used by any protected tables, issue the following statement: SELECT TABNAME FROM SYSCAT.TABLES WHERE SECPOLICYID = (SELECT SECPOLICYID FROM SYSCAT.SECURITYPOLICIES WHERE SECPOLICYNAME = '<security-policy>' )
To list the existing security labels that are associated with a security policy, use the following statement: SELECT SECLABELNAME FROM SYSCAT.SECURITYPOLICIES S, SYSCAT.SECURITYLABELS L WHERE L.SECPOLICYID = S.SECPOLICYID AND S.SECPOLICYNAME= '<security-policy>'
220
Chapter 6 • Label Based Access Control
To check whether an exemption is granted on rules used by a security policy, use this statement: SELECT GRANTEE, ACCESSRULENAME FROM SYSCAT.SECURITYPOLICYEXEMPTIONS WHERE SECPOLICYID = (SELECT SECPOLICYID FROM SYSCAT.SECURITYPOLICIES WHERE SECPOLICYNAME = '<security-policy>' )
If all three queries return empty result sets, the security policy can be dropped using the drop statement: DROP SECURITY POLICY <security-policy>
Otherwise, SQL20405N will be returned: SQL20405N The security policy object “<security-policy>” cannot be dropped because it is currently in use. Reason code “1.”
Dropping Security Label Component A security label component is not in use if no security policy is referring to it. To check whether a security policy is referring to a security label component, use the following query: SELECT SECPOLICYNAME FROM SYSCAT.SECURITYPOLICIES WHERE SECPOLICYID = (SELECT SECPOLICYID FROM SYSCAT.SECURITYPOLICYCOMPONENTRULES WHERE COMPID = (SELECT COMPID FROM SYSCAT.SECURITYLABELCOMPONENTS WHERE COMPNAME = '') )
If the query returns an empty result set, the security label component can be dropped using the drop statement: DROP SECURITY LABEL COMPONENT
Otherwise, SQL20406N will be returned: The security label component object “” cannot be dropped because it is part of a security policy. SQLSTATE=42893
Managing User Access to Protected Data
221
MANAGING USER ACCESS TO PROTECTED DATA Some general tasks for the LBAC security administrator include the following: • Checking for authorization ids granted with a particular security label • Managing the list of authorization ids that hold exemption granted on a security policy • Changing user privilege (for example, from accessing protected tables) A user needs to be granted with security labels and exemptions to access protected data. To manage user security labels, you must have SECADM authority. User access to security label information can be found in the SYSCAT.SECURITYLABELACCESS catalog view. A user can be granted one security label of each access type per security policy.
Granting Security Labels to Users The security administrator defines multiple security labels to protect a table and to grant user access. Before granting a security label to a user, the security administrator may need to view the security labels that belong to a security policy using the following query: SELECT SECLABELNAME FROM SYSCAT.SECURITYLABELS WHERE SECPOLICYID = (SELECT SECPOLICYID FROM SYSCAT.SECURITYPOLICIES WHERE SECPOLICYNAME = '<policy-name>' )
To check whether a security label is granted to a user, issue the following query: SELECT SECLABELNAME FROM SYSCAT.SECURITYLABELS WHERE SECLABELID= ANY (SELECT SECLABELID FROM SYSCAT.SECURITYLABELACCESS WHERE GRANTEE ='CKMWONG' AND SECPOLICYID = (SELECT SECPOLICYID FROM SYSCAT.SECURITYPOLICIES WHERE SECPOLICYNAME='<policy-name>') )
To grant a security label to a user, the syntax is as follows: >>--GRANT SECURITY LABEL--security-policy-name.security-label-name---> .---FOR ALL ACCESS---. >--TO USER---authorization-name---+--------------------+------------->< +--FOR READ ACCESS---+ '--FOR WRITE ACCESS--'
222
Chapter 6 • Label Based Access Control
Granting Exemptions to Users To check whether an exemption is granted to a user of a security policy, issue the following query: SELECT ACCESSRULENAME, ACTIONALLOWED FROM SYSCAT.SECURITYPOLICYEXEMPTIONS WHERE SECPOLICYID =(SELECT SECPOLICYID FROM SYSCAT.SECURITYPOLICIES WHERE SECPOLICYNAME = '<policy-name>' ) AND GRANTEE =''
To grant an exemption to a user, the syntax is as follows: >>--GRANT EXEMPTION ON RULE--+--DB2LBACREADARRAY------------------+---> +--DB2LBACREADTREE-------------------+ +--DB2LBACREADSET--------------------+ +--DB2LBACWRITEARRAY WRITEDOWN-------+ +--DB2LBACWRITEARRAY WRITEUP---------+ +--DB2LBACWRITETREE------------------+ +--DB2LBACWRITESET-------------------+ +---------------ALL------------------+ >--FOR--label-pol-name--TO--USER--authorization-name-----------------><
Revoking Security Labels from Users If a user of the database changes responsibilities and should no longer be allowed access to protected data, security labels granted should be revoked. To check what access type and security label is granted to a user for an LBAC security policy, issue the following query: SELECT ACCESSTYPE, SECLABELNAME FROM SYSCAT.SECURITYLABELACCESS A, SYSCAT.SECURITYLABELS L WHERE GRANTEE='' AND A.SECLABELID = ANY ( SELECT SECLABELID FROM SYSCAT.SECURITYLABELS WHERE SECPOLICYID = ( SELECT SECPOLICYID FROM SYSCAT.SECURITYPOLICIES WHERE SECPOLICYNAME = '<policy-name>' ) ) AND A.SECLABELID=L.SECLABELID
Revoking Exemptions from Users Exemptions are granted to users to bypass certain access rules in a particular security policy.
Managing Protected Tables
223
To check what exemption is granted to a user for a policy, issue the following query: SELECT GRANTOR, ACCESSRULENAME, ACCESSTYPE FROM SYSCAT.SECURITYPOLICYEXEMPTIONS WHERE GRANTEE='' and SECPOLICYID = (SELECT SECPOLICYID FROM SYSCAT.SECURITYPOLICIES WHERE SECPOLICYNAME = '<policy-name>')
Then, revoke any exemptions with the following REVOKE EXEMPTION statement: >>-REVOKE EXEMPTION ON RULE--+-access-rule-+--------------------> '-ALL---------' >--FOR--policy-name--FROM USER--authorization-name-------------><
MANAGING PROTECTED TABLES Some general tasks for the LBAC security administrator include the following: • Review lists of protected tables • Alter data protection • Add column protection • Add row protection if it does not exist • Drop column security • Alter security policy and security labels of a protected table • Remove protection from protected tables • Drop protected tables
Review List of Protected Tables Table information can be retrieved from the catalog view. When a table becomes protected, the SECPOLICYID field of the table definition will contain a value greater than zero. To retrieve the list of protected tables and the security label(s) that protect the table, you can issue the following query: SELECT TABNAME, SECPOLICYNAME FROM SYSCAT.TABLES T, SYSCAT.SECURITYPOLICIES P WHERE T.SECPOLICYID =P.SECPOLICYID
Find all protected tables and all the columns that are protected with this label: SELECT TABNAME, COLNAME FROM SYSCAT.COLUMNS WHERE SECLABELNAME = (SELECT SECLABELNAME FROM SYSCAT.SECURITYLABELS WHERE SECLABELNAME ='' AND
224
Chapter 6 • Label Based Access Control
SECPOLICYID = (SELECT SECPOLICYID FROM SYSCAT.SECURITYPOLICIES WHERE SECPOLICYNAME ='<policy-name>' ) )
Altering Table Protection:Adding Column Protection When a database is migrated from a previous release, you might have tables created that contain sensitive data. Perhaps access restrictions were imposed using discretionary access control, and views were created to allow users to see some of the columns. With LBAC, you can alter the tables to have column-level protection. To add column protection to a table, you have to do the following: • Attach a security policy to the table. • Attach security labels to the columns that need to be protected. ALTER TABLE --table-name----------------------------------> .------------------------------------------------. V .-COLUMN-. | >--+-ALTER--+--------+--| column-alteration |-------+-----> +-ADD SECURITY POLICY--policy-name------------------------>< column-alteration: |--column-name---------------------------------------> +-SECURED WITH--security-label-name-----------------------+
Alter table T2 to make it a protected table with the BONUS column protected with security label SL_CONFIDENTIAL with the following ALTER TABLE statement: ALTER TABLE T2 ALTER COLUMN BONUS SECURED WITH SL_CONFIDENTIAL ADD SECURITY POLICY DATA_ACCESS_POLICY
Defining a column of type DB2SECURITYLABEL fails if a table does not have a security policy associated with it. Error SQL20391N is returned. LBAC cannot be applied to the column because there is no security policy associated with the table.
Altering Table Protection: Adding Row Protection Row protection is used to restrict access to rows in a table. When rows are protected by security labels, users granted with security labels will be able to access some rows but not others depending on the security label being granted to them.
Managing Protected Tables
225
To add row protection to a table, you have to do the following: • Add a column of type DB2SECURITYLABEL to store the security label. • Attach a security policy to the table if the table is not already protected. The privileges held by the session authorization ID of the statement must include at least a security label with write access from the security policy associated with the table. For existing rows in the table, the value of the security label column defaults to the security label for write access of the session authorization ID at the time the ALTER statement that adds a row security label column is executed. ALTER TABLE --table-name------------------------------------> .-COLUMN-. >--+-ADD--+-+--------+--|--column-name --DB2SECURITYLABEL+--> >--+-ADD SECURITY POLICY--policy-name-----------------------><
Alter table T2 to make it a protected table with row level granularity where the new column SECLABELCOL stores the security labels with the following ALTER TABLE statement: ALTER TABLE T2 ADD COLUMN SECLABELCOL DB2SECURITYLABEL ADD SECURITY POLICY DATA_ACCESS_POLICY
Note • An existing column cannot be altered to become of type DB2SECURITYLABEL. • A column of type DB2SECURITYLABEL cannot be altered or dropped.
Altering Table Protection: Drop Column Protection Protected columns can be converted to nonprotected by removing the security label attached to the protected column. ALTER TABLE --table-name----------------------------------> .------------------------------------------------. V .-COLUMN-. | >--+-ALTER--+--------+--| column-alteration |-------+-----> column-alteration: |--column-name--- DROP COLUMN SECURITY --------------|
Alter table T2 to make it a protected table with the BONUS column protected with security label SL_CONFIDENTIAL with the following ALTER TABLE statement: ALTER TABLE T2 ALTER COLUMN BONUS DROP COLUMN SECURITY
226
Chapter 6 • Label Based Access Control
Altering Table Protection: Alter the Security Policy of a Protected Table In DB2 9, security objects cannot be altered after they are created. In cases where security label components represent some dynamic structure (for instance, an organization tree), elements could change over time. To update a protected table with new security label component definitions, the protected table has to be altered to drop the old security policy and attach the new security policy with the following steps: 1. Create the new security label components. 2. Create the new security policy. 3. Create the new security labels. 4. Alter the protected table T1: a. Drop the current security policy, say ‘Policy_1’. b. If the table is row protected, rename the DB2SECURITYLABEL column, say SEC_LABEL to SEC_LABEL_old. c. Attach the new security policy, say ‘Policy_2’. d. If the table is row protected, add a new DB2SECURITYLABEL column, SEC_LABEL. Then update the security label values as follows: UPDATE T1 SET SEC_LABEL = SECLABEL('Policy_2', SECLABEL_TO_CHAR('Policy_1', DB2SECURITYLABEL(SEC_LABEL_old)) )
e. Drop the SEC_LABEL_old column if it is not needed. 5. After the protected table has been altered, the old security labels granted to users that are no longer applicable should be revoked, and new security labels should be granted to restore user access to the protected table. 6. Security objects that are no longer in use can be discarded.
Remove Protection from Protected Tables To remove protection from a protected table, the administrator can simply detach the security policy from the protected table. After the security policy is detached, protected columns lose their protection. If the table has row protection, the column with data type DB2SECURITYLABEL is changed to VARCHAR(128) FOR BIT DATA. After the column is changed to VARCHAR, the column can be removed from the table. To detach a security policy from a protected table, follow the ALTER TABLE syntax: >>-ALTER TABLE--table-name---DROP SECURITY POLICY-------><
LBAC Support in Miscellaneous Utilities
227
Alter table T2 to remove table protection with the following statement: ALTER TABLE T2 DROP SECURITY POLICY
The privileges held by the session authorization ID of the statement must include SECADM authority.
Dropping Protected Tables Dropping a protected table is the same as dropping a regular table. LBAC credentials are not checked when you drop a table with protected data. If the session authorization ID has the required privileges to drop the table, the protected table can be dropped.
LBAC SUPPORT IN MISCELLANEOUS UTILITIES Views Views are created to allow users to see different presentations of the same set of data. Defining views on protected tables is the same as defining views for unprotected tables. LBAC access rules are enforced on the underlying tables when such view is being accessed. LBAC enforcement does not use the authorization ID used to define the view to determine access; the session authorization ID at the time of the attempted table access is used instead.
Query Through Views Views can be created from querying multiple tables. If two tables are protected by different security policies, how is this going to affect the user of the view? Consider the following scenario: • SALES table is row protected and attached to the REGION_POLICY. • EMPLOYEE table is row and column protected by EMPLOYEE_POLICY, with the SALARY column marked as CONFIDENTIAL. • A view EMPLOYEE_SALES is created by querying the SALES and EMPLOYEE table. CREATE view CKMWONG.EMPLOYEE_SALES (FIRSTNME, LASTNAME, REGION, SALES, DATE) AS SELECT E.FIRSTNME, E.LASTNAME, S.REGION, S.SALES_DATE, S.SALES FROM SALES S, EMPLOYEE E where S.SALES_PERSON=E.EMPNO
228
Chapter 6 • Label Based Access Control
Table 6.38
SALES Table Protected by REGION_POLICY
ID
SALES_DATE
SALES_PERSON
SALES
REGION
SEC_LABEL
1
01/04/2006
121
2000
EAST
SL_EAST
2
11/04/2006
211
3300
WEST
SL_WEST
3
30/04/2006
321
2320
CENTRAL_N
SL_CENTRAL_N
4
02/05/2006
311
1100
CENTRAL_S
SL_CENTRAL_S
5
20/05/2006
212
2020
WEST
SL_WEST
6
24/05/2006
111
3200
EAST
SL_EAST
Table 6.39
EMPLOYEE Table Protected by EMPLOYEE_POLICY
EMPNO FIRSTNME
LASTNAME PHONE
SEC_LABEL
SALARY (Attached to SL_MGMT)
121
Joe
Cool
905-384-2642
SL_D001
65000
211
Ray
Summer
905-979-2321
SL_D002
60000
321
Jane
Lu
416-343-3432
SL_D003
70000
111
Mike
Smith
416-343-3566
SL_D001_M
80000
212
Carol
Mo
647-804-2232
SL_D002_M
85000
311
Peter
San
416-784-3343
SL_D003_M
90000
Table 6.40
Some Users of the EMPLOYEE_SALES View
Responsibility
Session Authorization ID
REGION_POLICY
EMPLOYEE_POLICY
Sales manager for East region
Eason
SL_EAST—All
SL_D001_M—Read access SL_D001—Write access
Employee of East region
JoeC
SL_EAST—Read
SL_D001—Read No write
LBAC Support in Miscellaneous Utilities
229
Example Eason issues this query: SELECT * from EMPLOYEE_SALES;
The view does not involve reading protected columns. To read the protected rows, the user needs to hold the security labels for reading both tables. Eason holds the SL_EAST read security label to access the SALES table, and the SL_D001_M read security label for accessing the EMPLOYEE table. He can see the following rows. Table 6.41
Eason Can Read the Following Rows of the SALES Table
ID
SALES_DATE
SALES_PERSON
SALES
REGION
SEC_LABEL
1
01/04/2006
121
2000
EAST
SL_EAST
6
24/05/2006
111
3200
EAST
SL_EAST
Table 6.42
Eason Can Read the Following Rows of the EMPLOYEE Table
EMPNO
FIRSTNME LASTNAME
PHONE
SEC_LABEL SALARY (Attached to SL_MGMT)
121
Joe
Cool
905-384-2642 SL_D001
65000
111
Mike
Smith
416-343-3566 SL_D001_M
80000
The result of querying the EMPLOYEE_SALES view gives two records. Table 6.43
Results Returned When Eason Queries the EMPLOYEE_SALES View
FIRSTNME
LASTNAME
REGION
SALES
DATE
Joe
Cool
EAST
2000
01/04/2006
Mike
Smith
EAST
3200
24/05/2006
Example Another view EMPLOYEE_SALES_2 is created that accesses the protected column by querying the SALES and EMPLOYEE table and lists the sales and salary of each salesperson: CREATE view EMPLOYEE_SALES_2 (fname, lname, sales, salary) AS with S (sales_person, sales) as
230
Chapter 6 • Label Based Access Control
(select sales_person, sum(sales) from sales group by sales_person) select E.FIRSTNME, E.LASTNAME, S.SALES, E.SALARY FROM EMPLOYEE E, S where S.SALES_PERSON=E.LASTNAME
The SALARY column in the EMPLOYEE table is protected by SL_MGMT. JoeC holds the SL_EAST read security label to access the SALES table, and the SL_D001 read security label for accessing the EMPLOYEE table. JoeC issues this query: SELECT * from EMPLOYEE_SALES_2
He does not have read access to the SALARY column of the base EMPLOYEE table. The following error is returned: SQL20264N For table "EMPLOYEE," authorization ID "JOEC" does not have "READ" access to the column "SALARY." SQLSTATE=42512
However, if Joe issues the query SELECT fname, lname, sales from EMPLOYEE_SALES_2
he can read the following records. Table 6.44
Joe Can Read the Following Records of the SALES Table
ID
SALES_DATE
SALES_PERSON
SALES
REGION
SEC_LABEL
1
01/04/2006
121
2000
EAST
SL_EAST
6
24/05/2006
111
3200
EAST
SL_EAST
Table 6.45
Joe Can Read the Following Record of the EMPLOYEE Table
EMPNO
FIRSTNME
LASTNAME
PHONE
SEC_LABEL
121
Joe
Cool
905-384-2642
SL_D001
The result of querying the EMPLOYEE_SALES_2 view is shown in Table 6.46. Table 6.46
Query Result of the EMPLOYEE-SALES_2 View
FIRSTNME
LASTNAME
SALES
Joe
Cool
2000
Views can be created from the union of two tables with protected columns.
LBAC Support in Miscellaneous Utilities
231
Consider the following scenario: There are three SALES tables for three business units, as shown in Table 6.47. Table 6.47
Sales Table of the Three Business Units with Security Policy Attached
Table
Policy Attached
SALES_SOFTWARE
SALES_SOFTWARE_POLICY
SALES_HARDWARE
SALES_HARDWARE_POLICY
SALES_SERVICE
SALES_SERVICE_POLICY
Each table is protected by a different security policy. All of the tables have SALES_DATE, SALES, and REGION columns. Example The CEO wants to have an idea of the SALES from all business units so a UNION VIEW is created: CREATE view ALL_SALES (SALES_DATE, SALES, REGION) AS SELECT SALES_DATE, SALES, REGION FROM SALES_SOFTWARE UNION SELECT SALES_DATE, SALES, REGION FROM SALES_HARDWARE UNION SELECT SALES_DATE, SALES, REGION FROM SALES_SERVICE
George, the software group manager, has read access on the SALES_SOFTWARE table but has no access to the other two tables. If George queries the ALL_SALES view by issuing the statement SELECT * FROM ALL_SALES
he would see the records from the SALES_SOFTWARE table only.
INSERT through Views Inserting through views operations need read access on the base table. Insert through a view will work even if the authorization ID of that statement has no INSERT privilege on the base table as it is the view definer’s authorization that is used for such checks. However, the session authorization ID in which the INSERT statement was issued must have a valid security label to write to the base table.
232
Chapter 6 • Label Based Access Control
Materialized Query Table (MQT) MQTs are database tables that store query result sets. When a table has dependent MQTs, the table cannot be made protected. That means that an alter operation to make such table protected would fail. Similarly, the creation of MQTs to depend on one or more protected tables is not supported. Besides, MQTs cannot be made LBAC protected.
Staging Table Staging tables cannot be made LBAC protected.
Typed Table Typed tables cannot be made LBAC protected.
Import Importing data into a protected table is restricted as if the user is inserting rows into the protected table. To import data into a protected table with protected rows, the session authorization ID has to be granted with a security label for write access that is part of the security policy protecting the table. To import data into a protected table with protected columns, the session authorization ID has to be granted with a security label and/or exemptions for write access to all protected columns in such table.
Export LBAC access rules are applied when data is exported from a protected table. For protected tables with protected rows, only the rows for which the session authorization ID has read access are exported. For protected tables with protected columns, export will fail if any protected columns selected are not allowed to be read by the session authorization ID.
Load To load data into a protected table with protected rows, the session authorization ID has to be granted with a security label for write access from the LBAC security policy protecting the table.
LBAC Support in Miscellaneous Utilities
233
Note the following: • Loading a protected table with row level granularity may require the session authorization ID to write various security labels for different rows. If the session authorization ID is not allowed to insert a row with a particular security label, the row is inserted but the row security label column is set to the default security label for write access (that the session authorization ID was granted from the LBAC security policy protecting such table). • Access to an exception table is not enforced by LBAC access rules. When an exception table is specified for storing data rows in error (for example, rows with an invalid security label), users with access to such an exception table can gain knowledge about information that otherwise they may not be authorized for. For better security, the exception table should be dropped when the data rows in error are fixed and copied back to the protected table being loaded. Alternatively, access to the exception table should be granted only to authorized users. To load data into a protected table with protected columns, the session authorization ID has to be granted with security labels and/or exemptions for write access to all protected columns in such a table. It is recommended that the session authorization ID be granted an exemption on all the rules in the security policy attached to the protected table and granted a valid security label that will be used to label data rows that do not already have a security label.
Copy Table in Control Center Using the Control Center, users can copy a table from one database to another. The copy table action executes an EXPORT and IMPORT operation behind the scene. Such operations are enforced by LBAC access rules. Thus, if the session authorization ID does not have read-andwrite access to all the rows of the protected table, the table copied might not be an exact copy of the original table. To allow the session authorization ID to make an exact copy of a protected table, the SECADM might need to be granted an EXEMPTION on rules that are enforced on the protected table.
Stored Procedure: ADMIN_COPY_SCHEMA The ADMIN_COPY_SCHEMA procedure copies a specific schema and all objects contained in it. The procedure can be used to copy tables with or without the data of the original tables.
234
Chapter 6 • Label Based Access Control
If the schema contains protected tables, the session authorization ID used to call the stored procedure must have LBAC credentials that allow them to do the following: • Create the target table EMPLOYEE_RECORD_POLICY • Read the data from the source table, and write that data to the target table if data needs to be loaded
Database Backup LBAC access rules are not enforced for backup operations. When a protected table is backed up, LBAC credentials are not checked. Besides, protection applies only to data in the database. Data on the backup media is not protected. Therefore, backups that contain protected data need to be handled with extra caution. Any user with the backup and a place in which to restore it can gain access to the data. Data in backup is outside the scope of the database security capabilities. The catalogs determine the actual protection. When data is recovered from a backup, there is no way to guarantee that the catalog of the database into which the data is recovered has the same LBAC policy definitions and security labels granted as the originals.
Alter Table Altering a protected table could be restricted by LBAC access rules. • Cached dynamic SQL and packages—If there are cached dynamic SQL sections dependent on a table, adding protection would cause the cached dynamic SQL sections to be invalidated. Any packages that depend on the table are also invalidated. Similarly, if the table is altered to remove column protection, cached dynamic SQL sections and packages are also invalidated. • Partitioned tables—When you are attaching a partition to a protected partitioned table, the source table and the target table have to be protected with the same security policy, have the same row security label column, and have the same set of protected columns. When you are detaching a partition from a protected table, the target table automatically created by the DB2 system will be protected in exactly the same way the source table is protected.
Referential Integrity Constraints The following rules explain how LBAC rules are enforced in the presence of referential integrity constraints.
LBAC Support in Miscellaneous Utilities
235
Example EMPLOYEE table is the parent table. Its primary key is named “ID”. PROJECT table is the child table which references EMPLOYEE with foreign key, EMPID. CREATE TABLE EMPLOYEE (ID CHAR(5) NOT NULL, NAME VARCHAR(15) NOT NULL, DEPT CHAR(10) SECURED WITH SL_DEPT_LABEL, SECCOL DB2SECURITYLABEL, PRIMARY KEY (ID) ) SECURITY POLICY SECPOLICY_EMPLOYEE CREATE TABLE PROJECT (PJID VARCHAR(18) NOT NULL, NAME VARCHAR(30) NOT NULL, MGR CHAR(10) SECURED WITH SL_TEAM, FOREIGN KEY (ID) REFERENCES EMPLOYEE ON DELETE ) SECURITY POLICY SECPOLICY_PROJ
Rule 1: The LBAC read access rules are not applied for internally generated scans of child tables. This is to avoid having orphan children. Example Table PROJECT has set to RESTRICT. When rows are deleted from table EMPLOYEE, PROJECT will be scanned to check whether any row in PROJECT is referencing EMPLOYEE. The scan of child table is not restricted by the LBAC read access rules. Rule 2: The LBAC read access rules are not applied for internally generated scans of the parent tables. Example When a row is to be inserted into PROJECT, the EMPLOYEE table will be scanned to ensure the foreign keys exist in the parent table EMPLOYEE. The scan on the parent table is not restricted by the LBAC read rules.
Rule 3: The LBAC write rules are applied when a CASCADE operation is performed on child tables.
236
Chapter 6 • Label Based Access Control
Example If a user deletes a parent but cannot delete any of the children because of an LBAC write rule violation, the DELETE will be rolled back and an error will be raised.
Explain EXPLAIN is used to generate execution access plans to demonstrate how an SQL or XQuery statement will be executed. The read access that a user has on protected data does not affect the result of EXPLAIN. Even if a user does not have access to a protected column, EXPLAIN can be executed without error.
db2look db2look extracts the Data Definition Language (DDL) statements to reproduce database objects. To get the data definition of security objects of a database, you can issue the following db2look command: db2look –d dbname –e
To get the list of security objects granted to the database users, you can issue the following db2look command: db2look –d dbname –x
LAST WORDS Label Based Access Control provides a robust, powerful mechanism for restriction and control access of sensitive data. Before LBAC is applied, thorough analysis must be done to develop a list of what data needs to be protected, how the data should be protected, and who should have rights to access the data. LBAC security administrators must hold the SECADM authority and should understand the nature of each type of security label component and how the security labels are being compared to design a suitable and effective LBAC solution. After the security objects have been created, the definitions cannot be changed. The security objects can only be dropped and re-created. LBAC security administrators (and database administrators) should be aware that when a table is protected by a security policy, the utilities that interact with the protected table could be impacted. Commonly carried out tasks may fail unexpectedly if LBAC controls are not created and managed correctly.
REFERENCE MATERIAL • A Multi-Purpose Implementation of Mandatory Access Control in Relational Database Management Systems, by Walid Rjaibi, Paul Bird
CHAPTER
7
Encryption (Cryptography) in DB2
hen you were a kid, did you play hide and seek? Remember at twilight when you used to hide in the shadows and use the absence of light to provide an extra layer of concealment? Encryption is way better than that. It is even better than an invisible DBA cape.
W
FIRST WORDS The Internet is such a part of our lives these days. We use it more and more for normal day-to-day commerce. Banking and financial institutions are now online, as are many critical government agencies. International trade is facilitated via the Internet. With these communication advances, many of us can work “remotely” now with geographic restrictions no longer serving as a limiting factor on the proximity of our work location to our home location. But as technology gives, so can it take. By opening our lives through these electronic means, we also invite unwanted attention from those who would take undue advantage. If we want to continue to enjoy the freedoms offered by remote database access, we must be willing to provide mechanisms that protect us. In this remote database world, users may input their passwords or type in sensitive data such as Social Security numbers while accessing DB2 databases through an Internet connection. How can DB2 be used to secure the connection password, protect highly sensitive data through the network, and shield sensitive data when it is stored on disk? Encryption is the answer. Encryption can be used to send and receive secure data through the Internet, guard it all the way to the database, and protect the data as it sits on the disk.
237
238
Chapter 7 • Encryption (Cryptography) in DB2
If you are interested in a robust security implementation, you are probably already considering some form of encryption. You probably have questions: Which cryptography methods does DB2 use to secure data? What type of data can be secured? What setup is required to ensure data security? This chapter answers those questions. In the remainder of this chapter, you will see the terms cryptography and encryption. The term cryptography refers to the discipline and practice of data protection. Cryptography uses encryption as a mechanism for that protection.
THE CRYPTOGRAPHIC KEYS Cryptography is a complex topic, but a complete understanding of the topic is not necessary when using DB2 because the “work” of encryption has been designed into the product itself. Although we will briefly discuss the concepts of “public” versus “private” key design, this is not an in-depth tutorial. As you would expect, additional education on this topic can provide the DBA a stronger grasp of the concepts of cryptography and securing data in general. Many security certification designations (CISSP, for example) do require an understanding of cryptography to obtain the certification. If you desire additional information on cryptography, numerous colleges and technical schools offer courses. In addition, there are a number of good books on the topic, and Internet search engines will provide many “hits” on the term cryptography. The resources are plentiful if you want to learn more.
Private Key Cryptography Private Key Cryptography is also called symmetric cryptography. It uses a private (secret) key that is shared between two partners. Each partner has its own private key to encrypt and decrypt the data. An example of Private Key Cryptography is the Data Encryption Standard (DES), which applies a 56-bit key to each 64-bit block of data. There are many different ways to form a secret key. The simplest way is for both partners to connect through a secure channel and agree on a secret key. However, if there literally is a secure channel, there is no need to have cryptography at all. In its most simplistic terms, Private Key Cryptography relies on communication between two participating partners and, using an algorithm, allows a secret key to be derived. A number of different algorithms are widely used. The Diffie-Hellman Exchange algorithm is one that is used in many products including DB2. For the Diffie-Hellman Exchange algorithm, each partner has its own public and private key that they use to form a secret key.
What Type of Encryption Does DB2 Use?
239
Public Key Cryptography Public Key Cryptography is also called asymmetric cryptography. It consists of two keys: a public key and a private key. The public key is distributed to any peer, and the private key is kept secret. The message is encrypted with the public key and can be decrypted only with the private key. After the encryption, the encrypted message can be read by anyone; however, without the private key, the encrypted message is meaningless. An example of Public Key Cryptography is RSA. The name RSA comes from the initials of the inventors, Ron Rivest, Adi Shamir, and Leonard Adleman. On the other hand, if the data is encrypted by private key, it can be decrypted only with the corresponding public key. This forms the basis of a digital signature. In general, the public key has to be certified by a third party. Today, there are many companies who can certify a public key (for example VeriSign Inc.). Private key holders can certify the public key. If using the public key to send secret data to the private key holder, the data is encrypted with the public key. The encrypted data can then be decrypted by the private key holder.
WHAT TYPE OF ENCRYPTION DOES DB2 USE? Before we discuss what type of cryptography is being used in DB2, let’s consider what actually can be encrypted: • User ID and password sent in a “connection” statement • Sensitive data as it flows through the network • Sensitive data stored on disk DB2 uses the DES algorithm, a Private Key Cipher, from IBM Crypto for C (ICC) to perform the encryption and decryption on user ID and password in the connection statement and sensitive data through the network. For sensitive data that is stored on disk, any SQL statements must provide the password for encryption and decryption. DB2 uses the RC2 block cipher with padding to encrypt the data to be stored on disk.
Encryption for User IDs and Passwords Passed in the Connect Statement DB2 uses the DES algorithm to encrypt user ID and password entered with the connect statement. If a new password option is provided, it will also be encrypted. The symmetric key is negotiated using the Diffie-Hellman key exchange technique. The key is generated for every connection. Basically, the client first generates a public key that is sent to the server. The server receives the client public key and, by using its own private key, calls ICC to create the secret key. Afterward, the server returns its public key back to the client. The client intercepts the server public key, and
240
Chapter 7 • Encryption (Cryptography) in DB2
by using its own private key, the same secret key is created when ICC is called. Figure 7.1 shows the generation of secret keys at the client and server side.
Secret Key
ICC (2) Public Key from Client + Private Key from Server
(1) Public Key from Client Public Key
Private Key
CLIENT SIDE
SERVER SIDE
Private Key
Public Key (3) Public Key from Server
(4) Public Key from Server + Private Key from Client ICC
Secret Key
Figure 7.1
How to generate secret keys at client and server side
For any user ID and password that need to be encrypted, DES is applied by using the secret key. Because DES is a symmetric algorithm, the secret key can encrypt the user ID and password at the client side and can also decrypt the user ID and password at the server side. The graphic in Figure 7.2 shows the flow of the user ID/password between the client and server. For DB2 to encrypt the connection user ID and password, there are two steps. First, change the AUTHENTICATION mechanism in the Database Manager Configuration (DBM CFG) to SERVER_ENCRYPT. This can be done via the following command: db2 "update dbm cfg using authentication server_encrypt"
At the client side, the corresponding authentication method is set by cataloging the database with the authentication specification SERVER_ENCRYPT. After you set the authentication types correctly, DB2 calls the ICC module to perform encryption for the connection user ID, password,
What Type of Encryption Does DB2 Use?
241
and the new password. At the server side, the encrypted connection user ID, password, and the new password will be decrypted. The decrypted user ID and password will be used for authentication. The syntax of the CATALOG DATABASE COMMAND to enable SERVER_ENCRYPT on the client is as follows: db2 "catalog database at node <nodename> authentication server_encrypt"
Plain text username and password
DES Algorithm
Encrypted username and password
Encrypted username and password
Secret Key
DES Algorithm
Plain text username and password
Secret Key
SAME
Figure 7.2
Encryption and decryption for user ID and password at client and server side
Encryption for Sensitive Data Sent Through the Network The preceding section discussed how DB2 encrypts the connected user ID and password. However, encrypting a password does not prevent hackers from intercepting sensitive data as it travels through the network. To prevent hackers from reading user data, DB2 provides two Database Manager Configuration authentication parameters: DATA_ENCRYPT and DATA_ENCRYPT_CMP. The DATA_ENCRYPT authentication method is designed to provide encryption of data during client/server communication through the network (on the wire). DATA_ENCRYPT_CMP also provides data encryption, but only if the “connecting” client can also support the DATA_ENCRYPT authentication method. For both DATA_ENCRYPT and DATA_ENCRYPT_CMP, the encryption algorithm deployed by these parameters is the same as that used for SERVER_ENCRYPT password encryption. DATA_ENCRYPT
After the AUTHENTICATION Database Manager Configuration parameter has been set to DATA_ENCRYPT, the server accepts encrypted server authentication schemes plus encrypts the user data. The actual authentication of the user ID/password combination works exactly the same way as if SERVER_ENCRYPT were being used.
242
Chapter 7 • Encryption (Cryptography) in DB2
The following user data is encrypted when this authentication type is used: • SQL statements • SQL program variable data • Output data from the server processing a SQL statement (including a description of the data) • Some or all of the answer set data resulting from a query • Large object (LOB) streaming • SQLDA descriptors DATA_ENCRYPT_CMP
The authentication type DATA_ENCRYPT_CMP is designed for “back-level” client support. By using the DATA_ENCRYPT_CMP authentication method, it is possible for previous DB2 client installations (that cannot support these newer parameters) to reach the database. The DATA_ ENCRYPT_CMP authentication method allows those earlier release clients to use SERVER_ ENCRYPT functionality “under the covers” to successfully establish a connection to the database. DATA_ENCRYPT_CMP is especially useful during times when not all clients have been upgraded to the latest product versions. Those clients that have the latest versions will make full use of the DATA_ENCRYPT functionality, whereas those clients that are not yet upgraded will still be able to connect to the database via the SERVER_ENCRYPT functionality. One note, however: The DATA_ENCRYPT_CMP authentication method does not work under the following conditions: • The client level is Version 7.2 • The gateway level is Version 8 FixPak7 or later • The server is Version 8 FixPak 7 or later When these are all true, the client cannot connect to the server. To allow the connection, the user must do one of the following: • Upgrade the DB2 client to Version 8 or later • Have DB2 gateway level at Version 8 FixPak 6 or earlier Although user data will be encrypted as it flows through the network, the following items will not be encrypted: • SQLCA • Database name in the connection statement • Package information such as package name, package creator, consistency token, and section number
What Type of Encryption Does DB2 Use?
243
You might have noticed that the CATALOG DATABASE command shown previously in this chapter has an AUTHENTICATION stanza. The DATA_ENCRYPT_CMP authentication method is different in that it is valid only when set at the Database Manager Configuration level. It is not valid when used as a stanza on the CATALOG DATABASE command. This is not problematic from a connection standpoint. The CATALOG DATABASE command can still specify SERVER_ ENCRYPT, thus allowing down-level support to ensure successful connections with encrypted user IDs and passwords (after the Database Manager Configuration is set for DATA_ ENCRYPT_CMP). When you are setting up the encryption authentication values, DB2 will warn you if the client and server authentication type cannot be negotiated. If they are not compatible types during the connection attempt, the connection will be refused with an error (SQLCODE of -30082 reason code 17). The security mechanism specified by the client is invalid for this server.
Encrypting Sensitive Data Stored on Disk As you can see, sensitive data can be encrypted through the network by simply setting some parameters. However, even if the data is encrypted through the network, the data is decrypted before being saved to disk on the database server. If data is not encrypted when it is stored on disk, there is still a risk that hackers or insiders can breach sensitive data by reading the disk. To solve this issue, DB2 provides an additional encryption feature that can be used to encrypt any sensitive data that is stored on disk. After encrypting the data on disk, even those who gain access and can “read” the disk will no longer be able to identify the data. The result is that the data is private to the user who encrypted it. For any sensitive data, the best practice is to use both the DATA_ENCRYPT authentication type that was mentioned in the preceding section and the additional encryption features previously mentioned. Normally, the DB2 encryption features can also be used to encrypt nonsensitive data. However, because of performance considerations, data encryption is typically considered for only sensitive data. DB2’s disk encryption functionality relies on SQL built-in functions to encrypt and decrypt sensitive data. If you use the SQL built-in function ENCRYPT(), when data is stored to disk, the resulting data will be encrypted using an encrypted password supplied by the user. When data is fetched, the same password must be supplied to the SQL built-in functions DECRYPT_ CHAR()/DECRYPT_BIN() to decrypt the sensitive data. The result of the DECRYPT_BIN function is VARCHAR FOR BIT DATA, and the result of the DECRYPT_CHAR function is VARCHAR. DB2 also provides “ease-of-use” features that eliminate many keystrokes and assist with those “can’t remember my password” issues. Because the user may apply the same password multiple times within a connection, the ENCRYPT PASSWORD registry variable can be set for the duration of the connection. If users have multiple passwords, an optional parameter, PASSWORDHINT, can
244
Chapter 7 • Encryption (Cryptography) in DB2
be applied to the ENCRYPT function to supply a predetermined hint to the user for the password. The built-in function GETHINT can be issued to return the password hint of the encrypted data. Examples of setting the ENCRYPT PASSWORD registry variable, PASSWORDHINT parameter,
and GETHINT function will be shown later in this chapter. SQL Built-In Functions DB2 has three SQL built-in functions that are associated and used to encrypt/decrypt sensitive data, as follows: • ENCRYPT(data-string-expression, password-string-expression, hintstring-expression) The ENCRYPT function returns a value that is the result of encrypting the datastring-expression. The password used for encryption is either the passwordstring-expression value or the ENCRYPTION PASSWORD value (as assigned using the SET ENCRYPTION PASSWORD statement). In a Unicode database, if the supplied argument is a graphic string, it is first converted to a character string before the function is executed. To encrypt the data for the ENCRYPT function, DB2 uses an RC2 block cipher with padding where the secret key is derived from the password using an MD5 message digest. The encryption password is not tied to DB2 authentication, and is used for data encryption and decryption in the statement only. Figure 7.3 shows an example of applying the encryption function to sensitive data.
Figure 7.3
Example of applying the encryption function to sensitive data
• DECRYPT_CHAR(encrypted-data, password-string-expression) The DECRYPT_BIN and DECRYPT_CHAR functions both return a value that is the result of decrypting encrypted-data. The result of the DECRYPT_BIN function is VARCHAR FOR BIT DATA, and the result of the DECRYPT_CHAR function is VARCHAR. The password used for decryption is either the password-string-expression value or the ENCRYPTION PASSWORD value assigned by the SET ENCRYPTION PASSWORD statement. The DECRYPT_BIN and DECRYPT_CHAR functions can decrypt only values that were encrypted using the ENCRYPT function.
What Type of Encryption Does DB2 Use?
245
Figure 7.4 shows an example of applying the decryption function for sensitive data.
Figure 7.4
Example of applying the decryption function to sensitive data
• GETHINT(encrypted-data) Have you ever forgotten your password? Of course, we all do. Fortunately, DB2 can provide a “hint” to help you get it right. The built-in function GETHINT returns the password hint if one is found in the encrypted-data. A password hint is a phrase that will help data owners remember passwords; for example, Ocean is a hint to remember Pacific. In a Unicode database, if a supplied argument is a graphic string, it is first converted to a character string before the function is executed. The result of the function is VARCHAR(32). The result can be null; if the hint parameter was not added to the encrypted data by the ENCRYPT function or the first argument is null, the result is the null value. Figure 7.5 shows an example on providing an optional parameter, PASSWORDHINT, in the ENCRYPT function.
Figure 7.5 function
Example of providing an optional parameter, PASSWORDHINT in the ENCRYPT
Each record is associated with different hints. By using the GETHINT function, the PASSWORDHINT result will be returned (Figure 7.6).
Figure 7.6
Result of PASSWORDHINT by using the GETHINT function
246
Chapter 7 • Encryption (Cryptography) in DB2
Set Encryption Password Statement ENCRYPTION PASSWORD statement sets the password that will be used by the ENCRYPT, DECRYPT_BIN, and DECRYPT_CHAR functions. The password is not tied to DB2
The SET
authentication and is used for data encryption and decryption only. The length of encrypted password must be between 6 and 127 bytes. All characters must be specified in the exact case intended because there is no automatic conversion to uppercase characters. The initial value of the ENCRYPTION PASSWORD is the empty string (‘’). The ENCRYPTION PASSWORD registry variable value will apply to the rest of the connection. The advantage of setting the registry variable is to prevent the need to constantly input the password. Figure 7.7 shows an example of setting an encryption password.
Figure 7.7
Example on setting encryption password
Encrypt/Decrypt with DB2 Built-In Functions Now that you have an overview of the encryption functionality provided by DB2, let’s explore ways to use these built-in functions to encrypt and decrypt data. We will also walk through some examples to illustrate how to make use of encryption protection for sensitive data. When encrypting data, users can choose to encrypt a given column with the same password (Column Level Encryption) or encrypt the data in each cell of a column with a different password (Cell Level Encryption). Column Level Encryption Column level encryption is often used to encrypt a given column with the same password. Figure 7.8 shows an example of encrypting a given column with the same password.
Figure 7.8
Example of how to encrypt a given column with the same password
You probably noticed that in the first SQL statement in Figure 7.8 that the SSN column was declared as a VARCHAR FOR BIT DATA. All encryption columns (SSN in this example) must
What Type of Encryption Does DB2 Use?
247
be declared as VARCHAR FOR BIT DATA because this is the return data type for ENCRYPTION function. In the second SQL statement in the example, the encrypted password is set to 'abc123'. As mentioned previously, this password will now apply during the remainder of the connection. (That is, the encrypted password registry variable will be applied to the ENCRYPT function from the third SQL statement to fifth SQL statement.) For data to be encrypted, if neither the encryption password is provided nor the encrypted password registry variable set, the encryption will fail (Figure 7.9).
Figure 7.9
Failure without providing password
If users select the table directly without using the DECRYPT function, they will get back the encrypted sensitive data (Figure 7.10).
Figure 7.10
Getting back the encrypted sensitive data
The sensitive data remains undisclosed even if the user is a database administrator. Cell Level Encryption Cell level encryption is similar to column level encryption except that each cell in the column is encrypted with an individual password. The advantage for the cell level protection is that it is less likely to be subject to a brute-force attack. Even if someone manages to decrypt one of the passwords for one of the cells, the password for the next cell can be a completely different value. Thus, it makes it harder for the hackers to use a brute-force attack. However, as you can imagine, having cell level protection imposes complexity for key management. Instead of remembering one key, you can have potentially as many keys as the number of rows in the table using cell-level protection.
248
Chapter 7 • Encryption (Cryptography) in DB2
Figure 7.11 shows an example on how to encrypt individual cells with different passwords.
Figure 7.11
Encrypt individual cells with different passwords
For SQL statements from two through four shown in Figure 7.11, the column SSN is encrypted with different passwords accordingly. This is similar to column level encryption, selecting from the table will return encrypted sensitive data (see Figure 7.12).
Figure 7.12
Getting back the encrypted sensitive data
Because sensitive data can be encrypted, there must be a way to decrypt it; otherwise, it would be uselessly protected from ever being seen again. Because that is probably not the desired outcome, built-in functions DECRYPT_CHAR()/DECRYPT_BIN() can be used to decrypt sensitive data. As mentioned previously, there are two ways to encrypt the data, so there are also two ways to decrypt it. The first way is to use the encrypted password in the SET ENCRYPTION PASSWORD statement. The second way is to provide the password in the decrypt function accordingly. For column-level encryption, the decryption can be done using the DECRYPT_CHAR() SQL built-in function, as shown in Figure 7.13.
Figure 7.13
Getting back the sensitive data with column-level encryption
What Type of Encryption Does DB2 Use?
249
The DBA should realize that by using the encryption password in the SET ENCRYPTION PASSWORD statement, the password will apply to all of the columns in the decrypt function. The DECRYPT_CHAR() SQL built-in function can also apply to cell-level encryption. If celllevel encryption was used, the decryption can still be done, as shown in Figure 7.14.
Figure 7.14
Getting back the sensitive data with cell-level encryption
If the user does not provide the correct password, the SELECT statement is not going to return the decrypted data, as shown in Figure 7.15.
Figure 7.15
Sensitive data wasn’t returned with incorrect password
Password Hint In reality, users usually have multiple passwords and forget the passwords easily. An optional parameter PASSWORDHINT can be applied to the ENCRYPT function to provide the user with a hint of the password. The built-in SQL function GETHINT can be issued to return the password hint of the encrypted data. Figure 7.16 shows an example on providing an optional parameter, PASSWORDHINT, in the ENCRYPT function.
Figure 7.16 function
Examples on providing optional parameter PASSWORDHINT in the ENCRYPT
250
Chapter 7 • Encryption (Cryptography) in DB2
Each record is associated with different hints. If you use the GETHINT SQL function, the PASSWORDHINT result will be returned (Figure 7.17).
Figure 7.17
Getting the PASSWORDHINT result
Of course, if the user doesn’t have SELECT privilege on the table emp3, SQLCODE -551 will be returned instead of the desired information. With the ENCRYPT function, if the encryption password was supplied via the SET ENCRYPTION PASSWORD statement, the hint cannot be supplied on the ENCRYPTION call. To address this issue, the user can use cell-level encryption on the password with the PASSWORDHINT parameter. For those rows where hints are not provided, NULL is returned. As mentioned previously, the returned result data type of the ENCRYPT function is VARCHAR FOR BIT DATA. When defining columns and types to contain encrypted data (and optionally, a hint), always calculate the length attribute as follows: For encrypted data with no hint Maximum length of the nonencrypted data + 8 bytes + the number of bytes to the next 8 byte boundary = encrypted data column length An example of calculating the length when no hint is provided is shown in Figure 7-18. For this example, assume the maximum length of the nonencrypted data is 20. The column length of the table has to be defined as 32 (20 + 8 = 28, and the next 8-byte boundary will be 32). Otherwise, the insert statement will fail with SQLCODE -433. To test the calculation, create two tables, Testing1 and Testing2, each with a column named c1. In the Testing1 table, create the c1 column as varchar(31) for bit data. In Testing2, create the c1 column as varchar(32) for bit data. Following the sequence of events as shown in Figure 7.18, you can see that inserting a value of 20 characters into column c1 will fail on the Testing1 table but will succeed on the Testing2 table.
What Type of Encryption Does DB2 Use?
Figure 7.18
251
Example of defining the column length of nonencrypted data
For encrypted data with an embedded hint When using a password hint, the calculation above must be changed to accommodate the additional space necessary. Now the calculation becomes this: Maximum length of the non-encrypted data + 8 bytes + the number of bytes to the next 8 byte boundary + 32 bytes for the hint length = encrypted data column length To validate this calculation, we build another test scenario as shown in Figure 7.19. For this example, assume the maximum length of nonencrypted data is still 20 and that a password hint is required. The column length of the table has to be defined as 64 (20 + 8 = 28, and the next 8-byte boundary will be 32. The resulting size of the c1 column will now be 32 + 32 = 64). Otherwise, the insert statement will fail with SQLCODE -433.
Figure 7.19
Example of defining the column length of nonencrypted data with hint
How to Handle Noncharacter Data Types With the ENCRYPT SQL function, the first parameter of the function must be a character value (CHAR or VARCHAR). What happens to noncharacter data? How can it be encrypted? To solve this issue, a user can “cast” the noncharacter SQL types to VARCHAR or CHAR datatype so that they can be encrypted by the built-in function.
252
Chapter 7 • Encryption (Cryptography) in DB2
As an example, consider the EMP4 table shown in Figure 7.20. When the table is built, the c1 column is defined as an integer data type. In this example, the first attempt to use the encrypt function fails since the requirement for the data to be either VARCHAR or CHAR was not met. To succeed, an extra step is required to convert the integer data into character data. Using the SQL varchar() function, the conversion is done and the encryption succeeds, as shown in Figure 7.21.
Figure 7.20
Applying ENCRYPT function to a noncharacter column
Figure 7.21
Modify the noncharacter column to character column
Now that the data is correctly encrypted as a character data type, the user can decrypt the data as shown in Figure 7.22.
Figure 7.22
Applying DECRYPT function to character column
Other Tips on Using the Encrypt/Decrypt Function When sensitive data is encrypted, it can still be compared without first decrypting it. There are, however, both pros and cons to this approach. To see how comparing the data without first decrypting it functions, we will work through an example using two tables, EMP1 and EMP5. In Figure 7.23, the EMP5 table is created and some data is inserted. To illustrate the process of comparing the encrypted data, we need another table. In this case, we will use the EMP1 table as shown previously in the “Column-Level Encryption” section.
What Type of Encryption Does DB2 Use?
Figure 7.23
253
SQL statements for table EMP5
Now the comparison can be attempted using normal SQL queries. Figure 7.24 shows two different queries. The first does the comparison but does not use the DECRYPT function. The second query also does the comparison but does decrypt the data first.
Figure 7.24
Joining tables with and without using DECRYPT function
After running the queries, we notice that by joining the tables without applying the decryption function the query results are identical to those of the second query that did use the DECRYPT function. The obvious advantage of doing the comparison without first performing the decryption is performance, because it is not necessary to first decrypt every row on table EMP1 and EMP5 before the join operation. Conversely, without decryption, rows may not be returned if the password is not the same—because the sensitive data is stored differently after encryption.
254
Chapter 7 • Encryption (Cryptography) in DB2
LAST WORDS This chapter presented basic knowledge about DB2’s encryption functionality including dealing with the user ID and password in the connection statement and sensitive data as it flows through the network and resides on disk. However, applying encryption will always slow down the processing of the statements or commands because of the additional work for encryption. It comes down to a trade-off between security and performance. It is hard to say what the performance impact will be because it depends on factors such as length of data to be encrypted and the CPU speed of the machine. As a minimum, encryption should apply to passwords, sensitive statements, and sensitive data even though it may slow down the processing. A common misconception concerns the value of encryption versus the traditional methods that DB2 uses to keep data secure from unauthorized usage. Some security measures (for example, user ID/password controls) are ineffective against a person who can circumvent the operating system, such as the technician who services your storage subsystem and who might physically remove defective disks from that subsystem. On the other hand, encryption itself is not a protection against somebody who illicitly gains access to a password because DB2 will decrypt data on behalf of an authorized user. Thus, encryption and user ID/password controls are complementary aspects of security, helping to protect against different types of security exposures. The technical challenges associated with encryption can include application changes, performance overhead, and the difficulties of managing the encryption keys.
CHAPTER
8
Ready, Set, Implement?
hopping for a wardrobe one item at a time means that at some point, you have to put all the pieces together to achieve an outfit. Working through the pieces of DB2 security one step at a time means that, at some point, you need to step back and form the foundation that achieves the secure environment.
S
FIRST WORDS: JUST START…BUT WHERE ? Sometimes, just starting a task is the hardest part. Where should you begin the task of a secure DB2 implementation? You might be wondering why this chapter is not the first one in the book. But, without some foundational knowledge about the DB2 product and some understanding of how to create policies and procedures, “putting it all together” is not a logical conduit to creating a secure environment. Attempting to design and implement a secure environment without first understanding the technical implications may be worse than making no attempt at all. So, first, you must know the DB2 product. You must understand how it works and how it “plays” in your environment. You must have had some challenging experiences with DB2. You must be aware of its features. You must be comfortable that your skill set has enough muscle to see any security pluses and minuses for decisions made before, during, and after implementation. After you have jumped these hurdles, then you are ready to step back and actually do the work that has been, up until this point, primarily a thought process.
255
256
Chapter 8 • Ready, Set, Implement?
APPLY KNOWLEDGE REUSE Putting database security to work is a necessarily methodical and cyclical task. Although not every step in the process is applicable to every implementation, DBAs who have done numerous secure database deployment projects begin to recognize steps that are frequently repeated. With familiarity, each new implementation becomes easier. For this reason, many DBAs keep detailed documentation on what they did and how they did it and include a rationale for each step. Even though the security landscape seems to change with great frequency, especially as vendors step up to the challenges of building more security-related options into their products, those notes on projects that were completed years ago will still provide valuable time-saving shortcuts. Consider creating some type of “free-flow” document (similar, perhaps, to a personal blog or a mind map) as you work though any security exercise. The format is not important, but the thoughts captured there may aid you in future implementations. Of course, you must make sure that this document could not be used by someone to gain inappropriate access, but you might be surprised at how even “random” notes can serve as thought triggers that provide shortcuts for successive security projects.
AN IMPLEMENTATION BEGINNING POINT At this point, it is time to pull out those policies and procedures discussed in Chapter 2, “DB2 Security—The Starting Point.” These will be a valuable starting point for this phase of the process of security implementation. Hopefully, you have well-defined and concise documentation (and appropriate management buy-in) and can now begin the process of building secure DB2 database environments. Take time to review and revise these with any “new learning” that has been uncovered so far before proceeding.
KEEPING IT REAL—NO ONE SIZE FITS ALL Unfortunately, there is no one “boilerplate” for stepping through a security implementation. Even if you followed the advice of Chapter 2, even if you have excellent policies and procedures in place, even if you are wearing your Super-Invisible DBA cape, you will encounter unexpected hurdles at some point. The best this book can offer is the knowledge and understanding of the most critical steps that can be customized as necessary to meet the goals your organization has stated for security implementations. Obviously, the policies and procedures cannot cover every eventuality. DB2 policies, for example, are specific to DB2 databases and, typically, do not cover aspects of a secure implementation that are provided elsewhere. For example, password maintenance is typically not a DB2 DBA requirement, nor is data modeling, but an understanding and participation in these activities can lend strength to database security. Although it will seem overwhelming at times, just keep pushing forward, breaking large tasks into small and bridging the gaps until you arrive at the end goal.
Things Not Considered (That Likely Should Have Been)
257
THINGS NOT CONSIDERED (THAT LIKELY SHOULD HAVE BEEN) There are likely to be hiccups and glitches along the implementation timeline. A list of topics that “might” arise as the implementation progresses would take another book, but there are some “themes” that seem to recur on many security projects.
Password Authentication and Maintenance Because the DB2 DBA has typically relied on the operating system administrators to manage password authentication and maintenance, it might not be obvious why a DB2 DBA needs to be involved in this step of the security implementation. Although it is true that the DB2 policies may not address this topic, it is not one that should be ignored by the DBA team either. Special Connection IDs Consider a scenario for a purchased application such as a fictional Human Resources module. By design, the user logs in to her workstation with her normal user ID and successfully launches a Web browser to gain access to the HR system. The Web layer is then connected to an application server where the HR application software runs. The application server is where the connection to the database actually is instantiated. In the HR module product (as in some “real-world” products), the design is that this “application server” connection to the database uses one “connection ID” to pass a connection string to the database. Managing the password for this particular connection ID is challenging because it is not tied to a real “user,” but is embedded in an application. It might be tempting in a case such as the HR module application to allow this particular connection ID to keep its password forever. Obviously, the DBA who is tasked with a secure implementation is not going to be comfortable with that approach. Allowing the password to expire, however, brings up other issues. For example, after the password has expired, who holds the responsibility to reset it? When it is reset, what other steps (required by the application software) need to be accomplished to allow the connection ID to continue to access the database? Even if this is not a problem directly tasked to the DB2 DBA, because database access may become unavailable as a result of password issues for this special connection ID, the DB2 DBA’s expertise may be invaluable in creating a solution. Considering the implications, the DB2 DBA could recommend that the password be reset on a 12-week cycle during a routine database maintenance window so that an outage would already have been anticipated by the user community. This applies the necessary secure implementation approach while minimizing user outages. The DBA as a Victim (er…Recipient) Passwords for DBA IDs will also need to be reset from time to time. Applying Murphy’s law (if anything can go wrong, it will), this will occur at the worst possible time, perhaps at midnight
258
Chapter 8 • Ready, Set, Implement?
when the DBA has just been called in to perform a database restore. In her sleep-deprived “crisis in motion” state, she is not adept at hitting the proper keys in the right succession. After three unsuccessful attempts at changing her password, the DBA is locked out of the system. Being proactive in password maintenance discussions is to the DBAs advantage. For example, if the DBA tasked with doing the restore had known that her password was due to expire before the crisis, she may have been better prepared to create a new one. Also, if the next “on-call” DBA on the list also has to deal with an expired password, the cycle may actually repeat with that DBA getting locked out, too. (It is, after all, the middle of the night.) When discussing DBA password maintenance with the operating system administrators, it is a good idea to suggest that all DBA passwords not expire as a group, but rather that they expire independently of each other and on a different rotational cycle with a “warning” being communicated a day or two prior to the expiration. It may even be a good idea to set passwords to expire at some “reasonable” hour of the day. Be Involved Leaving password maintenance policies and procedures to the operating system administrators is still appropriate and provides a good system of “checks and balances.” However, DBAs should be involved in the policy and procedure making process to provide implementation suggestions toward achieving the strongest possible database security while still ensuring application and user community needs are met.
How Sensitive Are You? No, this question isn’t for you personally, but rather should be asked of data. Even though this book is all about security, the reality is that not every piece of data is sensitive. Identifying sensitive data and nonsensitive data may not be easy, but if achieved, the distinction can save a lot of time and energy. For example, if you have built the DB2 generic sample database (db2sampl) as the single database in the instance on a machine all by itself, you probably do not want to waste the time and effort required to “lock it down” since the database holds nothing of a sensitive nature. Consider, too, the differences in data. In many databases, you will find tables that hold nonidentifying information. These nonsensitive tables could be tables such as Zip Code “mapping” tables that hold only a City Name and Zip Code combination without any information that might identify someone. Considering that a hacker can get the same information from a search on the Internet, this data is not very valuable to someone who might be looking for sensitive information. Also consider that data in development environments might be merely “dummy” data. If this is the case, protecting the data might not be necessary. Of course, you still need to take steps to prevent unauthorized access, but applying LBAC (see Chapter 6, “Label Based Access Control”) or
Where Design Meets Implementation
259
encryption (see Chapter 7, “Encryption (Cryptography) in DB2”), for example, would not be a necessary exercise if it were undertaken solely to protect the dummy data. The other extreme is that some data is so sensitive that it must be protected using the strongest security measures possible. An example of this is a Social Security number. Because breaches that compromise persons’ identities are usually centered around getting SSN and date of birth information with a goal of identity theft, these fields are critical when considering a secure solution. Unfortunately, too many of today’s headlines indicate that these types of information thieves are succeeding where they should fail. Recognizing this, you should take all possible measures to protect these types of identifying information. Prioritizing the implementation tasks to take these “sensitivity” factors into consideration will help ensure that those pieces of information that need the most protection will receive it.
IMPLEMENTING FOUNDATIONAL SECURITY Security doesn’t just “happen” nor can a corporation count on security just accidentally being good enough to protect it. That much is probably obvious. What might not be as obvious is that security should be a primary consideration from the project’s beginning. Too often, a project is undertaken with the understanding that security will “happen” at some point prior to go-live. When this is the approach, retrofitting security into the design is destined to be more expensive and possibly much less effective than having approached security at the point in the project where it could have become a cornerstone. Where does the security implementation actually begin? The correct answer is at project inception. This is the appropriate time to think about how this project (and the DB2 database) is going to be safeguarded. Are there plans and policies to be created? If so, security should be a focus. Are there personnel to be hired? If so, they should have a background check. Are there regulations that must be met? Build them in from the start.
WHERE DESIGN MEETS IMPLEMENTATION Think about items such as the logical data model if the project has one. Meet with the data modelers prior to their initial effort, if possible, to discuss security. Help ensure that any security issues that can be addressed at this point are. At least a discussion on the topic of security may raise awareness of its importance. Then, there is the physical model implementation. Because this task is most often done by the DBA, this is a great opportunity to build in security from the moment the database is created. Security considerations should be well thought out and reviewed prior to creating the DDL that will be used to build the database objects.
260
Chapter 8 • Ready, Set, Implement?
When the physical model is ready to go, and the database is built, there is more opportunity to reduce risk. High-risk columns such as Social Security numbers, credit cards, and any personal identifying information should be handled with care in the physical design. If these “sensitive” fields seem to be in too many tables, consider condensing them into fewer tables and using joins to get the information with SQL queries. Of course, this type of decision must be weighed against performance goals. If this is a conversion or ETL (extract, transform, and load) project, there may be an opportunity to improve the new design based on any security discoveries of the past. Maybe secure fields, for example, can be removed from some tables during the conversion project or can be “condensed” into a limited number of tables. Dealing with the physical model in a secure manner is very much an “it depends” exercise. There are no hard-and-fast rules on how to approach this task, but doing so with security as part of the objective is the goal.
WATCH OUT FOR THE PUBLIC (WHAT DOES THE PUBLIC NEED TO KNOW AND WHEN DO THEY NEED TO KNOW IT?) When implementation begins, and when the database is being created (even before you run your first DML statement), the “public” should be on your mind. Although “watching out for the public” is a good idea as a general security approach, this topic deals more specifically with the PUBLIC group that is built as part of any default CREATE DATABASE command. This group is great for ease of administration of the database because it allows privileges to be assigned that can be “inherited” for everyone logging on to the database. The cost of this ease of administration, however, is a security risk that will likely outweigh the administration aspects. As discussed in Chapter 5, “Authorization—Authority and Privileges,” DB2 9 provides a new option for the CREATE DATABASE command that “restricts” the default access for the PUBLIC group. If your database has yet to be created, consider using this new option, because it enables you to grant only the permissions you want without granting other permissions by default. All DB2 databases will hold the database “system” information in the SYSIBM tables and SYSCAT views. These tables and views are built by default with the creation of the database and are required to remain. (Without them the database cannot function.) However, just because the tables must exist does not mean that everyone who connects to the database needs to be able to review the information held there. Whereas DBAs use the SYSIBM and SYSCAT information to do their job, the normal user community should remain blissfully unaware of what those objects hold, especially because these views and tables store information that might be used by someone to gather the tools to use to mount an attack.
Watch Out for the Public (What Does the Public Need to Know and When Do They Need to Know It?)
261
For example, the view named SYSCAT.TABLES holds a significant amount of information that would be useful to know if you wanted to compromise a DB2 database. This view holds specific “structure” for all the tables that exist in the database. For each table in the database (even the system tables), there will be one row in the SYSCAT.TABLES view that will hold uniquely interesting information. Some of these pieces of information can be highly sensitive. Consider a representation of the columns in the SYSCAT.TABLES view, as shown in Figure 8.1.
Figure 8.1
The columns of SYSCAT.TABLES
Pay special attention to the columns named definer and owner. The values for definer (or owner) are of special interest to someone who might want to surreptitiously gain access to this database. The id that holds the designation of table definer (or owner) is typically an id that holds elevated privileges. If that ID is compromised, then the next step the hacker may attempt is to try to learn its password, whether by “social engineering” or other means. In some environments, this could lead to a serious breach. See Chapter 5 for a complete discussion of the “definer versus owner” topic. This is not the only column of interest in SYSCAT.tables. Even something as seemingly innocuous as the card column can reveal information that might be best kept hidden. The card column is populated by the runstats utility functionality and can give someone who knows DB2 a good idea of the number of rows in a table. If there were a breach, even in databases with a
262
Chapter 8 • Ready, Set, Implement?
significant number of tables to be reviewed, SYSCAT.tables can be used to narrow the focus to those tables that might hold the “best” information by running a query similar to the following: db2 “select char(tabschema,15) as tabschema, char(tabname,35) as tabname, card from SYSCAT.tables order by 3 desc”
This query would return the schema and table name for all the tables in the database as well as the value of the card column. The results would be sorted by the value of the card column, with the highest values displaying first. Basically, this information shows, by table, how many rows were in the table during the last runstats cycle. One query, therefore, can provide a decent road map to someone who wants to know the names of the tables that are most likely to have the largest number of rows. A hacker might find it interesting, for example, that a table named credit_card holds two million rows. That piece of information may make the credit_card table a great candidate to be downloaded first by the hacker. Obviously, the PUBLIC group database access should be weighed against the risk, but first it is a good idea to have an understanding of what the PUBLIC group can do if the new DB2 9 RESTRICTIVE option is not used. Finding out what the PUBLIC group is capable of is as easy as opening the DB2 Control Center. For the database in question, choose USERS AND GROUP OBJECTS and the subfolder DB2 GROUPS. The PUBLIC group will appear in the right-hand display panel and can be selected by double-clicking the item. This launches a “change” window with a variety of tabs. Opening each tab one at a time will reveal the significant number of privileges that the PUBLIC group has by default. Examples of using the DB2 9 Control Center to view privileges can be seen in Figures 8.2 and 8.3.
Figure 8.2
Using the Control Center to see PUBLIC authorities
Watch Out for the Public (What Does the Public Need to Know and When Do They Need to Know It?)
Figure 8.3
263
Using the Control Center to discover tables that PUBLIC can see
Alternatively, SQL queries can be run against the SYSCAT views to gather the same information. To see what SELECT rights are held by the PUBLIC group for all the tables in the database, you could run the following query: db2 "SELECT CHAR(GRANTOR,12) as GRANTOR,CHAR(GRANTEE,12) as GRANTEE, GRANTEETYPE as Group_or_User, CHAR(TABSCHEMA, 12) as SCHEMA, CHAR(TABNAME,50) as TABLE, SELECTAUTH FROM SYSCAT.TABAUTH WHERE GRANTEE = 'PUBLIC'"
Of course, tables are only one aspect that should be considered when reviewing what the PUBLIC group can do. By default, the PUBLIC group has other authorities as well. See Chapter 5 for more SQL statements that can be used to show the types and number of permissions held by the PUBLIC group. To further illustrate the point regarding PUBLIC permissions, consider this fictional scenario. At a large university, most student information is held in a DB2 database. All students have access to a limited range of information such as class schedules and have the ability to update their personal information, which is held in a view named STUDENT_VIEW. This view was designed as a database security device to limit student ability to see all the data in the underlying tables. The DB2 group PUBLIC has access to read all the SYSTEM tables and SYSCAT views. In this scenario, a student, Helen, who recently took a class on DB2 logs in to the “student application” using her normal procedure. From her studies, she knows that the SYSCAT.VIEWS
264
Chapter 8 • Ready, Set, Implement?
column text holds the definition of the view itself. Running a query to get the content of the text column for the STUDENT_VIEW shows Helen the exact SQL that is run each time the view is called. From this information, Helen can determine that the STU.STUDENT and STU.CLASS_SCH tables hold students names and grades per course. Because Helen does not have access to those tables, this scenario may stop here; but if she wants to pursue a “hack” to gain access to that data, she is now one step closer thanks to her “inherited” access from the PUBLIC group. The PUBLIC permissions can be easily revoked via the Control Center or via SQL commands. They can be revoked “en masse” or one at a time. Examples using SQL commands are shown in Chapter 5. Examples of revoking PUBLIC permissions using the Control Center are shown in Figures 8.4, 8.5, and 8.6.
Figure 8.4
Using the Control Center to revoke from the PUBLIC group entirely
Right-click the Public group and choose Remove.
Watch Out for the Public (What Does the Public Need to Know and When Do They Need to Know It?)
Figure 8.5
Using the Control Center to remove certain PUBLIC group permissions
Right-click the Public group and choose Change to bring up the options.
265
266
Figure 8.6
Chapter 8 • Ready, Set, Implement?
Using the Control Center to remove Select authority from PUBLIC
Choosing the SHOW SQL option If you have removed privileges from the PUBLIC group, you might find that you have to add privileges for other groups or users to mitigate the change. From a security standpoint, this gives the DBA a much greater granularity of control than just allowing the permissions held by the PUBLIC group to be inherited by any ID logging on to the database. Because it is very likely that the PUBLIC group permissions that were removed will be needed by other users or groups, it is wise to keep a list of all removed permissions. This is even more critical when this exercise is being performed against an “up-and-running” database. Knowing what was changed facilitates the task of repairing any unexpected consequences so the DBA should always keep a list. The SHOW SQL option (as shown in the output in Figure 8.6) can prove useful in this regard. When implementation begins, remember to “think about the public.” Review the privileges held by this “special” group before running even the first DML statement in the new database. Apply the security standard of “least privilege” to this group and eliminate anything that can be eliminated.
Security and Database Performance
267
SECURITY CONSIDERATIONS FOR UPGRADES, MIGRATIONS, SCALABILITY Wouldn’t it be wonderful if implementation stopped at some point in time? But, as DBAs the world over know, implementation is an endless loop that never gets closed. With all the planning and learning that took place during the initial implementation, one might think that implementations for upgrades, migrations, and scalability would not imply the intensity of the original. Unfortunately, that is not always the case, although some environments proceed as if it were. The lesson here is to approach each new implementation armed with the idea of applying “lessons learned” from previous implementations and the realization that sometimes moving forward means looking back. What we mean by this is that new features of an upgrade can “break” or “hamper” the security that was built in previously. Migrations can move bad security from one database to another (or create it from scratch). Scalability (depending on the type) can exponentially challenge a currently secure implementation. Do not just approach an upgrade, migration, or scalability project as if it is only necessary to review security for the “new” pieces. Instead, realize that the “whole” of your secure implementation needs your attention.
SECURITY AND DATABASE PERFORMANCE Under the best-case scenario, the DBA team has discussed performance considerations before beginning the implementation process and expectations have been appropriately managed. If not, the implementation might be vulnerable to tossing out security in favor of performance. For example, DB2 auditing, although an extremely valuable security mechanism, does pose risks to performance, especially if CONTEXT auditing is enabled. If management is aware of this before implementation, they will not be as likely to sacrifice security for performance once the deployment is finished. Much can be done, however, to mitigate performance issues while maintaining a secure database environment. During implementation, make sure to follow known best practices for performance for items such as hardware specifications, model normalization, disk layout, tablespace design, and configuration parameters for both the operating system and the database. Research the new performance-enhancing features of DB2 9 and implement them as appropriate. If, after the implementation is completed, the desired performance does not meet expectations, make sure that all avenues have been explored for mitigation before even considering changing a security piece. Although there is always a trade-off, don’t let performance issues stomp out all your hard work and prevent you from implementing a secure database environment.
268
Chapter 8 • Ready, Set, Implement?
LAST WORDS Just getting started is sometimes a challenge when it comes to implementation, but reviewing the security plan and policies is a good first step. Participation by the DBA in all aspects of the predeployment design and planning is elemental to the tasks of “expectation setting” and eases the DBA anxiety levels after the implementation tasks actually begin. If you are the DBA and you are not being included in predeployment meetings, speak up! Although implementation can never be thought of as “one size fits all,” certain aspects of a secure database implementation can, and should, be reused. Therefore, keeping a “cheat sheet” of information may aid the DB2 DBA in the inevitable “next” deployment.
CHAPTER
9
Database Auditing and Intrusion Detection
I
n some ways, DB2 database auditing is like putting a security camera in a convenience store. The fact that the camera is there will deter some crooks. If the crooks are brazen enough to proceed anyway, the video, when reviewed, will lead to their capture.
FIRST WORDS Setting up database auditing has some similarity to the plot of numerous detective shows on TV. The TV detectives realize that not every event is important enough to deserve attention (otherwise the show would exceed its allotted time), but the events that are important will lead to the culprit. That is one of the benefits of database auditing (and auditing in general); it can capture information that is deemed important enough to warrant a review and can lead the reviewer to the “guilty” party. In some respects, database auditing serves as a reactionary security solution. It does not create access barriers. It does not shut down vulnerabilities or lock down permissions. It is not a first line of defense, but it can aid in determining the magnitude of the situation when other defensive mechanisms have been breached. Even though auditing begins as a reactive process, appropriate monitoring of DB2 database auditing output can give rise to further investigations that may prevent a small breach from becoming a huge one. When this type of discovery is identified, auditing does become part of a proactive approach toward a solution.
269
270
Chapter 9 • Database Auditing and Intrusion Detection
Auditing may mean primarily capturing events that are completely benign. In most organizations, normal business and day-to-day activities generate audit records. It is only when abnormal activity occurs that the audit trails become truly interesting and the investigation becomes intense. Just like the TV detective doing his job of discovery, auditing provides the clues needed to solve the crime. The subject of database auditing, in its broadest form, could fill more than one book. There are many facets to database auditing, from the initial planning through report generation and report review. This chapter takes you through the generalities of database auditing and introduces the specifics of DB2 auditing. Unfortunately, no one blueprint fits every organization, so the DBA must know something about the business process and the technical architecture of the environment before implementing a solution.
CRISIS MODE Imagine the DBA who has just been assigned the task of implementing “auditing” for the corporation’s new databases. There are no requirements; there have been no meetings; there is no management concurrence—just the command to “Go forth and audit!” The unvoiced questions must be screaming in her brain and among them, undoubtedly, “Where do I begin?” Unfortunately, similar scenarios happen all too frequently in the DBA realm. It seems that database auditing often becomes an afterthought with the assumption that it can be implemented by simply “setting a switch” without any analysis behind the decision. That is why DBAs must be vocal about the need to implement database auditing appropriately. They must educate their managerial audience about database auditing and seek input about what actually should be audited. They must avoid any urge to simply audit everything without a basis for doing so. Before any discussion about database auditing begins, it is important to recognize that there are both benefits and associated risks when implementing database auditing. Although this chapter will focus on the “good” of database auditing, the fact remains that implementing the database auditing process inadequately can prove to be worse than implementing no auditing at all. For example, database auditing might result in the collection of large volumes of information. Although data collection is part of the goal, at some point someone must actually do a review. Collecting data without ever reviewing it leads to a false sense of safety that is in conflict with the goal of a more secure environment. Database auditing, just for the sake of auditing, therefore, can actually increase the overall security risk for the organization, because it leads to complacency and provides a false sense of security. It is all too real that some organizations generate massive amounts of data via a database auditing process, but review it only occasionally or only after a breach. Database auditing should be thought of as a “living” process. It must have appropriate resources to achieve the intended results. If the organization cannot or will not allocate the time and the energy to review the audit
Initial Steps to DB2 Database Auditing
271
reports, all the while believing that auditing will “save” them, they are actually in a worse situation than if they never audited at all. They feel safe, but the appearance of safety is only a façade.
INITIAL STEPS TO DB2 DATABASE AUDITING Corporate Sponsor Just as in most Information Technology endeavors, a corporate sponsor is critical to a successful outcome for developing a database auditing solution. The corporate sponsor must champion the process and ensure that both human and financial resources are available for the tasks as needed. In most large organizations, an audit department exists for the sole purpose of managing this effort. It is tasked from the top of the organizational structure and reports solely to the board of directors. Smaller organizations may not have this luxury, but it is important that someone (or some team) performs this role.
Discovery Before proposing any database auditing solution, it is best to have some background about the application(s) for which database auditing is being proposed. Is database auditing mandated by some governmental regulation, such as SOX or HIPAA? Perhaps auditing is required because the company deals with financial or personal information or is a governmental entity. Knowing the reason that database auditing is required helps drive an appropriate database auditing response. Even if there is a regulatory requirement for database auditing, there is still a need for discovery. Typical questions that should be asked and answered during this phase include the following: What is the expected benefit of database auditing? What databases should be audited? What type of database events must be audited? Changes to the audit configuration? Starting or stopping DB2 database auditing? System events? Pruning or writing of the audit logs? Object creation or drops? Changes to grants or revokes? Authentication success and/or failure? All SQL statements?
272
Chapter 9 • Database Auditing and Intrusion Detection
Is rollback of unwanted changes required? Must every table be audited? If not, provide a list of tables to be audited. What is the “driver” for auditing? Is there a regulatory requirement? Is sensitive data held in the database? Is there concern about internal compromise? Is there concern about external compromise? Who will be the “business owner(s)” for database auditing? Who will review the audit trails? Will auditing be allowed to continue if database performance suffers? What is the appropriate length of time to keep audit output? Although the DBAs should provide ancillary technical knowledge during the discovery process, they should not be tasked with uncovering the corporation’s needs for auditing. Asking the DBAs to hold responsibility for both discovery and implementation may lead to gaps in the process that could introduce “errors of omission.” Discovery of auditing requirements should, instead, be documented and reviewed for completeness by the business process owners, developers, and appropriate levels of management. The end result should be presented to the DBAs for use as a road map. Dividing the work in this way helps to ensure the quality of the process. A suggested approach to discovery is to create a core team to focus on the task. The team members should include the CTO, appropriate members of the security team, business process owners, and developers. The team should have access to the corporation’s attorneys for legal counsel if database auditing is being done as part of a compliance effort. The team should also ask for and receive advice from the DBAs as needed. Even though the DBAs should not be tasked with discovering auditing requirements, when they are handed the documentation from the discovery team, it is still a good idea to review it for completeness and accuracy, especially if the DBA has a significant understanding of the application functionality. One method of discovering and confirming candidates for database auditing has been around for years but seems to be falling into neglect. In the past, no self-respecting DBA would have implemented a database without seeing a data model and understanding its metadata. With so many “canned” applications these days that deliver DDL along with the application code, the Entity Relationship (ER) data models that used to proliferate on DBAs cubicle walls have gone the way of plastic flowchart templates and keypunch cards. This is unfortunate because these diagrams provided a visual heartbeat for the core of the logical database. If you are lucky enough to still have a valid ER diagram for the databases you are implementing, check it for clues about sensitive data, the tables that house such data, and the relationships between those tables.
Initial Steps to DB2 Database Auditing
273
For DBAs Only The DBA team takes the information that is delivered from the discovery phase and begins the planning and design work. Given the complexities of large organizations, the DBA may be tasked with creating database auditing solutions for several databases at once. These databases might reside on different hardware with different operating systems and might even be housed in databases at different levels of DB2 software. After the DBA receives the report from the Discovery Team, the information needs to be analyzed and broken down in a way that facilitates planning. This effort can be overwhelming, so dividing the task into smaller steps can actually speed the overall process. Table 9.1 shows an example of a “first step” design that can be used by the DBA to keep track of databases and their auditing requirements at the start of the planning phase. Table 9.1
Organizing Information—Start with the Big Picture
db Name
Appl Type
Server
Software
Operating System
Audit
Regulatory
FinMod
OLTP
Topaz8
In House (.Net)
AIX
Full
GLBA
HRDB
OLTP
Garnet3
Peoplesoft
AIX
Partial
SOX
Whse
DSS
Diamond4
Cognos
Linux
Partial
SOX
Insure
OLTP
Pearl1
In House (C++)
Win2003
Full
HIPAA
The goal of this first step toward database auditing is simply to get a “big sky” viewpoint of the requirements to facilitate further steps. During the planning process, the information in Table 9.1 will be broken down further, based on the information provided by the discovery process. Planning Example Let’s work though a simple planning example for the HRDB database. Note that in Table 9.1, there is a regulatory requirement to audit some of the database information. Because this is only a partial database auditing requirement and not a full database auditing requirement, the discovery team must also provide a list of auditable items and an explanation of what type of auditing is required. This may be detailed in additional documentation that is provided by the Discovery Team. An example follows.
274
Chapter 9 • Database Auditing and Intrusion Detection
Sample Report Excerpt from Discovery Team Discovery Team Report Additional Information Database: HRDB Partial Database Auditing Requirements: There are five tables in the HRDB database that need to be audited to satisfy the requirements: Employment, Names, Salary, EmpHistory, and SalHistory. The Employment table needs to be audited for all inserts, updates, and deletes. The Names and Salary tables need to be audited for updates and deletes. The EmpHistory and SalHistory that hold only historic information only need to be audited for deletes. Additional Requirements: A report should be generated aggregating all audit events and reconciled by the HR Department on a daily basis. This report should include current row counts for the EmpHistory and SalHistory tables. None of the remaining 147 tables in the database need to be audited.
Based on this information, the DBA can create a grid, as shown in Table 9.2. Table 9.2
Organizing Information—by Database
Auditing Requirements for HRDB Database Audited Tables
Events
Review Cycle
Employment
Insert, Update, Delete
Daily
Names
Update, Delete
Daily
Salary
Update, Delete
Daily
EmpHistory
Delete
Daily
SalHistory
Delete
Daily
This is a fairly simple and straightforward database auditing requirement and one that could be accomplished by the db2audit facility and/or DB2 triggers. (See a complete discussion of these topics later in this chapter.) If this were the only requirement for database auditing, the DBA could stop here and begin the database auditing design.
Initial Steps to DB2 Database Auditing
275
Dealing with Complexity Typically, database auditing requirements are not as simplistic as those just outlined. In fact, they sometimes become so involved and convoluted that it is difficult to determine priorities, let alone solutions. When this is the case, one approach is to “weight” the auditing requirements and then assign a solution based on the weighted factor. This involves detailed analysis. If this type of approach is needed due to complexity, the auditing requirements could be detailed in a grid similar to that in Table 9.3. The goal is to capture the reasons for the auditing requirement so that similarities of approach can be discovered. Table 9.3
Organizing Information—Assigning Weights
ROW #
DB
Table
Column
Reason
Regulatory
Weight
1
HRDB
Employment
PayGrade
Highly Sensitive
SOX
2
2
DBINS
EMP08
PE630
Highly Sensitive
HIPAA, SOX
3
3
FIDB
ALL
ALL
Rollback
GLBA
4
4
CCPRD
SG1BC
AGN
Track # Changes
None
1
5
IMDB
ALL
ALL
Rollback
SOX
4
6
RBDB
G9H7
ALL
Track # Changes
None
1
Weight=1: Normal requirement Weight=2: Normal requirement with sensitive data Weight=3: Highly sensitive data and/or additional regulatory issues Weight=4: Rollback availability must be guaranteed
An examination of Table 9.3 shows that the Reason and Regulatory columns can be used by the DBA in a flexible manner. They may be used to capture the “significance” of the reason to audit. Using Row 3 as an example, this information has been identified as falling under a GLBA requirement. There is also an additional requirement to be able to capture before and after images of the data so that changes can be rolled back, if necessary. Based on this information, and the legend below the table, the combination of information may be used to assign a “weight” to the requirement. This can lead to further analysis and facilitate the development of an overall approach to auditing by a weighted category. Although there is no one boilerplate that can be used as an aide for database auditing analysis, this type of approach can assist the DBA in categorizing the requirements so that audit strategies can be reused where appropriate. In Table 9.3, the FIDB and IMDB databases both have a weight of 4. Based on the information provided, each database needs a full auditing solution with all tables audited for all changes. In addition, there is a requirement that any erroneous changes must be rolled back. This requires a
276
Chapter 9 • Database Auditing and Intrusion Detection
robust auditing solution and added functionality to enable rollback recovery. Based on the criteria established by the DBA, both these databases are assigned a weight of 4 for their database auditing needs. Categorizing the requirements in a manner similar to this assists in database auditing “solution reuse” because the solution that will work for the FIDB database will also likely work for the IMDB database. Similarly, the solution that will work for the CCPRD database (Table 9.3, Row 4) may also work for the RBDB database (Table 9.3, Row 6). Row 4 in Table 9.3 may be of interest because it only has been assigned a “normal” weight factor of 1. Because there is no regulatory requirement and no sensitive data, it is not initially obvious why it should be included in the database auditing process. The reason is actually simple. Even when not officially necessary, there are times when auditing is requested and/or expeditious. For example, consider the insurance carrier who has a staff of thousands of claim agents handling claims. It is easy for management to determine the number of new claims entered each day, because these become new rows in the database. It is more difficult for management to determine how many previous claims are “adjusted” or, in database terms, updated, each day. By incorporating database auditing functionality, this information is made readily available. Note that if Table 9.3 were based on a real corporation’s database auditing needs, it would likely grow quite large very quickly. The Reason column, especially, would hold multiple qualifying rationales for a specific auditing requirement. For example, it is not uncommon for an organization to be subject to two sets of governmental regulations simultaneously. The actual approach to organizing the data in preparation for creating database auditing solutions is not important. The examples here are just simplistic representations of approaches that the author has used in the past. The goal is not to put the information into a particular format; it is to lower the difficulty level and make the task more manageable. When considering how to tackle this step, the particular mechanisms used to put the information into an orderly, understandable format is not important if the resulting output facilitates next steps. One caution about any method that you use to collect and analyze this data is that the resulting documentation should be carefully guarded from unintended access. As mentioned many times in this book, just gathering and documenting information about security processes poses additional security risks that must be managed. The material gathered for auditing purposes is material that can lead to security breaches. Therefore, do not leave this information lying on a desk, on an unsecured shared drive, or in someone’s e-mail or physical “inbox.” Instead, guard and protect it carefully. If your organization has a security team, they should be consulted regarding the best way to secure this information.
FROM ANALYSIS TO PHYSICAL DESIGN When moving from the analysis to design phase of database auditing, the task begins to transition from the theoretical to the practical. The strength of the analysis is directly proportional to
From Analysis to Physical Design
277
the likelihood of designing the solution correctly the first time. If the auditing requirements are complex, good analysis can reduce the risk of missing something. Analysis, such as applying “weighted” factors, as discussed in the previous section, can also aid in solution reuse and, therefore, decreased effort. Before beginning the design phase, determine whether you are satisfied that the analysis is complete. When you are ready to begin the design phase, carefully consider your options. DB2 provides several mechanisms that you can deploy as part of a database auditing and intrusion detection solution. During the design phase, consider whether you should use db2audit, DB2 triggers, or DB2 Recovery Expert singly or in combination. Given the flexibility of DB2 stored procedures and user-defined functions, they may also be used as part of a DB2 auditing solution. db2audit and Intrusion Attempts How do you know if there has been an intrusion attempt on a database? Without some mechanism to audit events at the database level, determining abnormal database activity that would signal intrusion attempts might never be discovered. Even if a breach is discovered, there were probably many attempts to “hack” the database prior to actually doing so. Those unsuccessful attempts at database access were trial runs that could have forewarned the DBA if only she had known about them. Database auditing is a requirement in many establishments for a variety of reasons, not the least of which is intrusion detection. As mentioned in Chapter 1, “The Regulatory Environment,” numerous regulations require enterprises to incorporate some type of database auditing facility. Fortunately, DB2 has a solution. The db2audit facility is built in to DB2. No third-party software is needed, either during the setup, implementation, or for preparing the gathered information for review. The db2audit facility is useful as a means to detect and record database and data access and includes safeguards that capture configuration changes that might signify an intrusion attempt or indicate inappropriate activity. If fraud or other inappropriate access is suspected, the information captured by the db2audit facility can be queried retroactively to determine what transpired.
Before db2audit—Think—Test—Learn Although instantiating the db2audit facility using the db2audit facility commands is simple, the thought that goes into choosing the correct options for a particular environment can be extremely complex. A thorough understanding and a trial run (or two) before setting on a final design will verify that the events that should be captured are, in fact, being captured. As a general note, the best way to understand the db2audit facility is to set it up in a safe, nonproduction environment, testing different configurations and observing the results. Performing this learning exercise in a nonproduction environment will aide the DBA or security team in identifying what types of information might be most valuable to the organization. An added
278
Chapter 9 • Database Auditing and Intrusion Detection
benefit of this type of learning is that the DBA will then know what to expect from the db2audit facility and what the normal db2audit trails will look like, making it easier to identify any events that fall outside a normal range. To provide a starting point for the exploration of the db2audit facility, you will see real examples of the db2audit facility at work in this chapter, but further study on this topic is always encouraged. db2audit Facility—What Can It Do? Although the specifics will be discussed in depth later in this chapter, a high-level view of the db2audit facility shows that it has the following functionality: • Ability to start and stop auditing events at the instance level • Allows for creation or change of the db2audit configuration without stopping or starting the instance • Provides a mechanism to describe (list) the current db2audit configuration • Provides a command that can be used (if necessary) to force pending audit records to be written to the audit logs • Allows for audit record extraction to flat files or ASCII files that can be loaded into tables • Allows records to be pruned from the audit log if desired
Using db2audit for Multipartition Environments The functionality of db2audit does not change whether it is configured in a single-node environment or a multiple-node environment, so the information and examples in this chapter apply to all DB2 instances configured for db2audit capability. With DB2 databases that are using the DPF multipartition feature, however, db2audit captures the events at the coordinator partition (or at the catalog node if they are not the same partition). Because this means that individual audited events may be generated by more than one partition, each audit record provides information on the coordinator node and origination node for review purposes. db2audit Facility Safeguards With any auditing solution, it is important to safeguard the means being used to generate the audit. If your auditing solution has no security to prevent unauthorized changes to the audit configuration itself, the resulting audit trails will always be suspect. For this reason, reviewing the safeguards of the db2audit facility is a good first step. If you understand how the db2audit facility is protected from unauthorized change and how events are recorded and stored, you will be better equipped to keep the audit information secure.
From Analysis to Physical Design
279
Because the db2audit facility is configured at the instance level, it might seem logical for the auditing functionality to cease every time the instance is stopped and begin again when the instance restarts. If that were the case, there would be a large hole in the entire database auditing security mechanism. For example, with the instance stopped (offline), changes to the db2audit configuration could be made that would compromise security and never actually be captured in the audit trail. To avoid this problem, the db2audit facility is implemented as a UNIX process or as a Windows thread and is protected from being disabled when the instance is stopped. Even if the instance is not active, the db2audit facility still can be doing its job. Of course, there will be a need for audit configuration changes from time to time, so some level of authority must be allowed access to update the audit configuration. To protect the audit facility from unauthorized access, DB2 requires the highest level of authority, SYSADM, when modifying or configuring the db2audit facility. As a general rule, individuals who hold SYSADM authority should be kept at a minimum, and these individuals should be trusted employees.
The db2audit Facility Command Syntax One of the best ways to understand the capabilities of the db2audit facility is to study the options provided by the db2audit command statement syntax. Refer to Figure 9.1 for a visual guide to the commands and options. Configuring, Starting and Verifying db2audit Setup Before beginning work to configure and verify the db2audit facility setup, there are four important items to consider: • The db2audit facility works at the instance level and collects information on the instance and all the databases that reside in that instance. • The db2audit facility is not started or stopped automatically. It must be started and stopped explicitly by a user with SYSADM authority. • Configuring the db2audit facility to capture “everything” will likely result in the generation of large amounts of audit data and a potential decrease in database performance. • The db2audit facility is protected by privileged authority. Only a user who holds SYSADM authority can make changes using the db2audit system commands. This is a built-in safeguard to protect the integrity of the auditing configuration.
280
Chapter 9 • Database Auditing and Intrusion Detection
db2audit Step by Step Step 1: Configure The first step to enable db2audit in a new environment is configuring the db2audit facility options. Because the db2audit configuration is effective at the instance level and applies to all databases housed in that instance, the configuration steps can begin any time after the instance is created and may preexist creation of any databases. The instance does not need to be started prior to configuring db2audit, it just needs to exist. During the instance creation, a security subdirectory is created underneath the primary instance path. You will notice that the db2audit.cfg configuration file and the db2audit.log file (when created) will be placed in the instance’s security subdirectory. Configuration options for the db2audit facility should be chosen based on the analysis done previously and should be designed to capture only information that is pertinent to the task at hand. As you read through each of the configuration options explained here in detail, be aware that choosing some of the db2audit configuration options may result in large amounts of data being generated when the db2audit trails are extracted. Selectively choosing only those options that are actually necessary is the best strategy. The actual task of configuring the db2audit facility is surprisingly easy (even though the thought that goes into choosing the options can be highly complex). Any user who holds SYSADM authority can use basic command syntax to set the configuration. The basic syntax follows: db2audit CONFIGURE SCOPE <scope> STATUS <status> ERRORTYPE <errortype>
The CONFIGURE keyword indicates a planned parameter modification of the db2audit.cfg file, which is stored in the instance’s SECURITY subdirectory. It is possible to update this file via the db2audit facility commands even when the instance is shut down. If the instance is not running and changes are made to the configuration information, those changes take effect the next time the instance is started. If the instance is running when the configuration changes are made, the changes take effect dynamically. The db2audit CONFIGURE keyword can also be used to reset the db2audit facility configuration back to the defaults or to facilitate recovery if something has happened to the original db2audit.cfg file. To perform this action, run this command: db2audit configure reset
Use caution if you need to run the RESET command. After the db2audit configuration is reset, the db2audit facility must be explicitly restarted using the DB2AUDIT START command. The reset command also changes the SCOPE and STATUS of the db2audit facility back to their defaults, which may not be the desired effect.
282
Chapter 9 • Database Auditing and Intrusion Detection
The SCOPE parameter refers to the type(s) of auditing you plan to initiate. There are several categories or combinations of categories that can be chosen to participate in the scope of the audit. Based on the analysis of the auditing requirement, the SCOPE options relate to the type(s) of auditing required to fulfill the business need. If the command is run to reset the db2audit configuration, the db2audit facility SCOPE reverts to the default, which is to enable every scope category except CONTEXT. It is important to stress that when considering SCOPE options that can be invoked, remember that turning on more auditing than required is not a sound practice. Both performance and the size of the db2audit trail logs are impacted by the choices made for the db2audit SCOPE parameter. Given the importance of making appropriate choices regarding scope, each option of the SCOPE parameter is discussed in significant detail under the heading “Scoping Out Scope” later in this chapter. STATUS refers to the logging of events that failed or succeeded or if the event will be logged regardless of its success or failure. When thinking about the STATUS parameter, it is imperative to understand that this option applies to all the items chosen for the SCOPE of the audit. In other
words, the DBA cannot pick and choose some events to be audited for only success while other events are logged only for failure. Choosing the STATUS option, therefore, can necessitate auditing for both success and failure even though the requirements are to audit only successful events for some of the SCOPE options and only failed events for other scope options. The STATUS option applies globally to all chosen options of the SCOPE parameter. The only exception to the db2audit status rule relates to the auditing of CONTEXT events. CONTEXT events occur before the status of the audited operation can be determined; therefore, if CONTEXT events are being captured, they are logged regardless of the setting for the STATUS parameter. One more caution about the STATUS option. If the db2audit facility configuration is reset, STATUS reverts to the default and logs only failed events until reconfigured. ERRORTYPE deals with the db2audit facility’s management of errors. It determines whether SQL errors trapped by the db2audit facility can be ignored or if they should be returned to the user. When set to AUDIT, all errors are managed by DB2 with any negative SQLCODES returned to the user. When explicitly set to NORMAL (the default) or when the db2audit facility configuration is reset, any errors generated by the db2audit facility are ignored and only those errors associated with the operation actually being performed are returned to the user.
Scoping Out Scope The SCOPE parameter of the db2audit command allows the DBA to choose how wide a net to cast when it comes to auditing events. Seven categories of SCOPE events can be audited either separately or in combination. AUDIT How do you audit db2audit? The AUDIT scope option provides a significant security depth for any organization using the db2audit facility. This option provides the mechanism used to capture evidence of any changes made to the db2audit facility itself. Setting this SCOPE
From Analysis to Physical Design
283
option guarantees that any attempts to extract the recorded events to the audit trail logs will be captured. Given the criticality of ensuring that the AUDIT configuration settings stay as designed and that only authorized SYSADM users extract the resulting audit trails, this is a strong security failsafe mechanism that should be turned on in most DB2 environments. Figure 9.2 shows an example of the AUDIT scope functionality. Here, the db2audit facility scope is configured to verify AUDIT events, and the db2audit facility is started. The db2audit facility places the generated audit records into the db2audit.log file, which must be converted into a human readable format prior to review. This is done using the db2audit EXTRACT options. The extraction, by default, is made to a flat (text) file, named db2audit.out, unless other options are specified. Extracting the db2audit records and loading the resulting data into tables is also an option (discussed later in this chapter); but for this example, accepting the extraction defaults works. Unless otherwise specified, DB2 stores the extracted db2audit.out file in the insthome/security subdirectory. C:\Program Files\IBM\SQLLIB\DB2ASAM\security>db2audit configure scope audit AUD0000I
One of the best ways to learn about each of the db2audit facility scope options is to understand the record layout for the resulting audit trail. In the record layout for the AUDIT SCOPE, shown in Figure 9.3, all possible values that trigger an event for the audit scope are listed on the Audit Event line. Knowing the events that are captured when setting this scope value aids the DBA in both the decision-making process for db2audit setup and the review process to determine what events normally occur in the day-to-day business operations. It is a good idea to print or have ready access to the Record Layouts for each of the scope options and refer to them when deciding which audit scope options to configure. In addition to finding these record layouts in the DB2 Information Center (http://publib.boulder.ibm.com/ infocenter/db2luw/v9/index.jsp?topic=/com.ibm.db2.udb.doc/welcome.htm), see Appendix C, “DB2 Audit Scope Record Layouts,” for a complete listing of the record layouts for all the db2audit scope categories.
284
Chapter 9 • Database Auditing and Intrusion Detection
NAME
FORMAT
Timestamp
CHAR(26)
DESCRIPTION Date and time of the audit event.
Category
CHAR(8)
Category of audit event. Possible values are: AUDIT
Audit Event
VARCHAR(32)
Specific Audit Event. Possible values include: CONFIGURE, DB2AUD, EXTRACT, FLUSH, PRUNE, START, STOP, and UPDATE_ADMIN_CFG
Event Correlator
INTEGER
Correlation identifier for the operation being audited. Can be used to identify what audit records are associated with a single event.
Event Status
INTEGER
Status of audit event, represented by an SQLCODE where Successful event > = 0 Failed event < 0
User ID
VARCHAR(1024)
User ID at time of audit event.
Authorization ID
VARCHAR(128)
Authorization ID at time of audit event.
Figure 9.3
Audit record layout
CHECKING The primary purpose of the CHECKING option is to determine authorization attempts. Finding a CHECKING audit event in the extracted audit logs indicates that an attempt has been made to access, change, or, in some manner, manipulate a DB2 object or function. This audit option would be desired in most auditing scenarios to see what activity has been authorized for database objects and what authorization attempts were made without success. This option is one that can lead to a significant amount of audit trail data being collected, especially if every successful and failed authorization attempt is logged. The amount of data generated by the CHECKING scope is typically not one for one. For example, several CHECKING audit records may exist for a single SQL statement. Because the information collected via the CHECKING option is typically essential to determining unexpected or unusual occurrences that might indicate a security concern, the volume of data collection may be a secondary concern depending upon the environment. Figure 9.4 shows a sequence of events for the CHECKING scope that are captured by the db2audit.log during a connection to the Sample database and the successful creation of a new index. In this example, notice that more than one event is logged for the CHECKING audit events even though the only actions were to connect to the database and create the index. These multiple records show the actual authorization steps that DB2 does “under the covers” as they are captured by the db2audit facility. In this example, notice that the steps were as follows: 1. A user ID holding SYSADM authority connected to the SAMPLE database. 2. An attempt to EXECUTE an internal DB2 package was authorized. 3. Authorization was approved to CREATE the object. 4. CREATIN privilege was checked to determine whether authorization existed to create the index in the specified schema.
From Analysis to Physical Design
285
C:\Program Files\IBM\SQLLIB\DB2ASAM\security>db2audit configure scope checking status both AUD0000I
C:\Program Files\IBM\SQLLIB\DB2ASAM\security>db2 connect to sample Database Connection Information Database server SQL authorization ID Local database alias
= DB2/NT 8.2.3 = DB2ASAM = SAMPLE
C:\Program Files\IBM\SQLLIB\DB2ASAM\security>db2 ”create index dbasam.empl1 on db2asam.employee(newcol)” DB20000I The SQL command completed successfully. C:\Program Files\IBM\SQLLIB\DB2ASAM\security>db2audit extract AUD0000I
Also, notice that the db2audit.exe was called in an attempt to extract the audit records. This function was successfully authorized because the ID was a member of the SYSADM group. There is a difference in how db2audit records generate for the CHECKING option depending on the type of SQL and whether it is static or dynamic. If dynamic DML (for example, INSERT,
286
Chapter 9 • Database Auditing and Intrusion Detection
UPDATE) SQL statements are run, CHECKING audit records generate at the time the SQL statement is prepared or when an EXECUTE IMMEDIATE request is made. The statement can then be run by the same user repeatedly if it remains in cache without further CHECKING events occur-
ring, unless there has been a change in the system catalog tables relating to privileges. If change occurs in the catalog tables concerning privileges, the dynamic SQL statement creates further CHECKING events when it is called again. If the DML SQL is in a package (static), the CHECKING event for the SQL occurs at the time the package is precompiled, bound, or rebound to the database regardless of whether the package is explicitly bound by the user or implicitly bound by DB2. Although a package may contain more than just DML SQL, during complication, CHECKING events will be generated only for DML. An exception for static DML regarding the timing of the CHECKING event occurs when the VALIDATE RUN bind option is specified. Because this option means that the DML SQL is compiled at runtime, a CHECKING event is generated at runtime. DDL statements, such as grants or revokes, always generate a CHECKING event whenever the statements run. Given the nature of DDL statements and the risk associated with grant and revoking privileges, this is a strong plus for the CHECKING scope option. OBJMAINT The Object Maintenance (OBJMAINT) option should not be confused with the CHECKING option, although they may appear to be similar at first. Although both deal with database objects, the OBJMAINT option guarantees that objects that are dropped or created are logged
as an audited event. This option is not likely to spur large volumes of data collection in most database environments and can yield solid benefits if database objects start to appear or disappear. Even if there is no known security concern, this option can be useful as a way to track down changes made in an environment with many DBAs and developers. In Figure 9.5, the db2audit facility was configured with audit only OBJMAINT events. Because the db2audit facility started previously, the configuration change took place immediately. After the db2audit facility configuration change, a table (named work) was created successfully and the audit trail was extracted. In the resulting output, notice that the audit category OBJMAINT was responsible for the capture of this audited event. SECMAINT Part of any database auditing and intrusion detection effort should include capturing any changes being made to authorities or privileges. If database privileges, including DBADM authority, are granted or revoked, using the SECMAINT scope option ensures that those changes are logged. Another critical piece provided by this option is the capture of any changes made in the Database Manager Configuration to those groups that have the highest authorities. Any changes to the SYSADM_GROUP, SYSCTRL_GROUP, SYSMAINT_GROUP, SYSMON, or SECADM Database Manager Configuration parameters are logged if the db2audit facility SECMAINT category is active. Inappropriate changes to these values could signify a major security breach, so most enterprises will want to enable this option.
From Analysis to Physical Design
287
C:\Program Files\IBM\SQLLIB\DB2ASAM\security>db2audit configure scope objmaint status both AUD0000I
Operation succeeded.
C:\Program Files\IBM\SQLLIB\DB2ASAM\security>db2 ”create table db2asam.work(hours smallint, days smallint)” DB20000I The SQL command completed successfully. C:\Program Files\IBM\SQLLIB\DB2ASAM\security>db2audit extract AUD0000I
An example of SECMAINT at work is shown in Figure 9.6. The db2audit facility was configured to audit both successful and failed SECMAINT attempts. Although connected to the SAMPLE database, a successful attempt was made to grant DBADM authority on the database to the user BONDRE. The audit events were then extracted to the db2audit.log, which shows that the event was logged. Because DBADM authority grants significant privilege on the database, this type of event should be of interest in most environments. The volume of data generated when SECMAINT events are logged is highly dependent on the number and types of grants and revokes being issued. Many production environments are fairly stable regarding privileges and authorities; so in those environments, the volume of data generated by enabling SECMAINT would not be large. However, a number of authorities, if changed, will be captured by this option. If table select authority is granted and revoked frequently, for example, each change in authority will be logged if SECMAINT is on. Review the topic “List of Possible SECMAINT Privileges or Authorities” in Appendix D, “DB2 Audit—Additional Documentation,” for a complete list of items that generate an audit event when SECMAINT is enabled. C:\Program Files\IBM\SQLLIB\DB2ASAM\security>db2audit configure scope secmaint status both AUD0000I
Operation succeeded.
C:\Program Files\IBM\SQLLIB\DB2ASAM\security>db2 grant dbadm on database to bondre DB20000I The SQL command completed successfully. C:\Program Files\IBM\SQLLIB\DB2ASAM\security>db2audit extract AUD0000I
Chapter 9 • Database Auditing and Intrusion Detection
Because system administration operations are performed at the highest level of privilege, they represent a critical flashpoint in determining unexpected or unwarranted security compromises. The db2audit facility’s SYSADMIN scope option ensures that audit records are written any time a SYSADM, SYSMAINT, or SYSCTRL operation is performed. These operations can be as major as dropping a database. Given the consequences if these high-level accounts become compromised due to a security breach, it is a good idea to enable this option for most environments. The volume of data collected depends upon the activity of these higher-level activities. Some environments log very few events in this category, whereas others log them frequently, especially if the DB2 LOAD utility is used frequently. SYSADMIN
One example of using the SYSADMIN events to gather information is illustrated in Figure 9.7. In this case, a user with SYSADM authority has changed the db2audit configuration to record all SYSADMIN events. Because db2audit.exe commands are run by users with SYSADM authority, they will be captured by this setting. It is obvious that enabling the SYSADMIN audit category helps ensure the integrity of the db2audit facility in addition to recording events for any operation required to be initiated by a user with SYSADM authority. For a full list of these operations, see the topic “List of Possible SYSADMIN Audit Events” in Appendix D. After you review the possible SYSADMIN auditable events, you will have a better understanding regarding the volume of data generated by enabling this db2audit facility setting in a particular instance environment. C:\Program Files\IBM\SQLLIB\DB2ASAM\security>db2audit configure scope sysadmin status both AUD0000I
VALIDATE The VALIDATE scope option of the db2audit facility is designed to generate audit records when validating users and their associated groups or when retrieving system security information. Setting this scope option to audit both successes and failures will probably generate significant volumes of audit trail data because this check is done for each connection attempt. For example, review the output in Figure 9.8. Notice the number of lines generated for this db2audit scope during a connection to the Sample database.
From Analysis to Physical Design
C:\Program Files\IBM\SQLLIB\DB2ASAM\securitydb2audit configure scope validate status both AUD0000I
Operation succeeded.
C:\Program Files\IBM\SQLLIB\DB2ASAM\securitydb2 connect to sample user bondre Enter current password for bondre: Database Connection Information Database server SQL authorization ID Local database alias
Chapter 9 • Database Auditing and Intrusion Detection
Although the VALIDATE option may provide an additional level of assurance, beyond what is offered by the hosting operating system, that the user is valid, the cost of the overhead may be too great to make its use feasible. A test using this parameter may be a good idea to gauge the benefits and costs of incorporating the VALIDATE scope into your auditing solution. By default, the db2audit CONTEXT scope is set to false. This scope setting, when enabled for both success and failure, is more likely than any other to generate large amounts of audit trail data. The benefit of the CONTEXT switch is that it provides a way to interpret the audit trail information because an entire group of operations can be tied to a specific database operation. This can be done via the value in the “event correlator field.” The CONTEXT db2audit option does just as the name implies and provides a “context” or framework for the audit trail information. One of the ways it provides this framework is to include the specific SQL within the record. Because the SQL can be quite lengthy, and because it may repeat in the record for events such as a PREPARE and a DESCRIBE, setting the db2audit facility to audit CONTEXT should be carefully considered in light of the anticipated volume of data. CONTEXT
Figure 9.9 shows a very simplistic example of what the DBA might expect to see when auditing CONTEXT. In this example, the db2audit facility was configured to audit CONTEXT events (only) for both successes and failures. After the change took effect dynamically, a simple SQL query was run. Notice that five audit records were extracted for only this one transaction. Also notice that the SQL that was run is shown in its entirety twice, once in the prepare step and again in the describe step. Step 2:Verify and Display the db2audit Configuration Settings At any time prior to or after the db2audit configuration is set, the configured settings can be verified by running the db2audit describe command. This command displays the current settings for all the db2audit configuration options. In the example in Figure 9.10, notice that the db2audit facility is active (db2audit start has been run), every db2audit configuration option has been turned on for this instance, both successes and failures are being audited, and the audit errortype is set to "normal." Step 3:Start the db2audit Facility When the configuration is complete (and optionally verified by the describe command), the db2audit facility starts. The db2audit facility has to be explicitly started and stopped and functions independently of the instance commands, db2start and db2stop. The only users who have the authority to start or stop the db2audit facility are those who hold SYSADM authority. The commands to start and stop db2audit are simply db2audit start db2audit stop
From Analysis to Physical Design
291
C:\Program Files\IBM\SQLLIB\DB2ASAM\security>db2 ”select count(*) from syscat.tables t, syscat.columns c where t.tabname = ‘TABLES‘ and t.tabschema = ‘SYSCAT‘ and t.tabname in (select c.tabname from syscat.columns where c.colname = ‘TYPE‘)” 1_________ 1 1 record(s) selected. C:\Program Files\IBM\SQLLIB\DB2ASAM\security>db2audit extract AUD0000I
Operation succeeded.
C:\Program Files\IBM\SQLLIB\DB2ASAM\security>more db2audit.out timestamp=2005–11–14–17.09.01.232000;category=CONTEXT;audit event=PREPARE; event correlator=3; database=SAMPLE;userid=db2asam;authid=DB2ASAM; application id=*LOCAL.DB2ASAM.051114220824;application name=db2bp.exe; package schema=NULLID;package name=SQLC2E06; package section=201;text=select count(*) from syscat.tables t, syscat.columns c where t.tabname = ‘TABLES‘ and t.tabsc hema = ‘SYSCAT‘ and t.tabname in (select c.tabname from syscat.columns where c.colname = ‘TYPE); timestamp=2005–11–14–17.09.01.292000;category=CONTEXT;audit event=OPEN_CURSOR; event correlator=4 database=SAMPLE;userid=db2asam;authid=DB2ASAM; application id=*LOCAL.DB2ASAM.051114220824;application name=db2bp.exe; package schema=NULLID;package name=SQLC2E06; package section=201;text=SQLCUR201; timestamp=2005–11–14–17.09.01.332000;category=CONTEXT;audit event=DESCRIBE; event correlator=5; database=SAMPLE;userid=db2asam;authid=DB2ASAM; application id=*LOCAL.DB2ASAM.051114220824;application name=db2bp.exe; package schema=NULLID;package name=SQLC2E06; package section=201;text=select count(*) from syscat.tables t, syscat.columns c where t.tabname = ‘TABLES‘>;and t.tabsc hema = ‘SYSCAT‘ and t.tabname in (select c.tabname from syscat.columns where c.colname = ‘TYPE‘);
To verify that the db2audit facility has been successfully started or stopped, review the return code, which, when successful, will display the following: AUD0000I
Operation succeeded.
292
Chapter 9 • Database Auditing and Intrusion Detection
The db2audit describe command can also be used to verify that the db2audit facility has been started or stopped. Step 4: Resume Normal Operations Now that the db2audit facility has been configured, verified, and started, normal processing begins to initiate audited events. This is a good time to monitor database performance and compare response times to those achieved prior to starting db2audit. If you begin to notice performance degradation, you can extract the audit records to see what activities are being logged and formulate a performance-tuning strategy based on the workload. Step 5: Handle Pending Audit Records Prior to performing an extraction of the audited events, the DBA needs to ensure that all pending audit records have been flushed to disk. There are two ways to ensure this. One is to guarantee that all db2audit records are written to disk synchronously as a matter of course. The other option is to use a db2audit facility command to flush all records from the audit buffer. The option to ensure that audit records are written synchronously as they occur is handled by the audit_buf_sz parameter for the instance’s Database Manager Configuration. Leaving this
value set at its default setting of zero guarantees that no audit records are held in the audit buffer but are instead written directly to disk. In other words, if this parameter is set to zero, there will be no pending audit records. Note that if the audit_buf_sz parameter is changed, the change does not take effect until the next time the instance is stopped and started. The size range for the audit_buf_sz parameter is set in units of 4KB pages and can be set from zero (no buffering) to a maximum value of 65,000 pages. If the audit_buf_sz parameter has been set to some value other than zero and the instance has been stopped and started, the db2audit facility will utilize an audit buffer and write the audit records asynchronously. Although performance can be enhanced by allowing audit event records to be buffered prior to writing them to disk, the downside to this approach is that records in the audit buffer at the time of an instance crash might be lost. Each organization will have to weigh the pros and cons of setting the audit_buf_sz against their security requirements. If the audit_buf_sz is zero (synchronous mode), it is possible to lose one audit record (only the current record is at risk) during an unplanned system outage event. Alternatively, if audit_buf_sz is greater than zero (asynchronous mode), all the records in the audit buffer will be lost during a crash. This is the classic dilemma of performance versus security and one that has to be resolved on a case-by-case basis. If you decide to allow the audit records to be buffered, it is advisable to do some benchmarks to determine which setting performs best for your environment. In the code example that follows, commands were run to set the audit_buf_sz parameter to create and use 32,700 4KB pages (approximately 128MB) to buffer audit records:
If the audit_buf_sz is greater than zero, prior to performing an extraction of the audit records, it is a good idea to flush any buffered writes to disk. This can be accomplished using the following syntax while attached to the instance as a user with SYSADM authority: db2audit flush
When this command is run, any records in the audit buffer will be written to disk. Step 6: Extracting the Audit Records To provide an extra level of security, the audit records are written to the db2audit.log in the instancehome/security subdirectory. These records must be extracted using the db2audit facility by a user with SYSADM authority to make them available for review. When extracting the audit records, you may notice that the db2audit.log can grow quickly, so disk space may be a consideration. Adequately sizing for db2audit.log considerations is a challenging endeavor because the size of the db2audit.log is based on numerous variables. If you notice that your db2audit.log is filling up disk space faster than planned, you might consider mounting the sqllib/security subdirectory to a different machine (with dedicated disks). When ready to extract the audit trails, there are two major approaches to consider. The first approach is to generate the audit trails as text (or flat) files. The other is to generate the audit trails as ASCII files that can then be loaded into tables. Using the default extraction options will result in the generation of a file named db2audit.out. This text file format can then be reviewed using any available text editor. Because reviewing flat files manually can be a rather laborious chore, a second extraction option is available allowing the data to be formatted in a way that permits loading the data into tables within a database. To use the default option to extract records into the db2audit.out file, while logged on as a user with SYSADM authority, run the following command: db2audit extract
A new file, db2audit.out, will be created in the insthome/security subdirectory. When running this command, if the db2audit.out file already exists, the db2audit facility will return an error and an informational message, as shown in Figure 9.11. C:\>db2audit extract AUD0021N ”C:\PROGRA~1\IBM\SQLLIB\DB2ASAM\security\db2audit.out” already exists. It could be generated by previous db2au dit operation. Make sure that it does not contain any information you need, remove it and then retry the command. AUD0001N
Operation failed.
Figure 9.11
An extraction attempt fails when db2audit.out already exists
294
Chapter 9 • Database Auditing and Intrusion Detection
This is a protection mechanism to make sure that the extraction does not overwrite a file that is still needed. When the file db2audit.out is no longer in the insthome/security subdirectory, the extraction command can be successfully run again. If preferred, you may provide a filename and a path when doing the extraction. This option allows some flexibility over naming conventions that may provide an organizational benefit. For example, if you want to create a directory to store a week’s worth of audit data at a time, you could extract each day’s audit trails using a naming convention that included the date of the extraction. Your naming convention could also include the specific category or scope options that were extracted. Figure 9.12 shows an example. C:\audit>db2audit extract file c:\audit\aud.20061113.audit category audit AUD0000I
C:\audit>ls –ltr total 5 –rw–rw–rw 1user –rw–rw–rw 1user
Figure 9.12
group group
1036 Nov 12 21:34 aud.20061113.audit 2209 Nov 12 21:35 aud.20061113.sysadmin
Employing a naming standard for db2audit trails
When extracting the audit records, there is no requirement to extract every category if multiple categories have been audited. It is also possible to extract only success or failure events. In Figure 9.12, for example, although all categories are being audited, the SYSADM has chosen to extract only AUDIT and SYSADMIN events and has chosen to place each of these types of events in different text files in the directory c:\audit. Because the status option was not specified in the command, both successful and failed events were extracted by default. Many organizations prefer to extract their audit trail information in a format that allows the data to be loaded into tables. Doing so provides the ability to query the information with SQL rather than have to parse through text files. To format the output of the audit trail in delimited ASCII using the default options, run this command: db2audit extract delasc
The output is placed in the security subdirectory. Notice in Figure 9.13 that each category has a corresponding .del file even if there were no audit records recorded for that event. Also, a .del file is generated for each category whether that category is being audited or not.
C:\Program Files\IBM\SQLLIB\DB2ASAM\security>ls –ltr total 18 –rw–rw–rw 1user group 4096 Nov 13 00:58 –rw–rw–rw 1user group 5114 Nov 13 00:59 –rw–rw–rw 1user group 0 Nov 13 00:59 –rw–rw–rw 1user group 0 Nov 13 00:59 –rw–rw–rw 1user group 825 Nov 13 00:59 –rw–rw–rw 1user group 189 Nov 13 00:59 –rw–rw–rw 1user group 0 Nov 13 00:59 –rw–rw–rw 1user group 2389 Nov 13 00:59 –rw–rw–rw 1user group 4014 Nov 13 00:59
The db2audit command syntax provides the ability to specify ASCII file extraction for only specific categories, for only successful or failed events, and allows the specification of a delimiter other than the default (0xff) if desired. To illustrate, here is a command that can be run to extract the audit trail for the Sample database for only OBJMAINT events and sets the character string delimiter to ;. db2audit extract delasc delimiter ; category objmaint database sample
When the extraction is complete, the files can subsequently be loaded into any database, not necessarily one associated with the audit trail data. After a decision has been made to load the audit data into a database, it is a good idea to either store the information in a database created exclusively for that purpose or, at a minimum, create a separate schema in an existing database to house the audit information tables. This provides an extra layer of security for the data because privileges can be granted and revoked more easily when this data is segregated from the normal transactional tables. To create a new schema, connect to the appropriate database and run this command: db2 create schema <schema_name>
Prior to running any of the DDL to create the tables, be sure to set the schema so that the tables will be created appropriately. The command to set the schema is as follows: db2 set current schema <schema_name>
After the schema is set, you can run the DDL to create the tables. Although the DDL is included in this chapter, you can always find the most current version of the DDL on the IBM DB2 Information Center (http://publib.boulder.ibm.com/infocenter/db2luw/v9/index.jsp?topic=/com. ibm.db2.udb.doc/welcome.htm). When looking for the DDL in the DB2 Information Center, search on the topic “Creating tables to hold the DB2 audit data.”
296
Chapter 9 • Database Auditing and Intrusion Detection
With the tables built, loading the extracted audit data is the next step. This task is easily handled using the DB2 LOAD utility. Following the preceding example and using a semicolon as a delimiter, the following LOAD command could be used to load the data: db2 “load from checking.del of del modified by chardel; insert into audit.checking”
If the audit data were extracted using the default delimiter, the syntax would change slightly and the command would be as follows: db2 “load from context.del of del modified by chardel0xff insert into audit.context”
Another LOAD utility option that can prove valuable is the ability to replace the table data with the newly extracted data with a single command. Because the goal is to review the information, not just load it into tables, queries should be designed and run to retrieve the audit information. When the queries are run, however, and the results are analyzed (and depending on your organization’s requirements for keeping archived audit information), the data in these tables may no longer be needed. Rather than delete reviewed data that is no longer needed (a SQL delete operation incurs transaction logging overhead), using a LOAD REPLACE operation is advisable. The load utility also offers the ability to incorporate RUNSTATS as part of the load process. Having current runstats will help speed SQL query retrieval and should be considered either as part of the load operation or as a separate step. The load utility has a wealth of options. Obviously, the DBA should review the load utility syntax prior to running this command, especially if the data volumes are expected to be large or if optional parameters are desired.
From Analysis to Physical Design
299
Step 7: Prune Audit Records from the Current Audit Log The db2audit.log can grow quite large depending on the db2audit facility settings and transaction volume. After the audit records have been extracted, and optionally archived or moved to tables, pruning the db2audit.log is advisable. As a safeguard, only a user who holds SYSADM authority can perform this step. There are two primary ways to accomplish this task. The first is to prune all audit records by using this command: db2audit prune all;
The second option is to prune using a date and hour parameter. An example follows: db2audit prune 2006112008
Notice that the date format for the prune command is YYYYMMDDHH. All audit records that have a timestamp later than that supplied to the prune command will continue to be written to the db2audit.log and will be available for the next extraction operation. Pruning the db2audit.log in this manner immediately after an extraction prevents the situation where the same audit records are extracted a second time. One More Tip for Working with db2audit When planning the number of databases per instance, consider giving each database its own instance. Because the db2audit facility works at the instance level and is configured for all the databases in the instance, limiting the number of databases per instance provides a better level of granularity.
Triggers DB2 triggers are robust and can be designed to function as database auditing mechanisms. Some organizations do all their auditing with triggers. This can be a plus or a minus. On the plus side, DB2 triggers are typically easy to design, can be written “in-house” by the DBA team, and may provide good performance. On the negative side, triggers can be dropped by the DBAs, they are not fired during a DB2 load utility operation, and they will be invalidated if a trigger-dependent object is dropped. In addition, if more than one trigger is defined for one type of triggering statement, such as an update, the triggers are fired in the order of their creation. Therefore, is it better to consolidate multiple triggers into one if the result depends on the trigger firing sequence. If your auditing requirements are minimal, using DB2 triggers might accomplish the desired results, but care should be taken in complex environments. For example, at the beginning of this chapter in Table 9.2, the HRDB database requirements for auditing were found to be limited in scope. Only five tables met the requirement for database auditing. In this situation, using triggers might provide a viable solution. If the requirement had been to audit all 147 tables in the database, db2audit would have been a better choice. Following the example of the HRDB database, and specifically the EmpHist table requirement that any deletes should be captured, the steps to create a trigger to provide this functionality are
300
Chapter 9 • Database Auditing and Intrusion Detection
fairly straightforward. As an example, the following steps document the process that was used to create the trigger to satisfy the audit requirement for the EmpHist table. 1. Determine the structure of the current EmpHist table so that the trigger can be designed to accommodate it: — DDL Statements for table "DB2ASAM "."EMPHIST" CREATE TABLE "DB2ASAM "."EMPHIST" ( "EMPLID" CHAR(5) , "DEPT" CHAR(5) , "DOB" DATE , "TERM_DATE" DATE ) IN "USERSPACE1" ;
2. Create a new table to hold the audit information and add columns to hold the current user and session id that initiated the delete: C:\audit>db2 "create table db2asam.emphist_audit like db2asam.emphist" C:\audit>alter table db2asam.emphist_audit add column user char(28) add column session char(28);
3. Insert some records into the EMPHIST table for testing: insert into db2asam.emphist values ('10001', 'DBA01', '01/31/1980', '04/20/2004'), ('19001', 'ABF01', '02/28/1965', '07/10/2001'), ('09001', 'ABF99', null , '12/10/1999'), ('21001', 'CDF90', null , '06/10/1996');
4. Design the trigger and save it to a file named emphist.trig.sql: CREATE TRIGGER db2asam.emphist_trig after delete on db2asam.emphist referencing old as prev for each row mode db2sql BEGIN ATOMIC INSERT into db2asam.emphist_audit values (prev.emplid, prev.dept, prev.dob, prev.term_date, current_user, session_user); end@
5. While connected to the database, build the trigger: C:\audit>db2 -td@ -vf emphist.trig.sql
6. Verify that the trigger works as expected: C:\audit>db2 "select * from db2asam.emphist_audit" EMPLID DEPT DOB TERM_DATE USER SESSION ——— ——- ————— ————— ———————- ——————0 record(s) selected. C:\audit>db2 "select * from db2asam.emphist" EMPLID DEPT DOB TERM_DATE ——— ——- ————— ————— 10001 DBA01 01/31/1980 04/20/2004 19001 ABF01 02/28/1965 07/10/2001 09001 ABF99 12/10/1999 21001 CDF90 06/10/1996 4 record(s) selected.
From Analysis to Physical Design
301
C:\audit>db2 "delete from db2asam.emphist where emplid = '21001'" DB20000I The SQL command completed successfully. C:\audit>db2 "select * from db2asam.emphist" EMPLID DEPT DOB TERM_DATE ——— ——- ————— ————— 10001 DBA01 01/31/1980 04/20/2004 19001 ABF01 02/28/1965 07/10/2001 09001 ABF99 12/10/1999 3 record(s) selected. C:\audit>db2 "select * from db2asam.emphist_audit" EMPLID DEPT DOB TERM_DATE USER SESSION ——— ——- ————— ————— ——————— ———————— 21001 CDF90 06/10/1996 BONDR BONDR 1 record(s) selected.
When designing triggers for your environment, especially if this is an unfamiliar task, the DB2 Control Center offers a GUI option that makes the task easier. Regardless of which process you use to create your triggers, it is important to validate that they work, so testing is important. Also, remember that because triggers become invalid if any object on which they are dependent is dropped, you may need to rebuild triggers from time to time.
DB2 Recovery Expert for Multiplatform Some auditing requirements are more challenging than others. The requirement to restore data that has been mistakenly or maliciously changed is one of the more demanding requirements. If the requirement just refers to recoverability, DB2 has a native ability to recover the database to a point in time before the transaction in question occurred. If the requirement is the ability to reverse an erroneous transaction or two, restoring a database to accomplish that task is a considerable amount of overkill that can cause an unwanted database outage. Of course, if you knew which transactions were subject to going awry, triggers could be coded to save the data prior to allowing the transaction to commit. Then, update statements could be used to return the original data to its rightful place. Typically, that is not the case and predicting the future is still a skill beyond the scope of even the best DBA. One tool that allows the database to continue with business as usual while wayward transactions are corrected is the DB2 Recovery Expert for Multiplatform. This tool enables recovery of altered, corrupted, incorrect, or missing database assets without an outage. This tool is not part of the DB2 product but is a separately licensed product.
Stored Procedures, UDFs, and Other Programmatic Approaches to Auditing DB2 stored procedures have become easy to code because of great improvements in the Stored Procedure Builder GUI interface. Incorporating stored procedures, user-defined functions, and other programmatic approaches into an auditing solution is certainly an option. If your specific
302
Chapter 9 • Database Auditing and Intrusion Detection
audit requirements are minimal, it might even be possible to meet them with programmatic constructs alone.
Monitoring, Reporting, and Analyzing One of the most challenging facets of auditing is after everything is set up and running. Getting things set up is a single scope process. Continuing to be vigilant is a way of life. Being vigilant means that monitoring has to be done every day. Reports must be generated and reviewed. Analysis of the audited information must be undertaken. Abnormal events must be flagged and investigated. If there is no monitoring, no reporting, and no analysis, there is also no auditing.
LAST WORDS Database auditing should not be done until the analysis and requirements have been finalized and documented. Auditing just for auditing sake may leave an organization at greater peril than no auditing at all. Resist the urge to respond with a crisis mentality and, instead, educate your managerial audience on the appropriate steps to ensure a successful, secure implementation. Frequently, DBAs are reluctant to implement database auditing for fear of performance degradation. This is a common fear but one that does not have to be realized if the auditing is implemented appropriately. Although it is true that auditing every event might cause some observable degradation in database responsiveness, it is seldom the case that every database event must be audited. This means that it is important to know “what is important” for the specific organization. When handed the requirements, continue the process analysis. Find a way to summarize and condense requirements. Look for ways to reuse audit solutions to decrease complexity. The db2audit facility provides significant, configurable functionality. Before using this tool, it is important that the DBA understand the tool and that it is implemented appropriately. Working with the db2audit facility in a safe environment until the DBA becomes comfortable with the necessary skill set is strongly encouraged prior to implementation in a production environment. DB2 triggers can be used for database auditing as long as their inherent risks and limitations are understood and mitigated. DB2 triggers are probably more effective for limited auditing than as a 100 percent solution. Other programmatic measures may be used for database auditing, such as DB2 stored procedures or user-defined functions provided they can be coded effectively. You can purchase an additional product, DB2 Recovery Expert for Multiplatforms, if there is a need for wayward transaction recovery without a database outage. The task of database auditing is not just setting up the necessary structures and turning on a switch. The setup steps are merely the precursor to auditing. It is the monitoring and the review that actively forms the actual database audit.
CHAPTER
10
SSH for Data-Partitioning on UNIX Platforms
many pieces does it take to make a whole? The DBA’s answer: “It depends.” If you H ow are a DBA who manages a DPF environment, your invisible cape must be very thick indeed.
FIRST WORDS Security management for a single-partition environment is quite challenging, but multipartition databases require special considerations. What steps can you take to ensure that any machine-tomachine communications are as secure as possible?
SECURE SHELL (SSH) FOR DATA-PARTITIONING FEATURE ON UNIX With the DB2 Data-Partitioning Feature (DPF) on UNIX platforms, DB2 instances must execute commands at all partitions in db2nodes.cfg. For example, to start or stop DB2 instances, DB2 sends the actual db2start and db2stop commands to all partitions identified in the db2nodes.cfg file to be processed locally at the partition. A remote shell utility is necessary to flow the commands to those partitions. Other examples of remote processing are db2_all or rah utilities, which are sent to all partitions identified in the db2nodes.cfg file to be executed locally. Currently, DB2 supports both remote shell (RSH) and secure shell (SSH) to run these commands remotely. RSH is a program used to execute commands on a remote host. It has largely been replaced by SSH because of security concerns. RSH sends password and data in an unencrypted form, making it vulnerable to interception. Also, the rhosts mechanism used by RSH for trusted logon is
303
304
Chapter 10
SSH for Data-Partitioning on UNIX Platforms
vulnerable to spoofing because it does not have a means to authenticate the remote client. In comparison, SSH validates the identity of both sender and receiver much more reliably by using public key cryptography. Before we discuss how to activate SSH for DB2 on UNIX platforms, you first need to understand how to configure the SSH environment. In general, SSH is invoked by passing the remote username, address, and the command to be executed as arguments: % ssh [user@]hostname [command]
The user@ and command arguments are optional. If the username is omitted, the username of the local account is used. The command argument is the command to be executed on the remote host. If it is omitted, the default login shell is executed. If the remote host’s hostname is not in the known-hosts list, SSH prompts the user, asking whether to add it to the list and continue. If another authentication method such as public key authentication is not set up, SSH prompts you for the remote password. If the command is omitted, the remote login shell is executed. SSH supports many types of authentication. Public key authentication and host-based authentication are the types that can be used with DB2. For DB2 to work properly with SSH, the instance owner’s ID on the different physical partitions should be set up using trusted hosts so that the instance owner ID can log in to the account on any partitions (on any participating machine) without needing to enter a password.
THE SETUP STEPS In the following subsection, we first explore the general procedures necessary to set up public key and host-based authentication. Then, we cover setting up SSH for the DB2 DPF environment. To facilitate our discussion, assume that only two physical partitions are defined in the db2nodes.cfg for the database instance, machineA and machineB, respectively, with different fully qualified domain names and IP addresses. Machine Name
Fully Qualified Domain Name IP Address
machineA
machineA.domain
192.168.1.1
machineB
machineB.domain
192.168.1.2
Although the following examples are accurate on Linux platforms, some commands may vary on different platforms.
The Setup Steps
305
Public Key Authentication (per User Account) Public key authentication requires a key pair for each user account from which to execute the SSH command. The private key stays on the client machine, and the public key is copied to the server. Figure 10.1 shows the general procedures for setting public key authentication. Figure 10.2 shows the procedure used when setting public key authentication for DB2 DPF.
Figure 10.1
Figure 10.2
General procedure for setting public key authentication
Procedure for setting public key authentication for DB2 DPF
306
Chapter 10
SSH for Data-Partitioning on UNIX Platforms
Host-Based Authentication (per Machine) With host-based authentication, the host keys and a list of trusted hosts establish authenticity. Figure 10.3 shows the steps to set up host-based authentication.
Figure 10.3
Setting up host-based authentication
To determine whether public key or host-based SSH is best for your environment, consider the information in the following subsections.
The Setup Steps
307
Public Key Authentication Pros: • More secure because only the specified user account has access. • More flexible because usernames on the server and client do not have to be the same. • Root access is not required for configuration. Con: • More difficult to set up when there are lots of accounts. Host-Based Authentication Pro: • Easier to set up when lots of accounts require access to another host. Cons: • If one trusted host is compromised, all trusted hosts become vulnerable. • Root access is required for configuration. The database administrator needs to choose the appropriate method based on the corporate security policy that is applied to DB2 DPF on UNIX systems.
How to Configure DB2 to Use SSH As mentioned previously, the SSH utility is more secure than the RSH utility. For DB2 to use SSH, the DBA must set the DB2 registry variable DB2RSHCMD to the SSH executable. This is done with the db2set command, as shown in Figure 10.4.
Figure 10.4
Setting the DB2RSHCMD registry variable
After the DB2RSHCMD value has been set to use SSH, when DB2 issues internal commands such as db2start/db2stop or external commands such as db2_all (where the commands will be executed remotely), the SSH utility is chosen. After you have set the DB2RSHCMD registry variables, you must restart the instance so that the new setting will be in effect on the database server.
308
Chapter 10
SSH for Data Partitioning on UNIX Platforms
In some configurations on UNIX platforms, SSH may take much longer to authenticate than RSH. If DB2 does not receive a response from the remote nodes in the expected time frame, communication failure will be reported. To address this authentication timing issue, you can set another registry variable, DB2RSHTIMEOUT, to specify the amount of time, in seconds, that DB2 will wait to establish any single RSH connection before assuming there is a communication failure. Note that this registry variable will be used only when DB2RSHCMD is also set. Furthermore, this is a per-remote-command timeout; so, for instance, in a DB2 environment with an eightnode configuration, if the registry variable DB2RSHTIMEOUT is set to 4 seconds, the total cumulative time to establish all the remote connections may be up to 32 seconds. See an example of setting the DB2RSHTIMEOUT value in Figure 10.5.
Figure 10.5
Setting DB2RSHTIMEOUT registry variable
LAST WORDS Although only applicable in a DB2 DPF UNIX environment, machine-to-machine communication via SSH is strongly recommended. SSH adds depth to your secure DB2 DPF implementation and should be deployed whenever the implementation calls for multinode processing.
CHAPTER
11
Database Security— Keeping It Current
I
f DB2 database security were your boss, she would constantly be asking, “What have you done for me lately?”
FIRST WORDS Maintenance is a bore. If you own a home, you know that without preventive and necessary maintenance, the value of your home will decrease year after year. So, even though no one wants to do maintenance, it is a necessary duty to protect and preserve what you have. Would you really invest a million dollars in a home and never bother to keep it clean? It’s the same concept with DB2. Database security can be a challenge to set up, but when completed, the task of keeping it secure is never ending. This chapter deals with those requisite and perpetual needs and gives hints and tips to help you maintain that secure environment that everyone has worked so hard to foster.
DILIGENCE With every software product, there is the potential for discovery of previously unknown security vulnerabilities. These types of discoveries can be identified in several different ways. For example, IBM may identify vulnerabilities during additional development or testing. Outside security firms or persons who work with the product also may identify vulnerabilities. In a worstcase scenario, if there were a new type of attack or threat perpetrated or proposed, the act itself would also point toward a new vulnerability that would result in a mitigation effort.
309
310
Chapter 11
Database Security—Keeping It Current
Although vulnerabilities native to the DB2 product have, so far, been few, vigilance is always necessary, especially because the effort to gain inappropriate database access is so tempting. Reading the numerous high-profile headlines documenting any of the recent security breaches resulting in lost or compromised personal information simply underscores the attractiveness of the data that is housed in databases to thieves, hackers, and disgruntled employees. If a vulnerability involving or threatening DB2 is identified that requires action or mitigation, IBM announces the vulnerability and provides a solution, either in the form of advice or through the release of a Fixpack. As a rule of good practice, it is important for the DB2 DBA to be aware of the issuance of an IBM DB2 alert or the release of a new Fixpack, regardless of whether the issue is security related.
DB2 User Community Resources Fortunately, IBM provides several ways to be kept aware regarding critical information about DB2. To be proactive and make sure information is received as soon as it is released, sign up for e-mailed alerts at www-306.ibm.com/software/support/einfo.html (see Figure 11.1). After you sign up, if new vulnerabilities are discovered, e-mailed specifics will be sent directly to you via “alert” e-mails so that you can take appropriate action immediately.
Figure 11.1
Subscribing to DB2 e-mail alerts
Diligence
311
The DB2 support page provides a wealth of information and can be used to research any issue, including those related to security. It is also a portal to download Fixpacks. You can reach the main DB2 support page at www-306.ibm.com/software/data/db2/udb/support/. The DB2 9 information center is another valuable tool for researching security settings (in addition to being a powerful tool for understanding DB2 in general). You can access it via http://publib. boulder.ibm.com/infocenter/db2luw/v9/index.jsp?topic=/com.ibm.db2.udb.doc/welcome.htm. Another great source of information is provided via RSS (Really Simple Syndication) news reader feed. Using a news reader tool (many are freely available), you can keep current via “pushed” DB2 information. Although this is not necessarily limited to security information, it is a valuable tool to keep current on product information. To subscribe, navigate your Internet browser to www-306.ibm.com/software/data/db2/udb/support/. Choose the RSS option (news feed of new content), as shown in Figure 11.2, and follow the instructions to subscribe.
Figure 11.2
Subscribing to the DB2 RSS news feed
A free resource that posts articles of a security nature is the DB2 Magazine. This magazine is a premier resource for information specific to DB2 and provides informative articles written by individual contributors and by industry-recognized experts. You can access the DB2 Magazine site via www.db2mag.com/. In addition to the IBM resources, DBAs worldwide routinely review the DB2-L list maintained by the International DB2 Users Group (IDUG). This list is not exclusive to security issues, but if
312
Chapter 11
Database Security—Keeping It Current
you are a subscriber (a free registration is required), you can post questions regarding DB2 security or any other DB2 topic of interest. The URL is www.idugdb2-l.org/archives/db2-l.html.
Security Information on the Web Beyond the normal DB2 informational resources, many forums and websites can prove to be extremely useful for learning about security and for discovering how to mitigate newly found vulnerabilities. Any search on a major search engine can provide a wealth of information. For a start, considering visiting the following (listed in no particular order): http://isc.sans.org/ www.nsa.gov www.securiteam.com/ www.ittoolbox.com/ www.securityfocus.com/ www.microsoft.com/security/default.mspx www.cccure.org http://iase.disa.mil/index2.html
FIXPACKS Fixpacks hold the code that updates DB2 installations. IBM creates Fixpacks to update product features and make any necessary repairs to product code, whether security related or not. Keeping current with DB2 Fixpacks is one of the best ways to guard against security vulnerabilities and provides the extra benefit of making sure your DB2 installation is always at the most current product level. If a security vulnerability is discovered, IBM will recommend a product update via a Fixpack. Fixpacks are tied to the product version and operating system. For example, a Fixpack for Windows operating systems should not be applied to a DB2 installation on a UNIX system and vice versa. Each Fixpack includes all necessary documentation including information on prerequisites and typically includes Release Notes, a Readme file, and a detailed list of all items fixed through the application of the Fixpack. Each of the items fixed or upgraded via the Fixpack installation is known as an APAR (Authorized Program Analysis Report). Reviewing the APAR list will provide information on the items “fixed” in the Fixpack and, if security vulnerabilities are being mitigated via the Fixpack, they will be mentioned in this list.
Keeping Current Goes Beyond DB2
313
One word of caution is necessary regarding Fixpacks. Applying Fixpacks in production environments without proper testing may result in unwanted problems. It is always best to apply Fixpacks in development and test environments first, with an appropriate testing cycle to ensure that the new DB2 level does not conflict with the current production software. Most software vendors offer “certification” on certain code levels of DB2 that may lag behind the Fixpack release and make it unrealistic to apply a newly released Fixpack. The Fixpack “go/no go” decision becomes ever more difficult if security vulnerabilities have been mitigated in a Fixpack release, because the risk of not applying the Fixpack must be considered. Keep in mind that if the security vulnerability has a fix and that fix has been published (as in the case of a Fixpack release or an IBM alert), it is only a matter of time before some exploit of that vulnerability is introduced into the wild.
KEEPING CURRENT GOES BEYOND DB2 Although the focus of this book is DB2 security, remember that few environments are simple these days. It is likely that any mid-to-large enterprise environment has more than one database product and multiple software applications. Throw in operating systems into the mix and there is sufficient complexity to keep any security junkie happy. Even if your role is “only” that of DB2 DBA, keeping an eye on the rest of the environment should be a consideration if possible. If you want to be a hero, saving the company from a security lapse should accomplish that goal, whether the “save” is DB2 related or not. Consider the entire architecture, not just the databases, when thinking about current and timely application of upgrades and fixes. Third-party applications and operating systems typically publish upgrade/bug fix information on their websites prior to public product or fix releases. The task to check these resources should be formally assigned to someone in the enterprise. Subscriptions (e-mail or postal mail) to product security release information, available as a free service from most vendors, are one way to ensure that information on vulnerabilities and their appropriate fixes is received as it becomes available. Consider subscribing to e-mails for all products used at your organization even if it is not your primary responsibility. The information may be redundant because someone else in the organization may have received it; but the reality is that with heavy workloads being a norm in many shops, not all e-mails get someone’s attention. Make it your job to see that “fixable” vulnerabilities do not become hacks, regardless of whether the vulnerability is directly related to your daily tasks. It is important to remember that the enterprise databases are actually the goal of most hacks regardless of whether they are initiated at the database level or via another application or method.
314
Chapter 11
Database Security—Keeping It Current
MIXED DATABASE ENVIRONMENTS If there is more than one database product in an enterprise, the task of database security takes on several additional facets. Not only will the DBA need to keep current on DB2 security and all the supporting technical architecture, but he will also potentially have to be a security expert on other database products. Because each database product brings new security challenges, managing a mixed database environment requires a heightened awareness of all the “players,” their plusses and minuses in the realm of security and their willingness to provide patches quickly should a new vulnerability be discovered. Much like breaking the string holding a necklace of pearls, it takes only a small amount of damage to cause some serious issues. Your database environment is most likely only as secure as your least-secure database product. If you are a DBA tasked with managing databases in a mixed environment and want to maintain the strongest possible security architecture, consider these points: • Consolidate database products wherever possible. Do the analysis necessary to determine the smallest common denominator of database products that will provide functionality for all enterprise applications. If you support three database products, eliminating one will reduce your exposure by a third, so this effort can be highly effective from a security standpoint. • Eliminate databases that are not needed. Believe it or not, many companies actually keep databases around that are not being used. Attempt to discover and eliminate these. Do an inventory of databases and their “owners.” Make those owners justify keeping their databases around. Although this is a good idea even if only supporting one database product, it is especially useful in mixed database models because eliminating unused databases may also eliminate the need for multiple database product support. • Make a strong case for standardizing on one database product. Standardizing on one database product may not prevent the need for extra product support, but not standardizing encourages extra product support. Do the research to determine the product that offers the best security for your organization and present a strong case to management.
VULNERABILITY ASSESSMENTS As part of an active security awareness exercise, consider performing vulnerability assessments that include all managed databases on a regular basis. Alternatively, you can purchase services or applications that provide information and detail for areas that need security improvements.
Intrusion Detection
315
When performing a vulnerability assessment, you are attempting to look at your technical infrastructure in the same way that a hacker or disgruntled employee would view it. You are attempting to find flaws in the security defense, not just in the databases, but throughout the enterprise. Because DBAs are so involved in the day-to-day operations, it is hard for them to notice minor security flaws the way a hacker would. For this reason, it is usually best to either use purchased tools for this task or hire specialists to perform the vulnerability assessments.
INTRUSION DETECTION Perimeter-based intrusion detection is typically the most deployed technological enterprise solution to discover attacks. Because managing this is not typically a DBA responsibility, it might not be immediately clear why this topic would be included in a chapter on keeping DB2 security current. If thinking of the data in the database as the “target” of an intrusion attempt, however, it becomes clear that the DBA has a major role in both being aware of attacks and preventing future attacks (keeping current). Perimeter-based security focuses on external attacks and is a strong component for any security architecture. Unfortunately, if this is the only approach taken, the possibility of an internal-based attack might be overlooked. If recent news reports are any indication, internal attacks are actually more prevalent than external ones. After all, what better way to download millions of credit card numbers than to secure a position at a financial institution with legitimate access to the information? All it takes is a few keystrokes from a SQL query to gain the information if the employee has trusted access to the data. When thinking about intrusion detection from the DBA standpoint, first realize that the discovery of an attack is after the attack. If an attack is underway, by definition, attack prevention has failed. When looked at from that viewpoint, now the goal shifts to terminating the attack as close to its initiation as possible. The good news is that DB2 offers several ways to aid the DBA in discovering intrusion attempts, both from internal and external sources. Of course, DB2 auditing (discussed in Chapter 9, “Database Auditing and Intrusion Detection”) easily lends itself to aid in intrusion detection. The other mechanisms discussed in Chapter 9, such as triggers and stored procedures, can also be used. If you haven’t already done so, read that information when thinking about setting up intrusion detection mechanisms. What might not be as obvious is that you can use DB2 snapshots to aid in intrusion detection, too. Although DB2 snapshots are typically used with a goal of performance improvement, they provide useful information that, with analysis, can aid in the security effort. One issue to consider when thinking about intrusion detection is that the intrusion will most likely present as an abnormality. Discovering abnormalities is possible only when you understand the norms, so just issuing snapshots, hoping for some “needle in the haystack,” is not an
316
Chapter 11
Database Security—Keeping It Current
effective approach. Like most security processes, this one requires some analysis, maintenance, review, and change to keep it current. If there is a table in the database that has credit card numbers and addresses, for example, it might be a good table to study via snapshots. The TABLE snapshot may be highly valuable when used as a way to discover values outside of the normal ranges for table reads. If on Monday through Saturday, the number of rows read from the table is typically 8,000 and on Sunday the rows read is typically 1,000, you have the basis for norms. If those numbers begin to increase for reasons not related to business growth, you might have an abnormality that you should research. Another example is using snapshots to gather all dynamic SQL (although you have to be aware of a potential performance hit) in conjunction with setting the STATEMENT monitor switch. If the DBA knows, for instance, that a sensitive table is accessed only via a stored procedure launched by the application, but suddenly sees that an unrecognized or poorly formed SQL statement has been running against that table, discovery action could be initiated. Obviously, the DB2 audit facility provides functionality similar to the information that can be gathered using snapshots, but because not all corporations run a DB2 audit, or don’t fully utilize it, snapshots can provide some measure of intrusion detection discovery when properly thought out and initiated. To learn more about all the functionality of DB2 snapshots, including how to set the necessary monitor switches for information gathering, see the DB2 Information Center at http://publib.boulder.ibm.com/infocenter/db2luw/v9/index.jsp?topic=/com.ibm.db2.udb.doc/we lcome.htm or read about the topic in the DB2 Command Reference.
PREPARE FOR A BREACH If a breach occurs, despite all your valiant efforts, don’t panic. Undoubtedly, your heart rate and blood pressure will rise, but giving in to despair will not enable the type of response that is necessary. As with most situations in life, if you are prepared for any eventuality, it is easier to achieve a positive outcome. Prepare yourself and your organization now for the possibility of a breach. The best way to prepare for dealing with a hack is to practice a response. A highly effective way to ensure preparedness is to simulate a response to a breach of highly sensitive data. Before beginning this type of “trial run,” it is a good idea to create a checklist of items that need to be completed in the event of a breach. During the exercise, someone should function as an observer, noting any items that are not on the checklist (but should be), items that should be improved, items that should be removed, and items that are effective as written.
Preparing for the Future
317
In preparing for a response to a breach, preparation topics often overlooked include the following: • Keep a current list of all individuals who must be contacted in the event of a breach. If a breach occurs, who would you call? Do you have current contact information for those individuals? Should you call each person on the list or delegate that task to others? Who should be called first, second, and so on? How is the list to be stored? If electronically, what happens if the system is so compromised that the contact list cannot be accessed? Is the list maintained in a current state? Is the list reviewed regularly? Is there a secondary call list for individuals who might not need to be initially involved, but whose expertise will be needed to validate systems after the initial triage? Also, consider that the corporation’s attorneys, law enforcement, and regulatory bodies should be notified in most cases. • What is the scope of the breach? A breach could be minor or a worst-case scenario. In recent news, we have seen occasions where thousands of credit card numbers have been stolen and cases where only minor intrusions occurred. Until the scope of the breach is determined, it is difficult to formulate an action plan. Determining the scope of the breach should be a top priority. Consider who should be involved in the discovery process. More than a small number of individuals may actually be detrimental to the process. For example, a breach might have caused the databases to go or be taken offline. To perform “discovery,” the DBAs are using terminal access. If there is limited availability of terminal access, individuals who do not have terminal access may actually deter the work of those who do. Keep this group of individuals as small as possible to effectively do the work required. This is one case where “more” is not “better.” • Should the databases be taken offline? If the databases are still online after a breach, this could be a tough decision to make. If data was stolen, taking the database offline could prevent further intrusions, but such an action could also put a company out of business. A good approach is to meet with management prior to the simulation and formulate a list of guidelines that would best serve your organization. In most organizations, attorneys should also be involved in these types of discussions.
PREPARING FOR THE FUTURE It would be great if each of us knew what security vulnerabilities were coming so that we could be prepared beforehand. Because that is not possible, however, a good plan is to make ourselves as knowledgeable about past and present threats as possible while considering how these threats might “morph” into even stronger future threats.
318
Chapter 11
Database Security—Keeping It Current
When implementing a new database architecture, some normal operations, such as contingency planning, can also be a valuable exercise if applied to potential future threats. Think about contingencies to mitigate today’s concerns, as well as potential concerns five years forward. As an example of “thinking forward” for security, when creating a new database environment, the DB2 DBA may implement Label Based Access Control (LBAC), even though there is no formal requirement to do so. Although extra work might be required, the DBA knows that LBAC is inherently more secure than the official requirement and that database security will benefit now and in the future. The cost/benefit ratio might not be evident now but might be very evident at some point in the future. Consider planning a formal time on a quarterly or more-frequent basis, to do an evaluation of security as it applies to DB2 and the technical architecture in place in your organization. Approach your personal “security” education as a life-long learning experience. Ask questions, read newly released books and articles, study the news, and remain on guard so that the future doesn’t catch you unprepared to protect your databases.
LAST WORDS Security is not just a function of the original setup and installation. It is an ongoing task. It is important that those tasked with database security keep a focus on current security, an understanding of the successes and failures of the past, and an ability to look toward the future. This involves continuous diligence, a curiosity that inspires a commitment to continuous learning cycles, and an approach that includes keeping up with current events and news about security vulnerabilities.
CHAPTER
12
Final Thoughts: Security— The Human Factor
as human emotions, the reasons to consider the human factor in any security setA stingvaried are just as important as building the technological foundation for a secure architecture.
FIRST WORDS No security implementation would be complete without addressing the human factor. Throughout this book, the focus has been on the “geeky” side of DB2 security or, in some cases, the “managerial” side of security, both of which are critical. Until humans (and the strong emotions that drive them) can be eliminated from the security equation, security planning has to factor all the varieties of human intervention into building a secure environment. Think of it this way: No matter what technology is used, a human is at the heart and soul of every security exploit. Security is not merely about the technology. It’s about the technology and the people. If anything, this topic is as much on psychology and social norms as it is on security technology, but because an all encompassing road map of the human mind has yet to be graphed into a data model, DBAs must have an awareness of the human security risks so that, at a minimum, they don’t foster occasions for a security compromise. Because humans are so complex, it would be easy to throw up your hands and admit defeat when it comes to hardening your environment against the human factor. Certainly, no one can ever be completely prepared for the variety of intellectual mechanizations that can result in a “datacompromised” situation. Admitting defeat and walking away, however, is not an option if you want to continue receiving paychecks.
319
320
Chapter 12
Final Thoughts: Security—The Human Factor
Although it is challenging to work to protect ourselves from the human factor, if we use history as our guide, we can take steps to either mitigate the best known of these issues or to prevent them all together.
EDUCATION AND AWARENESS It would be difficult to overstress the importance of education when it comes to security. Although educating the technologists is always important, this topic is not referring to education just for the technologists, but education for the people who are often forgotten when planning a secure enterprise. For example, it is easy to plan on educating management regarding security policies and procedures because they are so “visible,” but what about the end users? How about the receptionist who greets visitors or answers the phone? How about your sales force? How about the janitor who empties the trash? Basically, all those who interact with or work near the secure system should receive some level of security education and should be required, in writing, on an annual basis, to agree (in terms proposed by the company attorneys) that they have been made aware of the company’s security policies and that they will not violate them.
For Geeks Only It is expected that technologists will understand the technology they support. Throw security into the mix and the knowledge to claim expertise in both DB2 and security is significant, requiring a breadth of experience well beyond the requirements of the technology itself. Why? Because those who would initiate a security exploit against databases are evolving and learning from the past. Even if the technologist is keeping pace learning about the new features of each DB2 product release and maintaining a security awareness, the new ways that humans will attempt to exploit the product are limited only if they have not been thought up. The minute the thought enters the brain of someone looking to compromise a DB2 database, the technologist who is trying to keep security intact is at a disadvantage. There is no such thing as too much experience or too much education when it comes to security. Consider recent history to recognize how quickly technology has changed. In 1971, a computer was a huge machine that, in many cases, provided less actual computing power than a child’s calculator does today. Security exploits were nonexistent. Now, as you look at your subcompact notebook computer, think back to the headlines of the last year … the credit card numbers stolen by the hundreds of thousands, the identities that were exposed, the financial transgressions aided by improper use of computers … and recognize the exponential change in what is only a short span of time for humanity. For technologists, life-long learning is a requisite. If you love what you do and are good at it, you probably already realize this and already understand that this continual learning cycle serves not just your own career, but the well-being of the organization that employs you. If you are committed to obtaining the most solid foundation in DB2, you will probably attend IBM classes and
Education and Awareness
321
conferences, study online materials, read books on the product, and try to find a mentor. Likely, these are all available to you, provided you have the funds to cover any associated costs. But, is that enough? Whereas in the past it might have been, now the DB2 DBA needs to reach out and learn about the ways that security can be improved and study ways that it has been compromised. You can no longer ignore educating yourself regarding security, both internal and external to the databases you are employed to administer. Product knowledge is absolutely essential, but an overarching understanding of security, including keeping up with current affairs, is vital. The DB2 DBA should consider supplementing the normal avenues for database administration learning with coursework in security. The ways to do this are varied and can be anything from subscribing to security-focused newsgroups, taking college courses on the topic, reading current books and magazines on the subject, attending boot camps, or taking week-long, focused classes. Finding this information could not be easier. A search on any major search engine will turn up numerous hits for security-related coursework and newsgroups. One caution, however, is that an education in security is a moving target, so your choices for education need to be reviewed periodically to determine whether they are staying on the cutting edge of the topic. As part of your continuing education, consider checking out these sites for topics on security: www.governmentsecurity.org/ http://niap.nist.gov/ www.cert.org/ www.zdnet.com www.ittoolbox.com/ http://groups.google.com/ www.linuxsecurity.com/
For the “Normal” Folks It’s obvious that the technology staff of any organization, in addition to being savvy about the products they support, needs to be aware of any security implications. It is also pretty obvious that personnel whose primary purpose within the organization actually is security needs to have a solid education and experiential focus on every aspect of security. What might not be so obvious are the educational needs of all the “others.” Those are the “normal” folks whose work lives do not necessarily revolve around technology and who don’t keep abreast of the most current hack and how it is being played out. Security training for all personnel should occur annually if not more often. True, this is not the role of the DB2 DBA; but if individuals in your organization are not made aware of proper security procedures, this will impact your job in some negative way at some point. For example, if a
322
Chapter 12
Final Thoughts: Security—The Human Factor
receptionist who inputs data into the DB2 database becomes lax and leaves her password taped to her keyboard in plain view, she has invited anyone who desires the opportunity to access (at a minimum) the same data that she does. If an intrusion occurs, the DB2 DBA is going to be inundated with work. Situations where employees are terminated, without following proper security safeguards, are also ripe for security exposure that would impact the DBAs. So, despite it not being a DB2 DBA’s job to provide adequate security training for all staff, it is in his or her best interest to raise the issue to management if the training has not been provided or is not comprehensive enough.
SOCIAL ENGINEERING It is a positive social condition, the desire to help others, which often leads to our security downfall when the root cause is “social engineering.” Social engineering, or the ability to employ societal norms to a dishonest advantage, is too seldom taken seriously when thinking about security. If you do not think that social engineering is a threat to your secure enterprise, think back to the last time you saw a stranger at work. You probably rationalized that the person was there for a valid reason. Perhaps, you thought the person was selling something or was a new employee; but your first thought was probably not, “This is the person who is going to try to gain access to our secure databases.” You applied your bias to the situation and assumed that the stranger was “safe.” It is just human nature that we attribute to others the thoughts, values, and social norms that we ourselves hold. Because we would never employ devious means to secure access, we assume others would not either. Given this tendency, social engineering can be a highly effective means to gather enough information to gain privileged access. Individuals who plan to use social engineering as a ploy know the nature of humans. They understand our innate desire to help. They know that we attribute our own traits to others. They understand that fear is a driving force. They understand our desire to avoid personally embarrassing situations. They devote time and energy to knowing these things so that they can use them to their advantage. The best defense against social engineering is an awareness of the vulnerabilities that the social engineer attempts to exploit. None of us is too smart to be manipulated given the right set of circumstances, but we can raise our awareness regarding these types of exploits so that they lose effectiveness or become enough of a challenge to drive the social engineer elsewhere. Role playing is one highly effective way to reinforce defenses against this type of exploit. Solid training is another.
Publish and/or Perish?
323
STEP ON A CRACK—BREAK SECURITY’S BACK In America, young children have a saying, “Step on a crack, break your mother’s back.” With each step they take, they work to avoid stepping on any cracks in the sidewalk for fear that their mother might suffer ill effects. Cracks in security, no matter how small, can result in a security break. While a 100 percent security success rate is unattainable, it should always be the goal. Just like the child’s diligence to protect their mother, the organization must proceed through every initiative with security in focus, and it should be as a first thought, not an afterthought. Businesses, and the humans who control them, always realize that the bottom line determines success or failure. It is a normal human condition to narrowly focus on the avenues that appear to best represent success, which, in this case, is measured by financial goals. Unfortunately, because security initiatives can deplete the bottom line, they are sometimes deliberately left “wanting” in pursuit of a larger “black” number on a balance sheet. In the past, many organizations have “gotten away with it” and ignored security while fattening their profits. They had no breaches and no one was the wiser. This brings to mind another human condition. We have a tendency to judge the future based on the past. If, in the past, your organization had no effective security in place, and there was no breach, the historical view is that it is not needed, and the impetus will be to maintain the status quo. Inertia may set in. Or, perhaps, there is a security focus now, but because there has been no breach, funding for future initiatives doesn’t include line items for security. This is a shortsighted view, however, and is equivalent to gambling with the company’s assets. Consider this personal note on the human factor and security. If you want to maintain your continued employment but you see that security is suffering due to inertia, take the initiative. It might not be as difficult as you believe to make something positive happen. Sometimes, it just takes one person to rally the troops.
PUBLISH AND/OR PERISH? Have you ever thought, as you watched the news, that current criminal events seems to mirror the story lines of prime-time detective shows? Was the pretend murder scenario that played before millions of viewers only a few weeks ago eerily similar to the real murder on the news channel tonight? It is hard to know for sure whether a correlation exists between fictional portrayals of events and the impetus for a corresponding copy of those events, but a casual observation seems to make the point that one does.
324
Chapter 12
Final Thoughts: Security—The Human Factor
This potential relationship between a portrayal and an actual event makes for an interesting discourse when thinking about security. Did the fictionalized account of the crime lead to the real crime? Was a thought planted by the fictional story that was nurtured until it became the root cause for a real event? Are security breaches, when published, leading to copycat attempts? If your organization participates in a simulation of a security breach, should you publish the results? The usual answer is “probably not.” Why? Because publishing the results of your simulation provides clues to how to breach your defenses. How often have you seen companies publish, for example, that a simulated penetration test on their defenses was breached in less than 60 seconds? You’re not likely to ever see this type of information willingly exposed to the world for fear that the information would encourage real security exploits. On the other hand, what about information on “real” security breaches? We’ve all seen those, but seldom have we seen the initial news release originating from the company that experienced the breach. Typically, a news agency has published the details of the breach, and then the company reacts to the initial news with a press release of its own. It seems that the organizations experiencing the breach are not inclined to publish until the events are exposed by others. Fortunately, the releases, whether by the organization or the news media, typically do not provide enough details for others to pick up on the exploit, but instead give generalities (such as 30,000 credit card numbers were stolen). Unfortunately, the publicity may encourage copycats who will see whether they can repeat the exploit either at the same company or on a new victim. In addition to current and proposed regulatory requirements regarding security breaches that result in an impact on individual’s lives, the company needs to weigh the impact of publishing or not publishing should a breach occur. Both options present risk and both present opportunities. Do Not Publish Like all of us, managers need to have a strong sense of self-preservation and don’t enjoy admitting that mistakes were made. It could never be a pleasant experience to call up a major news organization and admit that “under your watch” a security breach occurred. If the breach were small, it might not even be newsworthy, but “small” is in the eyes of the beholder. Aside from the normal tendency to not deliver bad news unnecessarily, however, there might be valid reasons to keep quiet about security breaches. For example, the FBI might be doing an investigation into the matter, and public disclosure could weaken their position. This is an obvious situation where no information should be published and does not require any further analysis to make a decision. However, there are often areas where an argument to keep the information quiet is not as black and white. For example, perhaps the breach was completely internal (an inside job), it has been rectified, the offenders were appropriately dealt with, and preventive steps have been taken. Is it valid to keep the breach from the public? One of the major reasons that many companies do not
Last Words
325
publish is fear of the resulting negative pressure on the stock price or the fear of increased outside scrutiny. Is the fear of a stock decline enough to warrant keeping the breach quiet? The reward with this “don’t publish” strategy is obvious. The information is not disseminated; therefore, to the outside world, no breach occurred. This is the “keep the secret” defense and is one that is the most frequently used. There is no public “black eye” and no stock-price drop. The significant risk with this strategy is that the secret will leak in an embarrassing public display that will harm the corporation more than had it openly disclosed the facts as soon as it was appropriate to do so. Publish Many years ago in the United States, a product-tampering scare caught the nation’s attention. Somehow, Tylenol®, a widely used over-the-counter drug, had been laced with poison. When the initial reports came out, it could have ruined the manufacturer, Johnson & Johnson. Even though the company quickly realized that the product tampering had probably only occurred in Illinois and that the rest of the country could still safely consume Tylenol, Johnson & Johnson embarked on a massive publicity campaign and took extraordinary measures to inform the public and ensure safety. These public measures are now widely cited as having saved the company from certain financial disaster. Apply that same thought process to the argument of the company willingly admitting being on the wrong side of a security incident. Conversely, if the breach is big enough to be “hushed up,” it is also big enough to cause some serious negative reactions when it is, eventually, found out. Companies that do practice public disclosure in an appropriate manner and in a timely fashion may be able to win the public’s trust with limited negative reaction. Your company may even benefit in the long run because the public may trust it to be honest. Most people prefer to do business with corporations that they consider trustworthy. The significant risks of this strategy is that it will not be perceived well by the public or even that it will spur others to test out the vulnerability by attempting a hack themselves. As usual, the decision of whether to publish or keep silent on security breaches can be made only after an effective analysis of the entire scope of the situation has been completed. To the question “publish or not?” the answer is “it depends.”
LAST WORDS Technology alone can never be the master of security. Only when recognizing the full scope and interplay of technology and the human factors surrounding all security aspects will the complete picture emerge.
This page intentionally left blank
APPENDIX
A
Independent Security Packages
T
his appendix lists some of the enterprise security packages that the DB2 DBA may encounter, along with some associated URLs. It is not an all-encompassing list: • IBM Tivoli® Risk Manager Tivoli Risk Manager enables you to integrate application, operating system, and network security approaches. It can provide risk alerts from firewalls, routers, networks, host- and application-based intrusion detection systems, desktops, and vulnerabilityscanning tools via one central console. For more information, see www-306.ibm.com/software/tivoli/products/risk-mgr/ • IBM Tivoli Identity Manager As the product name implies, Tivoli Identity Manager is a targeted solution useful for securely automating the complete user management cycle. Tivoli Identity Manager handles user account and password management and includes robust security compliance and regulatory reporting options. For more information, see www-306.ibm.com/software/tivoli/products/identity-mgr/index.html • IBM Tivoli Access Manager Tivoli Access Manager provides authentication and authorization functionality. It enables you to implement a single sign-on (SSO) solution and eases the administrative burden by allowing the centralization of enterprise security management.
327
328
Appendix A
Independent Security Packages
For more information, see the following websites: www-306.ibm.com/software/tivoli/sw-bycategory/subcategory/SWI10.html www-306.ibm.com/software/tivoli/products/access-mgr-e-bus/ www-306.ibm.com/software/tivoli/products/access-mgr-operating-sys/ www.devx.com/ibm/Article/26683
APPENDIX
B
Kerberos
Most of this appendix information was sourced from the developerWorks article “DB2 UDB security, Part 6: Configure Kerberos for authentication on DB2 UDB for Linux, UNIX, and Windows” at www-128.ibm.com/developerworks/db2/library/techarticle/dm-0603see/index. html.
CONFIGURING THE NAS KIT ON UNIX®/LINUX® SYSTEMS FOR THE IBMKRB5 PLUG-IN Step 1: Set up the KDC server. This guide assumes that you use the NAS kit for the KDC server. If you use another KDC server, refer the installation guide for your KDC software. For AIX, you can get the NAS server kit from the AIX installation bonus CD. Note that NAS server is available only for the AIX platform at the time of this writing. Steps to set up the NAS server - KDC: 1. 2.
Install the latest version of Network Authentication Service server from CD or download it as part of the AIX expansion pack. Configure the KDC server by the following command: /usr/krb5/sbin/config.krb5 -S -d domain -r realm (where realm is the realm you will be using).
3.
Start the KDC server by running: /usr/krb5/sbin/start.krb5
329
330
Appendix B
Kerberos
Step 2: Set up the NAS client. IBMkrb5 only supports NAS clients. Red Hat Linux
AIX
Solaris
You can obtain the NAS client kit from the AIX installation bonus CD or download it from as part of the AIX expansion pack.
DB2 requires Solaris Operating Environment 8 or later with IBM Network Authentication Service (NAS) client v1.3 or higher. For Solaris Operating Environment 10, NAS client v1.4.0.4 or later is required.
a.
Download the NAS client package from the NAS Kit download site link in the “Useful Links Section” and install the package.
From v82 on, DB2 requires Red Hat Enterprise Linux Advanced Server 3 (Intel 32 bit only) with IBM Network Authentication Service (NAS) v1.4 or higher. From v9 on, DB2 requires Red Hat Enterprise Linux Advanced Server 4 or Suse SLES 9 (Intel 32 bit and 64 bit) with IBM Network Authentication Service (NAS) v1.4.0.4 or higher.
b.
Set up the krb5 configuration file.
Issue the following commands to set up the client: /usr/krb5/sbin/config.
Solaris NAS does not ship with the
krb5 -C -r realm -d domain -c KDC -s kadmin_server. The config.krb5 creates the configuration file krb5.conf under /etc/krb5/.
config.krb5
executable; therefore, it requires you to manually edit the configuration file at /etc/krb5/ krb5.conf. Please
ensure that the edited file is /etc/krb5/ krb5.conf and not /etc/krb5.conf. You must also add the default realms, domain_realm, and so on to the file. Solaris supports only Single DES. Please ensure the krb5 configuration on both the NAS client and NAS server are modified to take this into consideration.
Configuring the NAS Kit on UNIX/Linux Systems for the IBMKrb5 Plug-In
331
Step 3: Create server principals (service principals) in the KDC. To use NAS, ensure that you add /usr/krb5/bin and /usr/krb5/sbin into the PATH of environment before any other Kerberos in your system. You might already have other Kerberos software installed when you install Red Hat Linux. To create a server principal, follow these steps: 1.
Issue the command /usr/krb5/sbin/kadmin on the DB2 server machine to start any kadmin session using the admin principals.
2. After the kadmin prompt, issue addprinc principal_name. The server principal name for the DB2 UDB instance is assumed to be /@REALM. This principal must be able to accept Kerberos security contexts, and it must exist before starting the DB2 UDB instance because the server name is reported to DB2 UDB by the plug-in at initialization time. 3.
Create an entry for the server principal in the keytab file. You are required to run the kadmin as root from the DB2 server machine. Otherwise, you may need to copy the keytab file to the DB2 server machine. Under the kadmin prompt, issue ktadd server_principals. The default keytab file is local under /etc/krb5/krb5.keytab, and it is readable only by the root. You are required to change the permission of the file to readable by the DB2 instance ID. If you want to change the local of the keytab file, you can use the NAS environment variable KRB5_KTNAME and add KRB5_KTNAME to db2envlist registry variable.
Step 4: Create Kerberos users (client principals). The principal may be found in either a two-part or multipart format (that is, name@REALM or name/instance@REALM). Because the name part will be used in the authorization ID (AUTHID) mapping, the name must adhere to the DB2 database naming rules. This means that the name may be up to 30 characters long, and it must adhere to the existing restrictions on the choice of characters used. Create the user principal by using addprinc under kadmin. Step 5: Set up the DB2 side to use Kerberos authentication. Chapter 3, “Understanding Identification and Authentication—The First Line of Defense,” provides a good explanation of this.
332
Appendix B
Kerberos
Step 6: Authenticate yourself to the KDC for both the DB2 client and server. Client
Server
To connect to the DB2 server, you must use the user principal as the username. For example: db2 connect to sample
To start DB2, log in to the DB2 server machine and run kinit, get the ticket for the instance ID, and then run db2start.
user boss/db2inst using password
Or you can run kinit first before obtaining the credentials. Then, you can connect to the DB2 without using a password.
CONFIGURING THE WINDOWS® CLIENT AND DOMAIN CONTROLLER TO ENABLE THE WINDOWS NATIVE KERBEROS ENVIRONMENT Setting up the DB2 client and server on Windows 2000 and later using Kerberos is trivial. All domain users are equivalent to Kerberos principals, and Active Directory acts as the KDC. Step 1: Set up the KDC. Basically, you need to set up a Windows 2000 (or later) server as a domain controller that has Active Directory enabled. The command to upgrade a Windows server to a domain controller is dcpromo. See the “How to promote and demote domain controllers in Windows 2000” link in the “Useful Links” section later in this chapter for more details. Requirements: Windows 2000 (or later) server with the Active Directory Setup: 1.
Enable the Active Directory.
2.
It is recommended that the domain name be in uppercase to facilitate compatibility with non-Windows Kerberos.
Step 2: Configure the Kerberos configuration file. Microsoft Active Directory uses DNS for Kerberos name mapping; therefore, there is no configuration file. Step 3: Create Kerberos users (client principals) and server principals (service principals) in the KDC. To add users and service principals in Active Directory, use the GUI tools on the Active Directory server machine. Click Manage User Accounts and Group Settings to bring up the Active Directory Users and Computers menu screen. Then, right-click the Users folder and create a new user (for example, “see”). Next, create another user (for example, “db2serv”) for the service principal.
Interoperability
333
Step 4: Set up the server key table (keytab) file. DB2 does not use a keytab file on Windows. The system automatically handles storing and acquiring the credentials handle for a service principal. Step 5: Set up the DB2 side to use Kerberos authentication. Chapter 3 provides a good explanation of this. Step 6: Authenticate yourself to the KDC for both the DB2 client and server. To authenticate to the Active Directory KDC, all you have to do is log on to the domain. Requirements: Windows 2000 (or later) workstation that is a part of a Windows 2000 or later domain Setup: 1.
Be sure your machine is a member of a domain. Log on to the machine as a domain user.
2.
On the server, start the DB2 service as a domain user (maybe started as the SYSTEM account if the client and server are both Windows machines that are part of the same domain).
Log on to the DB2 client machine using the domain account, and log on to the DB2 server machine using the domain account db2serv. Then, start the DB2 service on the DB2 server using that domain account as follows: Go to Control Panel, Administrative Tools, Services. Then, find the DB2 - service, right-click, go to Properties, Logon tab, and then be sure the domain user has been specified (and not Local System Account).
INTEROPERABILITY DB2 using Kerberos works in the following configurations: Table B.1
DB2 LUW Version 8.2 (Stinger Release) and Its Subsequent Fixpacks
AIX 5.1, AIX 5.2, Solaris 8, Solaris 9 RHEL AS 3, Win2000
↔
AIX 5.1, AIX 5.2, Solaris 8, Solaris 9 RHEL AS 3, Win2000 I/Series
→
Z/Series
334
Appendix B
Table B.2
Kerberos
DB2 LUW Version 9 (Viper Release) and Its Subsequent Fixpacks
AIX 5.2, AIX 5.3, Solaris 9, Solaris 10 Suse SLES 9 (2.6 Kernel), RHEL AS 4 (2.6 Kernel), Win2000
↔
AIX 5.2, AIX 5.3, Solaris 9, Solaris 10, Suse SLES 9 (2.6 Kernel), RHEL AS 4 (2.6 Kernel), Win2000 I/Series
→
Z/Series
The following table shows the difference between DB2 running on LUW, Z/Series, and I/Series in terms of Kerberos support.
Z/Series
I/Series
Linux/UNIX
Windows
What is required on the system
Requires Network Authentication and Privacy Service (NAPS)
Requires V5R2 and Network Authentication Service
Requires IBM Network Authentication Service
Domain controller that has Active Directory enabled
Mutual authentication
Does not support mutual authentication
Supports mutual authentication
Supports mutual authentication
Supports mutual authentication
Principal to user mapping
Done through RACF
Done through EIM (Enterprise Identity Mapping)
Done through KDC (NAS server)
Done through the domain controller
Server only or client with Kerberos
Can act as a server Can act as a server or client with or client with Kerberos Kerberos
Supports Kerberos Can act as a server as a client or a server or both
USEFUL LINKS Kerberos general references: • Kerberos FAQ www.cmf.nrl.navy.mil/CCS/people/kenh/kerberos-faq.html • MIT Kerberos http://web.mit.edu/kerberos/www/index.html • Microsoft Kerberos (SSPI) http://msdn.microsoft.com/library/default.asp?url=/library/en-us/rpc/rpc/security_ support_provider_interface_sspi_.asp
Useful Links
335
• J. Kohl and C. Neuman, “RFC 1510: The Kerberos Network Authentication Service (V5),” Internet Engineering Task Force, 1993 www.ietf.org/rfc/rfc1510.txt • Sharing a Secret: How Kerberos Works www.computerworld.com/computerworld/records/images/pdf/kerberos_chart.pdf Kerberos interoperability on different operating systems • Microsoft Step-by-Step Guide to Kerberos 5 (krb5 1.0) Interoperability www.microsoft.com/technet/prodtechnol/windows2000serv/howto/kerbstep.mspx • Kerberos on zOS and OS390 http://shareweb.share.org/proceedings/sh98/data/S1723.PDF • How to set up Kerberos interoperability between RACF on z/OS and Windows 2000 / XP domains (see Chapter 3 [3.7, 3.8]) www.redbooks.ibm.com/abstracts/sg246540.html?Open • Interoperability with Microsoft Windows 2000 Active Directory and Kerberos Services http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnactdir/html/ kerberossamp.asp NAS kit download site: • NAS kit Kerberos client for Solaris and Linux download www6.software.ibm.com/dl/dm/dm-nas-p Other related references: • Authenticating to AIX Using Kerberos http://publib16.boulder.ibm.com/pseries/en_US/aixbman/security/kerberos_auth_only_ load_module.htm • Configuring DB2 UDB with VAS for Active Directory authentication http://rc.vintela.com/topics/howto/db2/ • DB2 Authentication with Kerberos http://publib.boulder.ibm.com/infocenter/db2luw/v8/index.jsp?topic=/com.ibm.db2. udb.doc/admin/c0011990.htm • Understand the DB2 Universal Database security plug-ins www.ibm.com/developerworks/db2/library/techarticle/dm-0512chong/
336
Appendix B
Kerberos
• Step-by-Step Guide to Managing Active Directory www.microsoft.com/technet/prodtechnol/windowsserver2003/technologies/directory/ activedirectory/stepbystep/admng.mspx • How to promote and demote domain controllers in Windows 2000 http://support.microsoft.com/kb/q238369/
APPENDIX
C
DB2 Audit Scope Record Layouts
Table C.1
Audit Record Layout for AUDIT Events
Name
Format
Description
Timestamp
CHAR(26)
Date and time of the audit event.
Category
CHAR(8)
Shows that this is an AUDIT event.
Audit event
VARCHAR(32)
Specific audit event. Possible values include CONFIGURE, DB2AUD, EXTRACT, FLUSH, PRUNE, START, STOP, and UPDATE_ADMIN_CFG.
Event correlator
INTEGER
Correlation identifier for the operation being audited. Can be used to identify what audit records are associated with a single event.
Event status
INTEGER
Status of audit event, represented by a SQLCODE where successful event > = 0; failed event < 0.
User ID
VARCHAR(1024)
User ID at time of audit event.
Authorization ID
VARCHAR(128)
Authorization ID at time of audit event.
337
338
Table C.2
Appendix C
DB2 Audit Scope Record Layouts
Audit Record Layout for CHECKING Events
Name
Format
Description
Timestamp
CHAR(26)
Date and time of the audit event.
Category
CHAR(8)
Shows that this is a CHECKING event.
Audit event
VARCHAR(32)
Specific audit event. Possible values include CHECKING_OBJECT, CHECKING_FUNCTION, and CHECKING_TRANSFER.
Event correlator
INTEGER
Correlation identifier for the operation being audited. Can be used to identify what audit records are associated with a single event.
Event status
INTEGER
Status of audit event, represented by a SQLCODE where successful event > = 0; failed event < 0.
Database name
CHAR(8)
Name of the database for which the event was generated. Blank if this was an instance-level audit event.
User ID
VARCHAR(1024)
User ID at time of audit event.
Authorization ID
VARCHAR(128)
Authorization ID at time of audit event.
Origin node number
SMALLINT
Node number at which the audit event occurred.
Coordinator node number
SMALLINT
Node number of the coordinator node.
Application ID
VARCHAR (255)
Application ID in use at the time the audit event occurred.
Application name
VARCHAR (1024) Application name in use at the time the audit event occurred.
Package schema
VARCHAR (128)
Schema of the package in use at the time of the audit event.
Package name
VARCHAR (128)
Name of package in use at the time the audit event occurred.
Package section number
SMALLINT
Section number in package being used at the time the audit event occurred. (continues)
Appendix C
DB2 Audit Scope Record Layouts
Table C.2
339
Audit Record Layout for CHECKING Events (Continued)
Name
Format
Description
Object schema
VARCHAR (128)
Schema of the object for which the audit event was generated.
Object name
VARCHAR (128)
Name of object for which the audit event was generated.
Object type
VARCHAR (32)
Type of object for which the audit event was generated.
Access approval reason
CHAR(18)
Indicates the reason why access was approved for this audit event.
Access attempted
CHAR(18)
Indicates the type of access that was attempted.
Package version
VARCHAR (64)
Version of the package in use at the time that the audit event occurred.
Checked authorization VARCHAR(128) ID
Authorization ID is checked when it is different than the authorization ID at the time of the audit event.
340
Table C.3
Appendix C
DB2 Audit Scope Record Layouts
Audit Record Layout for OBJMAINT Events
Name
Format
Description
Timestamp
CHAR(26)
Date and time of the audit event.
Category
CHAR(8)
Shows that this is an OBJMAINT event.
Audit event
VARCHAR(32)
Specific audit event. Possible values include CREATE_OBJECT, RENAME_OBJECT, DROP_OBJECT, and ALTER_OBJECT. ALTER_OBJECT events are generated only when altering protected tables.
Event correlator
INTEGER
Correlation identifier for the operation being audited. Can be used to identify what audit records are associated with a single event.
Event status
INTEGER
Status of audit event, represented by a SQLCODE where successful event > = 0; failed event < 0.
Database name
CHAR(8)
Name of the database for which the event was generated. Blank if this is an instance-level audit event.
User ID
VARCHAR(1024)
User ID at time of audit event.
Authorization ID
VARCHAR(128)
Authorization ID at time of audit event.
Origin node number
SMALLINT
Node number at which the audit event occurred.
Coordinator node number
SMALLINT
Node number of the coordinator node.
Application ID
VARCHAR (255)
Application ID in use at the time the audit event occurred.
Application name
VARCHAR (1024) Application name in use at the time the audit event occurred.
Package schema
VARCHAR (128)
Schema of the package in use at the time of the audit event.
Package name
VARCHAR (128)
Name of the package in use at the time the audit event occurred.
Package section number
SMALLINT
Section number in package being used at the time the audit event occurred. (continues)
Appendix C
DB2 Audit Scope Record Layouts
Table C.3
341
Audit Record Layout for OBJMAINT Events (Continued)
Name
Format
Description
Object schema
VARCHAR (128)
Schema of the object for which the audit event was generated.
Object name
VARCHAR (128)
Name of object for which the audit event was generated.
Object type
VARCHAR (32)
Type of object for which the audit event was generated.
Package version
VARCHAR (64)
Version of the package in use at the time the audit event occurred.
Security policy name
VARCHAR(128)
The name of the security policy if the object type is TABLE and that table is associated with a security policy.
Alter action
VARCHAR(32)
Specific alter operation. Possible values include the following: ADD_PROTECTED_COLUMN ADD_COLUMN_PROTECTION DROP_COLUMN_PROTECTION ADD_ROW_PROTECTION ADD_SECURITY_POLICY
Protected column name
VARCHAR(128)
If the alter action is ADD_COLUMN_PROTECTION or DROP_COLUMN_PROTECTION, this is the name of the affected column.
Column security label
VARCHAR(128)
The security label protecting the column specified in the field Column Name.
Security label column name VARCHAR(128)
Name of the column containing the security label protecting the row.
342
Table C.4
Appendix C
DB2 Audit Scope Record Layouts
Audit Record Layout for SECMAINT Events
Name
Format
Description
Timestamp
CHAR(26)
Date and time of the audit event.
Category
CHAR(8)
Shows that this is a SECMAINT event.
Audit event
VARCHAR(32)
Specific audit event. Possible values include GRANT, REVOKE, IMPLICIT_GRANT, IMPLICIT_REVOKE, SET_SESSION_USER, UPDATE_DBM_CFG, and TRANSFER_OWNERSHIP.
Event correlator
INTEGER
Correlation identifier for the operation being audited. Can be used to identify what audit records are associated with a single event.
Event status
INTEGER
Status of audit event, represented by a SQLCODE where successful event > = 0; failed event < 0.
Database name
CHAR(8)
Name of the database for which the event was generated. Blank if this is an instance-level audit event.
User ID
VARCHAR(1024)
User ID at time of audit event.
Authorization ID
VARCHAR(128)
Authorization ID at time of audit event.
Origin node number
SMALLINT
Node number at which the audit event occurred.
Coordinator node number SMALLINT
Node number of the coordinator node.
Application ID
VARCHAR (255)
Application ID in use at the time the audit event occurred.
Application name
VARCHAR (1024)
Application name in use at the time the audit event occurred.
Package schema
VARCHAR (128)
Schema of the package in use at the time of the audit event.
Package name
VARCHAR (128)
Name of package in use at the time the audit event occurred.
Package section number
SMALLINT
Section number in package being used at the time the audit event occurred.
Appendix C
DB2 Audit Scope Record Layouts
Table C.4
343
Audit Record Layout for SECMAINT Events (Continued)
Name
Format
Description
Object schema
VARCHAR (128)
Schema of the object for which the audit event was generated. If the object type field is ACCESS_RULE, this field contains the security policy name associated with the rule. The name of the rule is stored in the field Object Name. If the object type field is SECURITY_LABEL, this field contains the name of the security policy that the security label is part of. The name of the security label is stored in the field Object Name.
Object name
VARCHAR (128)
Name of object for which the audit event was generated. If the object type field is ACCESS_RULE, this field contains the name of the rule. The security policy name associated with the rule is stored in the field Object Schema. If the object type field is SECURITY_LABEL, this field contains the name of the security label. The name of the security policy that it is part of is stored in the field Object Schema.
Object type
VARCHAR (32)
Type of object for which the audit event was generated.
Grantor
VARCHAR (128)
Grantor ID.
Grantee
VARCHAR (128)
Grantee ID for which a privilege or authority was granted or revoked.
Grantee type
VARCHAR (32)
Type of the grantee that was granted to or revoked from. Possible values include USER, GROUP, or BOTH.
Privilege or authority
CHAR(18)
Indicates the type of privilege or authority granted or revoked. (continues)
344
Table C.4
Appendix C
DB2 Audit Scope Record Layouts
Audit Record Layout for SECMAINT Events (Continued)
Name
Format
Description
Package version
VARCHAR (64)
Version of the package in use at the time the audit event occurred.
Access type
VARCHAR(32)
The access type for which a security label is granted. Possible values are as follows: READ WRITE ALL
Assumable AuthID
VARCHAR(128)
When the privilege granted is a SETSESSIONUSER privilege, this is the authorization ID that the grantee is allowed to set as the session user.
Appendix C
DB2 Audit Scope Record Layouts
Table C.5
345
Audit Record Layout for SYSADMIN Events
Name
Format
Description
Timestamp
CHAR(26)
Date and time of the audit event.
Category
CHAR(8)
Shows that this is a SYSADMIN event.
Audit event
VARCHAR(32)
Specific audit event. Possible values are numerous and include START_DB2, STOP_DB2, and UPDATE_DBM_CFG. A detailed list of SYSADMIN audit events is included in Appendix D (List of Possible SYSADMIN Audit Events).
Event correlator
INTEGER
Correlation identifier for the operation being audited. Can be used to identify what audit records are associated with a single event.
Event status
INTEGER
Status of audit event, represented by a SQLCODE where successful event > = 0; failed event < 0.
Database name
CHAR(8)
Name of the database for which the event was generated. Blank if this was an instance-level audit event.
User ID
VARCHAR(1024)
User ID at time of audit event.
Authorization ID
VARCHAR(128)
Authorization ID at time of audit event.
Origin node number
SMALLINT
Node number at which the audit event occurred.
Coordinator node number
SMALLINT
Node number of the coordinator node.
Application ID
VARCHAR (255)
Application ID in use at the time the audit event occurred.
Application name
VARCHAR (1024)
Application name in use at the time the audit event occurred.
Package schema
VARCHAR (128)
Schema of the package in use at the time of the audit event.
Package name
VARCHAR (128)
Name of package in use at the time the audit event occurred.
Package section number
SMALLINT
Section number in package being used at the time the audit event occurred.
Package version
VARCHAR (64)
Version of the package in use at the time the audit event occurred.
346
Table C.6
Appendix C
DB2 Audit Scope Record Layouts
Audit Record Layout for VALIDATE Events
Name
Format
Description
Timestamp
CHAR(26)
Date and time of the audit event.
Category
CHAR(8)
Shows that this is a VALIDATE event.
Audit event
VARCHAR(32)
Specific audit event. Possible values include GET_GROUPS, GET_USERID, AUTHENTICATE_PASSWORD, VALIDATE_USER, and GET_USERMAPPING_FROM_PLUGIN.
Event correlator
INTEGER
Correlation identifier for the operation being audited. Can be used to identify what audit records are associated with a single event.
Event status
INTEGER
Status of audit event, represented by a SQLCODE where successful event > = 0; failed event < 0.
Database name
CHAR(8)
Name of the database for which the event was generated. Blank if this was an instance-level audit event.
User ID
VARCHAR(1024)
User ID at time of audit event.
Authorization ID
VARCHAR(128)
Authorization ID at time of audit event.
Execution ID
VARCHAR(1024)
Execution ID in use at the time of the audit event.
Origin node number
SMALLINT
Node number at which the audit event occurred.
Coordinator node number SMALLINT
Node number of the coordinator node.
Application ID
VARCHAR (255)
Application ID in use at the time the audit event occurred.
Application name
VARCHAR (1024) Application name in use at the time the audit event occurred.
Authentication type
VARCHAR (32)
Authentication type at the time of the audit event.
Package schema
VARCHAR (128)
Schema of the package in use at the time of the audit event.
Package name
VARCHAR (128)
Name of package in use at the time the audit event occurred. (continues)
Appendix C
Table C.6
DB2 Audit Scope Record Layouts
347
Audit Record Layout for VALIDATE Events (Continued)
Name
Format
Description
Package section number
SMALLINT
Section number in package being used at the time the audit event occurred.
Package version
VARCHAR (64)
Version of the package in use at the time the audit event occurred.
Plug-in name
VARCHAR(32)
The name of the plug-in in use at the time the audit event occurred.
348
Table C.7
Appendix C
DB2 Audit Scope Record Layouts
Audit Record Layout for CONTEXT Events
Name
Format
Description
Timestamp
CHAR(26)
Date and time of the audit event.
Category
CHAR(8)
Category of audit event. Possible values are CONTEXT.
Audit event
VARCHAR(32)
Specific audit event. Possible values are numerous and include CONNECT, GET_DB_CFG, and ATTACH. A detailed list of CONTEXT audit events is included in Appendix D (List of Possible CONTEXT Audit Events).
Event correlator
INTEGER
Correlation identifier for the operation being audited. Can be used to identify what audit records are associated with a single event.
Database name
CHAR(8)
Name of the database for which the event was generated. Blank if this was an instance-level audit event.
User ID
VARCHAR(1024)
User ID at time of audit event.
Authorization ID
VARCHAR(128)
Authorization ID at time of audit event.
Origin node number occurred.
SMALLINT
Node number at which the audit event.
Coordinator node number
SMALLINT
Node number of the coordinator node.
Application ID
VARCHAR (255)
Application ID in use at the time the audit event occurred.
Application name
VARCHAR (1024) Application name in use at the time the audit event occurred.
Package schema
VARCHAR (128)
Schema of the package in use at the time of the audit event.
Package name
VARCHAR (128)
Name of package in use at the time the audit event occurred.
Package section number
SMALLINT
Section number in package being used at the time the audit event occurred.
Statement Text (statement)
CLOB (2M)
Text of the SQL or XQuery statement, if applicable. Null if no SQL or XQuery statement text is available.
Package version
VARCHAR (64)
Version of the package in use at the time the audit event occurred.
APPENDIX
D
DB2 Audit – Additional Documentation
Table D.1
Audit Record Object Types Based on Audit Events
Object Type
CHECKING Events
OBJMAINT Events
SECMAINT Events
NONE
X
X
X
TABLE
X
X
X
VIEW
X
X
X
ALIAS
X
X
FUNCTION
X
X
X
INDEX
X
X
X
X
INDEX EXTENSION PACKAGE
X
PACKAGE CACHE
X
X
X
X
DATA_TYPE NODEGROUP
X
X
SCHEMA
X
X
X
STORED_PROCEDURE
X
X
X
METHOD_BODY
X
X
X
BUFFERPOOL
X
X
SEQUENCE
X
X
TABLESPACE
X
X
X (continues)
349
350
Table D.1
Appendix D
DB2 Audit—Additional Documentation
Audit Record Object Types Based on Audit Events (Continued)
Object Type
CHECKING Events
OBJMAINT Events
EVENT_MONITOR
X
X
SECMAINT Events
X
TRIGGER DATABASE
X
INSTANCE
X
X
FOREIGN_KEY
X
PRIMARY_KEY
X
UNIQUE_CONSTRAINT
X
CHECK_CONSTRAINT
X
WRAPPER
X
X
SERVER
X
X
X
NICKNAME
X
X
X
USER MAPPING
X
X
SERVER OPTION
X
X
TYPE&TRANSFORM
X
X
TYPE MAPPING
X
X
FUNCTION MAPPING
X
X
SUMMARY TABLES
X
X
X
X
JAR_FILE ALL
X
REOPT_VALUES
X
SECURITY_LABEL
X
X
SECURITY_POLICY
X
X
SECURITY_LABEL_COMPONENT
X X
ACCESS_RULE XSR object
X
X
X
Appendix D
Table D.2
DB2 Audit—Additional Documentation
351
List of Possible CONTEXT Audit Events
CONNECT
SET_APPL_PRIORITY
CONNECT_RESET
RESET_DB_CFG
ATTACH
GET_DB_CFG
DETACH
GET_DFLT_CFG
DARI_START
UPDATE_DBM_CFG
DARI_STOP
SET_MONITOR
BACKUP_DB
GET_SNAPSHOT
RESTORE_DB
ESTIMATE_SNAPSHOT_SIZE
ROLLFORWARD_DB
RESET_MONITOR
OPEN_TABLESPACE_QUERY
OPEN_HISTORY_FILE
FETCH_TABLESPACE
CLOSE_HISTORY_FILE
CLOSE_TABLESPACE_QUERY
FETCH_HISTORY_FILE
OPEN_CONTAINER_QUERY
SET_RUNTIME_DEGREE
CLOSE_CONTAINER_QUERY
UPDATE_AUDIT
FETCH_CONTAINER_QUERY
DBM_CFG_OPERATION
SET_TABLESPACE_CONTAINERS
DISCOVER
GET_TABLESPACE_STATISTIC
OPEN_CURSOR
READ_ASYNC_LOG_RECORD
CLOSE_CURSOR
QUIESCE_TABLESPACE
FETCH_CURSOR
LOAD_TABLE
EXECUTE
UNLOAD_TABLE
EXECUTE_IMMEDIATE
UPDATE_RECOVERY_HISTORY
PREPARE
PRUNE_RECOVERY_HISTORY
DESCRIBE
SINGLE_TABLESPACE_QUERY
BIND
LOAD_MSG_FILE
REBIND
UNQUIESCE_TABLESPACE
RUNSTATS
ENABLE_MULTIPAGE
REORG
DESCRIBE_DATABASE
REDISTRIBUTE
DROP_DATABASE
COMMIT
CREATE_DATABASE
ROLLBACK
ADD_NODE
REQUEST_ROLLBACK
FORCE_APPLICATION
IMPLICIT_REBIND
352
Table D.3
Appendix D
DB2 Audit—Additional Documentation
List of Possible SYSADMIN Audit Events
START_DB2
ROLLFORWARD_DB
STOP_DB2
SET_RUNTIME_DEGREE
CREATE_DATABASE
SET_TABLESPACE_CONTAINERS
ALTER_DATABASE
UNCATALOG_DB
DROP_DATABASE
UNCATALOG_DCS_DB
UPDATE_DBM_CFG
UNCATALOG_NODE
UPDATE_DB_CFG
UPDATE_ADMIN_CFG
CREATE_TABLESPACE
UPDATE_MON_SWITCHES
DROP_TABLESPACE
LOAD_TABLE
ALTER_TABLESPACE
DB2AUDIT
RENAME_TABLESPACE
SET_APPL_PRIORITY
CREATE_NODEGROUP
CREATE_DB_AT_NODE
DROP_NODEGROUP
KILLDBM
ALTER_NODEGROUP
MIGRATE_SYSTEM_DIRECTORY
CREATE_BUFFERPOOL
DB2REMOT
DROP_BUFFERPOOL
DB2AUD
ALTER_BUFFERPOOL
MERGE_DBM_CONFIG_FILE
CREATE_EVENT_MONITOR
UPDATE_CLI_CONFIGURATION
DROP_EVENT_MONITOR
OPEN_TABLESPACE_QUERY
ENABLE_MULTIPAGE
SINGLE_TABLESPACE_QUERY
MIGRATE_DB_DIR
CLOSE_TABLESPACE_QUERY
DB2TRC
FETCH_TABLESPACE
DB2SET
OPEN_CONTAINER_QUERY
ACTIVATE_DB
FETCH_CONTAINER_QUERY
ADD_NODE
CLOSE_CONTAINER_QUERY
BACKUP_DB
GET_TABLESPACE_STATISTICS
CATALOG_NODE
DESCRIBE_DATABASE
CATALOG_DB
ESTIMATE_SNAPSHOT_SIZE (continues)
Appendix D
Table D.3
DB2 Audit—Additional Documentation
353
List of Possible SYSADMIN Audit Events (Continued)
CATALOG_DCS_DB
READ_ASYNC_LOG_RECORD
CHANGE_DB_COMMENT
PRUNE_RECOVERY_HISTORY
DEACTIVATE_DB
UPDATE_RECOVERY_HISTORY
DROP_NODE_VERIFY
QUIESCE_TABLESPACE
FORCE_APPLICATION
UNLOAD_TABLE
GET_SNAPSHOT
UPDATE_DATABASE_VERSION
LIST_DRDA_INDOUBT_TRANSACTIONS
CREATE_INSTANCE
MIGRATE_DB
DELETE_INSTANCE
RESET_ADMIN_CFG
SET_EVENT_MONITOR
RESET_DB_CFG
GRANT_DBADM
RESET_DBM_CFG
REVOKE_DBADM
RESET_MONITOR
GRANT_DB_AUTHORITIES
RESTORE_DB
REVOKE_DB_AUTHORITIES REDIST_NODEGROUP
Table D.4
List of Possible CHECKING Access Approval Reasons
0x0000000000000001 ACCESS DENIED Access is not approved; rather, it was denied. 0x0000000000000002 SYSADM Access is approved; the application or user has SYSADM authority. 0x0000000000000004 SYSCTRL Access is approved; the application or user has SYSCTRL authority. 0x0000000000000008 SYSMAINT Access is approved; the application or user has SYSMAINT authority. 0x0000000000000010 DBADM Access is approved; the application or user has DBADM authority. (continues)
354
Table D.4
Appendix D
DB2 Audit—Additional Documentation
List of Possible CHECKING Access Approval Reasons (Continued)
0x0000000000000020 DATABASE PRIVILEGE Access is approved; the application or user has an explicit privilege on the database. 0x0000000000000040 OBJECT PRIVILEGE Access is approved; the application or user has an explicit privilege on the object or function. 0x0000000000000080 DEFINER Access is approved; the application or user is the definer of the object or function. 0x0000000000000100 OWNER Access is approved; the application or user is the owner of the object or function. 0x0000000000000200 CONTROL Access is approved; the application or user has CONTROL privilege on the object or function. 0x0000000000000400 BIND Access is approved; the application or user has BIND privilege on the package. 0x0000000000000800 SYSQUIESCE Access is approved; if the instance or database is in quiesce mode, the application or user may connect or attach. 0x0000000000001000 SYSMON Access is approved; the application or user has SYSMON authority. 0x0000000000002000 SECADM Access is approved; the application or user has SECADM authority. 0x0000000000004000 SETSESSIONUSER Access is approved; the application or user has SETSESSIONUSER authority.
Appendix D
Table D.5
DB2 Audit—Additional Documentation
355
List of Possible CHECKING Access Attempted Types
The following is the list of possible CHECKING access attempted types. If audit event is CHECKING_TRANSFER, the audit entry reflects that a privilege is held or not. 0x0000000000000001 CONTROL Attempt to verify if CONTROL privilege is held. 0x0000000000000002 ALTER Attempt to alter an object or to verify if ALTER privilege is held if audit event is CHECKING_TRANSFER. 0x0000000000000004 DELETE Attempt to delete an object or to verify if DELETE privilege is held if audit event is CHECKING_TRANSFER. 0x0000000000000008 INDEX Attempt to use an index or to verify if INDEX privilege is held if audit event is CHECKING_ TRANSFER. 0x0000000000000010 INSERT Attempt to insert into an object or to verify if INSERT privilege is held if audit event is CHECKING_TRANSFER. 0x0000000000000020 SELECT Attempt to query a table or view or to verify if SELECT privilege is held if audit event is CHECKING_TRANSFER. 0x0000000000000040 UPDATE Attempt to update data in an object or to verify if UPDATE privilege is held if audit event is CHECKING_TRANSFER. 0x0000000000000080 REFERENCE Attempt to establish referential constraints between objects or to verify if REFERENCE privilege is held if audit event is CHECKING_TRANSFER. 0x0000000000000100 CREATE Attempt to create an object. 0x0000000000000200 DROP Attempt to drop an object. (continues)
356
Table D.5
Appendix D
DB2 Audit—Additional Documentation
List of Possible CHECKING Access Attempted Types (Continued)
0x0000000000000400 CREATEIN Attempt to create an object within another schema. 0x0000000000000800 DROPIN Attempt to drop an object found within another schema. 0x0000000000001000 ALTERIN Attempt to alter or modify an object found within another schema. 0x0000000000002000 EXECUTE Attempt to execute or run an application or to invoke a routine, create a function sourced from the routine (applies to functions only), or reference a routine in any DDL statement or to verify if EXECUTE privilege is held if Audit Event is CHECKING_TRANSFER. 0x0000000000004000 BIND Attempt to bind or prepare an application. 0x0000000000008000 SET EVENT MONITOR Attempt to set event monitor switches. 0x0000000000010000 SET CONSTRAINTS Attempt to set constraints on an object. 0x0000000000020000 COMMENT ON Attempt to create comments on an object. 0x0000000000040000 GRANT Attempt to grant privileges on an object to another user ID. 0x0000000000080000 REVOKE Attempt to revoke privileges on an object from a user ID. 0x0000000000100000 LOCK Attempt to lock an object. 0x0000000000200000 RENAME Attempt to rename an object. 0x0000000000400000 CONNECT Attempt to connect to an object. (continues)
Appendix D
Table D.5
DB2 Audit—Additional Documentation
357
List of Possible CHECKING Access Attempted Types (Continued)
0x0000000000800000 Member of SYS Group Attempt to access or use a member of the SYS group. 0x0000000001000000 Access All Attempt to execute a statement with all required privileges on objects held (only used for DBADM/SYSADM). 0x0000000002000000 Drop All Attempt to drop multiple objects. 0x0000000004000000 LOAD Attempt to load a table in a tablespace. 0x0000000008000000 USE Attempt to create a table in a table space or to verify if USE privilege is held if audit event is CHECKING_TRANSFER. 0x0000000010000000 SET SESSION_USER Attempt to execute the SET SESSION_USER statement. 0x0000000020000000 FLUSH Attempt to execute the FLUSH statement. 0x0000000040000000 STORE Attempt to view the values of a reoptimized statement in the EXPLAIN_PREDICATE table. 0x0000000400000000 TRANSFER Attempt to transfer an object. 0x0000000800000000 ALTER_WITH_GRANT Attempt to verify if ALTER with GRANT privilege is held. 0x0000001000000000 DELETE_WITH_GRANT Attempt to verify if DELETE with GRANT privilege is held. 0x0000002000000000 INDEX_WITH_GRANT Attempt to verify if INDEX with GRANT privilege is held. 0x0000004000000000 INSERT_WITH_GRANT Attempt to verify if INSERT with GRANT privilege is held. (continues)
358
Table D.5
Appendix D
DB2 Audit—Additional Documentation
List of Possible CHECKING Access Attempted Types (Continued)
0x0000008000000000 SELECT_WITH_GRANT Attempt to verify if SELECT with GRANT privilege is held. 0x0000010000000000 UPDATE_WITH_GRANT Attempt to verify if UPDATE with GRANT privilege is held. 0x0000020000000000 REFERENCE_WITH_GRANT Attempt to verify if REFERENCE with GRANT privilege is held. 0x0000040000000000 USAGE Attempt to use a sequence or an XSR object or to verify if USAGE privilege is held if audit event is CHECKING_TRANSFER.
Table D.6
List of Possible SECMAINT Privileges or Authorities
0x0000000000000001 Control Table Control privilege granted or revoked on a table or view. 0x0000000000000002 ALTER TABLE Privilege granted or revoked to alter a table. 0x0000000000000004 ALTER TABLE with GRANT Privilege granted or revoked to alter a table with granting of privileges allowed. 0x0000000000000008 DELETE TABLE Privilege granted or revoked to drop a table or view. 0x0000000000000010 DELETE TABLE with GRANT Privilege granted or revoked to drop a table with granting of privileges allowed. 0x0000000000000020 Table Index Privilege granted or revoked on an index. 0x0000000000000040 Table Index with GRANT Privilege granted or revoked on an index with granting of privileges allowed. 0x0000000000000080 Table INSERT Privilege granted or revoked on an insert on a table or view. (continues)
Appendix D
Table D.6
DB2 Audit—Additional Documentation
359
List of Possible SECMAINT Privileges or Authorities (Continued)
0x0000000000000100 Table INSERT with GRANT Privilege granted or revoked on an insert on a table with granting of privileges allowed. 0x0000000000000200 Table SELECT Privilege granted or revoked on a select on a table. 0x0000000000000400 Table SELECT with GRANT Privilege granted or revoked on a select on a table with granting of privileges allowed. 0x0000000000000800 Table UPDATE Privilege granted or revoked on an update on a table or view. 0x0000000000001000 Table UPDATE with GRANT Privilege granted or revoked on an update on a table or view with granting of privileges allowed. 0x0000000000002000 Table REFERENCE Privilege granted or revoked on a reference on a table. 0x0000000000004000 Table REFERENCE with GRANT Privilege granted or revoked on a reference on a table with granting of privileges allowed. 0x0000000000020000 CREATEIN Schema CREATEIN privilege granted or revoked on a schema. 0x0000000000040000 CREATEIN Schema with GRANT CREATEIN privilege granted or revoked on a schema with granting of privileges allowed. 0x0000000000080000 DROPIN Schema DROPIN privilege granted or revoked on a schema. 0x0000000000100000 DROPIN Schema with GRANT DROPIN privilege granted or revoked on a schema with granting of privileges allowed. 0x0000000000200000 ALTERIN Schema ALTERIN privilege granted or revoked on a schema. 0x0000000000400000 ALTERIN Schema with GRANT ALTERIN privilege granted or revoked on a schema with granting of privileges allowed. (continues)
360
Table D.6
Appendix D
DB2 Audit—Additional Documentation
List of Possible SECMAINT Privileges or Authorities (Continued)
0x0000000000800000 DBADM Authority DBADM authority granted or revoked. 0x0000000001000000 CREATETAB Authority CREATETAB authority granted or revoked. 0x0000000002000000 BINDADD Authority BINADD authority granted or revoked. 0x0000000004000000 CONNECT Authority CONNECT authority granted or revoked. 0x0000000008000000 Create not fenced Authority Create not fenced authority granted or revoked. 0x0000000010000000 Implicit Schema Authority Implicit schema authority granted or revoked. 0x0000000020000000 Server PASSTHRU Privilege granted or revoked to use the pass-through facility with this server (federated database data source). 0x0000000100000000 Table Space USE Privilege granted or revoked to create a table in a tablespace. 0x0000000200000000 Table Space USE with GRANT Privilege granted or revoked to create a table in a tablespace with granting of privileges allowed. 0x0000000400000000 Column UPDATE Privilege granted or revoked on an update on one or more specific columns of a table. 0x0000000800000000 Column UPDATE with GRANT Privilege granted or revoked on an update on one or more specific columns of a table with granting of privileges allowed. 0x0000001000000000 Column REFERENCE Privilege granted or revoked on a reference on one or more specific columns of a table. (continues)
Appendix D
Table D.6
DB2 Audit—Additional Documentation
361
List of Possible SECMAINT Privileges or Authorities (Continued)
0x0000002000000000 Column REFERENCE with GRANT Privilege granted or revoked on a reference on one or more specific columns of a table with granting of privileges allowed. 0x0000004000000000 LOAD Authority LOAD authority granted or revoked. 0x0000008000000000 Package BIND BIND privilege granted or revoked on a package. 0x0000010000000000 Package BIND with GRANT BIND privilege granted or revoked on a package with granting of privileges allowed. 0x0000020000000000 EXECUTE EXECUTE privilege granted or revoked on a package or a routine. 0x0000040000000000 EXECUTE with GRANT EXECUTE privilege granted or revoked on a package or a routine with granting of privileges allowed. 0x0000080000000000 EXECUTE IN SCHEMA EXECUTE privilege granted or revoked for all routines in a schema. 0x0000100000000000 EXECUTE IN SCHEMA with GRANT EXECUTE privilege granted or revoked for all routines in a schema with granting of privileges allowed. 0x000020000000000 EXECUTE IN TYPE EXECUTE privilege granted or revoked for all routines in a type. 0x0000400000000000 EXECUTE IN TYPE with GRANT EXECUTE privilege granted or revoked for all routines in a type with granting of privileges allowed. 0x000080000000000 CREATE EXTERNAL ROUTINE CREATE EXTERNAL ROUTINE privilege granted or revoked. 0x0001000000000000 QUIESCE_CONNECT QUIESCE_CONNECT privilege granted or revoked. (continues)
362
Table D.6
Appendix D
DB2 Audit—Additional Documentation
List of Possible SECMAINT Privileges or Authorities (Continued)
0x0004000000000000 SECADM Authority SECADM authority granted or revoked. 0x0040000000000000 SETSESSIONUSER Privilege SETSESSIONUSER granted or revoked. 0x0080000000000000 Exemption Exemption granted or revoked. 0x0100000000000000 Security label Security label granted or revoked.
APPENDIX
E
Security Considerations for DB2
he National Institute of Standards and Technology (NIST) published a series of securityreadiness review checklists for major database vendors such as IBM DB2. The DB2 Database Security Readiness Review Checklist is located at http://checklists.nist.gov/repository/ category.html.
T
From time to time, DB2 will also publish an advisory security-readiness checklist at the IBM developerWorks website: www-128.ibm.com/developerworks/db2/zones/db2udb/. In addition, there are many security consideration sections in the DB2 documentation that are centralized here for easier access.
SECURITY CONSIDERATIONS (SOURCED FROM ADMINISTRATION GUIDE: IMPLEMENTATION) Gaining Access to Data Through Indirect Means The following are indirect means through which users can gain access to data they may not be authorized for: • Catalog views. The DB2 catalog views store metadata and statistics about database objects. Users with SELECT access to the catalog views can gain some knowledge about data that they may not be qualified for otherwise. For example, some of the table statistics stored in the catalog views such as HIGH2KEY, LOW2KEY, and the column distribution statistics can reveal information about table data. For better security, users should
363
364
Appendix E
Security Considerations for DB2
make sure that only qualified users have access to the catalog views. In earlier versions of DB2 UDB, SELECT access on the catalog views is granted to PUBLIC by default. In v9.1, users can choose whether SELECT access to the catalog views is granted to PUBLIC or not via the new RESTRICT_ACCESS option on the CREATE DATABASE command. • Visual explain. Visual explain shows the access plan chosen by the query optimizer for a particular query. The visual explain information also includes statistics about columns referenced in the query. As with the catalog views, statistics can reveal information about tables’ content. • Explain snapshot. The explain snapshot is compressed information that is collected when a SQL statement is explained. It is stored as a binary large object (BLOB) in the EXPLAIN_STATEMENT table, and contains, among other things, column statistics. As mentioned earlier, column statistics can reveal information about table data. For better security, access to the explain tables should be granted to qualified users only. • Log reader APIs. A user authorized to run an API that understands the format of a log record can gain access to data in such logs. For example, a user with DBADM authority can execute the DB2READLOG API to gain access to data in the log files. Replication. The replication “Capture” program is an example user of the DB2READLOG API above. Users should be aware that replication moves data from a source location to a target location. For better security, users must ensure that the target location is at least as secure as the source location. • Exception tables. When loading data into a table and an exception table has been specified for storing data rows in error (for example, rows with an invalid security label), users with access to such exception table can gain knowledge about information that otherwise may not be authorized for. For better security, the exception table should be dropped when the data rows in error are fixed and copied back to the table being loaded. Alternatively, access to the exception table should be granted only to authorized users. • Backup tablespace/database. Users with the authority to run the backup command can run such command to take a backup of a database or a tablespace and restore such data somewhere else. Like with replication, this is the general problem of compromising data security by allowing data to be moved from one location to another. • Set session authorization. In earlier versions of DB2 UDB, a user with DBADM authority can set the session authorization to any database user using the SET SESSION AUTHORIZATION SQL statement. In DB2 v9.1, this is no longer possible. A user must be explicitly authorized by the security administrator (SECADM) to set the session authorization to another database user. However, when migrating an existing database to DB2 UDB v9.1, a user with existing explicit DBADM authority (that is, granted in SYSCAT.DBAUTH) will be assigned the ability to set the session authorization to any
Security Considerations (Sourced from Administration Guide: Implementation)
365
database user (in order not to break any existing application). Thus, a DBADM, who is not qualified to access labeled data, could gain access to such data by setting the session authorization to a qualified user. For more-restrictive security, the security administrator can override this setting using the REVOKE SETSESSIONUSER SQL statement. Refer to the SQL Reference changes for more information on granting and revoking set session privileges. • High Performance Unload (HPU). HPU is a utility that does not ship with DB2 but can be purchased separately. It is a utility that enables you to unload data from a table. DB2 does not enforce access control when HPU is used to unload a table. • Statement and deadlock monitoring. As part of the DB2 deadlock monitoring activity, values associated with parameter markers are written to the monitoring output when the WITH VALUES clause is specified. Thus, a user with access to the monitoring output may gain access to information for which he or she might not be authorized. • Traces. A trace can contain table data. Thus, a user with access to such trace may gain access to information that he or she might not be authorized for. • Dump files. To help in debugging certain problems, DB2 may generate some dump files in the SQLLIB\DB2DUMP directory. These dump files may or may not contain table data. If they do, users with access to such dump files may gain access to information that they may not be authorized for. • db2dart. The db2dart tool examines a database for architectural correctness and reports any encountered errors. The tool can access table data, and DB2 does not enforce access control for such access (other than the authority to run the db2dart tool). Thus, users with access to the db2dart output may gain access to information that they may not be authorized for. • REOPT BIND option. When the REOPT BIND option is specified, an explain snapshot information for each reoptimizable incremental bind SQL statement is placed in the explain tables at runtime. The explain will also show input data values. • db2cat. The db2cat tool is used to dump a table’s packed descriptor. The table’s packed descriptor contains, among other things, statistics about the table and its columns. Statistics can reveal information about a table’s content. Thus, users who run the db2cat tool may gain access to information that they may not be authorized for.
Default Privileges Granted upon Creating a Database The following are the default privileges granted when a database is created: 1. SYSIBM.SYSDBAUTH The database creator is granted the following privileges: DBADM
The special group PUBLIC is granted the following privileges: CREATETAB BINDADD CONNECT IMPLSCHEMA
2. SYSIBM.SYSTABAUTH The special group PUBLIC is granted the following privileges: SELECT on all SYSCAT, SYSIBM, and SYSCATV82 tables SELECT and UPDATE on all SYSSTAT tables 3. SYSIBM.SYSROUTINEAUTH The special group PUBLIC is granted the following privileges: EXECUTE with GRANT on all procedures in schema SQLJ EXECUTE with GRANT on all functions and procedures in schema SYSFUN EXECUTE with GRANT on all functions and procedures in schema SYSPROC EXECUTE on all table functions in schema SYSIBM EXECUTE on all other procedures in schema SYSIBM 4. SYSIBM.SYSPACKAGEAUTH The database creator is granted the following privileges: CONTROL on all packages created in the NULLID schema BIND with GRANT on all packages created in the NULLID schema EXECUTE with GRANT on all packages created in the NULLID schema The special group PUBLIC is granted the following privileges: BIND on all packages created in the NULLID schema EXECUTE on all packages created in the NULLID schema 5. SYSIBM.SCHEMAAUTH The special group PUBLIC is granted the following privileges: CREATEIN on schema SQLJ CREATE IN on schema NULLID
Windows Platform Security Considerations for Users (Sourced from Administration Guide: Implementation)
367
6. SYSIBM.TBSPACEAUTH The special group PUBLIC is granted the following privileges: USE on tablespace USERSPACE1
UNIX PLATFORM SECURITY CONSIDERATIONS FOR USERS (SOURCED FROM ADMINISTRATION GUIDE: IMPLEMENTATION) The DB2 database does not support root acting directly as a database administrator. You should use su - as the database administrator. For security reasons, we recommend you do not use the instance name as the Fenced ID. However, if you are not planning to use fenced UDFs or stored procedures, you can set the Fenced ID to the instance name instead of creating another user ID. The recommendation is to create a user ID that will be recognized as being associated with this group. The user for fenced UDFs and stored procedures is specified as a parameter of the instance creation script (db2icrt ... -u ). This is not required if you install the DB2 Clients or the DB2 Software Developer’s Kit.
WINDOWS PLATFORM SECURITY CONSIDERATIONS FOR USERS (SOURCED FROM ADMINISTRATION GUIDE: IMPLEMENTATION) System administration (SYSADM) authority is granted to any valid DB2 database user account that belongs to the local Administrators group on the machine where the account is defined. By default in a Windows domain environment, only domain users who belong to the Administrators group at the domain controller have SYSADM authority on an instance. Because DB2 always performs authorization at the machine where the account is defined, adding a domain user to the local Administrators group on the server does not grant the domain user SYSADM authority to the group.
NOTE: In a domain environment such as is found in Windows, DB2 only authenticates the first 64 groups that meet the requirements and restrictions, and to which a user ID belongs.You may have more than 64 groups. To avoid adding a domain user to the Administrators group at the PDC, you should create a global group and add the users (both domain and local) that you want to grant SYSADM authority.To do this, enter the following commands: DB2STOP DB2 UPDATE DBM CFG USING SYSADM_GROUP global_group DB2START
368
Appendix E
Security Considerations for DB2
SECURITY CONSIDERATIONS IN AN LDAP ENVIRONMENT (SOURCED FROM ADMINISTRATION GUIDE: IMPLEMENTATION) Before accessing information in the LDAP directory, an application or user is authenticated by the LDAP server. The authentication process is called binding to the LDAP server. It is important to apply access control on the information stored in the LDAP directory to prevent anonymous users from adding, deleting, or modifying the information. Access control is inherited by default and can be applied at the container level. When a new object is created, it inherits the same security attribute as the parent object. An administration tool available for the LDAP server can be used to define access control for the container object. By default, access control is defined as follows: • For database and node entries in LDAP, everyone (or any anonymous user) has read access. Only the directory administrator and the owner or creator of the object has read/write access. • For user profiles, the profile owner and the directory administrator have read/write access. One user cannot access the profile of another user if that user does not have directory administrator authority.
NOTE: The authorization check is always performed by the LDAP server and not by DB2. The LDAP authorization check is not related to DB2 authorization. An account or auth ID that has SYSADM authority may not have access to the LDAP directory. When running the LDAP commands or APIs, if the bind distinguished name (bindDN) and password are not specified, DB2 binds to the LDAP server using the default credentials, which may not have sufficient authority to perform the requested commands, and an error will be returned. You can explicitly specify the user’s bindDN and password using the USER and PASSWORD clauses for the DB2 commands or APIs.
SECURITY CONSIDERATIONS FOR ACTIVE DIRECTORY (SOURCED FROM ADMINISTRATION GUIDE: IMPLEMENTATION) The DB2 database and node objects are created under the computer object of the machine where the DB2 server is installed in the Active Directory. To register a database server or catalog a data-
Security Considerations for Routines (Sourced from SQL Guide)
369
base in the Active Directory, you need to have sufficient access to create or update the objects under the computer object. By default, objects under the computer object are readable by any authenticated users and updatable by administrators (users who belong to the Administrators, Domain Administrators, and Enterprise Administrators groups). To grant access for a specific user or a group, use the Active Directory Users and Computer Management Console (MMC) as follows: 1. Start the Active Directory Users and Computer administration tool (Start > Program > Administration Tools > Active Directory Users and Computer). 2. Under View, select Advanced Features. 3. Select the Computers container. 4. Right-click the computer object that represents the server machine where DB2 is installed and select Properties. 5. Select the Security tab, and then add the required access to the specified user or group. The DB2 registry variables and CLI settings at the user level are maintained in the DB2 property object under the User object. To set the DB2 registry variables or CLI settings at the user level, a user needs to have sufficient access to create objects under the User object. By default, only administrators have access to create objects under the User object. To grant access to a user to set the DB2 registry variables or CLI settings at the user level, use the Active Directory Users and Computer MMC as follows: 1. Start the Active Directory Users and Computer administration tool (Start > Program > Administration Tools > Active Directory Users and Computer). 2. Select the User object under the Users container. 3. Right-click the User object and select Properties. 4. Select the Security tab. 5. Add the username to the list by using the Add button. 6. Grant Write access and Create All Child Objects access. 7. Using the Advanced setting, set permissions to apply to This Object and All Child Objects. 8. Select the Allow Inheritable Permissions from Parent to Propagate to This Object check box.
SECURITY CONSIDERATIONS FOR ROUTINES (SOURCED FROM SQL GUIDE) Developing and deploying routines provides you with an opportunity to greatly improve the performance and effectiveness of your database applications. There can, however, be security risks if
370
Appendix E
Security Considerations for DB2
the deployment of routines is not managed correctly by the database administrator. The following sections describe security risks and means by which you can mitigate these risks. The security risks are followed by a section on how to safely deploy routines whose security is unknown.
Security Risks • NOT FENCED routines can access database manager resources. NOT FENCED routines run in the same process as the database manager. Because of their close proximity to the database engine, NOT FENCED routines can accidentally or maliciously corrupt the database manager’s shared memory, or damage the database control structures. Either form of damage will cause the database manager to fail. NOT FENCED routines can also corrupt databases and their tables.
To ensure the integrity of the database manager and its databases, you must thoroughly screen routines you intend to register as NOT FENCED. These routines must be fully tested, debugged, and exhibit no unexpected side effects. In the examination of the routine, pay close attention to memory management and the use of static variables. The greatest potential for corruption arises when code does not properly manage memory or incorrectly uses static variables. These problems are prevalent in languages other than Java and .NET programming languages. To register a NOT FENCED routine, the CREATE_NOT_FENCED_ROUTINE authority is required. When granting the CREATE_NOT_FENCED_ROUTINE authority, be aware that the recipient can potentially gain unrestricted access to the database manager and all its resources. NOTE: NOT FENCED routines are not supported in Common Criteria– compliant configurations. • FENCED THREADSAFE routines can access memory in other FENCED THREADSAFE routines. FENCED THREADSAFE routines run as threads inside a shared process. Each of these
routines is able to read the memory used by other routine threads in the same process. Therefore, it is possible for one threaded routine to collect sensitive data from other routines in the threaded process. Another risk inherent in the sharing of a single process is that one routine thread with flawed memory management can corrupt other routine threads, or cause the entire threaded process to crash. To ensure the integrity of other FENCED THREADSAFE routines, you must thoroughly screen routines you intend to register as FENCED THREADSAFE. These routines must be fully tested, debugged, and exhibit no unexpected side effects. In the examination of the
Security Considerations for Routines (Sourced from SQL Guide)
371
routine, pay close attention to memory management and the use of static variables. This is where the greatest potential for corruption lies, particularly in languages other than Java. To register a FENCED THREADSAFE routine, the CREATE_EXTERNAL_ROUTINE authority is required. When granting the CREATE_EXTERNAL_ROUTINE authority, be aware that the recipient can potentially monitor or corrupt the memory of other FENCED THREADSAFE routines. • Write access to the database server by the owner of fenced processes can result in database manager corruption. The user ID under which fenced processes run is defined by the db2icrt (create instance) or db2iupdt (update instance) system commands. This user ID must not have write access to the directory where routine libraries and classes are stored (in UNIX environments, sqllib/function; in Windows environments, sqllib\function). This user ID must also not have read or write access to any database, operating system, or otherwise critical files and directories on the database server. If the owner of fenced processes does have write access to various critical resources on the database server, the potential for system corruption exists. For example, a database administrator registers a routine received from an unknown source as FENCED NOT THREADSAFE, thinking that any potential harm can be averted by isolating the routine in its own process. However, the user ID that owns fenced processes has write access to the sqllib/function directory. Users invoke this routine, and unbeknownst to them, it overwrites a library in sqllib/function with an alternative version of a routine body that is registered as NOT FENCED. This second routine has unrestricted access to the entire database manager, and can thereby distribute sensitive information from database tables, corrupt the databases, collect authentication information, or crash the database manager. Ensure the user ID that owns fenced processes does not have write access to critical files or directories on the database server (especially sqllib/function and the database data directories). • Vulnerability of routine libraries and classes. If access to the directory where routine libraries and classes are stored is not controlled, routine libraries and classes can be deleted or overwritten. As discussed in the preceding bulleted item, the replacement of a NOT FENCED routine body with a malicious (or poorly coded) routine can severely compromise the stability, integrity, and privacy of the database server and its resources. To protect the integrity of routines, you must manage access to the directory containing the routine libraries and classes. Ensure that the fewest possible number of users can access this directory and its files. When assigning write access to this directory, be aware
372
Appendix E
Security Considerations for DB2
that this privilege can provide the owner of the user ID unrestricted access to the database manager and all its resources. • Deploying potentially insecure routines. If you happen to acquire a routine from an unknown source, be sure you know exactly what it does before you build, register, and invoke it. It is recommend that you register it as FENCED and NOT THREADSAFE unless you have tested it thoroughly and it exhibits no unexpected side effects. If you need to deploy a routine that does not meet the criteria for secure routines, register the routine as FENCED and NOT THREADSAFE. To ensure that database integrity is maintained, FENCED and NOT THREADSAFE routines: • Run in a separate DB2 process, shared with no other routines. If they abnormally terminate, the database manager will be unaffected. • Use memory that is distinct from memory used by the database. An inadvertent mistake in a value assignment will not affect the database manager. • Security of external routine library or class files. External routine libraries are stored in the file system on the database server and are not backed up or protected in any way by the DB2 database manager. For routines to continue to successfully be invoked, it is imperative that the library associated with the routine continues to exist in the location specified in the EXTERNAL clause of the CREATE statement used to create the routine. Do not move or delete routine libraries after creating routines; doing so will cause routine invocations to fail. To prevent routine libraries from being accidentally or intentionally deleted or replaced, you must restrict access to the directories on the database server that contain routine libraries and restrict access to the routine library files. You can do this by using operating system commands to set directory and file permissions.
SECURITY CONSIDERATIONS FOR DB2 ADMINISTRATION SERVER (DAS) ON WINDOWS (SOURCED FROM ADMINISTRATION GUIDE: IMPLEMENTATION) You might need to change the user ID under which the DAS service runs on Windows. After creating the DAS, you can set or change the logon account using the db2admin command as follows: db2admin setid <username> <password>
where <username> and <password> are the username and password of an account that has local Administrator authority. Before running this command, you must log on to a computer using an account or user ID that has local Administrator authority.
Security Considerations for User Mapping Plug-In for a Federated Environment
373
NOTE: Recall that passwords are case-sensitive. A mixture of upperand lowercase is allowed, which means that the case of the password becomes very important. On Windows, you should not use the Services utility in the Control Panel to change the logon account for the DAS, because some of the required access rights will not be set for the logon account. Always use the db2admin command to set or change the logon account for the DAS.
SECURITY CONSIDERATIONS FOR USER MAPPING PLUG-IN FOR A FEDERATED ENVIRONMENT (SOURCED FROM WEBSPHERE INFORMATION INTEGRATION DOCUMENTATION) When developing and using your plug-in, you are sending sensitive user IDs and passwords between multiple sources. You can protect your information by restricting access to code, auditing plug-in usage, and encrypting communication. You must develop your plug-in to use security settings that match the security settings that are used by your external repository. You should choose an external repository that allows you to encrypt sensitive information that is stored. The user mapping cryptography class must contain the encryption schema and secret key that allows for decrypting and decoding the passwords. You should restrict access to the source code of the plug-in so that this information stays secure. If auditing is turned on, any attempt to access a user mapping through plug-in by the federated server has a VALIDATE audit record. You can configure the db2audit tool to capture VALIDATE records: db2audit configure scope VALIDATE. You can also protect the communication between the federated server and the external repository by using a Secure Sockets Layer (SSL). When you create your configuration file for the user mapping plug-in, you can specify that the plug-in uses SSL to protect communications.
This page intentionally left blank
APPENDIX
F
Glossary of Authorization ID
(Contributed by DB2 security guru Paul Bird) authorization ID A term used to refer to a DB2-compatible ID (that is, an ID that follows the guidelines for DB2 authorization IDs) used for authorization purposes. Typically, it refers to both the primary and secondary authorization IDs when referring to privilege checking and only the primary authorization ID when referring to object ownership. primary authorization ID This term refers to the main authorization ID to be considered for authorization purposes and is the ID used for any catalog entries for object owner/definer and for any audit records generated. It usually represents a user’s authorization ID. secondary authorization ID This term refers to the collection of IDs associated with the primary authorization ID that can be used to supplement the primary authorization ID’s privileges where allowed by DB2. (Secondary authorization IDs are not always considered such as in the case of static SQL.) These IDs represent groups. The secondary authorization IDs are associated to the primary authorization ID through external associations (that is, unknown to DB2) where they represent external groups. The number of secondary authorization IDs is variable (and can be zero). Any group authorization IDs are requested by DB2 as required and remain associated with the primary authorization ID for the life of the communication with DB2. (That is, they are cached.) DB2 does not reflect any changes to the external associations subsequent to the commencement of that communication. (That is, changes to groups do not get reflected inside DB2 while the communication to DB2 is active.) For a connection, group information is requested immediately after the authentication stage of CONNECT processing.
375
376
Appendix F:
Glossary of Authorization ID
system authorization ID As part of the authentication process, an authorization ID compatible with DB2’s naming requirements is produced to represent the external user ID within DB2. This ID is referred to as the system authorization ID and is used to do any initial authorization checking such as checking for CONNECT privilege during CONNECT processing. This ID represents the user who created the connection in DB2-compatible terms. The SYSTEM_USER special register can be used to see the current value of this ID. The system authorization ID cannot be changed at this time. session authorization ID This is the authorization ID used for any session authorization checking subsequent to the initial checks performed during CONNECT processing. After a connection has been established, the session authorization ID represents the current user of the connection in DB2-compatible terms. The default value of the session authorization ID is the value of the system authorization ID. The SESSION_USER special register can be used to see the current value of this ID. The old USER special register is a synonym for SESSION_USER. The session authorization ID can be changed through use of the SET SESSION AUTHORIZATION statement. (Routine) invoker authorization ID This is the authorization ID that was the statement authorization ID for the statement that invoked a SQL routine. (Routine) definer authorization ID This is the authorization ID that is listed in the system catalogs as the definer of the SQL routine that has been invoked. package authorization ID This is the authorization ID that was used to bind a package to the database. This ID is obtained from the value of the OWNER bind option. This ID is sometimes referred to as the package binder or package owner. statement authorization ID This is the authorization ID associated with a specific SQL statement that is to be used for any authorization requirements and for determining object ownership (where appropriate). It takes its value from the appropriate source authorization ID depending on the type of SQL statement, as follows: Static SQL
The relevant package authorization ID is used.
Dynamic SQL (from nonroutine context)
If the value for the DYNAMICRULES option for the issuing package is RUN, the relevant session authorization ID is used. If the value for the DYNAMICRULES option for the issuing package is BIND, the relevant package authorization ID is used.
Appendix F:
Glossary of Authorization ID
377
If the value for the DYNAMICRULES option for the issuing package is DEFINERUN or INVOKERUN, the relevant session authorization ID is used. If the value for the DYNAMICRULES option for the issuing package is DEFINEBIND or INVOKEBIND, the relevant package authorization ID is used. Dynamic SQL (from routine context)
If the value for the DYNAMICRULES option for the issuing package is DEFINERUN or DEFINEBIND, the relevant definer authorization ID is used. If the value for the DYNAMICRULES option for the issuing package is INVOKERUN or INVOKEBIND, the relevant invoker authorization ID is used.
The CURRENT_USER special register can be used to see the current value of this ID. The statement authorization ID cannot be changed directly by the end user; it is changed automatically by DB2 to reflect the nature of each SQL statement.
This page intentionally left blank
APPENDIX
G
LBAC-Related SYSCAT Views
Table G.1
Definition of SYSCAT.SECURITYLABELACCESS Catalog View
Column Name
Type Schema
Type Name
Length
Scale
Nulls
GRANTOR
SYSIBM
VARCHAR
128
0
No
GRANTEE
SYSIBM
VARCHAR
128
0
No
GRANTEETYPE
SYSIBM
CHARACTER
1
0
No
SECLABELID
SYSIBM
INTEGER
4
0
No
SECPOLICYID
SYSIBM
INTEGER
4
0
No
ACCESSTYPE
SYSIBM
CHARACTER
1
0
No
GRANT_TIME
SYSIBM
TIMESTAMP
10
0
No
Table G.2
Definition of SYSCAT.SECURITYLABELS Catalog View
Column Name
Type Schema
Type Name
Length
Scale
Nulls
SECLABELNAME
SYSIBM
VARCHAR
128
0
No
SECLABELID
SYSIBM
INTEGER
4
0
No
SECPOLICYID
SYSIBM
INTEGER
4
0
No
SECLABEL
SYSPROC
DB2SECURITYLABEL
0
0
No
CREATE_TIME
SYSIBM
TIMESTAMP
10
0
No
REMARKS
SYSIBM
VARCHAR
254
0
Yes
379
380
Table G.3
Appendix G
LBAC-Related SYSCAT Views
Definition of SYSCAT.SECURITYPOLICIES Catalog View
Column Name
Type Schema
Type Name
Length
Scale
Nulls
SECPOLICYNAME
SYSIBM
VARCHAR
128
0
No
SECPOLICYID
SYSIBM
INTEGER
40
No
NUMSECLABELCOMP
SYSIBM
INTEGER
4
0
No
RWSECLABELREL
SYSIBM
CHARACTER
1
0
No
NOTAUTHWRITE SECLABEL
SYSIBM
CHARACTER
1
0
No
CREATE_TIME
SYSIBM
TIMESTAMP
10
0
No
REMARKS
SYSIBM
VARCHAR
254
0
Yes
Table G.4
Definition of SYSCAT.SECURITYLABELCOMPONENTS Catalog View
Column Name
Type Schema
Type Name
Length
Scale
Nulls
COMPNAME
SYSIBM
INTEGER
128
0
No
COMPID
SYSIBM
INTEGER
4
0
No
COMPTYPE
SYSIBM
CHARACTER
1
0
No
NUMELEMENTS
SYSIBM
INTEGER
4
0
No
CREATE TIME
SYSIBM
TIMESTAMP
10
0
No
REMARKS
SYSIBM
VARCHAR
256
0
Yes
Table G.5
Definition of SYSCAT.SECURITYLABELCOMPONENTELEMENTS Catalog View
Column Name
Type Schema
Type Name
Length
Scale
Nulls
COMPID
SYSIBM
INTEGER
4
0
No
ELEMENTVALUE
SYSIBM
VARCHAR
32
0
No
ELEMENTVALUEENCODING
SYSIBM
VARCHAR
32
0
No
ELEMENTVALUEENCODING
SYSIBM
CHARACTER
8
0
No
PARENTELEMENTVALUE
SYSIBM
VARCHAR
32
0
Yes
LBAC-Related SYSCAT Views
Table G.6
381
Definition of SYSCAT.SECURITYPOLICYCOMPONENTRULES Catalog View
Column Name
Type Schema
Type Name
Length
Scale
Nulls
SECPOLICYID
SYSIBM
INTEGER
4
0
No
COMPID
SYSIBM
INTEGER
4
0
No
ORDINAL
SYSIBM
INTEGER
4
0
No
READACCESSRULENAME
SYSIBM
VARCHAR
128
0
No
READACCESSRULETEXT
SYSIBM
VARCHAR
512
0
No
WRITEACCESSRULENAME
SYSIBM
VARCHAR
128
0
No
WRITEACCESSRULETEXT
SYSIBM
VARCHAR
512
0
No
Table G.7
Definition of SYSCAT.SECURITYPOLICYEXEMPTIONS Catalog View
Column Name
Type Schema
Type Name
Length
Scale
Nulls
GRANTOR
SYSIBM
VARCHAR
128
0
No
GRANTEE
SYSIBM
VARCHAR
128
0
No
GRANTEETYPE
SYSIBM
CHARACTER
1
0
No
SECPOLICYID
SYSIBM
INTEGER
4
0
No
ACCESSRULENAME
SYSIBM
VARCHAR
128
0
No
ACCESSTYPE
SYSIBM
CHARACTER
1
0
No
ORDINAL
SYSIBM
INTEGER
4
0
No
ACTIONALLOWDED
SYSIBM
CHARACTER
1
0
No
GRANT_TIME
SYSIBM
TIMESTAMP
10
0
No
This page intentionally left blank
APPENDIX
Security Plug-In Return Codes
383
H
APIs That Can Return
0
DB2SEC_PLUGIN_OKAY
The plug-in executed successfully.
All APIs
-1
DB2SEC_PLUGIN_UNKNOWNERROR
The plug-in encountered an unexpected error.
All APIs
-2
DB2SEC_PLUGIN_BADUSER
The ID passed in as input is not defined to the external world.
No such user or group. This is db2secDoesAuthIDExist, not treated as an error by DB2; db2secDoesGroupExist it is used on a grant statement to figure out whether an authorization ID is a user authorization ID or a group authorization ID.
-4
DB2SEC_PLUGIN_USERSTATUSNOTKNOWN
Unknown user status. This is db2secDoesAuthIDExist not treated as an error by DB2; it is used on a grant statement to figure out whether an authorization ID is a user ID or group ID.
-5
DB2SEC_PLUGIN_GROUPSTATUSNOTKNOWN
Unknown group status. db2secDoesGroupExist This is not treated as an error by DB2; it is used on a grant statement to figure out whether an authorization ID is a user ID or group ID.
Plug-in is unable to open and read a file for a reason other than a file missing or file permission.
All APIs
-19
DB2SEC_PLUGIN_FILENOTFOUND
Plug-in is unable to open and read a file because the file is missing from the file system.
All APIs
-20
DB2SEC_PLUGIN_CONNECTION_DISALLOWED The plug-in is refusing the connection because of the restriction on which the database is allowed to connect or which the TCP/IP address can connect to a specific database.
-21
DB2SEC_PLUGIN_NO_CRED
(GSS API plug-in only) Initial client credential is missing.
(GSS API plug-in only) The principal name is invalid.
db2secProcessServerPrincipalName
386
Return Code
All server-side plug-in APIs
Appendix H Security Plug-In Return Codes
Meaning
APIs That Can Return
-24
DB2SEC_PLUGIN_NO_CON_DETAILS
This return code is returned by the db2secGetConDetails callback (that is, from DB2 to the plug-in) to indicate DB2 is unable to determine the client’s TCP/IP address.
db2secGetConDetails
-25
DB2SEC_PLUGIN_BAD_INPUT_PARAMETERS
Some parameters are not valid or missing when the plug-in API is called.
All APIs
-26
DB2SEC_PLUGIN_INCOMPATIBLE_VER
The version of the APIs reported by the security plug-in is not compatible with DB2.
The plug-in runs out of resources when attempting to create a new process.
All APIs
-28
DB2SEC_PLUGIN_NO_LICENSES
The plug-in encountered a user license problem. Possible that the underlying mechanism license has reached the limit.
All APIs
Security Plug-In Return Codes
Define Value the Return Code
Appendix H
Return Code
387
This page intentionally left blank
APPENDIX
I
Detailed Implementation for the Case Study in Chapter 3
GROUP PLUG-IN To implement a group plug-in, application programming interfaces (APIs) are required. Note that when DB2 called the Init function, it passed a callback function db2secLogMessage where the plug-in code can log debugging or diagnostic information to db2diag.log.
db2secGroupPluginInit 1. Assign all the function addresses to the function pointers. 2. Set plugintype = DB2SEC_PLUGIN_TYPE_GROUP. 3. Set the version based on the version of the security plug-in API you are using. It is suggested that you use the latest version number (that is, the define DB2SEC_API_ VERSION from the header file db2secPlugin.h).
389
390
Appendix I
Listing I.1
Detailed Implementation for the Case Study in Chapter 3
A Sample Listing for the db2secGroupPluginInit API
db2secPluginTerm (Internal Name: Log_terminate_plugin) You need to do nothing because the plug-in did not do anything special on the initialization function.
db2secGetGroupsForUser (Internal Name: Log_get_groups) 1. Check the token input parameter. If it is not null, it should contain the group list for this authenticated user. The plug-in should just return the token as the group list and DB2SEC_PLUGIN_OK as the return code. Otherwise, continue to Step 2. 2. Establish communication with the daemon. 3. Send the auth ID from the input parameter to request the daemon to look for the group list. (D4) 4. Allocate memory for storing the group list to be returned to the caller if the number of groups is greater than zero. 5. Return the group list and return code that is replied by the daemon.
Appendix I
Server Authentication Plug-In
391
db2secDoesGroupExist (Internal Name: Log_is_group) Return DB2SEC_PLUGIN_GROUPSTATUSNOTKNOWN for simplicity because it will be quite hard to find if a given auth ID is the uppercase version of the group in one of the group lists in the database. As a result, you must specify the target auth ID type (USER or GROUP) when issuing a grant statement.
db2secFreeGroupListMemory (Internal Name: Log_free_group_list) Free the group list memory allocated in Step 3 of db2secGetGroupsForUser.
db2secFreeErrormsg (Internal Name: Log_free_error_message) Free the memory that is allocated for returning error messages for the other plug-in APIs.
SERVER AUTHENTICATION PLUG-IN To implement a server authentication plug-in, the following APIs are required. Just like the group plug-in, a callback function db2secLogMessage will be made available to the server authentication plug-in. In addition, DB2 provides yet another callback function called db2secGetConDetails that allows the plug-in to retrieve the information about the client that is attempting to establish the connection. Information such as the IP address and the network protocol used is made available for the server plug-in.
db2secServerAuthPluginInit 1. Assign all the function addresses to the function pointers. 2. Set plugintype = DB2SEC_PLUGIN_TYPE_USERID_PASSWORD. 3. Set the version based on the version of security plug-in API you are using. It is suggested that you use the latest version number (that is, the define DB2SEC_API_ VERSION from the header file db2secPlugin.h). Listing I.2
A Sample Listing for the db2secServerAuthPluginInit API
db2secServerAuthPluginTerm (Internal Name: Log_terminate_plugin) Nothing to do because the plug-in did not do anything special on the initialization function.
db2secValidatePassword (Internal Name: Log_validatePassword) 1. Calculate the hash value for the password in the input parameter. 2. If a new password is specified, calculate the hash value for the new password. 3. Establish communication with the daemon. 4. Send the user ID, the password hash value, and optionally a new password hash value to request that the daemon validates the password and retrieves the group list if validation is successful. (D1) 5. If the return code is not DB2SEC_PLUGIN_OK, the output token will be null. Otherwise, allocate memory to store the retrieve group list. This allocated memory will be freed when db2secFreeToken is called after performing a group lookup for the authenticated user.
Appendix I
Server Authentication Plug-In
393
db2secGetAuthIDs (Internal Name: Log_getauthids) 1. Establish communication with the daemon. 2. Send the userid from the input parameter to request the daemon for auth ID lookup. (D2) 3. Return the auth ID and return code that are returned by the daemon.
db2secDoesAuthIDExist (Internal Name: Log_is_user) 1. Establish communication with the daemon. 2. Send the auth ID from the input parameter to request that the daemon check that this user auth ID exists in the database. (D3) 3. Return the return code that is returned by the daemon.
db2secFreeToken (Internal Name: Log_free_token) Free the memory that is allocated to contain the token. In our design, the token is the group list for the authenticated user. If any user authenticated successfully, the token is the group list string.
db2secFreeErrormsg (Internal Name: Log_free_error_message) Free the memory that is allocated for returning an error message for the other plug-in APIs.
This page intentionally left blank
Index A access control. See also LBAC (Label Based Access Control) in LDAP, 368 for PUBLIC group during implementation, 260-266 under Sarbanes-Oxley Act of 2002, 10 security policy creation, 38 Account Lockout Duration setting (Windows), 109 Account Lockout Threshold setting (Windows), 109 account policy settings, Windows security, 107-108 accounts (Windows), locking down, 108-109 Active Directory, securing, 112, 368-369 administrative application for identity management case study, 83-84 Administrator account (Windows), locking down, 108 ADMIN_COPY_SCHEMA stored procedure, LBAC support, 233 altering protected tables (LBAC), 234 APAR (Authorized Program Analysis Report), 312 APIs for customized security plug-ins, 77-78 application vulnerabilities, discovering, 313 approving security policies, authority for, 35-36 ARRAY security label component (LBAC), 167 access rules example, 173 deleting data records, 197, 199 inserting data records, 191-194 retrieving data records, 194-196 updating data records, 196-197 AS (authentication service), Kerberos, 70 asymmetric cryptography, 239 attacks, response to, 316-317 audit record layouts AUDIT events, 337 CHECKING events, 338-339 CONTEXT events, 348 OBJMAINT events, 340-341 SECMAINT events, 342-344 SYSADMIN events, 345 VALIDATE events, 346-347 audit record object types, 349-350
AUDIT scope option, db2audit utility, 282-284, 337 auditing, 269-271 design phase, 276-301 granting privileges, 121 under HIPAA (Health Insurance Portability and Accountability Act), 14-15 planning for, 271-276 under Sarbanes-Oxley Act of 2002, 9 in security policy creation, 38-39 auth IDs. See authorization IDs auth plug-ins, 54 client-side auth plug-ins, 57-59 GSS API-based auth plug-ins, 55-56 client-server flow in, 67-69 enabling, 64 Kerberos, 70-73, 329-336 mixed use clients scenario, 88 restrictions on, 68 server-side auth plug-ins, 58, 60 user ID/password-based auth plug-ins, 54 enabling, 63-64 LDAP (Lightweight Directory Access Protocol), 73-76 authentication client authentication, 46-47 DATA_ENCRYPT authentication method, 241 DATA_ENCRYPT_CMP authentication method, 242-243 under HIPAA (Health Insurance Portability and Accountability Act), 15 host-based authentication, setting up for SSH (Secure Shell) data partitioning, 306-307 importance of, 41 instance-level operations, 46 mutual authentication, 70 by operating system, 42-43 of passwords, 257-258 public key authentication, setting up for SSH (Secure Shell) data partitioning, 305, 307 security plug-ins. See security plug-ins
395
396
AUTHENTICATION parameter (response files), 102 authentication requirements, security plan creation, 28 authentication service (AS), Kerberos, 70 authentication type, 43 for catalog database command, setting, 46 on DB2 connect gateway, 52 determining for connections, 52-53 hybrid authentication types, 48 list of supported authentication methods, 44, 46 negotiation between client and server, 47-51 selecting, 44 SRVCON_AUTH Database Manager Configuration parameter, 46-47 authorities database-level authorities, 134-136 determining with GET AUTHORIZATIONS command, 137-138 direct authority, indirect authority versus, 138 granting/revoking when changes take effect, 156-158 hierarchy of, 129-130 implicitly granted authorities, 144-145, 147 instance-level authorities, 129-134 object ownership management, 158-162 privileges versus, 129 for reviewing/approving/implementing/ maintaining security policies, 35-36 authorization, indirect access, 363-365 authorization checking for DB2 command/utilities, 147 for SQL statements, 147-156 authorization ID mapping, Kerberos, 72 authorization IDs defined, 118-119, 375 object owner, defined, 118 orphan authorization ID, 158-159 retrieving group membership list for, 149 session authorization ID, LBAC enforcement, 171 statement authorization ID, 147 system authorization ID, 147 types of, 375-377 user IDs versus, 58, 118 Authorized Program Analysis Report (APAR), 312 awareness, human factor in security, 320-322
Index
B backup command, 364 backups importance of, 2-3 LBAC support, 234 under Sarbanes-Oxley Act of 2002, 10-11 best practices, 119 documentation, 122-123 due diligence, 122 granting group privileges, 122 granting PUBLIC privileges, 125-128 “least privilege” principle, 120 “need to know” principle, 119-120 process control and review, 121-122 schemas, 123-124 “separation of duties” principle, 121 Bond, Rebecca, 2-3 BY ALL keywords, revoking database-level authorities, 136
C cached dynamic SQL, LBAC support, 234 case sensitivity of passwords, 373 case studies. See also sample scenarios identity management, 80-87, 389-393 LBAC, 207-217 catalog database command, setting authentication type, 46 catalog views, 363 CATALOG_NOAUTH parameter (response files), 102 cell-level encryption, 247-248 change control, 39-40 changes to authorities/privileges, when become effective, 156-158 CHECKING scope option, db2audit utility, 284-286, 338-339, 353, 355 client, negotiation of authentication type, 47-51 client authentication, 46-47 client-server flow in GSS API auth plug-ins, 67-69 client-side auth plug-ins, 57-59 COBIT (Control Objectives for Information and related Technology) framework, 8 column protection, 224-225 column security labels (LBAC), 169 column-level encryption, 246-247 column-level table protection (LBAC), 170 command syntax, db2audit utility, 279-299
Index
comments, creating in SQL, 122-123 Committee of Sponsoring Organizations of the Treadway Commission (COSO), 8 comparing encrypted data, 252-253 compiling customized security plug-ins, 78 compliance. See regulations CONFIGURE keyword, db2audit utility, 281 configuring DB2 for SSH (Secure Shell) data partitioning, 307-308 db2audit utility, 281-291 Windows for Kerberos, 332 connect statement, user IDs/passwords in, 239-241 connections authentication type, determining, 52-53 special connection IDs, password authentication, 257 CONTEXT scope option, db2audit utility, 290-291, 348, 351 Control Center, copying protected tables (LBAC), 233 Control Objectives for Information and related Technology (COBIT) framework, 8 CONTROL privileges, WITH GRANT OPTION and, 142-144 copying protected tables (LBAC), 233 corporate sponsorship for auditing, 271 CREATE_NOT_FENCED_ROUTINE database-level authority, 135 credential delegation, 92 cryptography, 238-239. See also encryption customized security plug-ins, creating, 76-78, 80 customizing Kerberos, 72
D daemon for identity management case study, 84-87 DAS (DB2 Administration Server), 96-97, 372 data partitioning with SSH (Secure Shell), 303-308 data records. See records (LBAC) database auditing. See auditing database backups, LBAC support, 234 database communication with different instances/authentication settings scenario, 89-90 Database Manager Configuration parameters NULL values for, 133-134 security plug-ins, 62-63 SRVCON_AUTH parameter, 46-47 database objects, schemas in security best practices, 123-124 database security plans. See security plans
397
database-level authorities granting and revoking, 136 list of, 134-135 separation of DBADM and SECADM authorities, 136 databases, default privileges for creating, 365, 367 DATA_ENCRYPT authentication method, 241 DATA_ENCRYPT_CMP authentication method, 242-243 DB2 commands, authorization checking, 147 configuring for SSH (Secure Shell) data partitioning, 307-308 connect gateway, authentication type, 52 e-mail alerts, 310 encryption. See encryption implementation. See implementation maintenance. See maintenance security plug-ins. See security plug-ins support web page, 311 utilities, authorization checking, 147 DB2 9 information center, 311 DB2 Administration Server. See DAS DB2 Anonymous Resolution under HIPAA (Health Insurance Portability and Accountability Act), 16-17 DB2 Data-Partitioning Feature (DPF). See data partitioning with SSH (Secure Shell) DB2 database security plans. See security plans DB2 Database Security Readiness Review Checklist, 363 DB2 for Windows, 95-106 DB2 for z/OS clients, Kerberos sample scenario, 91 DB2 Recovery Expert, 11 DB2 Recovery Expert for Multiplatform, 301 DB2-L mailing list, 311 db2audit utility audit record object types, 349-350 command syntax, 279-299 configuring, 281-291 extracting audit records, 293-298 functionality of, 278 intrusion detection, 277 multipartition environments, 278 pending audit records, 292-293 pruning audit records, 299 SCOPE parameter, 337-348, 351-355 securing, 278-279
398
starting, 290, 292 testing, 277-278 verifying configuration settings, 290-291 db2cat tool, 365 DB2COMM parameter (response files), 104 db2dart tool, 365 db2look command, LBAC support, 236 DB2_ADMINGROUP_NAME parameter (response files), 104 DB2_EXTSECURITY parameter (response files), 104 DB2_EXTSECURITY Windows registry key, 105-106 DB2_USERSGROUP_NAME parameter (response files), 104 DBA responsibilities auditing planning, role in, 273-276 under HIPAA (Health Insurance Portability and Accountability Act), 14-17 password maintenance, 257-258 under Sarbanes-Oxley Act of 2002, 8-13 system administrator responsibilities versus, 93-94 DBADM database-level authority, separation from SECADM authority, 132-133, 136 deadlock monitoring, 365 decryption, 248-249 DECRYPT_BIN function, 244, 248-249 DECRYPT_CHAR function, 244, 248-249 default privileges upon database creation, 365, 367 deleting. See also dropping data records from protected tables (LBAC), 182, 190-191, 197, 199, 206-207 protection from protected tables (LBAC), 226-227 deployment limitations, security plug-ins, 92. See also implementation design, implementation and, 259-260 design phase for auditing, 276-277 DB2 Recovery Expert for Multiplatform, 301 db2audit utility command syntax, 279-299 db2audit utility functionality, 278 intrusion detection, 277 monitoring the auditing, 302 multipartition environments, 278 securing db2audit utility, 278-279 stored procedures, 301 testing db2audit utility, 277-278 triggers, 299-301
Index
Diffie-Hellman Exchange algorithm, 238 direct authority, indirect authority versus, 138 disabling search on DAS (DB2 Administration Server), 97 disaster planning, importance of, 2-3 DISCOVER parameter (response files), 102 DISCOVER_INST parameter (response files), 103 discovery for auditing, 271-272 disk data encryption, 243-244 comparing encrypted data, 252-253 examples of usage, 246-249 noncharacter data types, 251-252 password hints, 249-251 SET ENCRYPTION PASSWORD statement, 246 SQL built-in functions, 244-245 Distributed Relational Database Architecture (DRDA), 47 documentation of DB2 for Windows installation, 95-96 in security best practices, 122-123 usefulness during implementation, 256 domain\user IDs, Windows support for, 105 DPF (DB2 Data-Partitioning Feature). See data partitioning with SSH (Secure Shell) DRDA (Distributed Relational Database Architecture), 47 dropping. See also deleting column protection from protected tables (LBAC), 225 protected tables (LBAC), 227 security label components (LBAC), 220 security labels (LBAC), 218-219 security policies (LBAC), 219-220 due diligence (security best practices), 122 dump files, 365 dynamic authorization model, 148 dynamic separation of duties security principle, 121 dynamic SQL rules, authorization checking, 151-154
E editing sample response files, 100 education, human factor in security, 320-322 enabling security plug-ins, 63-65 encapsulating objects, authorization checking for SQL statements, 155-156 ENCRYPT function, 244, 249-251
Index
encryption, 239. See also cryptography for disk data, 243-253 under HIPAA (Health Insurance Portability and Accountability Act), 15 for network data, 241-243 as part of cryptography, 238 under Sarbanes-Oxley Act of 2002, 11-12 security policy creation, 39 for user IDs/passwords in connect statement, 239-241 ERRORTYPE parameter, db2audit utility, 282 evalution of future security needs, 317-318 exception tables, 364 exemptions (LBAC), 169-170 access rules example, 175-176 granting, 222 revoking, 222 explain snapshot, 364 EXPLAIN statement, LBAC support, 236 exporting data records from protected tables (LBAC), 232 external routine libraries, 372 extracting audit records, db2audit utility, 293-298
F Federal Information Security Management Act (FISMA), 18-19 federated environments, user mapping plug-ins, 373 fenced processes, write access, 371 FENCED THREADSAFE routines, 370 FISMA (Federal Information Security Management Act), 18-19 Fixpacks, 114-115, 312-313 functions pointer, populating, 78 future security needs, evaluation of, 317-318
G GAAP (Generally Accepted Accounting Principles), 8 gateway. See DB2 connect gateway Generic Security Service. See GSS GET AUTHORIZATIONS command, 137-138 GETHINT function, 245, 249-251 global groups, creating, 367 Gramm-Leach-Bliley Act of 1999 (GLBA), 17-18 granting database-level authorities, 136 exemptions (LBAC), 222 group privileges, 122
399
privileges auditing of, 121 implicitly granted authorities/privileges, 144-145, 147 when changes take effect, 156-158 WITH GRANT OPTION, 142-144 PUBLIC privileges, 125-128 security labels (LBAC), 221 group auth IDs, 58, 118 group membership list, retrieving, 149 group plug-ins, 54, 58-59 enabling, 64 identity management case study, 389-391 group privileges checking for SQL statements, 149-151 granting, 122 groups global groups, creating, 367 naming conventions, security plan creation, 29-30 GSS API-based auth plug-ins, 55-56, 60-61 client-server flow in, 67-69 enabling, 64 Kerberos, 70-73, 329-336 mixed use clients scenario, 88 restrictions on, 68 Guest Account (Windows), locking down, 109
H header files, customized security plug-ins, 76-77 Health Insurance Portability and Accountability Act. See HIPAA High Performance Unload (HPU), 365 hints for passwords, 249-251 HIPAA (Health Insurance Portability and Accountability Act), 13-17 host-based authentication, setting up for SSH (Secure Shell) data partitioning, 306-307 HPU (High Performance Unload), 365 human factor in security, 319-325 Hurricane Katrina, 2-3 hybrid authentication types, 48
I IBM Tivoli Access Manager, 327 IBM Tivoli Identity Manager, 327 IBM Tivoli Risk Manager, 327 IBM-shipped security plug-ins, 56-57
400
IBMKrb5 plug-in configuring NAS kit, 329-332 support for, 73 identification, 41 identity management case study, 80-87, 389-393 implementation, 255 design and, 259-260 documentation from previous projects, usefulness of, 256 password authentication and maintenance, 257-258 performance considerations, 267 prioritizing sensitive data, 258-259 PUBLIC group access control, 260-266 security policies and, 35-36, 256 for upgrades/migrations/scalability projects, 267 when to start, 259 IMPLICIT_SCHEMA database-level authority, 135 implicitly granted authorities/privileges, 144-147 importing data records into protected tables (LBAC), 232 indirect access, 363-365 indirect authority, direct authority versus, 138 information gathering checklist, security plan creation, 24-25 insecure routines, 372 inserting data records into protected tables (LBAC), 180, 182-185, 191-194, 199-203 with views (LBAC), 231 installation client-side auth plug-ins, 57 DB2 for Windows, 95-104 installation user IDs, 105, 112-113 instance-level authorities, 129-134 instance-level operations, authentication, 46 internal controls (Sarbanes-Oxley Act of 2002), 7-8 interoperability, Kerberos support, 333-334 intrusion detection, 277, 315-316
J–K Johnson & Johnson, Tylenol product-tampering incident, 325 KDC (Kerberos Key Distribution Center), 70 Kerberos, 70-73, 329-336 authentication steps, 70-71 authorization ID mapping, 72
Index
customizing, 72 in DB2 for z/OS client environment scenario, 91 IBMKrb5 plug-in, 73, 329-332 NAS kit, configuring on UNIX/Linux systems, 329-332 source code, 72 support for, 333-334 Windows, configuring for, 332 Kerberos Key Distribution Center (KDC), 70 Kerberos plug-ins, enabling, 65
L LBAC (Label Based Access Control), 165-166 ADMIN_COPY_SCHEMA stored procedure, 233 architecture of, 166-171 case study, 207-217 database backups, 234 db2look command, 236 enforcement, 171-176 EXPLAIN statement, 236 under HIPAA (Health Insurance Portability and Accountability Act), 16 MQTs (materialized query tables), 232 protected tables. See protected tables (LBAC) referential integrity constraints, 234, 236 security label components, 218-220 security labels, 217-219 security plans, 177-179 security policies, 218-220 staging tables, 232 typed tables, 232 user access management, 221-223 views, 227-231 LDAP (Lightweight Directory Access Protocol), 73-76, 368 “least privilege” security principle, 120 legal issues. See regulations libraries, shared, 78-80 Lightweight Directory Access Protocol. See LDAP Linux. See UNIX/Linux systems listings db2secGroupPluginInit API, 390 db2secServerAuthPluginInit API, 391 GET AUTHORIZATIONS command output, 137 populating the function pointer structure, 78 security plug-in initialization API, 77 triggers used for auditing purposes, 155-156
Index
LOAD database-level authority, 135 LOAD utility, 298 loading data records into protected tables (LBAC), 232-233 security plug-ins, 66 log reader APIs, 364 LSA (Local System Account), 112-113
M maintenance, 309 discovering vulnerabilities, 309-313 evaluation of future needs, 317-318 Fixpacks, 312-313 intrusion detection, 315-316 mixed database environments, 314 preparation for attack response, 316-317 security policies, authority for, 35-36 vulnerability assessments, 314-315 mappings authorization ID mapping, Kerberos, 72 security policy creation, 38 materialized query tables (MQTs), LBAC support, 232 meeting facilitation tools, security plan creation, 27-28 meeting goals, security plan creation, 26-27 meeting participants. See team members migrations, implementation for, 267 mixed database environments, maintenance, 314 monitoring auditing process, 302 output, 365 MQTs (materialized query tables), LBAC support, 232 multipartition environments, db2audit utility, 278 mutual authentication, 70
N naming conventions security plan creation, 29-30 security policy creation, 37-38 user IDs, 72 NAS kit, configuring on UNIX/Linux systems, 329-332 “need to know” security principle, 119-120 negotiation of authentication type, 47-51 network data encryption, 241-243 New Orleans, 2-3 noncharacter data types, encryption, 251-252
401
NOT FENCED routines, 370 NULL values for database manager configuration parameters, 133-134
P package authorization ID, defined, 376 packages authorization checking for SQL statements, 152-154 LBAC support, 234 parameters in response files, 101-104 partitioned tables, LBAC support, 234 partitions, multipartition environments (db2audit utility), 278. See also data partitioning with SSH (Secure Shell) PASSWORDHINT parameter (ENCRYPT function), 249-251 passwords authentication, 257-258 case sensitivity, 373 cell-level encryption, 247-248 column-level encryption, 246-247 in connect statement, encryption, 239-241 decryption, 248-249 password hints, 249-251 security plan creation, 30-31 SET ENCRYPTION PASSWORD statement, 246 Windows security, 107-108 patches, importance for security, 114-115 PCAOB (Public Company Accounting Oversight Board), 8 pending audit records, db2audit utility, 292-293 performance considerations, implementation and, 267 perimeter-based intrusion detection, 315-316 physical security for Windows systems, 113-114 planning for auditing, 271-276. See also security plans policies. See security policies
402
populating functions pointer, 78 preparation for attack response, 316-317 primary authorization ID, defined, 375 prioritizing sensitive data for implementation, 258-259 Private Key Cryptography, 238 privileges authorities versus, 129 default privileges upon database creation, 365, 367 determining, 140 granting auditing of, 121 when changes take effect, 156-158 WITH GRANT OPTION, 142-144 group privileges checking for SQL statements, 149-151 granting, 122 hierarchy of, 138-139 implicitly granted privileges, 144-145, 147 list of, 140-141 object owner, defined, 118 object ownership management, 158-162 PUBLIC privileges, 125-128 of security plug-ins, 66 process control and review (security best practices), 121-122 protected tables (LBAC), 170-171 altering, 234 column protection, 224-225 copying, 233 deleting data records, 182 with ARRAY security label component, 197, 199 with SET security label component, 190-191 with TREE security label component, 206-207 deleting protection, 226-227 dropping, 227 enforcement, 171-176 exporting data, 232 importing data, 232 inserting data records, 180 with ARRAY security label component, 191-194 with SET security label component, 182-185 with TREE security label component, 199-203
Index
loading data, 232-233 retrieving data records, 180-181 with ARRAY security label component, 194-196 with SET security label component, 185-188 with TREE security label component, 204-205 reviewing, 223 row protection, adding, 224-225 security policies, changing, 226 updating data records, 181-182 with ARRAY security label component, 196-197 with SET security label component, 188-190 with TREE security label component, 205-206 user access management, 221-223 pruning audit records, db2audit utility, 299 pseudo databases under Sarbanes-Oxley Act of 2002, 12 Public Company Accounting Oversight Board (PCAOB), 8 PUBLIC group access control during implementation, 260-266 security plan creation, 29-30 public key authentication, setting up for SSH (Secure Shell) data partitioning, 305, 307 Public Key Cryptography, 239 PUBLIC privileges, 125-128 publishing security breaches, 323-325
Q–R querying. See retrieving data records QUIESCE_CONNECT database-level authority, 135 read access rules (LBAC), 171-172 records (LBAC) deleting from protected tables, 182, 190-191, 197, 199, 206-207 exporting from protected tables, 232 importing into protected tables, 232 inserting into protected tables, 180, 182-185, 191-194, 199-203 with views, 231 loading into protected tables, 232-233
Index
retrieving from protected tables, 180-181, 185-188, 194-196, 204-205 with views, 227-231 updating in protected tables, 181-182, 188-190, 196-197, 205-206 recovery under Sarbanes-Oxley Act of 2002, 10-11 referential integrity constraints, LBAC support, 234, 236 Registry (Windows), locking down, 110-112 regulations FISMA (Federal Information Security Management Act), 18-19 Gramm-Leach-Bliley Act of 1999 (GLBA), 17-18 HIPAA (Health Insurance Portability and Accountability Act), 13-17 reasons for, 5-6 Sarbanes-Oxley Act of 2002, 6-13 Remote Registry service (Windows), 110 Remote Shell (RSH), 303 removing. See deleting; dropping REOPT BIND option, 365 replication, 364 RESET command, db2audit utility, 281 Response File Generator utility, 99 response files, 97-104 RESTRICTIVE keyword, granting PUBLIC privileges, 125 retrieving data records from protected tables (LBAC), 180-181, 185-188, 194-196, 204-205 with views (LBAC), 227-231 return codes, security plug-ins, 384-387 reviewing protected tables (LBAC), 223 security label components (LBAC), 218 security labels (LBAC), 217 security policies, 35-36, 218 revoking database-level authorities, 136 exemptions (LBAC), 222 instance-level authorities, 131-132 privileges/authorities when changes take effect, 156-158 PUBLIC privileges, 126-128 security labels (LBAC), 222
S sample response files, 100-101 sample scenarios. See also case studies authorization checking for SQL statements, 150-151 database communication with different instances/authentication settings, 89-90 deleting data records with ARRAY security label component, 197, 199 with SET security label component, 190-191 with TREE security label component, 206-207 granting privileges, 142-144 inserting data records with ARRAY security label component, 191-194 with SET security label component, 183-185 with TREE security label component, 199-203 Kerberos in DB2 for z/OS client environment, 91 mixed use clients with GSS API plug-in, 88 retrieving data records with ARRAY security label component, 195-196 with SET security label component, 186-188 with TREE security label component, 204-205
404
updating data records with ARRAY security label component, 196-197 with SET security label component, 188-190 with TREE security label component, 205-206 Sarbanes-Oxley Act of 2002, 6 DBA responsibilities, 8-13 internal controls, 7-8 sections 302 and 404, 7 SARBOX. See Sarbanes-Oxley Act of 2002 scalability projects, implementation for, 267 scenarios. See sample scenarios schemas in security best practices, 123-124 SCOPE parameter, db2audit utility, 282 AUDIT option, 282-284, 337 CHECKING option, 284-286, 338-339, 353, 355 CONTEXT option, 290-291, 348, 351 OBJMAINT option, 286-287, 340-341 SECMAINT option, 286-287, 342-344 SYSADMIN option, 288, 345, 352-353 VALIDATE option, 288-290, 346-347 search, disabling on DAS (DB2 Administration Server), 97 SEC (Securities and Exchange Commission), 8 SECADM database-level authority, separation from DBADM authority, 136 SECMAINT scope option, db2audit utility, 286-287, 342-344 secondary authorization ID, defined, 375 Secure Shell. See SSH securing db2audit utility, 278-279 Securities and Exchange Commission (SEC), 8 security best practices, 119-128 breaches, publishing, 323-325 human factor in, 319-325 implementation. See implementation maintenance. See maintenance Windows security features, 106-115 security considerations Active Directory, 368-369 default privileges upon database creation, 365, 367 indirect access, 363-365 LDAP, access control, 368 routines, 369-372
system administrator responsibilities versus DBA responsibilities on Windows systems, 93-94 system authorization ID, 147, 376
T team members, security plan creation, 23-24 testing db2audit utility, 277-278 TGS (ticket-granting service), Kerberos, 70 TGT (ticket-granting ticket), Kerberos, 70 Tivoli Access Manager, 327 Tivoli Identity Manager, 327 Tivoli Risk Manager, 327 traces, 365 training. See education, human factor in security transferring object ownership, 159-162 TREE security label component (LBAC), 168 access rules example, 175 deleting data records, 206-207 inserting data records, 199-203 retrieving data records, 204-205 updating data records, 205-206 triggers for auditing, 299-301 authorization checking for SQL statements, 155-156 TRUST_ALLCLNTS parameter (response files), 103 TRUST_CLNTAUTH parameter (response files), 103 Tylenol product-tampering incident, 325 typed tables, LBAC support, 232
U UNIX/Linux systems configuring NAS kit, 329-332 SSH (Secure Shell) data partitioning, 303-308 users, 367 updating data records in protected tables (LBAC), 181-182, 188-190, 196-197, 205-206 upgrades, implementation for, 267 user access management (LBAC), 221-223 user authorization IDs, defined, 118 user ID/password-based auth plug-ins, 54 enabling, 63-64 LDAP (Lightweight Directory Access Protocol), 73-76 user IDs authorization IDs versus, 58, 118 in connect statement, encryption, 239-241 for DB2 for Windows installation, 96-97
Index
DBA user IDs, password maintenance for, 257-258 domain\user IDs, Windows support for, 105 installation user IDs, 105, 112-113 naming conventions, 72 user mapping plug-ins, 373 user security labels (LBAC), 169 user-designed pseudo databases under Sarbanes-Oxley Act of 2002, 12 users naming conventions, security plan creation, 29-30 UNIX platform, 367 Windows platform, 367