T4.2: Writes Secure Code

Knowledge Review - InterSystems IRIS Development Professional

1. Implements database and data element encryption

Key Points

  • Database encryption: Entire database encrypted at rest using AES in CBC mode with transparent application access
  • Data-element encryption: Encrypt specific sensitive properties (SSN, credit cards, PHI) using %SYSTEM.Encryption methods
  • Key management: Keys created externally or via Management Portal, then loaded and activated in IRIS
  • Key storage options: KMIP (remote key servers) or local key files with AES key wrap algorithm
  • Performance considerations: Hardware acceleration (AES-NI on Intel, AES VMX on POWER8) for minimal overhead

Detailed Notes

Overview

InterSystems IRIS provides two levels of encryption: database-level (encrypting entire IRIS.DAT files) and data-element level (encrypting specific properties programmatically).

Database Encryption

Uses AES (Advanced Encryption Standard) in CBC (Cipher Block Chaining) mode. Keys are created through the Management Portal's "Create New Encryption Key File" page, specifying key length (128, 192, or 256-bit), file location, and administrator credentials. The key is stored in an encrypted key file. Keys must be activated before use via the "Database Encryption" page. When creating a new database, set "Encrypt database" to "Yes" and select the activated key. Encryption is transparent to applications.

Data-Element Encryption

For granular control, use the %SYSTEM.Encryption class methods:

  • `$SYSTEM.Encryption.AESCBCManagedKeyEncrypt(plaintext, keyID)` - encrypts data, embedding the key ID in ciphertext
  • `$SYSTEM.Encryption.AESCBCManagedKeyDecrypt(ciphertext)` - decrypts data (key ID extracted automatically from ciphertext)
  • `$SYSTEM.Encryption.AESCBCManagedKeyEncryptStream(stream, keyID)` - for large data streams
  • `$SYSTEM.Encryption.AESCBCManagedKeyDecryptStream(stream)` - for decrypting streams

Key Management

IRIS supports up to 256 simultaneously activated keys. Key lifecycle methods:

  • `$SYSTEM.Encryption.CreateEncryptionKey()` - generates new keys
  • `$SYSTEM.Encryption.ActivateEncryptionKey()` - makes keys available
  • `$SYSTEM.Encryption.DeactivateEncryptionKey()` - removes keys from memory
  • `$SYSTEM.Encryption.ListEncryptionKeys()` - displays activated keys

Keys can be stored via KMIP (Key Management Interoperability Protocol) for enterprise key management, or in local key files protected with multiple layers of AES key wrap algorithm with PBKDF2-derived keys. The key ID is automatically stored with ciphertext, enabling real-time re-encryption without system downtime.

2. Establishes secure connections to external systems

Key Points

  • TLS/SSL configurations: Create named TLS configurations in Management Portal for encrypted connections
  • Certificate management: Import trusted CA certificates, configure client certificates for mutual authentication
  • Web service security: Use WS-Security standards for SOAP services with message-level encryption and signing
  • Database connections: Configure ODBC/JDBC with SSL/TLS for encrypted client-server communication
  • TCP/IP security: Enable TLS for custom TCP connections using %Net.SSLConfig and SSL device parameters

Detailed Notes

Overview

Secure connections to external systems are essential for protecting data in transit and ensuring trusted communication. InterSystems IRIS provides comprehensive TLS/SSL support through named TLS configurations managed in the Management Portal under System Administration > Security > SSL/TLS Configurations. These configurations specify protocol versions (TLS 1.2, TLS 1.3), cipher suites, certificate files, and verification requirements.

HTTPS Connections

For outbound HTTPS connections, developers use the %Net.HttpRequest class with the SSLConfiguration property set to a named TLS configuration. The SSL server certificate is automatically verified against trusted CA certificates installed in the configuration. For mutual TLS (mTLS), where the client must also present a certificate, configure the client certificate and private key in the TLS configuration. Example: Set httpRequest.SSLConfiguration = "MyTLSConfig" before calling httpRequest.Get().

Web Services Security (WS-Security)

Web services security extends beyond transport-layer encryption. SOAP-based web services can implement WS-Security standards for message-level security, including XML encryption, digital signatures, username tokens, and SAML assertions. This is configured through SOAP credentials in the Management Portal and WS-Security policies attached to web service definitions. Message-level security ensures end-to-end protection even when messages traverse multiple intermediaries.

Database Connections (ODBC/JDBC)

Database connections via ODBC and JDBC support SSL/TLS encryption when properly configured. JDBC connection strings include sslConnection=true and sslServerName parameters. ODBC connections configure SSL through the InterSystems ODBC driver settings. SQL Gateway connections to external databases also support TLS when connecting to remote systems that require encrypted connections.

Custom TCP/IP Connections

For custom TCP/IP connections using ObjectScript device I/O, developers use the /TLS device parameter and configure the connection using %Net.SSLConfig. The $SYSTEM.Encryption.SSLServer() and $SYSTEM.Encryption.SSLClient() methods establish encrypted channels. Always verify certificates, use strong cipher suites (avoid deprecated ciphers like RC4 and 3DES), and prefer TLS 1.2 or higher. Never disable certificate verification in production environments.

3. Prevents SQL injection vulnerabilities

Key Points

  • Parameterized queries: Always use host variables (:parameter) instead of string concatenation
  • Dynamic SQL with parameters: Use %SQL.Statement.Prepare() with ? placeholders and Execute() with parameter arrays
  • Input validation: Validate and sanitize all user input before use in queries
  • Avoid dynamic table/column names: If necessary, use whitelisting and strict validation
  • Embedded SQL safety: Host variables in embedded SQL are automatically parameterized

Detailed Notes

Overview

SQL injection is one of the most critical security vulnerabilities in database applications, occurring when untrusted user input is concatenated directly into SQL statements without proper sanitization. Attackers can inject malicious SQL code to access unauthorized data, modify database contents, or execute administrative operations. InterSystems IRIS provides robust protection mechanisms when developers follow secure coding practices.

Embedded SQL with Host Variables

The primary defense against SQL injection is parameterized queries using host variables. In embedded SQL, host variables are prefixed with colons and automatically handled as parameters: &sql(SELECT Name FROM Person WHERE ID = :id). The IRIS SQL compiler treats :id as a parameter placeholder, ensuring the value is properly escaped and cannot alter the query structure. Never concatenate user input: WRONG: &sql(SELECT * FROM Person WHERE Name = '"_userName_"') - this is vulnerable to injection.

Dynamic SQL with %SQL.Statement

For dynamic SQL, use the %SQL.Statement class with parameter placeholders. The Prepare() method accepts SQL with ? placeholders, and Execute() receives an array of parameter values: Set stmt = ##class(%SQL.Statement).%New() | Do stmt.%Prepare("SELECT * FROM Person WHERE Name = ?") | Set result = stmt.%Execute(userName). The driver handles proper escaping and type conversion automatically. This pattern prevents injection because parameter values are never interpreted as SQL code.

Input Validation and Defense-in-Depth

Input validation provides defense-in-depth. Validate data types (ensure numeric IDs are actually numbers), enforce length limits, use whitelists for enumerated values, and reject suspicious characters. For string inputs used in LIKE clauses, escape wildcard characters (% and _) if they should be treated literally. Use %SYSTEM.SQL.ValidateIdentifier() to validate table and column names when dynamic SQL must use variable identifiers.

Critical Best Practices

1) Never build SQL queries using string concatenation with user input. 2) Always use parameterized queries with host variables or ? placeholders. 3) Validate and sanitize all user input. 4) Use whitelisting for dynamic identifiers (table/column names). 5) Apply the principle of least privilege - database accounts should have minimal necessary permissions. 6) Log and monitor for SQL injection attempts. 7) Use stored procedures when possible to encapsulate database logic and reduce attack surface.

4. Prevents remote code execution vulnerabilities

Key Points

  • Avoid XECUTE with user input: Never execute user-supplied strings as ObjectScript code
  • Input validation for indirection: Strictly validate any input used with indirection (@) operator
  • Disable dynamic SQL execution: Configure $SYSTEM.SQL.SetSQLSecurity() to restrict dynamic operations
  • Web application security: Validate CSP inputs, use CSRF tokens, sanitize outputs to prevent XSS
  • ClassMethod execution control: Restrict public method exposure, validate parameters, use resource-based security

Detailed Notes

Overview

Remote code execution (RCE) vulnerabilities allow attackers to execute arbitrary code on the server, potentially leading to complete system compromise. In InterSystems IRIS, RCE risks primarily arise from improper use of dynamic code execution features like XECUTE, indirection (@), and dynamic SQL. Developers must understand these risks and implement appropriate safeguards.

XECUTE Command Risks

The XECUTE command evaluates and executes a string as ObjectScript code at runtime. While powerful for legitimate metaprogramming, XECUTE is extremely dangerous when used with user-supplied input. NEVER do this: XECUTE userInput. An attacker could inject malicious commands like "Do $SYSTEM.Security.Users.Modify()" or "Kill ^GlobalData". If dynamic code execution is absolutely necessary, use a strict whitelist approach where user input selects from predefined safe code blocks, never directly executes user strings.

Indirection Operator Risks

The indirection operator (@) evaluates a string as a variable name, global reference, or expression. Improper use with user input can lead to unauthorized data access or code execution. Example vulnerability: Set @userInput = value. An attacker could set userInput to "^%SYS" or malicious expressions. Mitigation: validate that input matches expected patterns using regex or whitelists, use $SYSTEM.SQL.ValidateIdentifier() for identifiers, and prefer direct variable access over indirection when possible.

Web Application Security

Web applications face additional RCE risks. CSP pages execute server-side ObjectScript, so unsanitized query parameters or form inputs can be exploited. Always validate input types, lengths, and formats. Use %CSP.Page security methods like %CheckCSRFToken() to prevent cross-site request forgery. Sanitize output to prevent cross-site scripting (XSS), which can lead to session hijacking and privilege escalation. Use $ZCVT(string, "O", "HTML") to encode HTML special characters in outputs.

ClassMethod Security

ClassMethod security is critical when methods are exposed through web services, REST APIs, or SQL procedures. Apply resource-based access control using the [%Method] keyword with Resources parameter: Method SensitiveOperation() [ SqlProc, Resources = "AdminResource" ]. Validate all method parameters - don't assume callers provide safe inputs. Use type checking, range validation, and business logic constraints. Log security-relevant operations for audit trails.

Configuration Best Practices

1) Enable application-level security in web applications. 2) Configure SQL security to restrict dynamic SQL generation. 3) Use resource-based access control for sensitive operations. 4) Implement comprehensive input validation on all external inputs. 5) Apply output encoding to prevent injection attacks in web interfaces. 6) Enable audit logging for security events. 7) Regular security testing including penetration testing and code review focusing on dynamic code execution patterns.

5. Leverages InterSystems IRIS security models effectively

Key Points

  • Role-based access control (RBAC): Assign users to roles, grant permissions to roles not users
  • Resource protection: Define resources to protect databases, applications, services, and operations
  • Application-level security: Configure web applications with authentication, roles, and privilege escalation
  • Service security: Enable/disable services (SQL, REST, SOAP, Telnet) and configure access controls
  • Audit trail: Enable auditing for security events, login attempts, privilege escalation, and data access

Detailed Notes

Overview

InterSystems IRIS implements a comprehensive role-based access control (RBAC) security model that provides granular control over system access and operations. Understanding and properly implementing this security model is essential for secure application development. The model consists of users, roles, resources, and privileges, with applications serving as security boundaries.

Users and Roles

Users are individual accounts that authenticate to the system. Each user is assigned one or more roles that determine their permissions. Roles are named collections of privileges and can include other roles (hierarchical roles). Privileges grant specific capabilities: database access (read/write/execute), service access (SQL, REST, CSP), resource permissions, and administrative functions. The key principle is to grant privileges to roles, then assign roles to users, never grant privileges directly to users. This simplifies administration and ensures consistent permission sets.

Resources and Permissions

Resources are protected entities defined in IRIS, including databases, applications, services, and custom-defined resources. Each resource has an associated permission level (Use, Read, Write). Database resources control access to specific databases - users must have appropriate database resources in their roles to query or modify data. Application resources protect web applications, REST services, and routines. Custom resources protect specific business operations, useful for implementing application-level authorization checks.

Application-Level Security

Application-level security integrates authentication and authorization into web applications. Web applications configure authentication methods (Password, Kerberos, LDAP, OAuth 2.0), required roles (Allowed Roles), and privilege escalation roles (Dispatch Class). Privilege escalation allows applications to perform operations on behalf of users that the users themselves couldn't perform directly. This is configured through the "Matching Roles" tab where you assign roles that the application can use. Always use this carefully as it bypasses normal user permissions.

Service Security

Service security controls which InterSystems IRIS services are enabled and who can access them. Services include SQL (JDBC, ODBC), REST APIs, SOAP web services, Telnet, and CSP. Each service can be enabled/disabled globally and restricted by role. For production systems, disable unused services to reduce attack surface. Enable services only for roles that require them. The %Service_Login service controls Management Portal access and should be restricted to administrators.

Auditing

Auditing provides comprehensive logging of security-relevant events. Enable audit logging in the Management Portal under System Administration > Security > Auditing. Configure events to audit: user login/logout, role/privilege changes, database access, SQL operations, and custom application events. Audit logs are tamper-resistant and stored in the IRISAUDIT database. Use %SYS.Auditing APIs to create custom audit events for application-specific security events. Regular audit log review detects unauthorized access attempts and policy violations.

Practical Implementation Guidelines

1) Design a role hierarchy matching organizational structure and job functions. 2) Create custom resources for sensitive business operations. 3) Implement application-level authorization checks using $SYSTEM.Security.Check() in code. 4) Use escalation roles sparingly and document their necessity. 5) Enable comprehensive auditing, especially for sensitive operations. 6) Regular access reviews - verify users have appropriate roles and remove unnecessary privileges. 7) Implement least privilege - grant minimum permissions necessary for job functions. 8) Separate administrative functions from application functions through different roles and applications.

Exam Preparation Summary

Critical Concepts to Master:

  1. Encryption Strategies
  2. Secure Communications
  3. SQL Injection Prevention
  4. Code Execution Security
  5. Security Model Implementation

Common Exam Scenarios:

  • Choosing appropriate encryption method for a security requirement
  • Configuring TLS for outbound HTTP connections
  • Identifying SQL injection vulnerabilities in code samples
  • Refactoring vulnerable code to use parameterized queries
  • Identifying RCE vulnerabilities using XECUTE or indirection
  • Designing role hierarchies for an organization
  • Configuring web application security settings
  • Implementing custom resource protection for business operations
  • Enabling audit logging for compliance requirements

Hands-On Practice Recommendations:

  1. Encryption Practice
  2. Secure Connections Practice
  3. SQL Security Practice
  4. RCE Prevention Practice
  5. Security Model Practice

Key Security Principles to Remember:

  • Defense in depth: Multiple layers of security controls
  • Least privilege: Grant minimum necessary permissions
  • Fail secure: Default to deny access, explicitly grant permissions
  • Input validation: Validate all external inputs at application boundaries
  • Output encoding: Encode outputs to prevent injection in target contexts
  • Secure by default: Enable security features in initial configuration
  • Audit and monitor: Log security events and review regularly
  • Separation of duties: Divide administrative and operational privileges
  • Regular updates: Keep security configurations current with threats

Important Security Classes and Methods:

  • %SYSTEM.Encryption: Encrypt(), Decrypt(), ActivateEncryptionKey()
  • %SYSTEM.Security: Check(), Login(), Logout(), ValidateUser()
  • %SQL.Statement: %Prepare(), %Execute() with parameters
  • %Net.HttpRequest: SSLConfiguration property
  • %CSP.Page: %CheckCSRFToken(), server variables
  • %Library.ResultSet: Security for query results
  • %SYS.Auditing: Custom audit event logging

Critical Documentation Sections:

  • System Administration Guide (GSA): Security chapters 9-13
  • Using InterSystems SQL (GSQL): Dynamic SQL and host variables chapters
  • Using Globals (GGBL): Encryption features
  • Object-Oriented Programming (GOBJ): Property encryption
  • Web Services Security (GSOAPSEC): WS-Security implementation
  • CSP Guide (GCSP): Web application security features

Report an Issue