11.1. Accessing the File System Using the UTL_FILE Package

The UTL_FILE package enables Oracle users to read and write to the file system. As already noted, access to files on the file system is achieved with the privileges of the Oracle user — so anything this user can read or write to can be read or written to by anyone else. The following PL/SQL code can be used to read files from the file system:

CREATE OR REPLACE PROCEDURE READ_FILE(DIRNAME VARCHAR2, FNAME VARCHAR2) AS invalid_path EXCEPTION; access_denied EXCEPTION; PRAGMA EXCEPTION_INIT(invalid_path, −29280); PRAGMA EXCEPTION_INIT(access_denied, −29289); FD UTL_FILE.FILE_TYPE; BUFFER VARCHAR2(260); BEGIN EXECUTE IMMEDIATE 'CREATE OR REPLACE DIRECTORY RW_FILE AS ''' || DIRNAME || ''''; FD := UTL_FILE.FOPEN('RW_FILE',FNAME,'r'); DBMS_OUTPUT.ENABLE(1000000); LOOP UTL_FILE.GET_LINE(FD,BUFFER,254); DBMS_OUTPUT.PUT_LINE(BUFFER); END LOOP; EXECUTE IMMEDIATE 'DROP DIRECTORY RW_FILE'; EXCEPTION WHEN invalid_path THEN DBMS_OUTPUT.PUT_LINE('File location or path is invalid.'); IF (UTL_FILE.IS_OPEN(FD) = TRUE) THEN UTL_FILE.FCLOSE(FD); END IF; EXECUTE IMMEDIATE 'DROP DIRECTORY RW_FILE'; WHEN access_denied THEN DBMS_OUTPUT.PUT_LINE('Access is denied.'); IF (UTL_FILE.IS_OPEN(FD) = TRUE) THEN UTL_FILE.FCLOSE(FD); END IF; EXECUTE IMMEDIATE 'DROP DIRECTORY RW_FILE'; WHEN NO_DATA_FOUND THEN DBMS_OUTPUT.PUT_LINE('End of file.'); IF (UTL_FILE.IS_OPEN(FD) = TRUE) THEN UTL_FILE.FCLOSE(FD); END IF; EXECUTE IMMEDIATE 'DROP DIRECTORY RW_FILE'; ...

Get The Oracle® Hacker's Handbook: Hacking and Defending Oracle now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.