256 65 4MB
English Pages 406 [433] Year 2006;2007
This page intentionally left blank
Understanding DB2® 9 Security
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
The authors and publisher have taken care in the preparation of this book, but make no expressed or implied warranty of any kind and assume no responsibility for errors or omissions. No liability is assumed for incidental or consequential damages in connection with or arising out of the use of the information or programs contained herein. © Copyright 2007 by International Business Machines Corporation. All rights reserved. Note to U.S. Government Users: Documentation related to restricted right. Use, duplication, or disclosure is subject to restrictions set forth in GSA ADP Schedule Contract with IBM Corporation. IBM Press Program Managers: Tara Woodman, Ellice Uffer Cover design: IBM Corporation Published by Pearson plc Publishing as IBM Press IBM Press offers excellent discounts on this book when ordered in quantity for bulk purchases or special sales, which may include electronic versions and/or custom covers and content particular to your business, training goals, marketing focus, and branding interests. For more information, please contact: U.S. Corporate and Government Sales 1-800-382-3419 [email protected] For sales outside the United States, please contact: International Sales [email protected] The following terms are trademarks or registered trademarks of International Business Machines Corporation in the United States, other countries, or both: DB2, CICS, IMS, Lotus, Tivoli, WebSphere, Rational, IBM, the IBM logo, and IBM Press. Java and all Java-based trademarks are trademarks of Sun Microsystems, Inc. in the United States, other countries, or both. Microsoft, Microsoft .NET, .NET, Windows, Windows NT, and the Windows logo are trademarks of the Microsoft Corporation in the United States, other countries, or both. Linux is a registered trademark of Linus Torvalds. Intel, Intel Inside (logo), MMX, and Pentium are trademarks of Intel Corporation in the United States, other countries, or both. OSF/1 and UNIX are registered trademarks and The Open Group is a trademark of the The Open Group in the United States and other countries. UML is a registered trademark of the Object Management Group (OMG). Other company, product, or service names mentioned herein may be trademarks or service marks of their respective owners. Any persons, businesses, government entities, academic institutions, locales or events used in this book are fictional and for the purpose of illustrating concepts related to the subject matter of this book. Any resemblance to actual persons (living or dead), businesses, government entities, academic institutions, locales or events is entirely coincidental.
This Book Is Safari Enabled The Safari‚ Enabled icon on the cover of your favorite technology book means the book is available through Safari Bookshelf. When you buy this book, you get free access to the online edition for 45 days. Safari Bookshelf is an electronic reference library that lets you easily search thousands of technical books, find code samples, download chapters, and access technical information whenever and wherever you need it. To gain 45-day Safari Enabled access to this book: • Go to http://www.awprofessional.com/safarienabled • Complete the brief registration form • Enter the coupon code AXGL-PY3I-2GNA-K7IL-C1HG If you have difficulty registering on Safari Bookshelf or accessing the online edition, please e-mail [email protected]. 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
xiii
47 52 52 53 54 54 56 57 58 58 58 60 62 63 66 67 67 68 70 72 72 73 73 73 76 76 76 77 78 78 79 80 80 80 83 87 88 89 91 92 92
xiv
Table of Contents
Chapter 4
Securing DB2 on Windows
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
93 93 94 95 95 95 96 105 105 105 105 106 107 108 110 112 112 113 113 114 114 115
117 117 117 118 118 119 119 119 120 121 121 122 122 122 123 125 125 126 127 129 129 134 137 138
Table of Contents
xv
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
138 138 144 147 147 147 148 149 155 156 158 159 163
165 165 166 167 168 168 169 169 169 169 170 171 171 172 173 174 175 175 177 177 177 178 179 180 180 181 182 182 182 185 185 188 190
xvi
Table of Contents
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
191 191 194 196 197 199 199 199 204 205 206 207 209 210 211 214 217 217 217 218 218 218 219 220 221 221 222 222 222 223 224 224 224 225 226 226 227 227 227 227 231 232 232 232 232 232
Table of Contents
xvii
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
232 233 233 234 234 234 236 236 236 236
237 237 238 238 239 239 239 241 243 254
255 255 256 256 256 257 257 258 259 259 260 266 267 267 268
269 269 270 271 271 271 273 276 277 277
xviii
Table of Contents
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
278 278 278 279 299 301 301 302 302
303 303 303 304 305 306 307 308
309 309 309 310 312 312 313 314 314 315 316 317 318
319 319 320 320 321 322 323 323 325
327 329 329 332
Table of Contents
xix
Interoperability Useful Links
Appendix C Appendix D Appendix E
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
383
Group Plug-In db2secGroupPluginInit db2secPluginTerm (Internal Name: Log_terminate_plugin) db2secGetGroupsForUser (Internal Name: Log_get_groups) db2secDoesGroupExist (Internal Name: Log_is_group) db2secFreeGroupListMemory (Internal Name: Log_free_group_list) db2secFreeErrormsg (Internal Name: Log_free_error_message) Server Authentication Plug-In db2secServerAuthPluginInit db2secServerAuthPluginTerm (Internal Name: Log_terminate_plugin) db2secValidatePassword (Internal Name: Log_validatePassword) db2secGetAuthIDs (Internal Name: Log_getauthids) db2secDoesAuthIDExist (Internal Name: Log_is_user) db2secFreeToken (Internal Name: Log_free_token) db2secFreeErrormsg (Internal Name: Log_free_error_message)
Index
389 389 389 390 390 391 391 391 391 391 392 392 393 393 393 393
395
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 :
SQLCA sqlcabc: 136 sqlcode: 0 sqlerml: 44 ¨ ¨ ¨ ¨ ¨¨¨¨ ¨¨ 1y819yNEWTON yKEVINSyQDB2/6000y7y7y0y819y0y SQL08025 (1) 1 (2) 1 (3) 0 (4) 1 (5) 0 (6) 0 sqlwarn : (1) (2) (3) (4) (5) (6) (7) (8) (9) (10) (11) sqlstate:0000
Figure 3.3
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
DB2 Client #1 sqllib/security/plugin/client krb5.dll lipkey.dll spkm.dll
DB2 Client #2 sqllib/security/plugin/client krb5.dll lipkey.dll Database DB2 Client #3 sqllib/security/plugin/client
dbm cfg srvcon_gssplugin_list= spkm, kipkey
spkm.dll
DB2 Client #4 sqllib/security/plugin/client
racf.dll
Figure 3.4
Supporting multiple GSS API-based security plug-ins
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
Security Plug-In-Specific Database Manager Configuration Parameters
Name of the DBM CFG Parameter
Description
SRV_PLUGIN_MODE
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
DB2 GSS API Authentication Process
Client
Server
1. Obtain client’s initial credentials if necessary (db2secGenerateInitialCreds); otherwise, obtain default login context (db2secGetDefaultLoginContext).
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.
Introduction to Security Plug-Ins
Client GSSAPI plugin
69
DRDA AR
DRDA AS
Server GSSAPI plugin
gss_init_sec_context(NULL) NULL -> ctoken1 GSS_S_CONTINUE_NEEDED
1 - SECCHK (ctoken1)
gss_init_sec_context(stoken2)
2 - SECCHKRM(stoken2)
gss_accept_sec_context(ctoken1) ctoken1—> stoken2 GSS_S_CONTINUE_NEEDED
SECCHKCD(continue)
stoken2 –> ctoken3 GSS_S_CONTINUE_NEEDED
3 - SECCHK(ctoken3)
gss_init_sec_context(stoken4)
4 - SECCHKRM(stoken4)
gss_accept_sec_context(ctoken1) ctoken3 –> stoken4 GSS_S_CONTINUE_NEEDED
SECCHKCD(continue)
stoken4 –> ctoken5 GSS_S_COMPLETE
5 - SECCHK(ctoken5)
gss_accept_sec_context(ctoken5) ctoken5 –> NULL GSS_S_COMPLETE
6 - SECCHKRM(NULL) SECCHKCD(success)
ACCRDG
Figure 3.9 tokens
Multiple flows where the client indicated it will no longer accept more authentication
Client GSSAPI plugin
DRDA AR
DRDA AS
Server GSSAPI plugin
gss_init_sec_context(NULL) NULL -> ctoken1 GSS_S_CONTINUE_NEEDED
1 - SECCHK (ctoken1)
gss_init_sec_context(stoken2)
2 - SECCHKRM(stoken2)
gss_accept_sec_context(ctoken1) ctoken1—> stoken2 GSS_S_CONTINUE_NEEDED
SECCHKCD(continue)
stoken2 –> ctoken3 GSS_S_CONTINUE_NEEDED
3 - SECCHK(ctoken3)
gss_accept_sec_context(ctoken1)
gss_init_sec_context(stoken4)
4 - SECCHKRM(stoken4)
GSS_S_COMPLETE
ctoken3 –> stoken4 SECCHKCD(success)
stoken4 –> NULL GSS_S_COMPLETE ACCRDG
Figure 3.10 tion tokens
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.
Kerberos—An IBM-Shipped GSS API-Based Security Plug-In
71
1. Request for TGT Client
Figure 3.11
2. KClient{SClient.KDC} + TGT=KKDC{SClientKDC + client info}
KDC
Requesting ticket-granting ticket (TGT)
1. Request for session key to access Server. 2. KClient{SClient,Server} + Ticket=KServer{SClient,Server + client info}
KDC
3. SClient.Server{authenticator} + ticket=KServer{SClient.Server + client info} Client
Figure 3.12
4. (Optional) SClient,Server{timestamp}
Server
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
dn: ou=Sales.o=ibm.c=us
dn: cn=mgr1,o=ibm.c=us
dn: cn=db2grp,o=ibm,c=us
objectclass: OrganizationUnit ou: IT
objectclass: OrganizationUnit our: Sales
objectclass: groupOfNames cn: mgr1 member: uid=usr1,ou=IT,o=ibm,c=us uid=usr2,ou=Sales,o=ibm,c=us
objectclass: groupOfNames cn: db2grp member:cn=mgr1,o=ibm,c=us
group dn: uid=usr1,ou=IT,o=ibm,c=us
dn: uid=usr2,ou=Sales,o=ibm,c=us
objectclass: inetOrgPerson cn: usr1 sn: db2
objectclass: inetOrgPerson cn: usr2 sn: db2
member
Figure 3.13
A sample LADP directory tree
member
member group
nested group
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
Security Plug-In Initialization API
SQL_API_RC SQL_API_FN db2secServerAuthPluginInit( db2int32
version,
void* server_fns, db2secGetConDetails* getConDetails_fn, db2secLogMessage* logMessage_fn, char** errormsg, db2int32* errormsglen) { struct userid_password_server_auth_functions_1 *fns = (struct userid_password_server_auth_functions_1*) server_fns; condetails_fn = getConDetails_fn; logMessage_Fn = logMessage_fn;
(continues)
78
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
Populating the Function Pointer Structure
fns->version = DB2SEC_API_VERSION; fns->db2secDoesGroupExist = &is_group; fns->db2secFreeErrormsg = &free_error_message; fns->db2secFreeGroupListMemory = &free_group_list; fns->db2secGetGroupsForUser = &get_groups; fns->db2secPluginTerm = &terminate_plugin;
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
• 32-bit Linux/UNIX sqllib/security32/plugin/client sqllib/security32/plugin/server sqllib/security32/plugin/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 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 using " ===>. 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
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
*DB2.TYPE *DB2.FCM_PORT_NUMBER *DB2.MAX_LOGICAL_NODES *DB2.FEDERATED
= = = =
101
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.
Figure 4.2
Generated response file showing encrypted passwords
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
SYSMAINT authority DBADM authority CREATETAB authority BINDADD authority CONNECT authority
= = = = =
NO YES YES YES YES
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
= = = = = = = =
YES YES YES YES YES NO YES NO
Indirect SYSMAINT authority Indirect DBADM authority Indirect CREATETAB authority
= NO = NO = YES
Indirect Indirect Indirect Indirect Indirect Indirect Indirect Indirect
= = = = = = = =
BINDADD authority CONNECT authority CREATE_NOT_FENC authority IMPLICIT_SCHEMA authority LOAD authority QUIESCE_CONNECT authority CREATE_EXTERNAL_ROUTINE authority SYSMON authority
YES YES NO YES NO NO NO NO
138
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
139
Index
Control
Package
Control
SYSCAT. INDEXAUTH
DBADM
Bind, Execute SYSCAT. PACKAGEAUTH
Routine
Execute
Schema
Alterin, Createin, Dropin
Security Lable
All access, Read access, Write access
Sequence
Usage Alter
SYSCAT. SEQUENCEAUTH
Server
Pass through
SYSCAT. PASSTHRUAUTH
Tablespace
Use
SYSCAT. ROUTINEAUTH
SYSCAT. SCHEMAAUTH
SYSCAT. SECURITYLABELACCESS
Privileges Privileges
Table, view, nickname
Control
XSR Object
Usage
SYSCAT. TBSPACEAUTH Delete, Insert, Select, Update; Table, nickname onlyAlter, Index, References SYSCAT. TABAUTH SYSCAT. XSROBJECTAUTH
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.
Security label
Sequence
(continues)
Privileges
Table 5.3
141
DB2 Privileges Summary (Continued)
Object
Privilege
Description
Table, view, nickname, materialized query table (MQT), staging table
ALL
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 >-GRANT EXEMPTION ON RULE--+-access-rule-+--FOR--policy-name---> '-ALL---------' >--TO USER--authorization-name--------------------------------->