🔐 Advanced Security with Oracle PL/SQL: Auditing, Encryption, and Best Practices

🧭 Introduction

In Oracle environments, data security is a top priority. PL/SQL offers powerful tools to protect sensitive information, audit critical operations, and prevent vulnerabilities such as SQL injection and privilege escalation. This article presents advanced security practices focused on auditing via triggers, data encryption, and secure coding techniques — essential for DBAs and developers working with business logic directly in the database.


🛡️ Auditing with Triggers

✅ Example: Audit Trigger

⚠️ Best Practices for Triggers

CREATE OR REPLACE TRIGGER trg_audit_employee
AFTER INSERT OR UPDATE OR DELETE ON employee
FOR EACH ROW
DECLARE
   v_operation VARCHAR2(10);
BEGIN
   IF INSERTING THEN
      v_operation := 'INSERT';
      INSERT INTO audit_log VALUES (
         audit_seq.NEXTVAL, 'EMPLOYEE', v_operation,
         NULL, :NEW.emp_name, USER, SYSTIMESTAMP
      );
   ELSIF UPDATING THEN
      v_operation := 'UPDATE';
      INSERT INTO audit_log VALUES (
         audit_seq.NEXTVAL, 'EMPLOYEE', v_operation,
         :OLD.emp_name, :NEW.emp_name, USER, SYSTIMESTAMP
      );
   ELSIF DELETING THEN
      v_operation := 'DELETE';
      INSERT INTO audit_log VALUES (
         audit_seq.NEXTVAL, 'EMPLOYEE', v_operation,
         :OLD.emp_name, NULL, USER, SYSTIMESTAMP
      );
   END IF;
END;
  • Avoid heavy logic inside triggers (use external procedures)

  • Use triggers only when necessary — excessive use can impact performance

  • Implement retention policies for audit logs


🔐 Encrypting Sensitive Data

✅ Example: Encrypting and Decrypting Passwords

DECLARE
   key RAW(128) := UTL_I18N.STRING_TO_RAW('secret_key');
   plain_password VARCHAR2(50) := 'SecurePassword123';
   encrypted_password RAW(128);
BEGIN
   -- Encrypt
   encrypted_password := DBMS_CRYPTO.ENCRYPT(
      src => UTL_I18N.STRING_TO_RAW(plain_password),
      typ => DBMS_CRYPTO.ENCRYPT_AES256 + DBMS_CRYPTO.CHAIN_CBC + DBMS_CRYPTO.PAD_PKCS5,
      key => key
   );
   DBMS_OUTPUT.PUT_LINE('Encrypted: ' || RAWTOHEX(encrypted_password));

   -- Decrypt
   plain_password := UTL_I18N.RAW_TO_CHAR(
      DBMS_CRYPTO.DECRYPT(
         src => encrypted_password,
         typ => DBMS_CRYPTO.ENCRYPT_AES256 + DBMS_CRYPTO.CHAIN_CBC + DBMS_CRYPTO.PAD_PKCS5,
         key => key
      )
   );
   DBMS_OUTPUT.PUT_LINE('Decrypted: ' || plain_password);
END;

🔒 Ideal for protecting passwords, credit card data, and personal information.


📋 PL/SQL Security Best Practices — Summary Table


🧩 Detailed Examples for Each Practice

🧱 1. Least Privilege Principle

CREATE ROLE app_user_role;
GRANT SELECT, INSERT ON customers TO app_user_role;
GRANT app_user_role TO app_user;

🧨 2. Preventing SQL Injection

❌ Bad practice:

EXECUTE IMMEDIATE 'SELECT * FROM users WHERE username = ''' || p_user || '''';

✅ Using bind variable:

EXECUTE IMMEDIATE 'SELECT * FROM users WHERE username = :1' USING p_user;

✅ Using DBMS_ASSERT:

v_user := DBMS_ASSERT.ENQUOTE_LITERAL(p_user);
EXECUTE IMMEDIATE 'SELECT * FROM users WHERE username = ' || v_user;

📌 3. Input Validation

IF p_id < 0 THEN
   RAISE_APPLICATION_ERROR(-20001, 'Invalid ID');
END IF;

🛡️ 4. Use of Triggers

Already covered above with the trg_audit_employee example.


🧬 5. Code Obfuscation

wrap iname=my_code.sql

Generates a .plb file with unreadable code, protecting business logic.


🔐 6. Execution Control: Invoker vs Definer Rights

CREATE OR REPLACE PROCEDURE fetch_sensitive_data
AUTHID CURRENT_USER
IS
BEGIN
   SELECT * FROM sensitive_table;
END;

Ensures the procedure runs with the caller’s privileges, not the creator’s.


🔒 7. Data Encryption

Already covered above using DBMS_CRYPTO.


🚨 8. Action Auditing

Beyond triggers, consider:

  • Oracle Fine-Grained Auditing (FGA)

  • Oracle Unified Audit for enterprise environments


🧯 9. Exception Handling

BEGIN
   -- logic
EXCEPTION
   WHEN OTHERS THEN
      RAISE_APPLICATION_ERROR(-20002, 'Unexpected error. Please contact support.');
END;

Avoid exposing technical error messages to end users. Log details internally.


📌 Conclusion

Security in Oracle PL/SQL requires attention to technical and architectural details. With practices like auditing via triggers, data encryption, privilege control, and rigorous input validation, you can build a robust, traceable, and resilient environment against internal and external threats.

These techniques not only protect your database but also help ensure compliance with regulations like GDPR, LGPD, and PCI-DSS.

#OracleSecurity #PLSQLTips #DatabaseAuditing #SQLInjectionPrevention #OracleDBA #SecureCoding #DBMS_CRYPTO #GDPRCompliance #OracleBestPractices

0
Subscribe to my newsletter

Read articles from Johnny Hideki Kinoshita de Faria directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Johnny Hideki Kinoshita de Faria
Johnny Hideki Kinoshita de Faria

Technology professional with over 15 years of experience delivering innovative, scalable, and secure solutions — especially within the financial sector. I bring deep expertise in Oracle PL/SQL (9+ years), designing robust data architectures that ensure performance and reliability. On the back-end side, I’ve spent 6 years building enterprise-grade applications using .NET, applying best practices like TDD and clean code to deliver high-quality solutions. In addition to my backend strengths, I have 6 years of experience with PHP and JavaScript, allowing me to develop full-stack web applications that combine strong performance with intuitive user interfaces. I've led and contributed to projects involving digital account management, integration of VISA credit and debit transactions, modernization of payment systems, financial analysis tools, and fraud prevention strategies. Academically, I hold a postgraduate certificate in .NET Architecture and an MBA in IT Project Management, blending technical skill with business acumen. Over the past 6 years, I’ve also taken on leadership roles — managing teams, mentoring developers, and driving strategic initiatives. I'm fluent in agile methodologies and make consistent use of tools like Azure Boards to coordinate tasks and align team performance with delivery goals.